title
stringlengths 10
172
| question_id
int64 469
40.1M
| question_body
stringlengths 22
48.2k
| question_score
int64 -44
5.52k
| question_date
stringlengths 20
20
| answer_id
int64 497
40.1M
| answer_body
stringlengths 18
33.9k
| answer_score
int64 -38
8.38k
| answer_date
stringlengths 20
20
| tags
sequence |
---|---|---|---|---|---|---|---|---|---|
In-game save feature (in tkinter game) | 40,071,582 | <p>I'm working on a text-based game in Python using Tkinter. All the time the window contains a Label and a few Buttons (mostly 3). If it didn't have GUI, I could just use Pickle or even Python i/o (.txt file) to save data and later retrieve it. But what is the best way to tell the program to load the exact widgets without losing bindings, buttons' commands, classes etc.? P.S.: Buttons lead to cleaning the frame of widgets and summoning new widgets. I'm thinking of assigning a lambda (button's command) to a variable and then saving it (Pickle?) to be able to load it in the future and get the right point in the plot. Should I go for it or is there a better, alternative way to accomplish the thing? (If using lambda may work, I'd still be grateful to see your way of doing that.)</p>
| 1 | 2016-10-16T14:46:37Z | 40,071,607 | <p>You need to save stuff in some kind of config file. In generel I'd recommend JSON and YAML as file formats also ini for ease of parsing.</p>
<p>Also, do not forget about the windows registry (portability lost then though).</p>
| 1 | 2016-10-16T14:49:05Z | [
"python",
"tkinter"
] |
In-game save feature (in tkinter game) | 40,071,582 | <p>I'm working on a text-based game in Python using Tkinter. All the time the window contains a Label and a few Buttons (mostly 3). If it didn't have GUI, I could just use Pickle or even Python i/o (.txt file) to save data and later retrieve it. But what is the best way to tell the program to load the exact widgets without losing bindings, buttons' commands, classes etc.? P.S.: Buttons lead to cleaning the frame of widgets and summoning new widgets. I'm thinking of assigning a lambda (button's command) to a variable and then saving it (Pickle?) to be able to load it in the future and get the right point in the plot. Should I go for it or is there a better, alternative way to accomplish the thing? (If using lambda may work, I'd still be grateful to see your way of doing that.)</p>
| 1 | 2016-10-16T14:46:37Z | 40,074,406 | <p>My understanding was that you need a widget manager, to put them where you want and it is easy to pick up values.</p>
<p>Create a new class called Manager, make two functions, _setNewWidget, _deleteWidget, like this:</p>
<pre><code>class Manager():
def __init__(self, *args, **kwargs):
objects = {}
def _createButton(self, frame, id, function, etc):
# object[id] = frame.Button(function, etc, ...) i dnt' know sintaxes, but this is the way
def _deleteWidget(self, id):
# object[id] = None or del(object[id]) same here
</code></pre>
<p>To get, just:</p>
<pre><code>manager = Manager()
manager._createWidget("button_fase_one", frameTk, etc, etc)
manager.objects["button_fase_one"].changeFrame() # example
print(manager.objects["button_fase_one"].text)
</code></pre>
<p>In this way u can create objects and blit where u want.</p>
<p>To save data just make another function and save as json.</p>
| 1 | 2016-10-16T19:17:15Z | [
"python",
"tkinter"
] |
How to invoke an endpoint method using App Engine? | 40,071,615 | <p>this is a very simple question for App Engine users.
I'm new in cloud computing but i would like to know how to invoke my endpoint.method. I'm developing on my machine using pycharm. This is my main.py code:</p>
<pre><code>@endpoints.api(name='firstapi', version='v1')
</code></pre>
<p>class MainHandler(webapp2.RequestHandler):</p>
<pre><code>def get(self):
self.response.write('Hello, world!')
@endpoints.method(
# This method does not take a request message.
message_types.VoidMessage,
# This method returns a GreetingCollection message.
message_types.VoidMessage,
path='goodbye',
http_method='GET',
name='firstapi.printgoodbye')
def printGoodBye(self):
self.response.write("Good Bye World")
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
</code></pre>
<p>What do i have to type in my browser in order to see "Good Bye World"?
I'm quite confused about this, any help is appreciated.</p>
| 0 | 2016-10-16T14:49:28Z | 40,083,927 | <p>You should follow the quick start guide for Google Endpoints for App Engine. <a href="https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python" rel="nofollow">https://cloud.google.com/endpoints/docs/frameworks/python/quickstart-frameworks-python</a></p>
| 0 | 2016-10-17T10:25:46Z | [
"python",
"google-app-engine",
"google-cloud-platform"
] |
Non Blocking calls using Tornado and Python Eve | 40,071,624 | <p>I have a Eve Application with Tornado. </p>
<pre><code>http_server = HTTPServer(WSGIContainer(app))
http_server.listen(5000)
IOLoop.instance().start()
</code></pre>
<p>I make a post call on of my API that takes a long time and sends a mail to the user when the process is done.
How can I make the call non blocking so that the user do not have to wait.</p>
<p>Thanks
DC </p>
| 1 | 2016-10-16T14:50:00Z | 40,077,706 | <p>Eve is written in Flask so by design it's blocking code and there's no simple way to make it magically non-blocking. Running your eve project in tornado will not help either. You can however use <a href="http://gunicorn.org/" rel="nofollow"><code>gunicorn</code></a> or <a href="https://hendrix.readthedocs.io/en/latest/" rel="nofollow"><code>hendrix</code></a> which can fork your <code>wsgi</code> app, act like a proxy, and make it seem like your project is running in a non-blocking manner. But I recommend using an async/threaded task runner (something like <a href="http://docs.celeryproject.org/en/latest/index.html" rel="nofollow"><code>celery</code></a>) to send the mail. This method will require you to rewrite your mailing functions using the task runner. I hope this helps, if not please provide some more examples of what your code does and maybe we can help.</p>
| 1 | 2016-10-17T02:34:36Z | [
"python",
"tornado",
"eve"
] |
How to look up rows in certain condition | 40,071,628 | <p>I have a dataframe and I would like to search strange rows like below :</p>
<pre><code>ããmonth
0 201605ãããã
1 201606
2 201607
3 08
4 nan
5 201610
</code></pre>
<p>For instance, I would like to extract rows with elements that is not 6 digits like below :</p>
<pre><code> month
3 08
4 nan
</code></pre>
<p>I have searched, but couldn't figure out how to extract rows.
How can I get this result?</p>
| 0 | 2016-10-16T14:50:34Z | 40,071,710 | <p>Suppose your month column is of <code>str</code> type, you can use <code>.str.len()</code> to get the number of digits for each element and use the result for subsetting:</p>
<pre><code>df[df.month.str.len() != 6]
# month
#3 08
#4 NaN
</code></pre>
| 1 | 2016-10-16T14:59:16Z | [
"python",
"pandas",
"dataframe"
] |
Python Regex sub doesn't replace line breaks | 40,071,919 | <p>I have a robot that brings me an html code like this:</p>
<pre><code><div class="std">
<p>CAR:
<span>Onix</span>
</p>
<p>MODEL: LTZ</p>
<p>
<span>COLOR:
<span>Black</span>
</p>
<p>ACESSORIES:
<span>ABS</span>
</p>
<p>
<span>DESCRIPTION:</span>
<span>The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.</span>
</p>
<p>TECHNICAL DETAIL:
<span>The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..</span>
</p>
</div>
</code></pre>
<p>I applied the code below to remove the HTML tags:</p>
<pre><code>cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr,'\n', html_code).strip()
</code></pre>
<p>It returns to me:</p>
<pre><code>CAR: Onix
MODEL: LTZ
COLOR:
Black
ACESSORIES:
ABS
DESCRIPTION:
The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.
TECHNICAL DETAIL:
The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..
</code></pre>
<p>Now I need to remove the line breaks to have something like this:</p>
<pre><code>CAR: Onix
MODEL: LTZ
COLOR: Black
ACESSORIES: ABS
DESCRIPTION: The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.
TECHNICAL DETAIL: The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..
</code></pre>
<p>I tried this code below, but it doesn't match the line breaks correctly:</p>
<pre><code>cleantext = re.sub(r':\s*[\r\n]*', ': ', cleantext)
</code></pre>
<p>I tried this another code also:</p>
<pre><code>cleantext = cleantext.replace(': \n', ': ')
</code></pre>
<p>It doesn't work also. How can I manage this?</p>
| 0 | 2016-10-16T15:19:48Z | 40,072,115 | <p>I think this should work for you </p>
<pre><code>>>> string = """
CAR: Onix
MODEL: LTZ
COLOR:
Black
ACESSORIES:
ABS
DESCRIPTION:
The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.
TECHNICAL DETAIL:
The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..
"""
>>> list_string = string.split("\n\n\n")
>>> for each in list_string:
print each.replace("\n","").strip()
CAR: Onix
MODEL: LTZ
COLOR:Black
ACESSORIES:ABS
DESCRIPTION:
The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.
TECHNICAL DETAIL:The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..
</code></pre>
| 0 | 2016-10-16T15:42:24Z | [
"python",
"regex",
"line-breaks"
] |
Python Regex sub doesn't replace line breaks | 40,071,919 | <p>I have a robot that brings me an html code like this:</p>
<pre><code><div class="std">
<p>CAR:
<span>Onix</span>
</p>
<p>MODEL: LTZ</p>
<p>
<span>COLOR:
<span>Black</span>
</p>
<p>ACESSORIES:
<span>ABS</span>
</p>
<p>
<span>DESCRIPTION:</span>
<span>The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.</span>
</p>
<p>TECHNICAL DETAIL:
<span>The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..</span>
</p>
</div>
</code></pre>
<p>I applied the code below to remove the HTML tags:</p>
<pre><code>cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr,'\n', html_code).strip()
</code></pre>
<p>It returns to me:</p>
<pre><code>CAR: Onix
MODEL: LTZ
COLOR:
Black
ACESSORIES:
ABS
DESCRIPTION:
The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.
TECHNICAL DETAIL:
The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..
</code></pre>
<p>Now I need to remove the line breaks to have something like this:</p>
<pre><code>CAR: Onix
MODEL: LTZ
COLOR: Black
ACESSORIES: ABS
DESCRIPTION: The Chevrolet Onix is a subcompact car launched by American automaker Chevrolet in Brazil at the 2012 São Paulo International Motor Show[1] to succeed some versions of Chevrolet Celta. Offered initially as a five-door hatchback, a four-door sedan was launched in 2013 and called the Chevrolet Prisma.[2] The Onix is currently only sold in some South American countries part of Mercosur, including Brazil, Argentina, Colombia, Paraguay and Uruguay.
TECHNICAL DETAIL: The Onix is available in three trim levels (LS, LT and LTZ) with two 4-cylinder engines, the 1.0-litre producing 78 PS (57 kW; 77 bhp) (petrol)/ 80 PS (59 kW; 79 bhp) (ethanol) and 1.4-litre 98 PS (72 kW; 97 bhp) (petrol)/106 PS (78 kW; 105 bhp) (ethanol) offering automatic or five-speed manual transmission..
</code></pre>
<p>I tried this code below, but it doesn't match the line breaks correctly:</p>
<pre><code>cleantext = re.sub(r':\s*[\r\n]*', ': ', cleantext)
</code></pre>
<p>I tried this another code also:</p>
<pre><code>cleantext = cleantext.replace(': \n', ': ')
</code></pre>
<p>It doesn't work also. How can I manage this?</p>
| 0 | 2016-10-16T15:19:48Z | 40,072,166 | <p>I think there are two parts to your problem,
First is to Join the string in two lines like below<br>
<code>COLOR:
Black</code></p>
<p>to<br>
<code>COLOR: black</code></p>
<p>and then remove all empty lines</p>
<p>For first part you could use replace your <code>re.sub</code> with following<br>
<code>cleantext = re.sub(r'(.*):\s*[\r\n](.*)', '\g<1>: \g<2>', cleantext)</code></p>
<p>And for removing empty lines it would be tricky to do it via re.sub so I would suggest to use
<code>cleantext = "\n".join([line for line in cleantext.split('\n') if line.strip() != ''])</code></p>
<p>This would give you answer as expected</p>
| 1 | 2016-10-16T15:47:43Z | [
"python",
"regex",
"line-breaks"
] |
How to use the NumPy installed by Pacman in virtualenv? | 40,071,987 | <p>My system is Archlinux.
My project will use NumPy, and my project is in a virtual environment created by virtualenv.</p>
<p>As it is difficult to install NumPy by pip, I install it by Pacman:</p>
<p><code>sudo pacman -S python-scikit-learn</code></p>
<p>But how can I use it in virtualenv?</p>
| 0 | 2016-10-16T15:27:56Z | 40,072,017 | <p>You can create the virtualenv with the <code>--system-site-packages</code> switch to use system-wide packages in addition to the ones installed in the stdlib.</p>
| 0 | 2016-10-16T15:30:59Z | [
"python",
"linux",
"virtualenv",
"pacman",
"archlinux-arm"
] |
hasattr returns always True for app engine ndb entity | 40,072,033 | <p>I am applying <a href="http://stackoverflow.com/a/19869907/492258">this answer</a> to my project</p>
<p>This is my ndb entity where is_deleted added later.</p>
<pre><code>class FRoom(ndb.Model):
location = ndb.StringProperty(default="")
is_deleted = ndb.BooleanProperty(default=False) #added later
#other fileds
</code></pre>
<p>when I do print my entities with logging.info, I have</p>
<pre><code>FRoom(key=Key('FRoom', 5606822106890240), is_deleted=False, location=u'denizli')
FRoom(key=Key('FRoom', 6169772060311552), is_deleted=False, location=u'aydin' )
FRoom(key=Key('FRoom', 6451247037022208), location=u'bursa')
</code></pre>
<p>When I do for do </p>
<pre><code>for froom in frooms:
logging.info(hasattr(froom, 'is_deleted')) # gives always True
</code></pre>
<p>but when I do for example:</p>
<pre><code>logging.info(hasattr(froom, 'is_deletedXXX')) #gives me False
</code></pre>
<p>What am I doing wrong?</p>
| 0 | 2016-10-16T15:33:01Z | 40,072,305 | <p>This is expected behaviour due to the <code>is_deleted</code> property having the <code>default</code> option set: the datastore will automatically return that default value if the property was not explicitly set.</p>
<p>From the <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#options" rel="nofollow">Property Options</a> table:</p>
<p><a href="https://i.stack.imgur.com/KBDES.png" rel="nofollow"><img src="https://i.stack.imgur.com/KBDES.png" alt="enter image description here"></a></p>
<p>So for properties for which you set the <code>default</code> option in the model the check if the property exists is unnecessary - it always exists, so you can directly do:</p>
<pre><code>for froom in frooms:
logging.info(froom.is_deleted)
# or
logging.info(getattr(froom, 'is_deleted'))
</code></pre>
<p>The <code>hasattr(froom, 'is_deletedXXX')</code> returns False because you don't have a <code>is_deletedXXX</code> property in <code>FRoom</code>'s model.</p>
| 0 | 2016-10-16T16:02:13Z | [
"python",
"google-app-engine",
"hasattr"
] |
Python server is sending truncated images over TCP | 40,072,052 | <p>I have a simple server on my Windows PC written in python that reads files from a directory and then sends the file to the client via TCP.</p>
<p>Files like HTML and Javascript are received by the client correctly (sent and original file match).<br>
The issue is that <strong>image data is truncated</strong>. </p>
<p>Oddly, different images are truncated at different lengths, but it's consistent per image.<br>
For example, a specific 1MB JPG is always received as 95 bytes. Another image which should be 7KB, is received as 120 bytes.</p>
<p>Opening the truncated image files in notepad++, the data that <em>is</em> there is correct. (The only issue is that the file ends too soon).<br>
I do not see a pattern for where the files end. The chars/bytes immediately before and after truncation are different per image. </p>
<p>I've tried three different ways for the server to read the files, but they all have the same result.</p>
<p>Here is a snippet of the reading and sending of files:</p>
<pre><code>print ("Cache size=" + str(os.stat(filename).st_size))
#1st attempt, using readlines
fileobj = open(filename, "r")
cacheBuffer = fileobj.readlines()
for i in range(0, len(cacheBuffer)):
tcpCliSock.send(cacheBuffer[i])
</code></pre>
<p> </p>
<pre><code>#2nd attempt, using line, same result
with open(filename) as f:
for line in f:
tcpCliSock.send(f)
</code></pre>
<p> </p>
<pre><code>#3rd attempt, using f.read(), same result
with open(filename) as f:
tcpCliSock.send(f.read())
</code></pre>
<p>The script prints to the console the size of the file read, and <em>the number of bytes matches the original image</em>. So this proves the problem is in sending, right?<br>
If the issue is with sending, what can I change to have the whole image sent properly?</p>
| 1 | 2016-10-16T15:34:58Z | 40,072,086 | <p>Since you're dealing with images, which are binary files, you need to open the files in <em>binary</em> mode.</p>
<pre><code>open(filename, 'rb')
</code></pre>
<p>From the Python documentation for <a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow"><code>open()</code></a>:</p>
<blockquote>
<p>The default is to use text mode, which may convert <code>'\n'</code> characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append <code>'b'</code> to the mode value to open the file in binary mode, which will improve portability. (Appending <code>'b'</code> is useful even on systems that donât treat binary and text files differently, where it serves as documentation.)</p>
</blockquote>
<p>Since your server is running on Windows, as you <code>read</code> the file, Python is converting every <code>\r\n</code> it sees to <code>\n</code>. For text files, this is nice: You can write platform-independent code that only deals with <code>\n</code> characters. For binary files, this <em>completely corrupts your data</em>. That's why it's important to use <code>'b'</code> when dealing with binary files, but also important to leave it off when dealing with text files.</p>
<hr>
<p>Also, as TCP is a stream protocol, it's better to <em>stream</em> the data into the socket in smaller pieces. This avoids the need to read an entire file into memory, which will keep your memory usage down. Like this:</p>
<pre><code>with open(filename, 'rb') as f:
while True:
data = f.read(4096)
if len(data) == 0:
break
tcpCliSock.send(data)
</code></pre>
| 3 | 2016-10-16T15:39:11Z | [
"python",
"tcp",
"server"
] |
How can i display my data in database and export it to pdf -Django | 40,072,058 | <p>my x variable is getting all the data in my database, i guess? someone help me how can i display all data and export it to pdf file.</p>
<pre><code>response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="WishList.pdf"'
buffer = BytesIO()
# Create the PDF object, using the BytesIO object as its "file."
p = canvas.Canvas(buffer)
x = Item.objects.all()
p.drawString(100, 100,x)
p.drawString(200,300,"sad")
# Close the PDF object cleanly.
p.showPage()
p.save()
# Get the value of the BytesIO buffer and write it to the response.
pdf = buffer.getvalue()
buffer.close()
response.write(pdf)
return response
</code></pre>
| 0 | 2016-10-16T15:35:40Z | 40,100,704 | <p>Your Variable x won't return anything you can print into the PDF, because its a querryset and not a couple strings attached to each other. I just started working with Django and getting the values works something like this:</p>
<pre><code>x = Item.objects.all[0].name
</code></pre>
<p>This Code snippet will asigne the vale of the row name of the first entry in your Item table to the variable x.
For more Information I can only recommend reading the
<a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#limiting-querysetshttp://" rel="nofollow">Tutorial about making queries</a> on the django website.</p>
| 0 | 2016-10-18T06:05:47Z | [
"python",
"django",
"django-models",
"django-views"
] |
How would i loop this bit of code so that It will go to the start again? | 40,072,080 | <p>I'm a new to python and i need a bit of help. I just need to know how would i loop this bit of code so that after it says "please try again..." it will then go onto "Do you want to roll or stick". Thanks in advance.</p>
<pre><code>Roll = input("Do you want to Roll or Stick?")
if Roll in ("Roll" , "roll"):
print("Your new numbers are," , +number10 , +number20 , +number30 , +number40 , +number50)
if Roll in ("Stick" , "stick"):
print("Your numbers are," , +number1 , +number2 , +number3 , +number4 , +number5)
else:
print("Please try again.")
</code></pre>
| 1 | 2016-10-16T15:38:36Z | 40,072,107 | <p>You can wrap up your code with <a href="https://wiki.python.org/moin/WhileLoop" rel="nofollow"><code>while</code></a> loop:</p>
<pre><code>while True:
Roll = input("Do you want to Roll or Stick?")
if Roll.lower() == 'exit':
break
...
else:
print("Please try again. Type 'exit' to exit.")
</code></pre>
| 1 | 2016-10-16T15:40:52Z | [
"python"
] |
Exception inside a while loop error | 40,072,126 | <p>I'm trying to get this code to loop until the user gives correct input but after the first loop if the user gives bad input again the program will crash and give me a ValueError</p>
<pre><code>while True:
try:
input1,input2= input("Enter the Lat and Long of the source point separated by a comma eg 50,30").split(',')
break
except ValueError:
print ("please Use a Comma")
input1,input2 = input("Enter the Lat and Long of the source point separated by a comma eg 50,30").split(',')
</code></pre>
| 0 | 2016-10-16T15:43:19Z | 40,072,539 | <p>The trick would be in using the <em>continue</em> statement when you get the exception. That will restart the loop and go into the area protected by the <em>try</em> statement so if you get another exception it won't crash your program.</p>
<pre><code>while True:
try:
value1, value2 = input("Enter the Lat and Long of the source point separated by a comma eg 50,30: ").split(',')
break
except ValueError:
print("Please Use a Comma")
continue
</code></pre>
| 0 | 2016-10-16T16:24:36Z | [
"python",
"while-loop",
"exception-handling"
] |
Random word generator python | 40,072,142 | <p>So this is the code I have. The outcome is something along "['jjjjjjj', 'tt', 'dddd', 'eeeeeeeee']". How can I change the list comprehension to allow for the function random.choice to repeat for each letter of each 'word'?</p>
<pre><code>lista=[random.randint(1,10)*random.choice(string.ascii_letters) for i in range(random.randint(1,10))]
</code></pre>
| 0 | 2016-10-16T15:44:44Z | 40,072,246 | <p>I suppose you mean you want "abcd" and "jdhn" instead of "aaaa" and "jjjj" for the purpose of testing a sorting algorithm or some such.</p>
<p>If so, try this</p>
<pre><code>lista=["".join(random.choice(string.ascii_letters) for j in range(random.randint(1,10)) ) for i in range(random.randint(1,10)) ]
</code></pre>
| 1 | 2016-10-16T15:56:41Z | [
"python"
] |
Random word generator python | 40,072,142 | <p>So this is the code I have. The outcome is something along "['jjjjjjj', 'tt', 'dddd', 'eeeeeeeee']". How can I change the list comprehension to allow for the function random.choice to repeat for each letter of each 'word'?</p>
<pre><code>lista=[random.randint(1,10)*random.choice(string.ascii_letters) for i in range(random.randint(1,10))]
</code></pre>
| 0 | 2016-10-16T15:44:44Z | 40,072,252 | <p>You'll need a nested list comorehension. You need to rerun random.choice for every letter. Something along the lines of</p>
<pre><code>[ [Random.choice(string.asciiletters) for x in range(y)] for you in range(5)]
</code></pre>
<p>Will give you 5 'words' each of length y.</p>
| 0 | 2016-10-16T15:57:32Z | [
"python"
] |
Installing matplotlib using pip gives error | 40,072,151 | <p>I am new to python and is using pip to download and install packages. I ran the following code on my command window and it throws an error</p>
<pre><code>pip install matplotlib
</code></pre>
<p>And the process starts as </p>
<pre><code>Collecting matplotlib
Using cached matplotlib-1.5.3-cp27-cp27m-win32.whl
Collecting numpy>=1.6 (from matplotlib)
Using cached numpy-1.11.2-cp27-none-win32.whl
Collecting python-dateutil (from matplotlib)
Using cached python_dateutil-2.5.3-py2.py3-none-any.whl
Collecting cycler (from matplotlib)
Using cached cycler-0.10.0-py2.py3-none-any.whl
Collecting pyparsing!=2.0.4,!=2.1.2,>=1.5.6 (from matplotlib)
Using cached pyparsing-2.1.10-py2.py3-none-any.whl
Collecting pytz (from matplotlib)
Using cached pytz-2016.7-py2.py3-none-any.whl
Collecting six>=1.5 (from python-dateutil->matplotlib)
Using cached six-1.10.0-py2.py3-none-any.whl
Installing collected packages: numpy, six, python-dateutil, cycler, pyparsing, pytz, matplotlib
Exception:
Traceback (most recent call last):
File "c:\python27\lib\site-packages\pip\basecommand.py", line 215, in main
status = self.run(options, args)
File "c:\python27\lib\site-packages\pip\commands\install.py", line 317, in run
prefix=options.prefix_path,
File "c:\python27\lib\site-packages\pip\req\req_set.py", line 742, in install
**kwargs
File "c:\python27\lib\site-packages\pip\req\req_install.py", line 831, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "c:\python27\lib\site-packages\pip\req\req_install.py", line 1032, in move_wheel_files
isolated=self.isolated,
File "c:\python27\lib\site-packages\pip\wheel.py", line 346, in move_wheel_files
clobber(source, lib_dir, True)
File "c:\python27\lib\site-packages\pip\wheel.py", line 324, in clobber
shutil.copyfile(srcfile, destfile)
File "c:\python27\lib\shutil.py", line 83, in copyfile
with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'c:\\python27\\Lib\\site-packages\\numpy\\core\\multiarray.pyd'
</code></pre>
<p>And it gives these traceback errors. I'm unable to figure out what these errors are and how to solve them. Please help. It works perfectly till collecting the packages but at the time of installing it throws errors.</p>
| 0 | 2016-10-16T15:45:50Z | 40,072,198 | <p>Try <code>python -m pip install matplotlib</code>.</p>
<p>or</p>
<ol>
<li>Open the <code>cmd</code> as administrator </li>
<li>then <code>python -m pip install matplotlib</code></li>
</ol>
| 0 | 2016-10-16T15:51:34Z | [
"python",
"matplotlib",
"pip"
] |
redirection not working in python for locally hosted form snippet for cgiserver | 40,072,177 | <p>I am trying to use the following created html page to access information from a cgiserver using python. I am implementing auto redirection using javascript at bottom</p>
<pre><code><form action="http://pi-web.cisco.com/pims-home/fcgi-bin/BugReport/DDTS.cgi?Function=DDTS">
<input type="hidden" name="Function" value="DDTS">
By Production Build: <td valign=top>
<table border=0 cellpadding=0 cellspacing=0>
<tr>
<td valign=top>
&nbsp;From:&nbsp;</td>
<td valign=top>
<select name=from_prod_build>
<option value="6_2_1_14I_DT_IMAGE" selected>6_2_1_14I_DT_IMAGE</option>
</select>
</td>
<td valign=top>
&nbsp;To:&nbsp;</td>
<td valign=top>
<select name=to_prod_build>
<option value="6_2_1_16I_DT_IMAGE" selected>6_2_1_16I_DT_IMAGE</option>
</select>
</td>
<td>
<input type=checkbox name=explicit_only value=1>
Explicit Commits Only</td>
<td valign=bottom>
&nbsp;&nbsp;&nbsp;<button type="submit" id="submit"name='by prod_bld'>
</button>
<script type="text/javascript">
document.getElementById("submit").click();</script>
</form>
</td>
</code></pre>
<p>However, i see in a web browser the page redirects and show the information but in python I can only fetch the created page and not redirected page. Below is the python script</p>
<pre><code>from lxml import html
import requests
page=requests.get('http://localhost/requestDDTS.html',allow_redirects=True)
print(page.url)
tree = html.parse(page.text)
</code></pre>
<p>How can i fix this?</p>
| -1 | 2016-10-16T15:48:47Z | 40,072,438 | <p>You can only get first page because there is no redirect.</p>
<p>In HTML page you have form, that is automatically submitted to <code>http://pi-web.cisco.com/pims-home/fcgi-bin/BugReport/DDTS.cgi?Function=DDTS</code>. First site returns with code 200 and not 301/302. Requests library doesn't parse javascript inside html document, it just fetches text content.</p>
<p>Put this in python script:</p>
<pre><code>payload = {
'Function': 'DDTS',
'by prod_bld': '', #this looks like typo, space instead of _ ?
'from_prod_build' : '6_2_1_14I_DT_IMAGE',
'to_prod_build' : '6_2_1_16I_DT_IMAGE'
}
page = requests.get('http://pi-web.cisco.com/pims-home/fcgi-bin/BugReport/DDTS.cgi', params=payload)
</code></pre>
<p>This should return the same page as the one you see after form submit in browser.</p>
| 0 | 2016-10-16T16:14:31Z | [
"javascript",
"python",
"cgi",
"python-requests"
] |
Python 2.7: Add 2 list items in a function | 40,072,224 | <p>I want to be able to add multiple items to my code with a function. But I want to be able to still add one single item, or none. Here is and example.</p>
<pre><code>listX = ["a", "b", "c"]
def addList(add):
if add != "null":
listX.append(add)
addList("d")
</code></pre>
<p>Adds d at the end. Simple.</p>
<pre><code>print listX
addList("e" + "f")
print listX
</code></pre>
<p>Now it's ['a', 'b', 'c', 'd', 'ef']. <strong>I want it to be ['a', 'b', 'c', 'd', 'e', f].</strong> Also, I also want to have only one argument for adding an item the (add) one.</p>
<p>How do I do this? Please help. And as always, thanks in advance.</p>
| 1 | 2016-10-16T15:54:23Z | 40,072,261 | <p>Your Function <code>addList</code> expects only 1 argument, when you say</p>
<pre><code>addList("e" + "f") # it passes it as addList("ef")
</code></pre>
<p>To solve your problem simply use <code>*</code> to get multiple arguments, and <code>extend</code> to add to it easily:</p>
<pre><code>listX = ['a', 'b', 'c']
def addList(*args):
listX.extend(args)
addList('d', 'e', 'f')
print (listX)
</code></pre>
<p>returns:</p>
<pre><code>['a', 'b', 'c', 'd', 'e', 'f']
</code></pre>
| 1 | 2016-10-16T15:58:20Z | [
"python",
"python-2.7",
"function",
"variables"
] |
Python 2.7: Add 2 list items in a function | 40,072,224 | <p>I want to be able to add multiple items to my code with a function. But I want to be able to still add one single item, or none. Here is and example.</p>
<pre><code>listX = ["a", "b", "c"]
def addList(add):
if add != "null":
listX.append(add)
addList("d")
</code></pre>
<p>Adds d at the end. Simple.</p>
<pre><code>print listX
addList("e" + "f")
print listX
</code></pre>
<p>Now it's ['a', 'b', 'c', 'd', 'ef']. <strong>I want it to be ['a', 'b', 'c', 'd', 'e', f].</strong> Also, I also want to have only one argument for adding an item the (add) one.</p>
<p>How do I do this? Please help. And as always, thanks in advance.</p>
| 1 | 2016-10-16T15:54:23Z | 40,072,291 | <p>The problem is breaking down the <code>'e' + 'f'</code> thing you have there.</p>
<p>As long as your parameter is an interable, this should work</p>
<pre><code>def addList(iterable):
for item in iterable:
listX.append(item)
</code></pre>
| 0 | 2016-10-16T16:01:05Z | [
"python",
"python-2.7",
"function",
"variables"
] |
Why can't I install Cassandra-driver | 40,072,283 | <p>I am studying Cassandra by its document.
But when I use "pip install cassandra-driver" to install cassandra-driver ,failed like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>weikairen2@weikairen2-virtual-machine:~$ pip install cassandra-driver
Collecting cassandra-driver
Using cached cassandra-driver-3.7.0.tar.gz
Requirement already satisfied (use --upgrade to upgrade): six>=1.6 in ./.local/lib/python2.7/site-packages (from cassandra-driver)
Requirement already satisfied (use --upgrade to upgrade): futures in ./.local/lib/python2.7/site-packages (from cassandra-driver)
Building wheels for collected packages: cassandra-driver
Running setup.py bdist_wheel for cassandra-driver ...
^Z
[1]+ 已忢 pip install cassandra-driver
weikairen2@weikairen2-virtual-machine:~$ ls
cassandra jdk å
Œ
±ç å¾ç é³ä¹
cassandra-driver-3.7.0 pycharm æ¨¡æ¿ ææ¡£ æ¡é¢
examples.desktop PycharmProjects è§é¢ ä¸è½½
weikairen2@weikairen2-virtual-machine:~$ cd cassandra-driver-3.7.0
weikairen2@weikairen2-virtual-machine:~/cassandra-driver-3.7.0$ ls
cassandra ez_setup.py MANIFEST.in README.rst setup.py
cassandra_driver.egg-info LICENSE PKG-INFO setup.cfg
weikairen2@weikairen2-virtual-machine:~/cassandra-driver-3.7.0$ python setup.py install
^Z
[2]+ 已忢 python setup.py install
weikairen2@weikairen2-virtual-machine:~/cassandra-driver-3.7.0$ python setup.py build</code></pre>
</div>
</div>
</p>
<p>as you can see,there is no response
and I have to stop it by ctrl+z</p>
<p>I also tried manul install
no response again</p>
<p>So where is the error? How can I fix it?</p>
| 0 | 2016-10-16T16:00:28Z | 40,072,524 | <p>I figure out</p>
<p>"sudo pip install cassandra-driver"</p>
<p>it takes a little long time
I was just too impatient </p>
| 0 | 2016-10-16T16:23:02Z | [
"python",
"database",
"cassandra"
] |
Appending to a list from a for loop (to read a text file) | 40,072,316 | <p>How do I append to an undetermined list from a for loop?
The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems! </p>
<p>Each line in the text file looks like the following:
2014-06-13,42.7,-73.8,27</p>
<p>program so far:</p>
<pre><code>f = open('Lightning.txt')
lightning =list()
for templine in f:
if not templine.startswith('2014'): continue
templine = templine.rstrip('-')
line = templine.split()
print line[2]
</code></pre>
<p>Thank you community,</p>
| 0 | 2016-10-16T16:03:02Z | 40,072,518 | <p>Do this: <code>for templine in f.read():</code>
You forgot the read() methid</p>
| -1 | 2016-10-16T16:22:25Z | [
"python",
"string",
"list",
"append",
"slice"
] |
Appending to a list from a for loop (to read a text file) | 40,072,316 | <p>How do I append to an undetermined list from a for loop?
The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems! </p>
<p>Each line in the text file looks like the following:
2014-06-13,42.7,-73.8,27</p>
<p>program so far:</p>
<pre><code>f = open('Lightning.txt')
lightning =list()
for templine in f:
if not templine.startswith('2014'): continue
templine = templine.rstrip('-')
line = templine.split()
print line[2]
</code></pre>
<p>Thank you community,</p>
| 0 | 2016-10-16T16:03:02Z | 40,072,665 | <p>Try something like that if you want to get list of formated strings.</p>
<pre><code>f = open('Lightning.txt')
lightning =list()
for templine in f:
if not templine.startswith('2014'): continue
# We are splitting the line by ',' to get [2014-06-13, 42.7,-73.8, 27]
templine = templine.split(',')
# After splitting is done, we know that at the 1st place is the date,
# and at the last one is the number of video recordings.
#Here we asign the first item to "data" and the last one to "num_of_strikes"
date, num_of_strikes = templine[0], templine[-1]
# After that is done, we create the output string with placeholders
# {data} and {num} waiting for data to be passed
output = '{date} : {num} lightning strikes were recorded.'
# Here we are appending the formated string, passing our data to placeholders
# And yes, they work like a dictionary, so u can write (key = value)
lightning.append(output.format(date= date, num= num_of_strikes))
</code></pre>
| 0 | 2016-10-16T16:36:09Z | [
"python",
"string",
"list",
"append",
"slice"
] |
Appending to a list from a for loop (to read a text file) | 40,072,316 | <p>How do I append to an undetermined list from a for loop?
The purpose is to first slice each line by '-'. Then I would like to append these slices to an array without a determined size. I have the following code, and am loosing hair because of how simple this seems! </p>
<p>Each line in the text file looks like the following:
2014-06-13,42.7,-73.8,27</p>
<p>program so far:</p>
<pre><code>f = open('Lightning.txt')
lightning =list()
for templine in f:
if not templine.startswith('2014'): continue
templine = templine.rstrip('-')
line = templine.split()
print line[2]
</code></pre>
<p>Thank you community,</p>
| 0 | 2016-10-16T16:03:02Z | 40,073,657 | <p>This is an ideal job for the <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow">csv</a> lib:</p>
<pre><code>import csv
with open('Lightning.txt') as f:
data = []
# unpack the elements from each line/row
for dte, _, _, i in csv.reader(f):
# if the date starts with 2014, add the date string and the last element i
if dte.startswith('2014'):
data.append((dte, i))
</code></pre>
<p>Which can all be done using a list comp:</p>
<pre><code>import csv
with open('Lightning.txt') as f:
data = [(dte, i) for dte, _, _, i in csv.reader(f) if dte.startswith('2014')]
</code></pre>
| 0 | 2016-10-16T18:07:51Z | [
"python",
"string",
"list",
"append",
"slice"
] |
Python String Extraction for football results | 40,072,320 | <p>I have the following string:</p>
<pre><code>"W-Leicester-3-0-H|W-Hull-2-0-A|L-Arsenal-0-3-A|L-Liverpool-1-2-H|D-Swansea-2-2-A"
</code></pre>
<p>What I would like to do is manipulate the string above so it returns the results of each game which is the first letter after each "|". In this instance it would be WWLLD.</p>
<p>Many thanks in advance, Alan.</p>
| -2 | 2016-10-16T16:03:14Z | 40,072,348 | <p>Try something like this:</p>
<pre><code> string = "W-Leicester-3-0-H|W-Hull-2-0-A|L-Arsenal-0-3-A|L-Liverpool-1-2-H|D-Swansea-2-2-A"
result = ''.join([s[0] for s in string.replace('||', '|').split('|')])
</code></pre>
| 1 | 2016-10-16T16:05:28Z | [
"python",
"string"
] |
Converting Complex-Valued Angles from Radians to Degrees in Python? | 40,072,329 | <p>After using cmath to compute the asin of 1.47, which returns a complex angle measured in radians;</p>
<blockquote>
<p>cmath.asin(1.47)</p>
<p>(1.5707963267948966+0.9350931316301407j)</p>
</blockquote>
<p>Is there a way in which can I convert this value to degrees? math.degrees does not work since it cannot compute with complex values.</p>
<p>Thanks!</p>
| 0 | 2016-10-16T16:03:55Z | 40,072,830 | <p>Degrees make little sense in complex numbers. But if you must use them, just use the same math formula as for real numbers:</p>
<pre><code>cmath.asin(1.47) * 180 / math.pi
</code></pre>
<p>You get the result</p>
<pre><code>(90+53.576889894078214j)
</code></pre>
<p>Note the 90 degrees in the real part.</p>
<p>The usefulness of this depends on the context. For example, when taking a complex logarithm, only the imaginary part of the result is an angle and thus can be expressed in degrees. The real part is the logarithm of the modulus of the parameter and has nothing to do with an angle. In that case, use the above conversion only on the imaginary part. In your arcsine example, usually only the real part is considered an angle, which is why you got the simple <code>90</code> for the real part but a mess for the imaginary part.</p>
<p>Let us know just what you are doing with this and we can help you determine the best way to use degrees.</p>
| 1 | 2016-10-16T16:50:37Z | [
"python",
"python-2.7"
] |
Converting Complex-Valued Angles from Radians to Degrees in Python? | 40,072,329 | <p>After using cmath to compute the asin of 1.47, which returns a complex angle measured in radians;</p>
<blockquote>
<p>cmath.asin(1.47)</p>
<p>(1.5707963267948966+0.9350931316301407j)</p>
</blockquote>
<p>Is there a way in which can I convert this value to degrees? math.degrees does not work since it cannot compute with complex values.</p>
<p>Thanks!</p>
| 0 | 2016-10-16T16:03:55Z | 40,073,176 | <p>To use math.degrees(), you need to get the real part of the complex number first.</p>
<pre><code>import cmath
import math
rad = cmath.asin( 1.47 )
math.degrees( rad.real )
</code></pre>
| 0 | 2016-10-16T17:23:36Z | [
"python",
"python-2.7"
] |
Python: pexpect does not execute `backtick` command | 40,072,385 | <p>I'm trying to run this command:</p>
<pre><code>foo=`ls /`
</code></pre>
<p>Works perfectly on bash but not if I execute it via pexpect:</p>
<pre><code>p = pexpect.spawn("foo=`ls /`").interact()
// Gives error command was not found or not executable: foo=`ls
</code></pre>
<p>What is the cause and how do I fix it? I've even tried escaping the ` but it seems its not working.</p>
| -1 | 2016-10-16T16:08:33Z | 40,072,663 | <p>The command you are trying to execute requires <code>bash</code>. <code>pexpect</code> does not pass your command through <code>bash</code>, instead invoking your executable directly as if it were the shell.</p>
<p>From <a href="http://pexpect.sourceforge.net/pexpect.html#spawn" rel="nofollow">the docs</a>:</p>
<blockquote>
<p>Remember that Pexpect does NOT interpret shell meta characters such as
redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
If you want to run a command and pipe it through another command then
you must also start a shell. For example:</p>
</blockquote>
<pre><code>child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
child.expect(pexpect.EOF)
</code></pre>
<p>Although the documentation doesn't mention them, this would certainly also apply to backticks. So write your code to invoke <code>bash</code> explicitly:</p>
<pre><code>p = pexpect.spawn('/bin/bash -c "foo=`ls /`"').interact()
</code></pre>
| 1 | 2016-10-16T16:36:00Z | [
"python",
"bash",
"pexpect"
] |
Interpolate without having negative values in python | 40,072,420 | <p>I've been trying to create a smooth line from these values but I can't have negative values in my result. So far all the methods I tried do give negative values. Would love some help.</p>
<pre><code>import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
y = np.asarray([0,5,80,10,1,10,40,30,80,5,0])
x = np.arange(len(y))
plt.plot(x, y, 'r', ms=5)
spl = UnivariateSpline(x, y)
xs = np.linspace(0,len(y)-1, 1000)
spl.set_smoothing_factor(2)
plt.plot(xs, spl(xs), 'g', lw=3)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/RY5hW.png" rel="nofollow"><img src="https://i.stack.imgur.com/RY5hW.png" alt="enter image description here"></a></p>
| 2 | 2016-10-16T16:13:38Z | 40,072,832 | <p>This does it, albeit in some sections better than others.</p>
<pre><code>import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
y = np.asarray([0,5,80,10,1,10,40,30,80,5,0])
x = np.arange(len(y))
plt.plot(x, y, 'r', ms=5)
spl = UnivariateSpline(x, y)
xs = np.linspace(0,len(y)-1, 1000)
spl.set_smoothing_factor(2)
#new code
ny = spl(xs).clip(0,max(spl(x)))
spl2 = UnivariateSpline(xs, ny)
plt.plot(xs, spl(xs) , 'g', lw=2,label="original")
plt.plot(xs, spl2(xs), 'b', lw=2,label="stack mod")
plt.legend()
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/OO5JD.png" rel="nofollow"><img src="https://i.stack.imgur.com/OO5JD.png" alt="enter image description here"></a></p>
| 2 | 2016-10-16T16:50:43Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"interpolation"
] |
Interpolate without having negative values in python | 40,072,420 | <p>I've been trying to create a smooth line from these values but I can't have negative values in my result. So far all the methods I tried do give negative values. Would love some help.</p>
<pre><code>import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
y = np.asarray([0,5,80,10,1,10,40,30,80,5,0])
x = np.arange(len(y))
plt.plot(x, y, 'r', ms=5)
spl = UnivariateSpline(x, y)
xs = np.linspace(0,len(y)-1, 1000)
spl.set_smoothing_factor(2)
plt.plot(xs, spl(xs), 'g', lw=3)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/RY5hW.png" rel="nofollow"><img src="https://i.stack.imgur.com/RY5hW.png" alt="enter image description here"></a></p>
| 2 | 2016-10-16T16:13:38Z | 40,074,468 | <p>Spline fitting is known to overshoot. You seem to be looking for one of the so-called <em>monotonic</em> interpolators. For instance,</p>
<pre><code>In [10]: from scipy.interpolate import pchip
In [11]: pch = pchip(x, y)
</code></pre>
<p>produces</p>
<pre><code>In [12]: xx = np.linspace(x[0], x[-1], 101)
In [13]: plt.plot(x, y, 'ro', label='points')
Out[13]: [<matplotlib.lines.Line2D at 0x7fce0a7fe390>]
In [14]: plt.plot(xx, pch(xx), 'g-', label='pchip')
Out[14]: [<matplotlib.lines.Line2D at 0x7fce0a834b10>]
</code></pre>
<p><a href="https://i.stack.imgur.com/xuYMR.png"><img src="https://i.stack.imgur.com/xuYMR.png" alt="enter image description here"></a></p>
| 5 | 2016-10-16T19:24:25Z | [
"python",
"numpy",
"matplotlib",
"scipy",
"interpolation"
] |
How to remove elements from list when each character is identical (Python)? | 40,072,449 | <pre><code>sample = ['AAAA','ABCB','CCCC','DDEF']
</code></pre>
<p>I need to eliminate all elements where every character is identical to itself in the element eg. AAAAA,CCCCC</p>
<pre><code>output = ['ABCB','DDEF']
sample1 =[]
for i in sample:
for j in i:
if j == j+1: #This needs to be corrected to if all elements in i identical to each other i.e. if all "j's" are the same
sample1.pop(i)
</code></pre>
<p>print sample</p>
| 0 | 2016-10-16T16:16:01Z | 40,072,461 | <pre><code> sample = ['AAAA','ABCB','CCCC','DDEF']
output = [sublist for sublist in sample if len(set(sublist)) > 1]
</code></pre>
<h1>EDIT to answer comment.</h1>
<pre><code>sample = [['CGG', 'ATT'], ['ATT', 'CCC']]
output = []
for sublist in sample:
if all([len(set(each)) > 1 for each in sublist]):
output.append(sublist)
# List comprehension (doing the same job as the code above)
output2 = [sublist for sublist in sample if
all((len(set(each)) > 1 for each in sublist))]
</code></pre>
| 6 | 2016-10-16T16:16:59Z | [
"python",
"for-loop"
] |
How to remove elements from list when each character is identical (Python)? | 40,072,449 | <pre><code>sample = ['AAAA','ABCB','CCCC','DDEF']
</code></pre>
<p>I need to eliminate all elements where every character is identical to itself in the element eg. AAAAA,CCCCC</p>
<pre><code>output = ['ABCB','DDEF']
sample1 =[]
for i in sample:
for j in i:
if j == j+1: #This needs to be corrected to if all elements in i identical to each other i.e. if all "j's" are the same
sample1.pop(i)
</code></pre>
<p>print sample</p>
| 0 | 2016-10-16T16:16:01Z | 40,072,474 | <pre><code>sample = ['AAAA','ABCB','CCCC','DDEF']
sample1 = []
for i in sample:
if len(set(i)) > 1:
sample1.append(i)
</code></pre>
| 2 | 2016-10-16T16:17:51Z | [
"python",
"for-loop"
] |
Class vectors - multiplication of two vectors of non-specific dimension | 40,072,501 | <pre><code>class MyVector:
def __init__(self, vector): # classic init
self.vector = vector
def get_vector(self):
return self.vector
def __mul__(self, other):
for i in range(0, len(self.vector)): #cycle
# if I did scalar_product += (self.vector[i] * other.vector[i]) here,
# it didn't work
scalar_product = (self.vector[i] * other.vector[i])
return (scalar_product)
if __name__ == "__main__": #just testing program
vec1 = MyVector([1, 2, 3, 4])
vec2 = MyVector([4, 5, 6, 7])
print(vec1.get_vector())
print(vec2.get_vector())
scalar_product = vec1*vec2
print(scalar_product) # shows only 4*7 but not others
</code></pre>
<p>What do I have to do to make this program work? Now it just multiplies the last digits, for example 4 * 7, but not the other ones.</p>
| 1 | 2016-10-16T16:20:19Z | 40,072,517 | <p>You need to define your scalar product first:</p>
<pre><code> def __mul__(self, other):
scalar_product = 0 # or 0.0
for i in range(0, len(self.vector)):
scalar_product += self.vector[i] * other.vector[i]
return scalar_product
</code></pre>
<p>You should also return an object of type <code>MyVector</code></p>
| 1 | 2016-10-16T16:22:23Z | [
"python",
"class",
"vector"
] |
Print part of String with matching Index | 40,072,528 | <p>I'm trying to make a Program that takes a given text, checks to see at which indexes (") is located throughout the text and prints anything in-between the quotation marks (") i.e. "xyz" blablabla "abc". In this case, xyz between 0 and 4 and abc between 16 and 20 would be printed. I've got the indexes part to work but can't seem to find a way to print whatever's within the range of these indexes. Here's my code:</p>
<pre><code>text = '"bleed" seed "deed"'
index = 0
a = 0
find = int(input("Would you like to find all the links in the file?\n If yes, enter 1: "))
def Link_Finder(a):
index = 0
if find == 1:
while index < len(text):
index = text.find('"', index)
if index == -1:
break
print('" found at', index)
index = index + 2
return index
Link_Finder(a)
print(text[index:])
</code></pre>
<p>I'm only printing the Indexes for my own reference. I'm quite new to Python so I'm not really familiar with complex stuff yet.</p>
<p>One way to do this in my opinion would be to return the Index values and then use the returned values to print the required text.</p>
<p>Thanks.</p>
| 0 | 2016-10-16T16:23:17Z | 40,072,637 | <p>If you don't mind using regular expressions, I think this is an easier solution:</p>
<pre><code>import re
print(re.findall(r'"([^"]*)"', text))
</code></pre>
<p>If not, you can use your <code>link_finder</code> function:</p>
<pre><code>def link_finder(s):
index = 0
while index < len(s):
index = s.find('"', index)
if index == -1:
break
yield index
index = index + 2
</code></pre>
<p>And then iterate through the results in pairs</p>
<pre><code>results = list(link_finder(text))
for start, end in zip(results[::2], results[1::2]):
print text[start+1:end]
</code></pre>
| 1 | 2016-10-16T16:33:41Z | [
"python",
"python-3.x"
] |
REALLY simple functions with tuples (python) | 40,072,541 | <p>I know this is really easy but I can't understand how to code at all. So I need to create two functions (if you can only help me with one that's fine):</p>
<p>Function a which receives a positive integer and transforms it into a tuple, like this:</p>
<pre><code>>>>a(34500)
(3, 4, 5, 0, 0)
>>>a(3.5)
ValueError: a: error
</code></pre>
<p>And function b which receives a tuple and transforms it into an integer, like this:</p>
<pre><code>>>>b((3, 4, 0, 0, 4))
34004
>>>b((2, âaâ, 5))
ValueError: b: error
</code></pre>
<p>I haven't learned much yet, only functions, while and for cycles, tuples, raise and isinstance(for the error message?), and probably some other things. I've tried looking for answers but they all used things I haven't learned.</p>
| -4 | 2016-10-16T16:24:44Z | 40,072,742 | <p>The comments already state what you can do:
Convert the int to str by doing (I know this does not work for floats, here you can show some further effort:)) </p>
<pre><code>for c in str(integerVariable):
print c
</code></pre>
<p>The other way around is even more simple.</p>
<pre><code>''.join(tupleVariable)
</code></pre>
| 0 | 2016-10-16T16:43:31Z | [
"python",
"function",
"tuples"
] |
REALLY simple functions with tuples (python) | 40,072,541 | <p>I know this is really easy but I can't understand how to code at all. So I need to create two functions (if you can only help me with one that's fine):</p>
<p>Function a which receives a positive integer and transforms it into a tuple, like this:</p>
<pre><code>>>>a(34500)
(3, 4, 5, 0, 0)
>>>a(3.5)
ValueError: a: error
</code></pre>
<p>And function b which receives a tuple and transforms it into an integer, like this:</p>
<pre><code>>>>b((3, 4, 0, 0, 4))
34004
>>>b((2, âaâ, 5))
ValueError: b: error
</code></pre>
<p>I haven't learned much yet, only functions, while and for cycles, tuples, raise and isinstance(for the error message?), and probably some other things. I've tried looking for answers but they all used things I haven't learned.</p>
| -4 | 2016-10-16T16:24:44Z | 40,072,770 | <p>Try this</p>
<pre><code>def a(n):
result = []
while n > 0:
result.append(n%10)
n=n//10
return tuple(reversed(result))
</code></pre>
<p>for question 2, try doing the same thing in reverse i.e. multiplying each number by 1, 10, 100 and adding them up.</p>
<p>also don't forget error checking code.</p>
| 0 | 2016-10-16T16:46:20Z | [
"python",
"function",
"tuples"
] |
REALLY simple functions with tuples (python) | 40,072,541 | <p>I know this is really easy but I can't understand how to code at all. So I need to create two functions (if you can only help me with one that's fine):</p>
<p>Function a which receives a positive integer and transforms it into a tuple, like this:</p>
<pre><code>>>>a(34500)
(3, 4, 5, 0, 0)
>>>a(3.5)
ValueError: a: error
</code></pre>
<p>And function b which receives a tuple and transforms it into an integer, like this:</p>
<pre><code>>>>b((3, 4, 0, 0, 4))
34004
>>>b((2, âaâ, 5))
ValueError: b: error
</code></pre>
<p>I haven't learned much yet, only functions, while and for cycles, tuples, raise and isinstance(for the error message?), and probably some other things. I've tried looking for answers but they all used things I haven't learned.</p>
| -4 | 2016-10-16T16:24:44Z | 40,072,842 | <pre><code>def to_tuple(input_number):
# check if input number is int or not
if isinstance(input_number,(int)):
# convert number to string
to_string = str(input_number)
# finally convert string to
# list of numbers followed by converting the list to tuple
tuple_output = tuple(map(int,to_string))
return tuple_output
# if not int return empty tuple
# well coz nobody likes useful but ugly python tracebacks
else:
return ()
# lets see example
number = 3450
print to_tuple(number)
(3, 4, 5, 0)
number = 353984
print to_tuple(number)
(3, 5, 3, 9, 8, 4)
number = 2.6
print to_tuple(number)
()
</code></pre>
<p>If you like this example I'd post answer for the second part</p>
| 0 | 2016-10-16T16:51:34Z | [
"python",
"function",
"tuples"
] |
How to iterate through instances in a tree? | 40,072,568 | <p>I have a problem with a self-written tree class in python:</p>
<pre><code>class Tree:
def __init__(self, parent=0, value=0):
self.value = value
self.parent = parent
def __iter__(self): return self
def next(self):
tmp = self.value
try:
self.parent = self.parent.parent
self.value = self.parent.value
except AttributeError:
raise StopIteration
return tmp
def sum(self):
list_ = [item for item in self]
print list_
return sum(list_)
</code></pre>
<p>Actually, the "tree" is not fully written, but the current problem blocks further progress.
The structure has only two instance variables (<code>value</code>, <code>parent</code>).
I would like to sum values from the current instance to the first parent with iterators (if it is all together possible). The <code>sum</code> method is used for that (additional <code>list_</code> variable is unnecessary, but helps further to explain the problem). </p>
<p>When running a test case</p>
<pre><code>parent = Tree()
child = Tree(parent=parent, value=8)
child2 = Tree(parent=child,value=10)
print child2.sum()
</code></pre>
<p>I obtain the following:</p>
<pre><code>[10]
10
</code></pre>
<p>Please, could anybody explain why the list of values contains only one number though it should look like <code>[10,8]</code>? Seems the problem is in the implementation of <code><strong>iter</strong></code> and <code>next</code>, but I can't understand how to repair the solution.</p>
<p>Thank you in advance.</p>
| 1 | 2016-10-16T16:27:08Z | 40,072,941 | <p>Here you go:</p>
<pre><code>class Tree:
def __init__(self, parent=None, value=0):
self.value = value
self.parent = parent
def __iter__(self):
yield self.value
root = self
while root.parent is not None:
yield root.parent.value
root = root.parent
raise StopIteration
def tree_sum(self):
return sum(list(self))
parent = Tree()
child = Tree(parent=parent, value=8)
child2 = Tree(parent=child,value=10)
</code></pre>
<p>I've changed the default <code>parent</code> value to None.</p>
<pre><code>for i in child2:
print(i)
10
8
0 # 0 is here because the parent value is 0 by default.
</code></pre>
| 0 | 2016-10-16T17:02:39Z | [
"python",
"python-2.7"
] |
How to iterate through instances in a tree? | 40,072,568 | <p>I have a problem with a self-written tree class in python:</p>
<pre><code>class Tree:
def __init__(self, parent=0, value=0):
self.value = value
self.parent = parent
def __iter__(self): return self
def next(self):
tmp = self.value
try:
self.parent = self.parent.parent
self.value = self.parent.value
except AttributeError:
raise StopIteration
return tmp
def sum(self):
list_ = [item for item in self]
print list_
return sum(list_)
</code></pre>
<p>Actually, the "tree" is not fully written, but the current problem blocks further progress.
The structure has only two instance variables (<code>value</code>, <code>parent</code>).
I would like to sum values from the current instance to the first parent with iterators (if it is all together possible). The <code>sum</code> method is used for that (additional <code>list_</code> variable is unnecessary, but helps further to explain the problem). </p>
<p>When running a test case</p>
<pre><code>parent = Tree()
child = Tree(parent=parent, value=8)
child2 = Tree(parent=child,value=10)
print child2.sum()
</code></pre>
<p>I obtain the following:</p>
<pre><code>[10]
10
</code></pre>
<p>Please, could anybody explain why the list of values contains only one number though it should look like <code>[10,8]</code>? Seems the problem is in the implementation of <code><strong>iter</strong></code> and <code>next</code>, but I can't understand how to repair the solution.</p>
<p>Thank you in advance.</p>
| 1 | 2016-10-16T16:27:08Z | 40,073,031 | <p>I'm not sure you can call this a <code>Tree</code>. One would expect parent node(s) and multiple leaf nodes, and not just a linear connection of objects.</p>
<p>See: <a href="http://stackoverflow.com/questions/2482602/a-general-tree-implementation-in-python">a general tree implementation in python</a></p>
<p>On another note, if you want to implement a linkedlist, suggestions made in the comment to your question by Barny should be considered and as well, you can give an eye to: <a href="http://stackoverflow.com/questions/280243/python-linked-list">Python Linked List</a></p>
<p>Coming to your current implementation, you'll need some sort of loop, to walk from the current child node up until the head parent node. And when the next parent attribute is not found, stop the iteration. The following puts the logic in the <code>__iter__</code> method of the class, which is now a generator function:</p>
<pre><code>class Tree:
def __init__(self, parent=None, value=0):
self.value = value
self.parent = parent
def __iter__(self):
_parent = self.parent
yield self.value
while True:
try:
yield _parent.value
_parent = _parent.parent
except AttributeError:
break
def sum_from_node(self):
list_ = [item for item in self]
print list_
return sum(list_)
</code></pre>
<p><em>Demo:</em></p>
<pre><code>parent = Tree()
child = Tree(parent=parent, value=8)
child2 = Tree(parent=child,value=10)
child3 = Tree(parent=child2,value=4)
print child3.sum_from_node()
# [4, 10, 8, 0]
# 22
</code></pre>
| 0 | 2016-10-16T17:11:10Z | [
"python",
"python-2.7"
] |
Cython numpy array indexer speed improvement | 40,072,572 | <p>I wrote the following code in pure python, the description of what it does is in the docstrings:</p>
<pre><code>import numpy as np
from scipy.ndimage.measurements import find_objects
import itertools
def alt_indexer(arr):
"""
Returns a dictionary with the elements of arr as key
and the corresponding slice as value.
Note:
This function assumes arr is sorted.
Example:
>>> arr = [0,0,3,2,1,2,3]
>>> loc = _indexer(arr)
>>> loc
{0: (slice(0L, 2L, None),),
1: (slice(2L, 3L, None),),
2: (slice(3L, 5L, None),),
3: (slice(5L, 7L, None),)}
>>> arr = sorted(arr)
>>> arr[loc[3][0]]
[3, 3]
>>> arr[loc[2][0]]
[2, 2]
"""
unique, counts = np.unique(arr, return_counts=True)
labels = np.arange(1,len(unique)+1)
labels = np.repeat(labels,counts)
slicearr = find_objects(labels)
index_dict = dict(itertools.izip(unique,slicearr))
return index_dict
</code></pre>
<p>Since i will be indexing very large arrays, i wanted to speed up the operations by using cython, here is the equivalent implementation:</p>
<pre><code>import numpy as np
cimport numpy as np
def _indexer(arr):
cdef tuple unique_counts = np.unique(arr, return_counts=True)
cdef np.ndarray[np.int32_t,ndim=1] unique = unique_counts[0]
cdef np.ndarray[np.int32_t,ndim=1] counts = unique_counts[1].astype(int)
cdef int start=0
cdef int end
cdef int i
cdef dict d ={}
for i in xrange(len(counts)):
if i>0:
start = counts[i-1]+start
end=counts[i]+start
d[unique[i]]=slice(start,end)
return d
</code></pre>
<h1>Benchmarks</h1>
<p>I compared the time it took to complete both operations:</p>
<pre><code>In [26]: import numpy as np
In [27]: rr=np.random.randint(0,1000,1000000)
In [28]: %timeit _indexer(rr)
10 loops, best of 3: 40.5 ms per loop
In [29]: %timeit alt_indexer(rr) #pure python
10 loops, best of 3: 51.4 ms per loop
</code></pre>
<p>As you can see the speed improvements are minimal. I do realize that my code was already partly optimized since i used numpy.</p>
<p>Is there a bottleneck that i am not aware of?
Should i not use <code>np.unique</code> and write my own implementation instead?</p>
<p>Thanks.</p>
| 1 | 2016-10-16T16:27:38Z | 40,072,854 | <p>With <code>arr</code> having non-negative, not very large and many repeated <code>int</code> numbers, here's an alternative approach using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> to simulate the same behavior as <code>np.unique(arr, return_counts=True)</code> -</p>
<pre><code>def unique_counts(arr):
counts = np.bincount(arr)
mask = counts!=0
unique = np.nonzero(mask)[0]
return unique, counts[mask]
</code></pre>
<p><strong>Runtime test</strong></p>
<p>Case #1 :</p>
<pre><code>In [83]: arr = np.random.randint(0,100,(1000)) # Input array
In [84]: unique, counts = np.unique(arr, return_counts=True)
...: unique1, counts1 = unique_counts(arr)
...:
In [85]: np.allclose(unique,unique1)
Out[85]: True
In [86]: np.allclose(counts,counts1)
Out[86]: True
In [87]: %timeit np.unique(arr, return_counts=True)
10000 loops, best of 3: 53.2 µs per loop
In [88]: %timeit unique_counts(arr)
100000 loops, best of 3: 10.2 µs per loop
</code></pre>
<p>Case #2:</p>
<pre><code>In [89]: arr = np.random.randint(0,1000,(10000)) # Input array
In [90]: %timeit np.unique(arr, return_counts=True)
1000 loops, best of 3: 713 µs per loop
In [91]: %timeit unique_counts(arr)
10000 loops, best of 3: 39.1 µs per loop
</code></pre>
<p>Case #3: Let's run a case with <code>unique</code> having some missing numbers in the min to max range and verify the results against <code>np.unique</code> version as a sanity check. We won't have a lot of repeated numbers in this case and as such isn't expected to be better on performance.</p>
<pre><code>In [98]: arr = np.random.randint(0,10000,(1000)) # Input array
In [99]: unique, counts = np.unique(arr, return_counts=True)
...: unique1, counts1 = unique_counts(arr)
...:
In [100]: np.allclose(unique,unique1)
Out[100]: True
In [101]: np.allclose(counts,counts1)
Out[101]: True
In [102]: %timeit np.unique(arr, return_counts=True)
10000 loops, best of 3: 61.9 µs per loop
In [103]: %timeit unique_counts(arr)
10000 loops, best of 3: 71.8 µs per loop
</code></pre>
| 1 | 2016-10-16T16:52:27Z | [
"python",
"performance",
"numpy",
"cython"
] |
Issues deploying Django project | 40,072,623 | <p>Okay I am new to the Django framework but I have a basic site that I want live. I have a droplet up on Digital Ocean and my files have been moved over to there.</p>
<p>I get this error:</p>
<pre><code>ImportError at /
cannot import name patterns
Request Method: GET
Request URL: http://188.166.147.202/
Django Version: 1.10.2
Exception Type: ImportError
Exception Value:
cannot import name patterns
Exception Location: /home/django/django_project/django_project/urls.py in <module>, line 1
Python Executable: /usr/bin/python
Python Version: 2.7.6
Python Path:
['/home/django/django_project',
'/home/django',
'/usr/bin',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/gtk-2.0']
Server time: Sun, 16 Oct 2016 16:26:46 +0000
</code></pre>
<p>urls.py looks like:</p>
<pre><code>from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include('personal.urls')),
url(r'^blog/', include('blog.urls')),
]
</code></pre>
<p>The doplet is currently using python 2.7 but I used python3 while developing so how can I upgrade the version of python on my droplet?</p>
| 0 | 2016-10-16T16:32:39Z | 40,072,684 | <p><code>patterns</code> was deprecated in Django 1.8 and removed in Django 1.10. </p>
<p>Your <code>urlpatterns</code> is already as it should be, a list of <code>url()</code> instances. Simply change your import to:</p>
<pre><code>from django.conf.urls import include, url
</code></pre>
| 2 | 2016-10-16T16:38:12Z | [
"python",
"django",
"digital-ocean"
] |
Displaying nodes sorted by distance to a given node in Python | 40,072,645 | <p>I have a number of nodes, each has an x-axis and y-axis values which indicate a distance from each other. For example, </p>
<pre><code>nodes = [
{'name': 'node1', 'x': 2, 'y': 4, 'friend': True},
{'name': 'node2', 'x': -3, 'y': 2, 'friend': True},
{'name': 'node3', 'x': 5, 'y': 0, 'friend': False},
{'name': 'node4', 'x': -6, 'y': 1, 'friend': False},
{'name': 'node5', 'x': 0, 'y': 3, 'friend': True}
]
</code></pre>
<p>I need to create a function that returns only nodes who are friends sorted by a distance to a given node (say <code>main_node = nodes[0]</code>) based on the X and Y values.</p>
<p>I would appreciate your help.</p>
| 0 | 2016-10-16T16:34:34Z | 40,072,708 | <p>The sort function takes a key parameter:</p>
<pre><code>main_node = nodes[0]
nodes.sort(key=lambda node: math.hypot(node["x"] - main_node["x"], node["y"] - main_node["y"]))
</code></pre>
| 0 | 2016-10-16T16:40:48Z | [
"python",
"function",
"sorting",
"nodes"
] |
IndexError in function | 40,072,775 | <pre><code>def AddVct(Vct1,Vct2,VctLen):
Vct3 = []
n=1
while n < VctLen:
Vct3[n] = Vct1[n] + Vct2[n]
n += 1
print(Vct[n])
return Vct3
</code></pre>
<p>The program outputs:</p>
<p><code>IndexError: list assignment index out of range.</code></p>
<p>Could anyone tell me how to avoid this? Thanks in advance</p>
| 1 | 2016-10-16T16:46:35Z | 40,072,818 | <p>You can't assign to a list element that doesn't exist. And since you start with an empty list, no elements exist in it. Generally, you would <code>append()</code> instead.</p>
<pre><code>Vct3.append(Vct1[n] + Vct2[n])
</code></pre>
<p>Or, you could initialize <code>Vct3</code> to be the size you want beforehand:</p>
<pre><code>Vct3 = [0] * VctLen + 1
</code></pre>
<p>Then the assignment you already have works fine.</p>
<p>Assuming you start with an empty list and use <code>append()</code>, list indices start at 0, so you should define <code>Vct3</code> as a single-element list so that the indices match between the input and output lists.</p>
<pre><code>Vct3 = [None] # or whatever you want the first value to be
</code></pre>
<p>Or else initialize <code>n</code> to 0 instead of 1 if you want to consider all the elements of the lists.</p>
<p>In that case, however, it would be more Pythonic to use a list comprehension</p>
<pre><code>Vct3 = [a + b for (a, b) in zip(Vct1, Vct2)]
</code></pre>
<p>N. B. It's generally not necessary to pass in the length of a list as its own parameter. You can trivially get it using <code>len()</code>.</p>
| 0 | 2016-10-16T16:49:30Z | [
"python",
"indexing"
] |
Basic threading with one background worker and other thread | 40,072,838 | <p>I'm very much a beginner in both python and programming. Trying to get multithreading work but haven't managed so far. Grateful for any help or tips.</p>
<pre><code>from threading import Thread
import time
import requests
class crawler:
def get_urls(self):
while True:
#r = self.s.get('http:\\someurl')
time.sleep(1)
print 'Thread 1'
def thread_test(self):
while True:
print 'Thread 2'
time.sleep(1)
crawl = crawler()
if __name__ == '__main__':
Thread(target=crawl.get_urls()).start()
Thread(target=crawl.thread_test()).start()
</code></pre>
| 0 | 2016-10-16T16:51:26Z | 40,072,905 | <p>It has been a while since i have done thread programming in python but I remembered that you will have to call <code>.join()</code> on each thread or else the main thread will exit before your spawn thread get a chance to execute.</p>
<pre><code>T1 = Thread(target=crawl.get_urls()).start()
T2 = Thread(target=crawl.thread_test()).start()
T1.join()
T2.join()
</code></pre>
<p>should do the trick</p>
<p><code>edit</code> I just looked into python <code>threading</code> library the issue is that <code>target</code> is expecting a callable object. when you call <code>target=crawl.get_urls()</code> the method was being evaluated rather than passing the method. </p>
<pre><code>from threading import Thread
</code></pre>
<p>import time
import requests</p>
<p>class crawler:</p>
<pre><code>def get_urls(self):
while True:
#r = self.s.get('http:\\someurl')
time.sleep(1)
print 'Thread 1'
def thread_test(self):
while True:
print 'Thread 2'
time.sleep(1)
crawl = crawler()
if __name__ == '__main__':
Thread(target=crawl.get_urls).start()
Thread(target=crawl.thread_test).start()
</code></pre>
<p>ref: <a href="https://docs.python.org/3/library/threading.html#threading.Thread" rel="nofollow">https://docs.python.org/3/library/threading.html#threading.Thread</a></p>
| 0 | 2016-10-16T16:58:54Z | [
"python",
"multithreading"
] |
statistical summary table in sklearn.linear_model.ridge? | 40,072,870 | <p>In OLS form StatsModels, results.summary shows the summary of regression results (such as AIC, BIC, R-squared, ...). </p>
<p>Is there any way to have this summary table in sklearn.linear_model.ridge? </p>
<p>I do appreciate if someone guide me. Thank you.</p>
| 1 | 2016-10-16T16:54:17Z | 40,078,035 | <p>As I know, there is no R(or Statsmodels)-like summary table in sklearn. (Please check <a href="http://stackoverflow.com/a/26326883/3054161">this answer</a>) </p>
<p>Instead, if you need it, there is <a href="http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.fit_regularized.html#statsmodels-regression-linear-model-ols-fit-regularized" rel="nofollow">statsmodels.regression.linear_model.OLS.fit_regularized</a> class. (<code>L1_wt=0</code> for ridge regression.)</p>
<p>For now, it seems that <code>model.fit_regularized(~).summary()</code> returns <code>None</code> despite of docstring below. But the object has <code>params</code>, <code>summary()</code> can be used somehow.</p>
<blockquote>
<p>Returns: A RegressionResults object, of the same type returned by <code>fit</code>.</p>
</blockquote>
<p><strong>Example.</strong></p>
<p>Sample data is not for ridge regression, but I will try anyway.</p>
<p>In.</p>
<pre><code>import numpy as np
import pandas as pd
import statsmodels
import statsmodels.api as sm
import matplotlib.pyplot as plt
statsmodels.__version__
</code></pre>
<p>Out.</p>
<pre><code>'0.8.0rc1'
</code></pre>
<p>In.</p>
<pre><code>data = sm.datasets.ccard.load()
print "endog: " + data.endog_name
print "exog: " + ', '.join(data.exog_name)
data.exog[:5, :]
</code></pre>
<p>Out.</p>
<pre><code>endog: AVGEXP
exog: AGE, INCOME, INCOMESQ, OWNRENT
Out[2]:
array([[ 38. , 4.52 , 20.4304, 1. ],
[ 33. , 2.42 , 5.8564, 0. ],
[ 34. , 4.5 , 20.25 , 1. ],
[ 31. , 2.54 , 6.4516, 0. ],
[ 32. , 9.79 , 95.8441, 1. ]])
</code></pre>
<p>In.</p>
<pre><code>y, X = data.endog, data.exog
model = sm.OLS(y, X)
results_fu = model.fit()
print results_fu.summary()
</code></pre>
<p>Out.</p>
<pre><code> OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.543
Model: OLS Adj. R-squared: 0.516
Method: Least Squares F-statistic: 20.22
Date: Wed, 19 Oct 2016 Prob (F-statistic): 5.24e-11
Time: 17:22:48 Log-Likelihood: -507.24
No. Observations: 72 AIC: 1022.
Df Residuals: 68 BIC: 1032.
Df Model: 4
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
x1 -6.8112 4.551 -1.497 0.139 -15.892 2.270
x2 175.8245 63.743 2.758 0.007 48.628 303.021
x3 -9.7235 6.030 -1.613 0.111 -21.756 2.309
x4 54.7496 80.044 0.684 0.496 -104.977 214.476
==============================================================================
Omnibus: 76.325 Durbin-Watson: 1.692
Prob(Omnibus): 0.000 Jarque-Bera (JB): 649.447
Skew: 3.194 Prob(JB): 9.42e-142
Kurtosis: 16.255 Cond. No. 87.5
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
</code></pre>
<p>In.</p>
<pre><code>frames = []
for n in np.arange(0, 0.25, 0.05).tolist():
results_fr = model.fit_regularized(L1_wt=0, alpha=n, start_params=results_fu.params)
results_fr_fit = sm.regression.linear_model.OLSResults(model,
results_fr.params,
model.normalized_cov_params)
frames.append(np.append(results_fr.params, results_fr_fit.ssr))
df = pd.DataFrame(frames, columns=data.exog_name + ['ssr*'])
df.index=np.arange(0, 0.25, 0.05).tolist()
df.index.name = 'alpha*'
df.T
</code></pre>
<p>Out.</p>
<p><a href="https://i.stack.imgur.com/fSR9N.png" rel="nofollow"><img src="https://i.stack.imgur.com/fSR9N.png" alt="enter image description here"></a></p>
<p>In.</p>
<pre><code>%matplotlib inline
fig, ax = plt.subplots(1, 2, figsize=(14, 4))
ax[0] = df.iloc[:, :-1].plot(ax=ax[0])
ax[0].set_title('Coefficient')
ax[1] = df.iloc[:, -1].plot(ax=ax[1])
ax[1].set_title('SSR')
</code></pre>
<p>Out.</p>
<p><a href="https://i.stack.imgur.com/irutn.png" rel="nofollow"><img src="https://i.stack.imgur.com/irutn.png" alt="enter image description here"></a></p>
<p>In.</p>
<pre><code>results_fr = model.fit_regularized(L1_wt=0, alpha=0.04, start_params=results_fu.params)
final = sm.regression.linear_model.OLSResults(model,
results_fr.params,
model.normalized_cov_params)
print final.summary()
</code></pre>
<p>Out.</p>
<pre><code> OLS Regression Results
==============================================================================
Dep. Variable: y R-squared: 0.543
Model: OLS Adj. R-squared: 0.516
Method: Least Squares F-statistic: 20.17
Date: Wed, 19 Oct 2016 Prob (F-statistic): 5.46e-11
Time: 17:22:49 Log-Likelihood: -507.28
No. Observations: 72 AIC: 1023.
Df Residuals: 68 BIC: 1032.
Df Model: 4
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
x1 -5.6375 4.554 -1.238 0.220 -14.724 3.449
x2 159.1412 63.781 2.495 0.015 31.867 286.415
x3 -8.1360 6.034 -1.348 0.182 -20.176 3.904
x4 44.2597 80.093 0.553 0.582 -115.564 204.083
==============================================================================
Omnibus: 76.819 Durbin-Watson: 1.694
Prob(Omnibus): 0.000 Jarque-Bera (JB): 658.948
Skew: 3.220 Prob(JB): 8.15e-144
Kurtosis: 16.348 Cond. No. 87.5
==============================================================================
Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
</code></pre>
| 0 | 2016-10-17T03:21:58Z | [
"python",
"statsmodels",
"sklearn-pandas"
] |
Why do we need locks for threads, if we have GIL? | 40,072,873 | <p>I believe it is a stupid question but I still can't find it. Actually it's better to separate it into two questions:</p>
<p>1) Am I right that we could have a lot of threads but because of GIL in one moment only one thread is executing?</p>
<p>2) If so, why do we still need locks? We use locks to avoid the case when two threads are trying to read/write some shared object, because of GIL twi threads can't be executed in one moment, can they?</p>
| 3 | 2016-10-16T16:54:29Z | 40,072,907 | <p>the GIL prevents simultaneous execution of multiple threads, but not in all situations.</p>
<p>The GIL is temporarily released during I/O operations executed by threads. That means, multiple threads can run at the same time. That's one reason you still need locks.</p>
<p>I don't know where I found this reference.... in a video or something - hard to look it up, but you can investigate further yourself</p>
| 0 | 2016-10-16T16:58:58Z | [
"python",
"multithreading"
] |
Why do we need locks for threads, if we have GIL? | 40,072,873 | <p>I believe it is a stupid question but I still can't find it. Actually it's better to separate it into two questions:</p>
<p>1) Am I right that we could have a lot of threads but because of GIL in one moment only one thread is executing?</p>
<p>2) If so, why do we still need locks? We use locks to avoid the case when two threads are trying to read/write some shared object, because of GIL twi threads can't be executed in one moment, can they?</p>
| 3 | 2016-10-16T16:54:29Z | 40,072,999 | <p>GIL protects the Python interals. That means:</p>
<ol>
<li>you don't have to worry about something in the interpreter going wrong because of multithreading</li>
<li>most things do not really run in parallel, because python code is executed sequentially due to GIL</li>
</ol>
<p>But GIL does not protect your own code. For example, if you have this code:</p>
<pre><code>self.some_number += 1
</code></pre>
<p>That is going to read value of <code>self.some_number</code>, calculate <code>some_number+1</code> and then write it back to <code>self.some_number</code>.</p>
<p>If you do that in two threads, the operations (read, add, write) of one thread and the other may be mixed, so that the result is wrong.</p>
<p>This could be the order of execution:</p>
<ol>
<li>thread1 reads <code>self.some_number</code> (0)</li>
<li>thread2 reads <code>self.some_number</code> (0)</li>
<li>thread1 calculates <code>some_number+1</code> (1)</li>
<li>thread2 calculates <code>some_number+1</code> (1)</li>
<li>thread1 writes 1 to <code>self.some_number</code></li>
<li>thread2 writes 1 to <code>self.some_number</code></li>
</ol>
<p>You use locks to enforce this order of execution:</p>
<ol>
<li>thread1 reads <code>self.some_number</code> (0)</li>
<li>thread1 calculates <code>some_number+1</code> (1)</li>
<li>thread1 writes 1 to <code>self.some_number</code></li>
<li>thread2 reads <code>self.some_number</code> (1)</li>
<li>thread2 calculates <code>some_number+1</code> (2)</li>
<li>thread2 writes 2 to <code>self.some_number</code></li>
</ol>
<h2>EDIT: Let's complete this answer with some code which shows the explained behaviour:</h2>
<pre><code>import threading
import time
total = 0
lock = threading.Lock()
def increment_n_times(n):
global total
for i in range(n):
total += 1
def safe_increment_n_times(n):
global total
for i in range(n):
lock.acquire()
total += 1
lock.release()
def increment_in_x_threads(x, func, n):
threads = [threading.Thread(target=func, args=(n,)) for i in range(x)]
global total
total = 0
begin = time.time()
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print('finished in {}s.\ntotal: {}\nexpected: {}\ndifference: {} ({} %)'
.format(time.time()-begin, total, n*x, n*x-total, 100-total/n/x*100))
</code></pre>
<p>There are two functions which implement increment. One uses locks and the other does not.</p>
<p>Function <code>increment_in_x_threads</code> implements parallel execution of the incrementing function in many threads.</p>
<p>Now running this with a big enough number of threads makes it almost certain that an error will occur:</p>
<pre><code>print('unsafe:')
increment_in_x_threads(70, increment_n_times, 100000)
print('\nwith locks:')
increment_in_x_threads(70, safe_increment_n_times, 100000)
</code></pre>
<p>In my case, it printed:</p>
<pre><code>unsafe:
finished in 0.9840562343597412s.
total: 4654584
expected: 7000000
difference: 2345416 (33.505942857142855 %)
with locks:
finished in 20.564176082611084s.
total: 7000000
expected: 7000000
difference: 0 (0.0 %)
</code></pre>
<p>So without locks, there were many errors (33% of increments failed). On the other hand, with locks it was 20 time slower.</p>
<p>Of course, both numbers are blown up because I used 70 threads, but this shows the general idea.</p>
| 4 | 2016-10-16T17:07:55Z | [
"python",
"multithreading"
] |
Why do we need locks for threads, if we have GIL? | 40,072,873 | <p>I believe it is a stupid question but I still can't find it. Actually it's better to separate it into two questions:</p>
<p>1) Am I right that we could have a lot of threads but because of GIL in one moment only one thread is executing?</p>
<p>2) If so, why do we still need locks? We use locks to avoid the case when two threads are trying to read/write some shared object, because of GIL twi threads can't be executed in one moment, can they?</p>
| 3 | 2016-10-16T16:54:29Z | 40,073,002 | <p>At any moment, yes, only one thread is executing Python code (other threads may be executing some IO, NumPy, whatever). That is mostly true. However, this is trivially true on any single-processor system, and yet people still need locks on single-processor systems.</p>
<p>Take a look at the following code:</p>
<pre><code>queue = []
def do_work():
while queue:
item = queue.pop(0)
process(item)
</code></pre>
<p>With one thread, everything is fine. With two threads, you might get an exception from <code>queue.pop()</code> because the other thread called <code>queue.pop()</code> on the last item first. So you would need to handle that somehow. Using a lock is a simple solution. You can also use a proper concurrent queue (like in the <code>queue</code> module)--but if you look inside the <code>queue</code> module, you'll find that the <code>Queue</code> object has a <code>threading.Lock()</code> inside it. So either way you are using locks.</p>
<p>It is a common newbie mistake to write multithreaded code without the necessary locks. You look at code and think, "this will work just fine" and then find out many hours later that something truly bizarre has happened because threads weren't synchronized properly.</p>
<p>Or in short, there are many places in a multithreaded program where you need to prevent another thread from modifying a structure until you're done applying some changes. This allows you to maintain the invariants on your data, and if you can't maintain invariants, then it's basically impossible to write code that is correct.</p>
<p>Or put in the shortest way possible, "You don't need locks if you don't care if your code is correct."</p>
| 2 | 2016-10-16T17:08:04Z | [
"python",
"multithreading"
] |
AttributeError in a pygame.sprite.Sprite subclass | 40,072,913 | <p>I am currently developing a 2D platformer game with pygame and I have discovered an issue. I usually handled sprite rendering with a single sprite group declared inside of the main function. Now that I need to have some specific sprites over others/under sprites, having a single group won't cut it, and having multiple groups just laying about is a mess. So I decided to add groups into my Entity class:</p>
<pre><code>class Entity(pygame.sprite.Sprite):
entitiesTop = pygame.sprite.Group()
entitiesMid = pygame.sprite.Group()
entitiesBot = pygame.sprite.Group()
entities = [entitiesBot, entitiesMid, entitiesTop]
def __init__(self, force = None):
pygame.sprite.Sprite.__init__(self)
if force is None:
if isinstance(self, Platform):
Entity.entitiesTop.add(self)
elif isinstance(self, (Bullet, Gun)):
Entity.entitiesMid.add(self)
else:
Entity.entitiesBot.add(self)
else:
Entity.entities[force].add(self)
</code></pre>
<p>and I made all the other subclasses of Entity automatically get added to a group using its <code>__init__</code> method. I think it was working fine with the classes, since the error didn't show when I initialized the entities themselves, rather when I tried to run this code</p>
<pre><code> for group in Entity.entities:
</code></pre>
<p>an <code>AttributeError</code> appeared</p>
<pre><code>AttributeError: type object 'Entity' has no attribute 'entities'
</code></pre>
<p>I am relatively new to python OOP, so I don't quite get what I am missing here. Does anyone know the solution to this?</p>
| 1 | 2016-10-16T16:59:48Z | 40,073,133 | <p>furas at the comments has solved the mystery. I just forgot to remove the old definition of the class! Silly me. Its all working fine now. </p>
| 0 | 2016-10-16T17:19:33Z | [
"python",
"class",
"python-3.x",
"oop",
"pygame"
] |
Concatenating pandas DataFrames keeping only rows with matching values in a column? | 40,072,950 | <p>I am trying to "merge-concatenate" two pandas DataFrames. Basically, I want to stack the two DataFrames, but only keep the rows from each DataFrame which matching values in the other DataFrame. So for example:</p>
<pre><code>data1:
+---+------------+-----------+-------+
| | first_name | last_name | class |
+---+------------+-----------+-------+
| 0 | Alex | Anderson | 1 |
| 1 | Amy | Ackerman | 2 |
| 2 | Allen | Ali | 3 |
| 3 | Alice | Aoni | 4 |
| 4 | Andrew | Andrews | 4 |
| 5 | Ayoung | Atiches | 5 |
+---+------------+-----------+-------+
data2:
+---+------------+-----------+-------+
| | first_name | last_name | class |
+---+------------+-----------+-------+
| 0 | Billy | Bonder | 4 |
| 1 | Brian | Black | 5 |
| 2 | Bran | Balwner | 6 |
| 3 | Bryce | Brice | 7 |
| 4 | Betty | Btisan | 8 |
| 5 | Bruce | Bronson | 8 |
+---+------------+-----------+-------+
</code></pre>
<p>Then the resulting data frame after performing this operation on <code>data1</code> and <code>data2</code> should look like:</p>
<pre><code>result:
+---+------------+-----------+-------+
| | first_name | last_name | class |
+---+------------+-----------+-------+
| 3 | Alice | Aoni | 4 |
| 4 | Andrew | Andrews | 4 |
| 5 | Ayoung | Atiches | 5 |
| 0 | Billy | Bonder | 4 |
| 1 | Brian | Black | 5 |
+---+------------+-----------+-------+
</code></pre>
<p>Basically, I'm trying to merge the two data sets, and then stack the columns. I can think of a couple ways to do this, but they're all sort of hack-y. I could merge <code>data1</code> and <code>data2</code> and then stack up the columns, or use a map like:</p>
<pre><code>map1 = data1['subject_id'].map(lambda x: x in list(data2['subject_id']))
map2 = data2['subject_id'].map(lambda x: x in list(data1['subject_id']))
pd.concat([data1[map1], data2[map2]])
</code></pre>
<p>But is there a more elegant solution to this?</p>
| 2 | 2016-10-16T17:03:12Z | 40,073,112 | <p>How about this?</p>
<pre><code>In [335]: cls = np.intersect1d(data1['class'], data2['class'])
In [336]: cls
Out[336]: array([4, 5], dtype=int64)
In [337]: pd.concat([data1.ix[data1['class'].isin(cls)], data2.ix[data2['class'].isin(cls)]])
Out[337]:
first_name last_name class
3 Alice Aoni 4
4 Andrew Andrews 4
5 Ayoung Atiches 5
0 Billy Bonder 4
1 Brian Black 5
</code></pre>
<p>or:</p>
<pre><code>In [338]: data1.ix[data1['class'].isin(cls)].append(data2.ix[data2['class'].isin(cls)])
Out[338]:
first_name last_name class
3 Alice Aoni 4
4 Andrew Andrews 4
5 Ayoung Atiches 5
0 Billy Bonder 4
1 Brian Black 5
</code></pre>
| 1 | 2016-10-16T17:17:48Z | [
"python",
"pandas",
"dataframe"
] |
Trying to split string with regex | 40,072,960 | <p>I'm trying to split a string in Python using a regex pattern but its not working correctly.</p>
<p>Example text:</p>
<p><code>"The quick {brown fox} jumped over the {lazy} dog"</code></p>
<p>Code:</p>
<p><code>"The quick {brown fox} jumped over the {lazy} dog".split(r'({.*?}))</code></p>
<p>I'm using a capture group so that the split delimiters are retained in the array.</p>
<p>Desired result:</p>
<p><code>['The quick', '{brown fox}', 'jumped over the', '{lazy}', 'dog']</code></p>
<p>Actual result:</p>
<p><code>['The quick {brown fox} jumped over the {lazy} dog']</code></p>
<p>As you can see there is clearly not a match as it doesn't split the string. Can anyone let me know where I'm going wrong? Thanks.</p>
| 0 | 2016-10-16T17:04:05Z | 40,072,984 | <p>You're calling the strings' split method, not re's</p>
<pre><code>>>> re.split(r'({.*?})', "The quick {brown fox} jumped over the {lazy} dog")
['The quick ', '{brown fox}', ' jumped over the ', '{lazy}', ' dog']
</code></pre>
| 1 | 2016-10-16T17:06:28Z | [
"python",
"regex"
] |
Patch Extracting In Python | 40,072,988 | <p>I have an image and I would like to extract patches of it and then save each patch as an image in that folder. Here is my first attempt:</p>
<pre><code>from sklearn.feature_extraction import image
from sklearn.feature_extraction.image import extract_patches_2d
import os, sys
from PIL import Image
imgFile = Image.open('D1.gif')
window_shape = (10, 10)
B = extract_patches_2d(imgFile, window_shape)
print imgFile
</code></pre>
<p>But I get the following error:</p>
<p>AttributeError: shape</p>
<p>I have searched through internet and I couldn't find anything. I would be very grateful if anyone can help me on this.</p>
<p>Thanks in advance</p>
| 0 | 2016-10-16T17:06:41Z | 40,073,244 | <p>As per <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.image.extract_patches_2d.html" rel="nofollow">documentation</a> first parameter for extract_patches_2d is an array or a shape. </p>
<p>You should first create an array from your imgFile so you get the pixels, and then pass that array to the function.</p>
<pre><code>import numpy
import PIL
# Convert Image to array
img = PIL.Image.open("foo.jpg").convert("L")
arr = numpy.array(img)
</code></pre>
| 0 | 2016-10-16T17:30:46Z | [
"python",
"image",
"patch"
] |
Create Image Histogram Manually and Efficiently in Python | 40,073,003 | <p>I want to write codes that can show the histogram of an image without using built in Matplotlib hist function.</p>
<p>Here is my codes:</p>
<pre><code>import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
def manHist(img):
row, col = img.shape # img is a grayscale image
y = np.zeros((256), np.uint64)
for i in range(0,row):
for j in range(0,col):
y[img[i,j]] += 1
x = np.arange(0,256)
plt.bar(x,y,color="gray",align="center")
plt.show()
def main():
img = cv.imread("C:/Users/Kadek/Documents/MATLAB/2GS.jpg")
manHist(img)
main()
</code></pre>
<p>My question is, is there a more efficent way to make an array of pixel value frequency without using for loop?</p>
| 1 | 2016-10-16T17:08:09Z | 40,073,188 | <p>A NumPy based vectorized solution would be with <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> -</p>
<pre><code>out = np.bincount(img.ravel(),minlength=256)
</code></pre>
<p>Another vectorized approach based on <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.sum.html" rel="nofollow"><code>.sum()</code></a> -</p>
<pre><code>out = (img.ravel() == np.arange(256)[:,None]).sum(1)
</code></pre>
<p>Sample run to verify results -</p>
<pre><code>In [155]: # Input image (512x512) as array
...: img = np.random.randint(0,255,(512,512))
...:
...: # Original code
...: row, col = img.shape
...: y = np.zeros((256), np.uint64)
...: for i in range(0,row):
...: for j in range(0,col):
...: y[img[i,j]] += 1
...:
In [156]: out1 = np.bincount(img.ravel(),minlength=256)
In [157]: out2 = (img.ravel() == np.arange(256)[:,None]).sum(1)
In [158]: np.allclose(y,out1)
Out[158]: True
In [159]: np.allclose(y,out2)
Out[159]: True
</code></pre>
| 1 | 2016-10-16T17:24:25Z | [
"python",
"opencv",
"numpy",
"image-processing",
"matplotlib"
] |
Cannot webdriver.get(url) an IP address in Selenium 3 | 40,073,124 | <p>So I wrote a python script that uses Selenium 2 to do various things to my modem. This fully works. </p>
<p>I am now busy updating the script to use Selenium 3, but I immediately ran into a problem where I cannot even get to the login page of the modem. The problem seems to be with the <code>get()</code>.</p>
<p>First of all it now crashes when given a fake URL. I then gave it the Google URL and it works perfectly, but now I need to go to the modem's IP. But when I use <code>driver.get(_rout_ip)</code>, where <code>_rout_ip</code> is <strong>10.0.0.2</strong>, it just appends the IP address to the Google URL. Removing the <code>get</code> for the fake URL is not an option since for some reason it is required as it cannot directly go to the modem ip.</p>
<p>The code for getting the webdriver instance is below </p>
<pre><code>def get_driver():
"""
Get an instance of a webdriver that is initialized to the router login page
:return: A webdriver instance
"""
if not os.path.exists(os.getcwd() + '\\' + _driver_name):
print('ERROR: The specified driver does not exist, %s' % (os.getcwd() + '\\' + _driver_name))
exit()
print "Initializing the webdriver"
# Set the path to the driver to be used
os.environ["webdriver.gecko.driver"] = os.getcwd() + '\\' + _driver_name
driver = webdriver.Firefox()
# Go to a fake website. This is needed since it cannot go to the modem directly for some reason
try:
driver.get('http://poop_smells_nice.com')
except Exception:
print('WOOT')
waiter.sleep(_SLEEP_TIME) # Pause a bit to be safe
print "Switching to the router login page"
# Go to the modem ip
driver.get(_rout_ip)
driver.switch_to.default_content()
return driver
</code></pre>
<p>Does anyone have any idea why this is happening?</p>
| 0 | 2016-10-16T17:19:03Z | 40,073,166 | <p><code>10.0.0.2</code> is not a URL and so the browser falls back on searching for it. Try <code>http://10.0.0.2/</code></p>
| 1 | 2016-10-16T17:21:55Z | [
"python",
"selenium",
"firefox",
"selenium-webdriver"
] |
How to test standalone code outside of a scrapy spider? | 40,073,136 | <p>I can test my xpaths on a HTML body string by running the two lines under (1) below.</p>
<p>But what if I have a local file <code>myfile.html</code> whose content is exactly the <code>body</code> string. How would I run some standalone code, <strong>outside of a spider</strong>? I am seeking something that is roughly similar to the lines under (2) below.</p>
<p>I am aware that <code>scrapy shell myfile.html</code> tests xpaths. My intention is to run some Python code on the response, and hence <code>scrapy shell</code> is lacking (or else tedious).</p>
<pre><code>from scrapy.selector import Selector
from scrapy.http import HtmlResponse
# (1)
body = '<html><body><span>Hello</span></body></html>'
print Selector(text=body).xpath('//span/text()').extract()
# (2)
response = HtmlResponse(url='file:///tmp/myfile.html')
print Selector(response=response).xpath('//span/text()').extract()
</code></pre>
| 0 | 2016-10-16T17:19:39Z | 40,084,225 | <p>You can have a look at <a href="https://github.com/scrapy/scrapy/blob/master/tests/test_linkextractors.py" rel="nofollow">how scrapy tests for link extractors</a> are implemented.</p>
<p>They use a <code>get_test_data()</code> helper to <a href="https://github.com/scrapy/scrapy/blob/129421c7e31b89b9b0f9c5f7d8ae59e47df36091/tests/__init__.py#L31" rel="nofollow">read a file</a> as bytes,
and then instanciate a <code>Response</code> with a fake URL and body set to the bytes read with <code>get_test_data()</code>:</p>
<pre><code>...
body = get_testdata('link_extractor', 'sgml_linkextractor.html')
self.response = HtmlResponse(url='http://example.com/index', body=body)
...
</code></pre>
<p>Depending on the encoding used for the local HTML files, you may need to pass a non-UTF-8 <code>encoding</code> argument to <code>Response</code></p>
| 0 | 2016-10-17T10:38:45Z | [
"python",
"xpath",
"scrapy"
] |
Find Max in List Using the Reduce Function | 40,073,160 | <p>In Torbjörn Lager's 46 python exercises, number 26 is finding the max in a list using the reduce function. I know how to add and multiply using the reduce function but it doesn't make sense to me how you could use it to find the largest number. Does anyone know how to do this?</p>
| -2 | 2016-10-16T17:21:29Z | 40,073,232 | <p>Write a function that returns the larger of two numbers:</p>
<pre><code>def larger(a, b):
return a if a > b else b
</code></pre>
<p>Then use it with <code>reduce</code>:</p>
<pre><code>reduce(larger, [1, 2, 3, 4])
</code></pre>
<p>Conveniently, Python already has a function like <code>larger</code> that's called <code>max</code>. So this will work:</p>
<pre><code>reduce(max, [1, 2, 3, 4])
</code></pre>
<p>Of course <code>max</code> will do the whole kaboodle for you without <code>reduce</code>:</p>
<pre><code>max([1, 2, 3, 4])
</code></pre>
<p>And that's what you'd actually use if you weren't learning to work with <code>reduce</code>. It doesn't use <code>reduce</code> under the hood, though; that's actually a rather inefficient way to do the job.</p>
| 2 | 2016-10-16T17:29:26Z | [
"python"
] |
How to remove a character from element and the corresponding character in another element in a list (Python)? | 40,073,167 | <pre><code>sample = ['A$$N','BBBC','$$AA']
</code></pre>
<p>I need to compare every element to every other element in the list. So compare sample[0] and sample[1], sample[0] and sample[2], sample[1] and sample[2].
a
If any pair in the comparison has "$", then "$" and the corresponding element needs to be eliminated.
Eg. in </p>
<pre><code>sample[0] and sample[1] Output1 : ['AN','BC']
sample[0] and sample[2] Output2 : ['N', 'A']
sample[1] and sample[2] Output3 : ['BC','AA']
for i in range(len(sample1)):
for j in range(i + 1, len(sample1)):
if i == "$" or j == "$":
#Need to remove "$" and the corresponding element in the other list
#Print the pairs
</code></pre>
| 1 | 2016-10-16T17:21:58Z | 40,073,306 | <p>This may not be the most beautiful code but will do the job.</p>
<pre><code>from itertools import combinations
sample = ['A$$N','BBBC','$$AA']
output = []
for i, j in combinations(range(len(sample)), 2):
out = ['', '']
for pair in zip(sample[i], sample[j]):
if '$' not in pair:
out[0] += pair[0]
out[1] += pair[1]
output.append(out)
print(output)
</code></pre>
| 1 | 2016-10-16T17:36:52Z | [
"python",
"list",
"character",
"pop",
"del"
] |
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail" | 40,073,205 | <p>TL;DR: I am getting this error and don't know why:</p>
<blockquote>
<p>django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field.</p>
</blockquote>
<p>I am going through the <a href="http://www.django-rest-framework.org/tutorial/3-class-based-views/" rel="nofollow">django-rest-framework tutorial</a> and am currently at a point where function based views (FBV) were switched to class, mixin, and generic based views (CBV, MBV, GBV respectively). After switching to GBV, when I went to test my API, I received this error <code>AssertionError: Expected view SnippetDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the '.lookup_field' attribute on the view correctly.</code>. I did some research and found that <code>lookup_field</code> <a href="http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview" rel="nofollow">needs to be set to the in the urlpatterns</a>. Currently, my urls.py look like this:</p>
<pre><code>from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
# API endpoints
urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^snippets/$',
views.SnippetList.as_view(),
name='snippet-list'),
url(r'^snippets/(?P<id>[0-9]+)/$',
views.SnippetDetail.as_view(),
name='snippet-detail'),
url(r'^users/$',
views.UserList.as_view(),
name='user-list'),
url(r'^users/(?P<id>[0-9]+)/$',
views.UserDetail.as_view(),
name='user-detail')
])
# Login and logout views for the browsable API
urlpatterns += [
url(r'^auth/', include('rest_framework.urls',
namespace='rest_framework')),
]
</code></pre>
<p>and my views.py look like so:</p>
<pre><code>from snippets.models import Snippet
from snippets.serializers import SnippetSerializer, UserSerializer
from snippets.permissions import IsOwnerOrReadOnly
from rest_framework import generics
from rest_framework import permissions
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from django.contrib.auth.models import User
@api_view(['GET'])
def api_root(request, format=None):
return Response({
'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request, format=format)
})
class UserList(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly, )
</code></pre>
<p>when I add <code>lookup_field = 'id'</code> in both UserDetail and SnippetDetail, the exception resolves itself. (Yay!). But, when I visit <a href="http://127.0.0.1/users/1/" rel="nofollow">http://127.0.0.1/users/1/</a> <code>ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field.</code> is thrown. When I check the console, however, there is a second exception: </p>
<blockquote>
<p>django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with
arguments '()' and keyword arguments '{'pk': 1}' not found. 2
pattern(s) tried: ['users/(?P[0-9]+)\.(?P[a-z0-9]+)/?$',
'users/(?P[0-9]+)/$']</p>
<p>During handling of the above exception, another exception occurred:</p>
<p>django.core.exceptions.ImproperlyConfigured: Could not resolve URL for
hyperlinked relationship using view name "user-detail". You may have
failed to include the related model in your API, or incorrectly
configured the 'lookup_field' attribute on this field.</p>
</blockquote>
<p>What I find interesting is that the kwargs for the first exception is <code>{'pk': 1}</code>, not <code>{'id':1}</code>. After some help from chat, someone pointed me to <a href="http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview" rel="nofollow">this</a> piece of information:</p>
<blockquote>
<p>Note that when using hyperlinked APIs you'll need to ensure that both the API views and the serializer classes set the lookup fields if you need to use a custom value.</p>
</blockquote>
<p>This is useful as <code>User</code> serializer extends <code>HyperlinkedModelSerializer</code>:</p>
<pre><code>from rest_framework import serializers
from django.contrib.auth.models import User
from snippets.models import Snippet
class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True)
class Meta:
model = User
fields = ('url', 'id', 'username', 'snippets')
</code></pre>
<p>the <code>User</code> model and serializer has a reverse relationship with <code>Snippet</code>. Now, when I add <code>lookup_field='id'</code> to snippets attribute of <code>UserSerializer</code> (<code>snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail', read_only=True, lookup_field='id')</code>), like it asks me to do so <a href="http://www.django-rest-framework.org/api-guide/serializers/#how-hyperlinked-views-are-determined" rel="nofollow">here</a>, the error is persistent.</p>
<p>What am I doing incorrectly? What can I do to fix this? Is it not having anything to do with <code>lookup_id</code>?</p>
<p>I understand that I could replace <code><id></code> with <code><pk></code> in my urlpatterns, but I would like to understand <em>why</em> this is happening. Thank you for any help.</p>
| 0 | 2016-10-16T17:26:57Z | 40,077,012 | <p>I eventually fixed my second exception by printing the serializer in the Django shell/python interactive console. The result I got was this:</p>
<pre><code>>>> from snippets.serializers import UserSerializer
>>> print(UserSerializer())
UserSerializer():
url = HyperlinkedIdentityField(view_name='user-detail')
id = IntegerField(label='ID', read_only=True)
username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>])
snippets = HyperlinkedRelatedField(lookup_field='id', many=True, read_only=True, view_name='snippet-detail')
</code></pre>
<p>It turns out that to change <code><pk></code> to <code><id></code> in urlspatterns, you need to add <code>url = HyperlinkedIdentityField(view_name='user-detail', lookup_field='id')</code> in the <code>UserSerializer</code> class. </p>
| 0 | 2016-10-17T00:34:48Z | [
"python",
"django",
"rest",
"hyperlink",
"django-rest-framework"
] |
How do I created a class with a printing function? | 40,073,246 | <p>I want to create a separate file class that will be a print function. So I want it to print out a list when it gets the parameter. So lets call the class <code>print_list</code> and let's take the start variable I want the function to go through the list and print out the data. How do I create this function?</p>
<pre><code> from print_list import *
class node:
pass
start = node
point = start
point.data= 1
print (point.data )
point.next = node ()
point = point.next
point.data= 2
print (point.data )
point.next = node ()
point = point.next
point.data= 3
print (point.data )
point.next = node ()
point = point.next
point.data= 4
print (point.data )
point.next = None
point = point.next
</code></pre>
| -1 | 2016-10-16T17:31:03Z | 40,073,600 | <p>Why not try the build in <code>print</code> function of python? Something like</p>
<pre><code>print(x)
</code></pre>
<p>or, if x is an iterable like a list, you could also do</p>
<pre><code>print(*x)
</code></pre>
| 0 | 2016-10-16T18:02:35Z | [
"python"
] |
python quiz with jinja | 40,073,247 | <p>i'm learning at moment python and for a exercise i have to build a quiz with jinja.
for the quiz i have to build a random function, so that the questions comes random. but i have the problem that my codes don't run the right way. with my code, i get the Error "TypeError: list indices must be integers, not NoneType"
does anybody have a tip, how it might work?</p>
<pre><code>#!/usr/bin/env python
import os
import jinja2
import webapp2
import random
template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)
class BaseHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
return self.response.out.write(*a, **kw)
def render_str(self, template, **params):
t = jinja_env.get_template(template)
return t.render(params)
def render(self, template, **kw):
return self.write(self.render_str(template, **kw))
def render_template(self, view_filename, params=None):
if not params:
params = {}
template = jinja_env.get_template(view_filename)
return self.response.out.write(template.render(params))
class MainHandler(BaseHandler):
def get(self):
city = cities[secret]
return self.render_template("index.html", params={"picture" : city.picture, "country" : city.country})
def post(self):
capital = self.request.get("capital")
city = cities[secret]
if capital == city.name:
return self.write("That's right :)")
else:
return self.write("Sorry, it's wrong")
class City(object):
def __init__(self, name, country, picture):
self.name = name
self.country = country
self.picture = picture
cities = [City (name="Vienna""Berlin", country="Austria""Germany", picture="http://www.mpnpokertour.com/wp-content/uploads/2015/08/Slider-Vienna.png""http://polpix.sueddeutsche.com/bild/1.1406949.1355282590/940x528/berlin-staedtetipps-szkorrespondenten.jpg")]
secret = random.seed(len(cities))
app = webapp2.WSGIApplication([
webapp2.Route('/', MainHandler),
], debug=True)
</code></pre>
| 1 | 2016-10-16T17:31:11Z | 40,073,383 | <pre><code>secret = random.seed(len(cities))
</code></pre>
<p>This sets <code>secret</code> to <code>None</code>, because the seed function returns nothing.
You probably confused <a href="https://docs.python.org/2/library/random.html#random.seed" rel="nofollow">seed</a> with <a href="https://docs.python.org/2/library/random.html#random.randint" rel="nofollow">randint</a>. Seed is used to initialize the random number generator (usually unneeded as python does it automatically), while randint picks a random number and returns it.</p>
<pre><code>secret = random.randint(0, len(cities) - 1)
</code></pre>
<p>â this will set <code>secret</code> to a random integer between 0 and the number of cities (minus one), inclusive.</p>
| 1 | 2016-10-16T17:44:59Z | [
"python",
"jinja2"
] |
Invalid literal for int() | 40,073,276 | <p>I am learning python and I am trying to code a calculator that compares prices of butter, calculates percentage differences, and which one has the lowest price for 100 grams.</p>
<pre><code>def procenta(x,y):
vysledek = (y-x)/x * 100 # (b-a) : a * 100
return round(vysledek, 2)
tesco = float(input("Zadejte cenu masla v Tescu: "))
tesco_g = int(input("Zadejte gramaz v Tescu: "))
lidl = float(input("Zadejte cenu masla v Lidlu: "))
lidl_g = int(input("Zadejte gramaz v Lidlu: "))
kaufland = float(input("Zadejte cenu masla v Kauflandu: "))
kaufland_g = int(input("Zadejte gramaz v Kauflandu: "))
cena_tesco = int(tesco)/(tesco_g[:2]/10)
cena_lidl = int(lidl)/(lidl_g[:2]/10)
cena_kaufland = int(kaufland)/(kaufland_g[:2]/10)
</code></pre>
<p>Traceback:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "python", line 6, in <module>
ValueError: invalid literal for int() with base 10: ''
</code></pre>
<p>Don´t worry about what does the other text means, it's my native language, can translate it eventually. However, if I change it to:</p>
<p><code>cena_tesco = float(tesco/(tesco_g[:2]/10))</code></p>
<p>I get <code>TypeError float object is not subscriptable</code>.</p>
| -1 | 2016-10-16T17:33:37Z | 40,073,337 | <p>You've defined <code>tesco_g</code> to be an integer by casting it with your 5th line. Your TypeError is telling you that the <code>varname[:2]</code> syntax doesn't work because your type doesn't have indices. To reframe what the interpreter is doing:
1. It reads <code>tesco_g[:2]</code>
2. It checks: does the type of <code>tesco_g</code> have a method for indexing up to the second element?
3. It doesn't find that method, and throws an error.</p>
<p>What is the <code>cena_tesco</code> line supposed to do?</p>
| 0 | 2016-10-16T17:39:58Z | [
"python",
"python-3.x"
] |
Invalid literal for int() | 40,073,276 | <p>I am learning python and I am trying to code a calculator that compares prices of butter, calculates percentage differences, and which one has the lowest price for 100 grams.</p>
<pre><code>def procenta(x,y):
vysledek = (y-x)/x * 100 # (b-a) : a * 100
return round(vysledek, 2)
tesco = float(input("Zadejte cenu masla v Tescu: "))
tesco_g = int(input("Zadejte gramaz v Tescu: "))
lidl = float(input("Zadejte cenu masla v Lidlu: "))
lidl_g = int(input("Zadejte gramaz v Lidlu: "))
kaufland = float(input("Zadejte cenu masla v Kauflandu: "))
kaufland_g = int(input("Zadejte gramaz v Kauflandu: "))
cena_tesco = int(tesco)/(tesco_g[:2]/10)
cena_lidl = int(lidl)/(lidl_g[:2]/10)
cena_kaufland = int(kaufland)/(kaufland_g[:2]/10)
</code></pre>
<p>Traceback:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "python", line 6, in <module>
ValueError: invalid literal for int() with base 10: ''
</code></pre>
<p>Don´t worry about what does the other text means, it's my native language, can translate it eventually. However, if I change it to:</p>
<p><code>cena_tesco = float(tesco/(tesco_g[:2]/10))</code></p>
<p>I get <code>TypeError float object is not subscriptable</code>.</p>
| -1 | 2016-10-16T17:33:37Z | 40,073,434 | <p>If I will get it to work , it will be printed :</p>
<pre><code>print("Tesco is the cheapest shop with price of",*cena_tesco*,"for 100 grams of butter.")
</code></pre>
<p>Its supposed to calculate price of butter for 100g.
What should I do with tesco_g[:2] so it take first two digits from tesco_g and use them to calculate the price ?</p>
| 0 | 2016-10-16T17:49:05Z | [
"python",
"python-3.x"
] |
Plotting list of lists in a same graph in Python | 40,073,322 | <p>I am trying to plot <code>(x,y)</code> where as <code>y = [[1,2,3],[4,5,6],[7,8,9]]</code>. </p>
<p>Say, <code>len(x) = len(y[1]) = len(y[2])</code>..
The length of the y is decided by the User input. I want to plot multiple plots of y in the same graph i.e, <code>(x, y[1],y[2],y[3],...)</code>. When I tried using loop it says <code>dimension error</code>.</p>
<p>I also tried: <code>plt.plot(x,y[i] for i in range(1,len(y)))</code> </p>
<p>How do I plot ? Please help.</p>
<pre><code>for i in range(1,len(y)):
plt.plot(x,y[i],label = 'id %s'%i)
plt.legend()
plt.show()
</code></pre>
| 0 | 2016-10-16T17:38:29Z | 40,073,609 | <p>Assuming some sample values for x below is the code that could give you the desired output.</p>
<pre><code>import matplotlib.pyplot as plt
x = [1,2,3]
y = [[1,2,3],[4,5,6],[7,8,9]]
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("A test graph")
for i in range(len(y)):
plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i)
plt.legend()
plt.show()
</code></pre>
<p>Assumptions: <code>x</code> and any element in <code>y</code> are of the same length.
The idea is reading element by element so as to construct the list <code>(x,y[0]'s)</code>, <code>(x,y[1]'s)</code> and <code>(x,y[n]'s</code></p>
<p>Below is the plot I get for this case:
<a href="https://i.stack.imgur.com/0wvlq.png" rel="nofollow"><img src="https://i.stack.imgur.com/0wvlq.png" alt="Sample plot"></a></p>
| 0 | 2016-10-16T18:03:09Z | [
"python",
"matplotlib",
"nested-lists"
] |
Python Django Queryset | 40,073,348 | <p>I'm playing with querysets in django.</p>
<p>What I'm looking it's to save a new foreign product or item but I can not achieve it.</p>
<p><em>shell</em></p>
<pre><code>from applaboratorio.models import Datos_empresa_DB, Datos_equipo_DB
detalle = Datos_empresa_DB.objects.filter(pk=58)
resp = Datos_equipo_DB(equipo='dell-labtop',marca='dell', modelo='432423',Foraneo_Datos_empresa_DB = detalle)
</code></pre>
<p><strong><em>models.py</em></strong></p>
<pre><code>class Datos_empresa_DB(models.Model):
nombre = models.CharField(max_length=150)
empresa = models.CharField(max_length=150)
class Datos_equipo_DB(models.Model):
Foraneo_Datos_empresa_DB = models.ForeignKey(Datos_empresa_DB)
equipo = models.CharField(max_length=300)
marca = models.CharField(max_length=300)
modelo = models.CharField(max_length=300)
</code></pre>
<p>What am I doing bad?</p>
<p>I'm trying to create a new product for a client that already exist in db.</p>
| 1 | 2016-10-16T17:41:56Z | 40,073,393 | <p>I think you're nearly there. You need to call the <code>save</code> method of the new product to <em>save</em> to the DB, and to <em>retrieve</em> the related client object, you should <code>get</code> not <code>filter</code> so you have the object itself and not a list of objects (or <em>QuerySet</em>):</p>
<pre><code>detalle = Datos_empresa_DB.objects.get(pk=58)
# ^^^
resp = Datos_equipo_DB(equipo='dell-labtop',marca='dell', modelo='432423',Foraneo_Datos_empresa_DB =detalle)
# Save on model's related field <-^^^^^^^
resp.save()
</code></pre>
| 2 | 2016-10-16T17:46:01Z | [
"python",
"django",
"django-queryset"
] |
Converting python time stamp to day of year | 40,073,373 | <p>How can I convert a python timestamp into day of year:</p>
<pre><code>Timestamp('2015-06-01 00:00:00')
</code></pre>
<p>I want a number where Jan 1 is 1, Jan 2 is 2... Dec 31 is 365 (for a non-leap year)</p>
| -3 | 2016-10-16T17:43:41Z | 40,073,424 | <p>You might want to take a look at the function <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.timetuple" rel="nofollow"><code>datetime.timetuple()</code></a> which returns a <a href="https://docs.python.org/2/library/time.html#time.struct_time" rel="nofollow"><code>time.struct_time</code></a> object with your desired attribute. I has a named tuple interface, so you can access the values by index or attribute name.</p>
<pre><code>import datetime
date = datetime.datetime.strptime("2015-06-01 00:00:00",
"%Y-%m-%d %H:%M:%S")
print date.timetuple().tm_yday
#=> 152
</code></pre>
| 2 | 2016-10-16T17:48:23Z | [
"python",
"datetime"
] |
Converting python time stamp to day of year | 40,073,373 | <p>How can I convert a python timestamp into day of year:</p>
<pre><code>Timestamp('2015-06-01 00:00:00')
</code></pre>
<p>I want a number where Jan 1 is 1, Jan 2 is 2... Dec 31 is 365 (for a non-leap year)</p>
| -3 | 2016-10-16T17:43:41Z | 40,073,571 | <p>First, you can convert it to a <code>datetime.datetime</code> object like this:</p>
<pre><code>>>> import datetime
>>> format = "%Y-%m-%d %H:%M:%S"
>>> s = "2015-06-01 00:00:00"
>>> dt = datetime.datetime.strptime(s, format)
</code></pre>
<p>Now you can use the methods on <code>dt</code> to get what you want,except that <code>dt</code> doesn't have the function you want directly, so you need to convert to a time tuple</p>
<pre><code>>>> tt = dt.timetuple()
>>> tt.tm_yday
152
</code></pre>
| 2 | 2016-10-16T18:00:18Z | [
"python",
"datetime"
] |
what type is,when I use web crawler to download the information from web? | 40,073,381 | <pre><code>import requests
from bs4 import BeautifulSoup
from pandas import Series,DataFrame
def name1():
url='''https://www.agoda.com/zh-tw/pages/agoda/default/DestinationSearchResult.aspx?asq=%2bZePx52sg5H8gZw3pGCybdmU7lFjoXS%2ba
xz%2bUoF4%2bbAw3oLIKgWQqUpZ91GacaGdIGlJ%2bfxiotUg7cHef4W8WIrREFyK%2bHWl%2ftRKlV7J5kUcPb7NK6DnLacMaVs1qlGagsx8liTdosF5by%2
fmvF3ZvJvZqOWnEqFCm0staf3OvDRiEYy%2bVBJyLXucnzzqZp%2fcBP3%2bKCFNOTA%2br9ARInL665pxj%2fA%2bylTfAGs1qJCjm9nxgYafyEWBFMPjt2s
g351B&city=18343&cid=1732641&tag=41460a09-3e65-d173-1233-629e2428d88e&gclid=Cj0KEQjwvve_BRDmg9Kt9ufO15EBEiQAKoc6qlyYthgdt9
CgZ7a6g6yijP42n6DsCUSZXvtfEJdYqiAaAvdW8P8HAQ&tick=636119092231&isdym=true&searchterm=%E5%A2%BE%E4%B8%81&pagetypeid=1&origi
n=TW&cid=1732641&htmlLanguage=zh-tw&checkIn=2016-10-20&checkOut=2016-10-21&los=1&rooms=1&adults=2&children=0&isFromSearchB
ox=true&ckuid=1b070b17-86c2-4376-a4f5-d3b98fc9cf45'''
#æå®ç¶²å
source_code=requests.get(url)
#åå¾ç¶²åçsource code
plain_text=source_code.text
#æsource codeåætext
soup=BeautifulSoup(plain_text,"lxml")
#ç¨BSå»è§£ç¢¼
for a in soup.find_all("h3",{"class":"hotel-name"}):
print (list(a))
name1()
</code></pre>
<p>I want to sort the data ,craw from Agoda. It seems that I download the many list but a one list. I wonder a list about hotel-name but it has too much things I don't need ex: blank,<code>tag(<h3>...</h3>)</code>. </p>
<p>Please tell me, how to clean the data downloaded from web with python.</p>
| -3 | 2016-10-16T17:44:47Z | 40,073,518 | <p>Use <code>.text</code> to get without tags. And <code>.strip()</code> to remove wihtespaces</p>
<pre><code>for a in soup.find_all("h3",{"class":"hotel-name"}):
print(a.text.strip())
</code></pre>
| 0 | 2016-10-16T17:55:39Z | [
"python",
"python-3.x",
"beautifulsoup",
"web-crawler"
] |
wxpython phoenix says that Frame init args are wrong | 40,073,408 | <p>I am trying to create simple window with menu in wx python 3.0.4.
Actually I get an error:</p>
<blockquote>
<p>wx.Frame.<strong>init</strong>(self, ID_ANY, "Title", DefaultPosition, (350,200), DEFAULT_FRAME_STYLE, FrameNameStr) TypeError: Frame():</p>
<p>arguments did not match any overloaded call: overload 1: too many</p>
<p>arguments overload 2: argument 1 has unexpected type 'StandardID'</p>
</blockquote>
<p>Even this code is from documentation. Could someone tell me what am I doing wrong, please?</p>
<pre><code>import wx
from wx import *
class MainWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, ID_ANY, "Title", DefaultPosition, (350,200), DEFAULT_FRAME_STYLE, FrameNameStr)
self.Bind(wx.EVT_CLOSE, self.OnClose)
menuBar = wx.MenuBar()
menu = wx.Menu()
m_exit = menu.Append(wx.ID_EXIT, "E&xit", "Close window and exit program.")
self.Bind(wx.EVT_MENU, self.OnClose, m_exit)
menuBar.Append(menu, "&File")
menu = wx.Menu()
m_about = menu.Append(wx.ID_ABOUT, "&About", "Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, m_about)
menuBar.Append(menu, "&Help")
self.SetMenuBar(menuBar)
self.main_panel = MainPanel(self)
def OnClose(self, e):
self.Close()
def OnAbout(self, event):
dlg = AboutBox(self)
dlg.ShowModal()
dlg.Destroy()
class MainPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
class AboutBox(wx.MessageDialog):
def __init__(self, parent):
wx.MessageDialog.__init__(parent, "About", "About", wx.OK | wx.ICON_INFORMATION, pos=DefaultPosition)
self.CentreOnParent(wx.BOTH)
self.SetFocus()
if __name__ == "__main__":
app = wx.App(False)
frame = MainWindow()
frame.Show()
app.MainLoop()
</code></pre>
| 0 | 2016-10-16T17:47:07Z | 40,073,924 | <pre><code>Frame(parent, id=ID_ANY, title="", pos=DefaultPosition,
size=DefaultSize, style=DEFAULT_FRAME_STYLE, name=FrameNameStr)
</code></pre>
<p>You missed the parent argument.</p>
<p>Working code</p>
<pre><code>import wx
class MainWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(
self, None, wx.ID_ANY, "Title", wx.DefaultPosition, (350,200),
wx.DEFAULT_FRAME_STYLE, wx.FrameNameStr)
self.Bind(wx.EVT_CLOSE, self.OnClose)
menuBar = wx.MenuBar()
menu = wx.Menu()
m_exit = menu.Append(
wx.ID_EXIT, "E&xit", "Close window and exit program.")
self.Bind(wx.EVT_MENU, self.OnClose, m_exit)
menuBar.Append(menu, "&File")
menu = wx.Menu()
m_about = menu.Append(
wx.ID_ABOUT, "&About", "Information about this program")
self.Bind(wx.EVT_MENU, self.OnAbout, m_about)
menuBar.Append(menu, "&Help")
self.SetMenuBar(menuBar)
self.main_panel = MainPanel(self)
def OnClose(self, e):
self.Destroy()
def OnAbout(self, event):
dlg = AboutBox(self)
dlg.ShowModal()
dlg.Destroy()
class MainPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
class AboutBox(wx.MessageDialog):
def __init__(self, parent):
wx.MessageDialog.__init__(
self, parent, "About", "About", wx.OK | wx.ICON_INFORMATION,
pos=wx.DefaultPosition)
self.CentreOnParent(wx.BOTH)
if __name__ == "__main__":
app = wx.App(False)
frame = MainWindow()
frame.Show()
app.MainLoop()
</code></pre>
| 1 | 2016-10-16T18:30:30Z | [
"python",
"user-interface",
"wxpython",
"python-3.5"
] |
Removing negative values and printing the original and the new list | 40,073,642 | <p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p>
<p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and after ( without the negative items of course).
My problem is that it prints out the original list and the new list without negative items on the Before print and the original one on After.
Like this: </p>
<pre><code>Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
-2, -9, -14, 2, -10, -5, 8, 7]
[2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]
After: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9,
-14, 2, -10, -5, 8, 7]
</code></pre>
<p>This is what I've done and I just can't seem to figure out what I should do...</p>
<pre><code>import random
def removeNegatives(listOfIntegers):
l = listOfIntegers[:] #takes a copy of the list
for item in listOfIntegers:
if item < 0: #checks if it is lower than 0
l.remove(item)
print l
l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
l.append(random.randint(-15,15))
print "Before:", l #should only print out the original list of numbers
removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are <0
</code></pre>
| 0 | 2016-10-16T18:06:38Z | 40,073,861 | <p>You aren't modifying global variable <code>l</code> in your function.</p>
<p>I propose this code in Python, which should work correctly:</p>
<pre><code>import random
def removeNegatives(listOfIntegers):
return [x for x in listOfIntegers if not x < 0]
l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
l.append(random.randint(-15,15))
print "Before:", l #should only print out the original list of numbers
l = removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are <0
</code></pre>
<p>It's way shorter. What do you think about it?</p>
| 1 | 2016-10-16T18:25:52Z | [
"python",
"python-2.7"
] |
Removing negative values and printing the original and the new list | 40,073,642 | <p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p>
<p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and after ( without the negative items of course).
My problem is that it prints out the original list and the new list without negative items on the Before print and the original one on After.
Like this: </p>
<pre><code>Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
-2, -9, -14, 2, -10, -5, 8, 7]
[2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]
After: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9,
-14, 2, -10, -5, 8, 7]
</code></pre>
<p>This is what I've done and I just can't seem to figure out what I should do...</p>
<pre><code>import random
def removeNegatives(listOfIntegers):
l = listOfIntegers[:] #takes a copy of the list
for item in listOfIntegers:
if item < 0: #checks if it is lower than 0
l.remove(item)
print l
l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
l.append(random.randint(-15,15))
print "Before:", l #should only print out the original list of numbers
removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are <0
</code></pre>
| 0 | 2016-10-16T18:06:38Z | 40,074,223 | <p>Just saw your comment relative to not being able to modify the code below l = []</p>
<p>In that case, you need to reassign to listOfIntegers coming out of your function</p>
<pre><code>def removeNegatives(listOfIntegers):
global l
k = listOfIntegers[:] #takes a copy of the list
for item in listOfIntegers:
if item < 0: #checks if it is lower than 0
k.remove(item)
print k
l = k
</code></pre>
<p>You make a copy of the global as you come in the function, you just need to repoint it to the modified copy as you leave.</p>
<p>Edit: other comments relative to modifying a list while you iterate it are not accurate, as you are not modifying the list you are iterating on, you are modifying the "copy" of the list. While others have offered good suggestions on improving the conciseness of the method, your original method was perfectly valid with the above tweaks. </p>
<p>Edit2: volcano's 'comment' relative to the global is correct, the global statement should be added inside the def to perform it this way. reference volcano's answer for the best approach, but I'll leave this around for the discussion point. </p>
| 0 | 2016-10-16T18:57:52Z | [
"python",
"python-2.7"
] |
Removing negative values and printing the original and the new list | 40,073,642 | <p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p>
<p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and after ( without the negative items of course).
My problem is that it prints out the original list and the new list without negative items on the Before print and the original one on After.
Like this: </p>
<pre><code>Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
-2, -9, -14, 2, -10, -5, 8, 7]
[2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]
After: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9,
-14, 2, -10, -5, 8, 7]
</code></pre>
<p>This is what I've done and I just can't seem to figure out what I should do...</p>
<pre><code>import random
def removeNegatives(listOfIntegers):
l = listOfIntegers[:] #takes a copy of the list
for item in listOfIntegers:
if item < 0: #checks if it is lower than 0
l.remove(item)
print l
l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
l.append(random.randint(-15,15))
print "Before:", l #should only print out the original list of numbers
removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are <0
</code></pre>
| 0 | 2016-10-16T18:06:38Z | 40,074,433 | <p>The "cleanest" way to modify external list will be to change its contents without reassigning - which changes list object reference. You can't remove elements when looping over list, and removing each non-compliant element while iterating over copy is very ineffective. </p>
<p>But you may reassign contents of list without re-assigning list object reference - using <strong>slice</strong> on the left side of the assignment</p>
<pre><code>def removeNegatives(listOfIntegers):
listOfIntegers[:] = filter(lambda x: x >= 0, listOfIntegers)
</code></pre>
<p>This code creates new list of non-negative values, and replaces whole content of the external-scope list.</p>
| 1 | 2016-10-16T19:20:51Z | [
"python",
"python-2.7"
] |
Removing negative values and printing the original and the new list | 40,073,642 | <p>To start of I am telling you this is for school as I am learning to code with Python. Please do explain why I should do something :)! I am looking to learn not just getting the answer.</p>
<p>I am trying to get rid of the negative items in the list. I want to print the list Before (including the negative items) and after ( without the negative items of course).
My problem is that it prints out the original list and the new list without negative items on the Before print and the original one on After.
Like this: </p>
<pre><code>Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
-2, -9, -14, 2, -10, -5, 8, 7]
[2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]
After: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9,
-14, 2, -10, -5, 8, 7]
</code></pre>
<p>This is what I've done and I just can't seem to figure out what I should do...</p>
<pre><code>import random
def removeNegatives(listOfIntegers):
l = listOfIntegers[:] #takes a copy of the list
for item in listOfIntegers:
if item < 0: #checks if it is lower than 0
l.remove(item)
print l
l = []
for i in xrange(0, random.randint(15,25)): #gives me the random numbers
l.append(random.randint(-15,15))
print "Before:", l #should only print out the original list of numbers
removeNegatives(l)
print "After:", l #should only print out the new list without the numbers that are <0
</code></pre>
| 0 | 2016-10-16T18:06:38Z | 40,096,774 | <p>Since you're studying Python, this is a good place to learn <code>list comprehension</code>:</p>
<pre><code>$ cat /tmp/tmp.py
_list = [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14,
-2, -9, -14, 2, -10, -5, 8, 7]
print("Before:",_list)
print("After:",[a for a in _list if a >= 0])
$ python3 /tmp/tmp.py
Before: [2, 7, -3, -3, 13, -14, 13, 5, 11, -4, 10, 5, 0, -5, -14, -2, -9, -14, 2, -10, -5, 8, 7]
After: [2, 7, 13, 13, 5, 11, 10, 5, 0, 2, 8, 7]
</code></pre>
<p>As you can see, the elimination of the negative number in the list comprehension stage is concise, clear, and if you test it, you'd find it's faster than the comparable solution using loops.</p>
| 0 | 2016-10-17T22:40:41Z | [
"python",
"python-2.7"
] |
How do I change my code to use arrays? | 40,073,699 | <p>This is my code so far. I can get my code to prompt the user to input 4 test scores. I have made it so it asks "Enter the score for test number N:" </p>
<p>My problem lies in being able to extract the input values from what the user would input. My end goal is to be able to drop the lowest test grade and calculate an average with the remaining scores. Input data used would be 99, 99, 99 and 77. </p>
<p>I have an example that takes the min from a variable that is assigned X numbers but not from when you would get it from a user input. </p>
<pre><code>def main():
scores = getNumbers()
def getNumbers():
testCountIs = 0
testNum = 4
totalScore = 0
for test in range(1, testNum+1):
print('Enter the score for test number', int(testCountIs+1), end='')
testScores = int(input(': '))
testCountIs += 1
main()
</code></pre>
<p>Edit2: below is the code that works for this program.</p>
<pre><code> def main():
scores = getNumbers()
print("The average with the lowest score dropped is: ",float(sum(scores))/len(scores))
def getNumbers():
scores=[]
for testNum in range(4):
print('Enter the score for test number',int(testNum+1),end='')
scores.append(int(input(': ')))
scores=[score for score in scores if min(scores)!=score]
return scores
main()
</code></pre>
| 0 | 2016-10-16T18:12:53Z | 40,073,821 | <p>This is what you want:</p>
<pre><code>def getNumbers():
scores=[]
for testNum in range(4):
print('Enter the score for test number %d'%(testNum+1)),
scores.append(input(': '))
scores=[score for score in scores if min(scores)!=score]
return scores
scores= getNumbers()
average= float(sum(scores))/len(scores)
print average
</code></pre>
<p><strong>Edit</strong> For python3</p>
<pre><code>def getNumbers():
scores=[]
for testNum in range(4):
print('Enter the score for test number',int(testNum+1),end='')
scores.append(int(input(': ')))
scores=[score for score in scores if min(scores)!=score]
return scores
scores= getNumbers()
print(float(sum(scores))/len(scores))
</code></pre>
| 0 | 2016-10-16T18:22:28Z | [
"python",
"arrays"
] |
How do I change my code to use arrays? | 40,073,699 | <p>This is my code so far. I can get my code to prompt the user to input 4 test scores. I have made it so it asks "Enter the score for test number N:" </p>
<p>My problem lies in being able to extract the input values from what the user would input. My end goal is to be able to drop the lowest test grade and calculate an average with the remaining scores. Input data used would be 99, 99, 99 and 77. </p>
<p>I have an example that takes the min from a variable that is assigned X numbers but not from when you would get it from a user input. </p>
<pre><code>def main():
scores = getNumbers()
def getNumbers():
testCountIs = 0
testNum = 4
totalScore = 0
for test in range(1, testNum+1):
print('Enter the score for test number', int(testCountIs+1), end='')
testScores = int(input(': '))
testCountIs += 1
main()
</code></pre>
<p>Edit2: below is the code that works for this program.</p>
<pre><code> def main():
scores = getNumbers()
print("The average with the lowest score dropped is: ",float(sum(scores))/len(scores))
def getNumbers():
scores=[]
for testNum in range(4):
print('Enter the score for test number',int(testNum+1),end='')
scores.append(int(input(': ')))
scores=[score for score in scores if min(scores)!=score]
return scores
main()
</code></pre>
| 0 | 2016-10-16T18:12:53Z | 40,074,622 | <p>Your code was close. Just need to define a list, append to it, then return it </p>
<pre><code>scores = []
for test in range(testNum):
print('Enter the score for test number', int(test + 1), end='')
score = int(input(': ')
scores.append(score)
return scores
</code></pre>
<p>You should calculate the minimum, drop it, and find the average outside of this function </p>
| 0 | 2016-10-16T19:38:52Z | [
"python",
"arrays"
] |
Function giving unexpected result | 40,073,719 | <p>Could anyone explain why this function gives "None" at the end? </p>
<pre><code>def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
</code></pre>
| 0 | 2016-10-16T18:15:02Z | 40,073,748 | <p>If a function doesn't return anything, then it automatically returns <code>None</code>.</p>
| 1 | 2016-10-16T18:16:55Z | [
"python",
"function"
] |
Function giving unexpected result | 40,073,719 | <p>Could anyone explain why this function gives "None" at the end? </p>
<pre><code>def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
</code></pre>
| 0 | 2016-10-16T18:15:02Z | 40,073,777 | <p>The function is returning None because there is no other explicit return value; If a function has no return statement, the default is None.</p>
| 2 | 2016-10-16T18:18:45Z | [
"python",
"function"
] |
Set number of digits after decimal | 40,073,862 | <p>I'm trying to set 3 digits after point but it returns me 0.03 instead of 0.030
Here's the code:</p>
<pre><code>import decimal
decimal.getcontext().prec = 3
a = float(input())
qur = []
x = 2
b = a / 100
while x < 12:
qur.append(b)
b = (a * x) / 100
x += 1
print(" ".join([str(i) for i in qur]))
</code></pre>
| 0 | 2016-10-16T18:25:54Z | 40,073,917 | <p>You are not using <code>decimal</code>s, so setting their precision has no effect. For output with a fixed number of digits, use string formatting:</p>
<pre><code>print(" ".join('{0:.3f}'.format(i) for i in qur))
</code></pre>
| 2 | 2016-10-16T18:30:07Z | [
"python"
] |
Strange Bug in creating Co-occurrence Matrix in Python | 40,073,874 | <p>I am trying to create a co-occurrence matrix in Python that outputs the number which words in L1 appear in pears (cat dog, cat house, cat tree e.t.c.) in L2, my code so far is:</p>
<pre><code>co = np.zeros((5,5)) #the matrix
L1 = ['cat', 'dog', 'house', 'tree', 'car'] #tags
L2 = ['cat car dog', 'cat house dog', 'cat car', 'cat dog'] #photo text
n=0 # will hold the sum of each occurance
for i in range(len(L1)):
for j in range(len(L1)):
for s in range(len(L2)):
#find occurrence but not on same words
if L1[i] in L2[s] and L1[j] in L2[s] and L1[i] != L1[j]:
n+=1 # sum the number of occurances
#output = L1[i], L1[j] # L2[s]
#print output
co[i][j] = s #add to the matrix
print co
</code></pre>
<p>The output should be </p>
<pre><code>[[ 0. 3. 1. 0. 2.]
[ 3. 0. 1. 0. 1.]
[ 1. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 2. 1. 0. 0. 0.]]
</code></pre>
<p>But instead:</p>
<pre><code>[[ 0. 3. 1. 0. 2.]
[ 3. 0. 1. 0. 0.]
[ 1. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 0.]
[ 2. 0. 0. 0. 0.]]
</code></pre>
<p>Every second row there is an error... The if part works well, I have checked the output:</p>
<pre><code>output = L1[i], L1[j] # L2[s]
print output
('cat', 'dog')
('cat', 'dog')
('cat', 'dog')
('cat', 'house')
('cat', 'car')
('cat', 'car')
('dog', 'cat')
('dog', 'cat')
('dog', 'cat')
('dog', 'house')
('dog', 'car')
('house', 'cat')
('house', 'dog')
('car', 'cat')
('car', 'cat')
('car', 'dog')
</code></pre>
<p>So I guess there is something going on when filing the matrix?:</p>
<pre><code>co[i][j] = s
</code></pre>
<p>Any suggestions???</p>
| 1 | 2016-10-16T18:27:02Z | 40,074,031 | <p>It's giving a correct result because you have <code>car</code> and <code>dog</code> in first item of <code>L2</code> which is <code>0</code> index.</p>
<p>Here is a more pythonic approach that get the index based on first occurrence of the pairs in <code>L2</code>:</p>
<pre><code>In [158]: L2 = ['cat car dog', 'cat house dog', 'cat car', 'cat dog']
In [159]: L2 = [s.split() for s in L2]
In [160]: combinations = np.column_stack((np.repeat(L1, 5), np.tile(L1, 5))).reshape(5, 5, 2)
# with 0 as the start of the indices
In [162]: [[next((i for i, sub in enumerate(L2) if x in sub and y in sub), 0) for x, y in row] for row in combinations]
Out[162]:
[[0, 0, 1, 0, 0],
[0, 0, 1, 0, 0],
[1, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
# with 1 as the start of the indices
In [163]: [[next((i for i, sub in enumerate(L2, 1) if x in sub and y in sub), 0) for x, y in row] for row in combinations]
Out[163]:
[[1, 1, 2, 0, 1],
[1, 1, 2, 0, 1],
[2, 2, 2, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 0, 0, 1]]
</code></pre>
| 3 | 2016-10-16T18:39:31Z | [
"python",
"numpy",
"matrix"
] |
Python not executing in browser | 40,073,888 | <p>I have a cgi script which imports functions from a different python file. I'm using these files to setup a Hadoop cluster. So it's mostly got commands.getstatusoutput codes. The cgi file just calls these functions while passing the parameters. </p>
<p>But it doesn't execute the functions. This works fine when i run it through terminal. I would appreciate any help on this.</p>
<p>cgi file:</p>
<pre><code>#!/usr/bin/python
import cgi
import cgitb
import os
import commands
import base2
cgitb.enable()
print "content-type:text/html"
print ""
dn_iplist=[]
base2.ipscanner();
base2.freemem();
base2.procno();
base2.freehd();
dn_iplist = sorted(base2.spacedict, key=lambda x: float(base2.spacedict[x][:-1]), reverse=True)[:2]
masterdict = base2.memdict.copy()
for key in dn_iplist:
if key in masterdict:
del masterdict[key]
#print masterdict
#####################Resource Manager IP
rmip = max(masterdict, key=lambda key: int(masterdict[key]))
del masterdict [rmip]
#####################Namenode IP
nnip = max(masterdict, key=lambda key: int(masterdict[key]))
del masterdict[nnip]
#####################Client IP
cip = max(masterdict, key=lambda key: int(masterdict[key]))
print """
<html>
<head>
<title>Hadoop Cluster Services - Create and Manage your Hadoop clusters</title>
<link rel="stylesheet" type="text/css" href="/css/style1.css">
</head>
<body>
<br><b>
<div class="drop">
<ul class="drop_menu">
<li><a href="home.html">HOME</a></li>
<li><a href="create.cgi">CLUSTER</a>
<ul>
<li><a href="/loader.html">Create Cluster</a></li>
<li><a href="#">Manage Cluster</a></li>
</ul>
</li>
<li><a href="#">SERVICES</a>
<ul>
<li><a href="#">Shell</a></li>
<li><a href="#">Create Cluster</a></li>
<li><a href="#">System Admin</a></li>
</ul>
</li>
</ul>
</div>
<br><br><br><br><br>
<div id="autoips">
Resource Manager IP: """
print rmip
print "<br><br>Namenode IP: "
nport = "9001"
print nnip + ":" + nport
print "<br><br>Client IP: "
print cip
print "<br><br>Datanodes/NodeManagers: "
for k in dn_iplist:
print k + ","
print """<br><br><input type="submit" value="Accept"> """
print "<br><br><br> BUILDING CLUSTER"
print"""
</div>
</body>
</html>
"""
base2.make_rm(rmip,nnip,nport)
print "<br>"
base2.make_nn(nnip,nport)
print "<br>"
base2.make_client(nnip,nport,rmip,cip)
print "<br>"
for dnip in dn_iplist:
print dnip
base2.make_dnnm(nnip,nport,rmip,dnip)
print "<br>"
</code></pre>
<p>a part of the py file: </p>
<pre><code>#resourcemanager creation
def make_rm(rmip,nip,nport):
fp = open("temp1.txt",mode="w")
fp.write('<?xml version="1.0"?>\n<!-- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions and limitations under the License. See accompanying LICENSE file.-->\n\n<configuration>\n\n<!-- Site specific YARN configuration properties -->\n\n<property>\n<name>yarn.resourcemanager.resource-tracker.address</name>\n<value>'+rmip+':8025</value>\n</property>\n\n<property>\n<name>yarn.resourcemanager.scheduler.address</name>\n<value>'+rmip+':8030</value>\n</property>\n\n</configuration>')
fp.close()
commands.getstatusoutput("sshpass -p redhat scp temp1.txt "+rmip+":/hadoop2/etc/hadoop/yarn-site.xml")
fp = open("temp2.txt",mode="w")
fp.write('<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="configuration.xsl"?>\n<!-- Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions and limitations under the License. See accompanying LICENSE file.-->\n\n<!-- Put site-specific property overrides in this file. -->\n\n <configuration>\n\n<property>\n <name>fs.default.name</name>\n<value>'+nip+':' +nport+ '</value>\n</property>\n</configuration>\n')
fp.close()
commands.getstatusoutput("sshpass -p redhat scp temp2.txt "+rmip+":/hadoop2/etc/hadoop/core-site.xml")
# print("Resourcemanager setup.\n")
commands.getstatusoutput("sshpass -p redhat ssh -o StrictHostKeyChecking=no root@"+rmip+" yarn-daemon.sh start resourcemanager")
a = commands.getstatusoutput("sshpass -p redhat ssh -o StrictHostKeyChecking=no root@"+rmip+" /usr/java/jdk1.7.0_79/bin/jps | grep 'ResourceManager' | awk '{print $2}'")
if a[1] == "ResourceManager":
print("ResourceManager setup complete!")
</code></pre>
<p>This is the result i get. It shows Setup complete. But nothing's been done. But it executes perfectly via terminal.</p>
<p><a href="https://i.stack.imgur.com/oPMq3.png" rel="nofollow"><img src="https://i.stack.imgur.com/oPMq3.png" alt="enter image description here"></a></p>
<p>There should be a similar Datanode setup complete! beside the 192.168.100.107 IP at the bottom.
This code isn't copying the temp files to the other VM. </p>
<p>EDIT: Could it be something related to the commands.getstatusoutput command??
Why is it only affecting scp</p>
| 0 | 2016-10-16T18:27:58Z | 40,114,028 | <p>Finally fixed it. I had to add a root@ipaddress to the scp commands</p>
<p>from</p>
<pre><code>commands.getstatusoutput("sshpass -p redhat scp temp1.txt "+rmip+":/hadoop2/etc/hadoop/core-site.xml")
</code></pre>
<p>to</p>
<pre><code>commands.getstatusoutput("sshpass -p redhat scp temp1.txt root@"+rmip+":/hadoop2/etc/hadoop/core-site.xml")
</code></pre>
<p>This change has to be made to all the ssh/scp commands.
Without this, httpd tries to ssh using the "apache" user which doesn't have root permissions. This is the reason for the code to fail in the browser.</p>
| 0 | 2016-10-18T16:58:35Z | [
"python",
"apache",
"shell",
"cgi",
"httpd.conf"
] |
Where does pip install its modules? What if using a virtualenv? Also getting an error setting up mod_wsgi | 40,073,901 | <p>I am new to Python and there are some things which I am not able to apprehend. Questions may seem like very kiddish, so bear with me. </p>
<p>As you know, Ubuntu comes with an outdated Python version. I wished to use the latest python. But since it is recommended not to override the system's python, I installed <code>virtualenv</code>.</p>
<p>I installed <code>pip</code> first, using <code>sudo apt-get install python-pip</code>.</p>
<p>Then installed <code>virtualenv</code>, using <code>sudo pip install virtualenv</code>, and did all the configurations required to link it to the latest python. </p>
<p>The questions which I want to ask are-</p>
<ol>
<li><p>Where does the command <code>pip install <module></code> store the module in the system? I am asking this question because there is a section in this <a href="https://pypi.python.org/pypi/mod_wsgi" rel="nofollow">link</a>, which says "Installation into Python". I was confused by this, thinking whether installing a python module is sensitive to which python version I am using. If it is so, then where does <code>pip</code> install the module if I am using <code>virtualenv</code> and otherwise. </p></li>
<li><p>I have manually installed Apache HTTP Server 2.4.23 using this <a href="https://ksmanisite.wordpress.com/2016/10/05/manually-install-apache-http-server-in-ubuntu/" rel="nofollow">link</a>. While installing <code>mod_wsgi</code> using command <code>sudo pip install mod_wsgi</code>, I am getting this error</p>
<blockquote>
<p>RuntimeError: The 'apxs' command appears not to be installed or is not
executable. Please check the list of prerequisites in the
documentation for this package and install any missing Apache httpd
server packages.</p>
</blockquote></li>
</ol>
<p>I searched for it and the solution is to install developer package of Apache. But the problem is that I am not able to find it anywhere on it's site. I want to install it manually. What to do? Also, If I install it through <code>sudo apt-get install apache2-dev</code>, Will there be any difference ? </p>
<p>Note: As mentioned on this <a href="https://pypi.python.org/pypi/mod_wsgi" rel="nofollow">link</a>, I have already set the value of <code>APXS</code> environment variable to the location of <code>apxs</code> script, which is <code>/usr/local/apache/bin/apxs</code>. </p>
| 1 | 2016-10-16T18:28:52Z | 40,074,107 | <p>Concerning 1., if I have well understood, you would like to have the last 2.7 or 3.5 Python version on your distribution. Actually, you can have multiple python distribution on your distribution. I would suggest you to have a look on conda/anaconda (<a href="https://www.continuum.io/downloads" rel="nofollow">https://www.continuum.io/downloads</a>) : it is very powerful and i think it would better suit you than virtualenv: virtualenv would enable you to create a separate python environnement, but it would not install a newer version of Python.</p>
<p>Concerning 2, I am not an expert in Apache2, but I would have used apt-get instead of re-compiling apache. While compiling, you may need some dependancies to build the mod_wsgi module. So I think it is way more easy to use the pre-built packages from your ubuntu. </p>
| 0 | 2016-10-16T18:47:12Z | [
"python",
"apache",
"ubuntu",
"mod-wsgi"
] |
How to configure elasticsearch to use SSL with basic auth | 40,073,938 | <p>I am trying to deploy an app that uses Ramses (<a href="http://ramses.tech" rel="nofollow">http://ramses.tech</a>) on IBM Bluemix. Unfortunately, the app is crashing during the deploy process.
In the local.ini configuration file I have set the following:</p>
<pre><code># ElasticSearch
elasticsearch.hosts = xxxx.dblayer.com:9999
elasticsearch.http_auth = user:secret
elasticsearch.http.use_ssl = true
elasticsearch.verify_certs = true
elasticsearch.sniff = false
elasticsearch.index_name = my_api
elasticsearch.index.disable = false
elasticsearch.enable_refresh_query = false
elasticsearch.enable_aggregations = false
elasticsearch.enable_polymorphic_query = false
</code></pre>
<p>However when I attempt to deploy my app on ibm bluemix, I get the following error:</p>
<pre><code>2016-10-16T13:40:52.226-0400[DEA/64]OUTStarting app instance (index 0) with guid 30875156-21f2-4e49-b115-882ec3efc41a
2016-10-16T13:41:01.121-0400[App/0]ERR2016-10-16 17:41:01,120 INFO [nefertari_mongodb.signals][MainThread] signals.setup_es_signals_for: setup_es_signals_for: <class 'nefertari_mongodb.documents.ESBaseDocument'>
2016-10-16T13:41:01.130-0400[App/0]ERR2016-10-16 17:41:01,129 INFO [nefertari.json_httpexceptions][MainThread] json_httpexceptions.includeme: Include json_httpexceptions
2016-10-16T13:41:01.130-0400[App/0]ERR2016-10-16 17:41:01,129 INFO [ramses][MainThread] __init__.includeme: Parsing RAML
2016-10-16T13:41:01.125-0400[App/0]ERR2016-10-16 17:41:01,124 INFO [nefertari][MainThread] __init__.includeme: nefertari 0.7.0
2016-10-16T13:41:01.186-0400[App/0]ERR2016-10-16 17:41:01,185 INFO [ramses.generators][MainThread] generators.generate_models: Configuring model for route `schools`
2016-10-16T13:41:01.191-0400[App/0]ERR2016-10-16 17:41:01,190 INFO [ramses.utils][MainThread] utils.resource_schema: Searching for model schema
2016-10-16T13:41:01.191-0400[App/0]ERR2016-10-16 17:41:01,190 INFO [ramses.models][MainThread] models.setup_data_model: Generating model class `School`
2016-10-16T13:41:01.184-0400[App/0]ERR2016-10-16 17:41:01,183 INFO [ramses][MainThread] __init__.includeme: Starting models generation
2016-10-16T13:41:01.198-0400[App/0]ERR2016-10-16 17:41:01,198 INFO [ramses.utils][MainThread] utils.resource_schema: Searching for model schema
2016-10-16T13:41:01.200-0400[App/0]ERR2016-10-16 17:41:01,199 INFO [nefertari_mongodb.signals][MainThread] signals.setup_es_signals_for: setup_es_signals_for: <class 'mongoengine.base.metaclasses.User'>
2016-10-16T13:41:01.199-0400[App/0]ERR2016-10-16 17:41:01,198 INFO [ramses.models][MainThread] models.setup_data_model: Generating model class `User`
2016-10-16T13:41:01.203-0400[App/0]ERR2016-10-16 17:41:01,203 INFO [nefertari_mongodb.signals][MainThread] signals.setup_es_signals_for: setup_es_signals_for: <class 'mongoengine.base.metaclasses.School'>
2016-10-16T13:41:01.206-0400[App/0]ERR2016-10-16 17:41:01,205 INFO [nefertari.elasticsearch][MainThread] elasticsearch.setup: Including Elasticsearch. {'chunk_size': 500, 'index.disable': 'false', 'verify_certs': 'true', 'host': 'https://xxxx.dblayer.com:9999', 'enable_refresh_query': 'false', 'enable_aggregations': 'false', 'port': '443', 'index_name': 'quartolio_api', 'enable_polymorphic_query': 'false', 'hosts': 'xxxx.dblayer.com:9999', 'sniff': 'false', 'http_auth': 'user:secret'}
2016-10-16T13:41:01.205-0400[App/0]ERR2016-10-16 17:41:01,204 INFO [ramses.generators][MainThread] generators.generate_models: Configuring model for route `users`
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/elasticsearch/connection/http_urllib3.py", line 94, in perform_request
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/urllib3/connectionpool.py", line 384, in _make_request
2016-10-16T13:41:01.218-0400[App/0]ERR _stacktrace=sys.exc_info()[2])
2016-10-16T13:41:01.218-0400[App/0]ERR chunked=chunked)
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/httplib.py", line 1136, in getresponse
2016-10-16T13:41:01.218-0400[App/0]ERRTraceback (most recent call last):
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/httplib.py", line 453, in begin
2016-10-16T13:41:01.218-0400[App/0]ERR response = self.pool.urlopen(method, url, body, retries=False, headers=self.headers, **kw)
2016-10-16T13:41:01.218-0400[App/0]ERR httplib_response = conn.getresponse(buffering=True)
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/urllib3/util/retry.py", line 251, in increment
2016-10-16T13:41:01.218-0400[App/0]ERR version, status, reason = self._read_status()
2016-10-16T13:41:01.218-0400[App/0]ERR2016-10-16 17:41:01,216 WARNI [elasticsearch][MainThread] base.log_request_fail: HEAD http://xxxx.dblayer.com:9999/my_api [status:N/A request:0.011s]
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/urllib3/connectionpool.py", line 594, in urlopen
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/httplib.py", line 417, in _read_status
2016-10-16T13:41:01.218-0400[App/0]ERR response.begin()
2016-10-16T13:41:01.218-0400[App/0]ERR raise six.reraise(type(error), error, _stacktrace)
2016-10-16T13:41:01.218-0400[App/0]ERR raise BadStatusLine(line)
2016-10-16T13:41:01.218-0400[App/0]ERRProtocolError: ('Connection aborted.', BadStatusLine("''",))
2016-10-16T13:41:01.221-0400[App/0]ERR return command.run()
2016-10-16T13:41:01.221-0400[App/0]ERR File "/home/vcap/app/.heroku/python/bin/pserve", line 11, in <module>
2016-10-16T13:41:01.221-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 247, in loadapp
2016-10-16T13:41:01.221-0400[App/0]ERR return loadapp(app_spec, name=name, relative_to=relative_to, **kw)
2016-10-16T13:41:01.221-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 272, in loadobj
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/urlmap.py", line 31, in urlmap_factory
2016-10-16T13:41:01.221-0400[App/0]ERR2016-10-16 17:41:01,221 ERROR [nefertari.json_httpexceptions][MainThread] json_httpexceptions.create_json_response: 400 BAD REQUEST: {"explanation": "('Connection aborted.', BadStatusLine(\"''\",))", "extra": {"data": "ConnectionError(('Connection aborted.', BadStatusLine(\"''\",))) caused by: ProtocolError(('Connection aborted.', BadStatusLine(\"''\",)))"}, "status_code": 400, "message": null, "timestamp": "2016-10-16T17:41:01Z", "title": "Bad Request"}
2016-10-16T13:41:01.222-0400[App/0]ERR val = callable(*args, **kw)
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/util.py", line 55, in fix_call
2016-10-16T13:41:01.221-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/scripts/pserve.py", line 328, in run
2016-10-16T13:41:01.221-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/scripts/pserve.py", line 58, in main
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 710, in create
2016-10-16T13:41:01.222-0400[App/0]ERR File "/home/vcap/app/quartolio_api/quartolio_api/__init__.py", line 14, in main
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 710, in create
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/config/__init__.py", line 755, in include
2016-10-16T13:41:01.222-0400[App/0]ERR **context.local_conf)
2016-10-16T13:41:01.221-0400[App/0]ERR global_conf=vars)
2016-10-16T13:41:01.221-0400[App/0]ERR sys.exit(main())
2016-10-16T13:41:01.221-0400[App/0]ERRSTACK BEGIN>>
2016-10-16T13:41:01.222-0400[App/0]ERR return fix_call(context.object, context.global_conf, **context.local_conf)
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 350, in get_app
2016-10-16T13:41:01.222-0400[App/0]ERR return func(*args, params=params, **kwargs)
2016-10-16T13:41:01.221-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/scripts/pserve.py", line 363, in loadapp
2016-10-16T13:41:01.222-0400[App/0]ERR return self.object_type.invoke(self)
2016-10-16T13:41:01.221-0400[App/0]ERR return loadobj(APP, uri, name=name, **kw)
2016-10-16T13:41:01.222-0400[App/0]ERR params=params)
2016-10-16T13:41:01.222-0400[App/0]ERR config.include('nefertari.elasticsearch')
2016-10-16T13:41:01.222-0400[App/0]ERR app = loader.get_app(app_name, global_conf=global_conf)
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 144, in invoke
2016-10-16T13:41:01.222-0400[App/0]ERR return context.create()
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/elasticsearch/transport.py", line 327, in perform_request
2016-10-16T13:41:01.222-0400[App/0]ERR cls.api.indices.exists([index_name])
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/json_httpexceptions.py", line 78, in __init__
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/elasticsearch.py", line 213, in create_index
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/util.py", line 55, in fix_call
2016-10-16T13:41:01.223-0400[App/0]ERR return loadapp(app_spec, name=name, relative_to=relative_to, **kw)
2016-10-16T13:41:01.222-0400[App/0]ERR name=name, global_conf=global_conf).create()
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/json_httpexceptions.py", line 67, in exception_response
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/config/__init__.py", line 755, in include
2016-10-16T13:41:01.222-0400[App/0]ERR c(configurator)
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/elasticsearch.py", line 69, in includeme
2016-10-16T13:41:01.222-0400[App/0]ERR return STATUS_MAP[status_code](**kw)
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/json_httpexceptions.py", line 26, in add_stack
2016-10-16T13:41:01.222-0400[App/0]ERR val = callable(*args, **kw)
2016-10-16T13:41:01.222-0400[App/0]ERR c(configurator)
2016-10-16T13:41:01.222-0400[App/0]ERR ES.create_index()
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/ramses/__init__.py", line 56, in includeme
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/elasticsearch.py", line 60, in perform_request
2016-10-16T13:41:01.223-0400[App/0]ERR **context.local_conf)
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/elasticsearch/client/indices.py", line 225, in exists
2016-10-16T13:41:01.222-0400[App/0]ERR create_json_response(self, **kw)
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 146, in invoke
2016-10-16T13:41:01.223-0400[App/0]ERR return loadobj(APP, uri, name=name, **kw)
2016-10-16T13:41:01.222-0400[App/0]ERR extra=dict(data=e))
2016-10-16T13:41:01.222-0400[App/0]ERR status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
2016-10-16T13:41:01.223-0400[App/0]ERR File "/home/vcap/app/.heroku/python/bin/pserve", line 11, in <module>
2016-10-16T13:41:01.222-0400[App/0]ERR msg += '\nSTACK BEGIN>>\n%s\nSTACK END<<' % add_stack()
2016-10-16T13:41:01.223-0400[App/0]ERRTraceback (most recent call last):
2016-10-16T13:41:01.224-0400[App/0]ERR c(configurator)
2016-10-16T13:41:01.222-0400[App/0]ERRSTACK END<<
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/scripts/pserve.py", line 328, in run
2016-10-16T13:41:01.223-0400[App/0]ERR global_conf=vars)
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/json_httpexceptions.py", line 58, in create_json_response
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 710, in create
2016-10-16T13:41:01.223-0400[App/0]ERR return command.run()
2016-10-16T13:41:01.223-0400[App/0]ERR val = callable(*args, **kw)
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/scripts/pserve.py", line 58, in main
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/scripts/pserve.py", line 363, in loadapp
2016-10-16T13:41:01.223-0400[App/0]ERR return self.object_type.invoke(self)
2016-10-16T13:41:01.223-0400[App/0]ERR return fix_call(context.object, context.global_conf, **context.local_conf)
2016-10-16T13:41:01.223-0400[App/0]ERR return context.create()
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/util.py", line 55, in fix_call
2016-10-16T13:41:01.224-0400[App/0]ERR extra=dict(data=e))
2016-10-16T13:41:01.223-0400[App/0]ERR return self.object_type.invoke(self)
2016-10-16T13:41:01.223-0400[App/0]ERR File "/home/vcap/app/quartolio_api/quartolio_api/__init__.py", line 14, in main
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/util.py", line 55, in fix_call
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/config/__init__.py", line 755, in include
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 144, in invoke
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 247, in loadapp
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 710, in create
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/ramses/__init__.py", line 56, in includeme
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/pyramid/config/__init__.py", line 755, in include
2016-10-16T13:41:01.224-0400[App/0]ERR config.include('nefertari.elasticsearch')
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 272, in loadobj
2016-10-16T13:41:01.224-0400[App/0]ERR ES.create_index()
2016-10-16T13:41:01.224-0400[App/0]ERR c(configurator)
2016-10-16T13:41:01.224-0400[App/0]ERRnefertari.json_httpexceptions.JHTTPBadRequest: ('Connection aborted.', BadStatusLine("''",))
2016-10-16T13:41:01.223-0400[App/0]ERR val = callable(*args, **kw)
2016-10-16T13:41:01.224-0400[App/0]ERR status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 350, in get_app
2016-10-16T13:41:01.223-0400[App/0]ERR config.include('ramses')
2016-10-16T13:41:01.223-0400[App/0]ERR app = loader.get_app(app_name, global_conf=global_conf)
2016-10-16T13:41:01.224-0400[App/0]ERR params=params)
2016-10-16T13:41:01.223-0400[App/0]ERR name=name, global_conf=global_conf).create()
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/elasticsearch.py", line 69, in includeme
2016-10-16T13:41:01.224-0400[App/0]ERR return func(*args, params=params, **kwargs)
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/elasticsearch/transport.py", line 327, in perform_request
2016-10-16T13:41:01.224-0400[App/0]ERR cls.api.indices.exists([index_name])
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/elasticsearch.py", line 60, in perform_request
2016-10-16T13:41:01.218-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/urllib3/connectionpool.py", line 643, in urlopen
2016-10-16T13:41:01.222-0400[App/0]ERR return self.object_type.invoke(self)
2016-10-16T13:41:01.223-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/urlmap.py", line 31, in urlmap_factory
2016-10-16T13:41:01.222-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/paste/deploy/loadwsgi.py", line 146, in invoke
2016-10-16T13:41:01.218-0400[App/0]ERR2016-10-16 17:41:01,217 ERROR [nefertari.elasticsearch][MainThread] elasticsearch.perform_request: ('Connection aborted.', BadStatusLine("''",))
2016-10-16T13:41:01.222-0400[App/0]ERR config.include('ramses')
2016-10-16T13:41:01.223-0400[App/0]ERR sys.exit(main())
2016-10-16T13:41:01.224-0400[App/0]ERR File "/app/.heroku/python/lib/python2.7/site-packages/nefertari/elasticsearch.py", line 213, in create_index
2016-10-16T13:41:01.262-0400[App/0]OUT
2016-10-16T13:41:01.315-0400[DEA/64]ERRInstance (index 0) failed to start accepting connection
</code></pre>
<p>Based on the error, it looks like a connection is trying to be made to <a href="http://xxxx.dblayer.com:9999" rel="nofollow">http://xxxx.dblayer.com:9999</a> instead of https:// xxxx.dblayer.com:9999.</p>
<p>I have tried many different configurations:</p>
<ol>
<li><p>I tried setting <code>elasticsearch.host</code> and <code>elasticsearch.port</code>
instead of <code>elasticsearch.hosts</code> and I get an <code>Exception: Bad or
missing settings for elasticsearch. 'hosts'</code> from Nefertari.</p></li>
<li><p>I have tried setting <code>elasticsearch.hosts</code> with https:// prepended,
which results in a <code>ValueError: too many values to unpack</code> from
nefertari (it appears that it's trying to split using the colon as a
delimeter).</p></li>
<li><p>I have tried setting <code>elasticsearch.hosts</code> to be blank, or just a
colon surrounded by whitespace, while setting <code>elasticsearch.host</code>
and <code>elasticsearch.port</code> and I get <code>ValueError: need more than 0
values to unpack</code></p></li>
</ol>
<p>How do I configure elasticsearch to connect to my bluemix elasticsearch service?</p>
| 0 | 2016-10-16T18:31:49Z | 40,091,483 | <p>You will need to use the self-signed certificate provided as <code>ca_certificate_base64</code> in your VCAP_SERVICES credentials.</p>
<p>It is base64 encoded. You need to decode the key before using it, as shown in the sample application at <a href="https://github.com/IBM-Bluemix/compose-elasticsearch-helloworld-nodejs/blob/master/server.js#L56" rel="nofollow">https://github.com/IBM-Bluemix/compose-elasticsearch-helloworld-nodejs/blob/master/server.js#L56</a></p>
| 0 | 2016-10-17T16:36:06Z | [
"python",
"ssl",
"elasticsearch",
"ibm-bluemix",
"elasticsearch-py"
] |
Regex doesn't filter out the right text on datatime | 40,073,942 | <p>I have a string below:</p>
<pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM"
</code></pre>
<p>I created a regex to filter out the datetime portion:</p>
<pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4} \d{2}:\d{2} (AM|PM)"
</code></pre>
<p>I tested the regex in regex101.com and it works as expected, however, when running it in my python test script, it fails to give me the right text, can anyone help me fix it?</p>
<p>Using it this way:</p>
<pre><code>real_senton = re.findall(reg_datetime, senton)
print real_senton
</code></pre>
<p>Produces this result (<a href="https://i.stack.imgur.com/Si8U8.jpg" rel="nofollow">here is the screenshot</a>):</p>
<pre><code>[('Friday', 'June', 'PM')]
</code></pre>
<p>Thank you very much.</p>
| 1 | 2016-10-16T18:32:08Z | 40,074,035 | <p>If you want regex to return the all those values you have to make sure that they're in separate groups, like so:</p>
<pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) (\d{1,2}), (\d{4}) (\d{2}):(\d{2}) (AM|PM)"
</code></pre>
| 0 | 2016-10-16T18:40:03Z | [
"python",
"regex"
] |
Regex doesn't filter out the right text on datatime | 40,073,942 | <p>I have a string below:</p>
<pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM"
</code></pre>
<p>I created a regex to filter out the datetime portion:</p>
<pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4} \d{2}:\d{2} (AM|PM)"
</code></pre>
<p>I tested the regex in regex101.com and it works as expected, however, when running it in my python test script, it fails to give me the right text, can anyone help me fix it?</p>
<p>Using it this way:</p>
<pre><code>real_senton = re.findall(reg_datetime, senton)
print real_senton
</code></pre>
<p>Produces this result (<a href="https://i.stack.imgur.com/Si8U8.jpg" rel="nofollow">here is the screenshot</a>):</p>
<pre><code>[('Friday', 'June', 'PM')]
</code></pre>
<p>Thank you very much.</p>
| 1 | 2016-10-16T18:32:08Z | 40,074,053 | <p>The problem is that the match results that are returned to you are the ones between '(' ')' which are called group match.
Thus, your regex should look like this to return all the data: </p>
<pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) (\d{1,2}), (\d{4}) (\d{2}:\d{2}) (AM|PM)"
</code></pre>
<p>You can see <a href="https://regex101.com/r/caY6xP/1" rel="nofollow">here</a> the demo. Or if you want all the date in one single string, just add all the regex between '(' ')' </p>
| 0 | 2016-10-16T18:41:33Z | [
"python",
"regex"
] |
Regex doesn't filter out the right text on datatime | 40,073,942 | <p>I have a string below:</p>
<pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM"
</code></pre>
<p>I created a regex to filter out the datetime portion:</p>
<pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4} \d{2}:\d{2} (AM|PM)"
</code></pre>
<p>I tested the regex in regex101.com and it works as expected, however, when running it in my python test script, it fails to give me the right text, can anyone help me fix it?</p>
<p>Using it this way:</p>
<pre><code>real_senton = re.findall(reg_datetime, senton)
print real_senton
</code></pre>
<p>Produces this result (<a href="https://i.stack.imgur.com/Si8U8.jpg" rel="nofollow">here is the screenshot</a>):</p>
<pre><code>[('Friday', 'June', 'PM')]
</code></pre>
<p>Thank you very much.</p>
| 1 | 2016-10-16T18:32:08Z | 40,074,145 | <p>Function <a href="https://docs.python.org/2/library/re.html#re.findall" rel="nofollow"><code>re.findall</code></a> does the following:</p>
<blockquote>
<p>Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.</p>
</blockquote>
<p>So, if there are groups, it returns the groups. A <em>group</em> is anything in the regular expression enclosed in parenthesis.</p>
<h2>solution 1</h2>
<p>To get every item separately, put everything into parentesis:</p>
<pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), "\
"(January|February|March|April|May|June|July|August|September|October|November|December)"\
" (\d{1,2}), (\d{4}) (\d{2}):(\d{2}) (AM|PM)"
</code></pre>
<p>Then will <code>re.findall(reg_datetime, senton)</code> return:</p>
<pre><code>[('Friday', 'June', '18', '2010', '12', '57', 'PM')]
</code></pre>
<h2>solution 2</h2>
<p>Alternatively, put everything into one big group:</p>
<pre><code>reg_datetime = "((Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), "\
"(January|February|March|April|May|June|July|August|September|October|November|December)"\
" \d{1,2}, \d{4} \d{2}:\d{2} (AM|PM))"
</code></pre>
<p>Now the big group is returned as well:</p>
<pre><code>[('Friday, June 18, 2010 12:57 PM', 'Friday', 'June', 'PM')]
</code></pre>
<h2>solution 3</h2>
<p>Or change the existing grops into non-capturing groups (syntax <code>(?:...)</code>)</p>
<pre><code>reg_datetime = "(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), "\
"(?:January|February|March|April|May|June|July|August|September|October|November|December)"\
" \d{1,2}, \d{4} \d{2}:\d{2} (?:AM|PM)"
</code></pre>
<p>Result:</p>
<pre><code>['Friday, June 18, 2010 12:57 PM']
</code></pre>
<h2>solution 4</h2>
<p>Or don't use <code>findall</code> at all. Use <a href="https://docs.python.org/2/library/re.html#re.search" rel="nofollow"><code>re.search</code></a>. It returns a <a href="https://docs.python.org/2/library/re.html#match-objects" rel="nofollow"><code>Match</code></a> object, which gives you more options. With the original <code>reg_datetime</code> it works this way:</p>
<pre><code>>>> m = re.search(reg_datetime, senton)
>>> m.group(0)
'Friday, June 18, 2010 12:57 PM'
>>> m.group(1)
'Friday'
>>> m.group(2)
'June'
>>> m.group(3)
'PM'
</code></pre>
| 1 | 2016-10-16T18:50:53Z | [
"python",
"regex"
] |
Regex doesn't filter out the right text on datatime | 40,073,942 | <p>I have a string below:</p>
<pre><code>senton = "Sent: Friday, June 18, 2010 12:57 PM"
</code></pre>
<p>I created a regex to filter out the datetime portion:</p>
<pre><code>reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4} \d{2}:\d{2} (AM|PM)"
</code></pre>
<p>I tested the regex in regex101.com and it works as expected, however, when running it in my python test script, it fails to give me the right text, can anyone help me fix it?</p>
<p>Using it this way:</p>
<pre><code>real_senton = re.findall(reg_datetime, senton)
print real_senton
</code></pre>
<p>Produces this result (<a href="https://i.stack.imgur.com/Si8U8.jpg" rel="nofollow">here is the screenshot</a>):</p>
<pre><code>[('Friday', 'June', 'PM')]
</code></pre>
<p>Thank you very much.</p>
| 1 | 2016-10-16T18:32:08Z | 40,074,146 | <p>without change <code>reg_datetime</code> and only use <code>search</code> </p>
<pre><code>import re
senton = "Sent: Friday, June 18, 2010 12:57 PM"
reg_datetime = "(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (January|February|March|April|May|June|July|August|September|October|November|December) \d{1,2}, \d{4} \d{2}:\d{2} (AM|PM)"
l = re.search(reg_datetime,senton,re.M|re.I)
print l.group()
</code></pre>
<p>and run:</p>
<pre><code>$ python file.py
Friday, June 18, 2010 12:57 PM
$
</code></pre>
| 1 | 2016-10-16T18:50:53Z | [
"python",
"regex"
] |
Models in Python Django not working for Many to Many relationships | 40,073,984 | <p>I am trying to create the proper Django model that could fit the following reqs:</p>
<p>Person Class has 1 to many relations with the Address Class</p>
<p>Person Class has many to many relations with the Group Class</p>
<p>Book Class contains the collections of the Persons and the Groups</p>
<p>This is my code:</p>
<pre><code>class Person(models.Model):
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=20)
def __str__(self):
return self.first_name+ ' - ' + self.last_name
class Address(models.Model):
person = models.ForeignKey(Person)
address_line = models.CharField(max_length=200)
def __str__(self):
return self.address_line
class Group(models.Model):
group_name = models.CharField(max_length=12)
persons = models.ManyToManyField(Person)
def __str__(self):
return self.group_name
class Book(models.Model):
record_name = models.CharField(max_length=12)
person = models.ForeignKey(Person )
group = models.ForeignKey(Group )
def __str__(self):
return self.record_name
</code></pre>
<p>However it's not correct:
1) A Group can now contain multiple Persons but the Persons do not contain any Group.
I am not sure if I should add to the Person class the following code:</p>
<pre><code>groups = models.ManyToManyField(Group)
</code></pre>
<p>2) The Book class now contains only 1 record of Person & Group per Book record. </p>
<p>3) When I added the Foreign Keys to the models, I removed
on_delete tag:</p>
<pre><code>person = models.ForeignKey(Person, on_delete=models.CASCADE())
</code></pre>
<p>because it does not compile it, asking for some params.</p>
<p>I know how to make all this for C#, but I am a kinda stucked with this simple task in Python/Django.</p>
| 1 | 2016-10-16T18:35:21Z | 40,074,153 | <p>1) The ManyToMany field should appear only in one of the models, and by looks of things you probably want it in the Person model.
Its important to understand that the data about the ManyToMany field is saved in a differant table. Django only allows this field to be visable through buth models (so basiclly, choose where it is move convinient).</p>
<p>2)By the look of your structure I will suggest you use a ManyToMany field <strong>through</strong> a different table. here is an example:</p>
<pre><code>class Activity(models.Model):
name = models.CharField(max_length=140)
description = models.TextField(blank=True, null=True)
class Route(models.Model):
title = models.CharField(max_length=140)
description = models.TextField()
activities_meta = models.ManyToManyField(Activity, through = 'RouteOrdering')
class RouteOrdering(models.Model):
route = models.ForeignKey(Route, on_delete=models.CASCADE)
activity = models.ForeignKey(Activity, on_delete=models.CASCADE, related_name='activita')
day = models.IntegerField()
order = models.IntegerField(default=0)
</code></pre>
<p>that way the data is binded to the ManyToMany field</p>
| 1 | 2016-10-16T18:51:16Z | [
"python",
"django",
"django-models"
] |
Why this for loop in Python3 return dictionary value split in letters? | 40,073,995 | <p>I am lerning Python from a book and there is this example. I rewrote example as it is shown in book, but the result differs from books.</p>
<p><strong>This is the code</strong></p>
<pre><code>favorite_languages = {
'jen': ['python','ruby'],
'bil': 'c',
'edward': ['ruby','haskell'],
'phil': 'python',
'marcis': ['octave','python','mysql'],
}
for name, languages in favorite_languages.items():
print("\n" +name.title()+"'s favorite language(s) are:")
for language in languages:
print("\t" + language.title())
</code></pre>
<p>This is the consoles printed result. Problem as you see are in the way console prints value 'python' for Phil's sentence.</p>
<p><a href="https://i.stack.imgur.com/qgyQq.png" rel="nofollow"><img src="https://i.stack.imgur.com/qgyQq.png" alt="Console spells word Python by letters in each line"></a></p>
<p>I have tried other IDLE and the same result!<br>
<strong>Why does name python is spelled by letters in each line for Phil's example? Is it an some sort of Python language or my code problem?</strong></p>
| 0 | 2016-10-16T18:36:51Z | 40,074,036 | <p>Because line:</p>
<pre><code>for language in languages:
</code></pre>
<p>is iterating over string 'python' and giving you single letters, if you write it as ['python'] it'll iterate over list and write it as one word</p>
| 3 | 2016-10-16T18:40:10Z | [
"python",
"python-3.x",
"for-loop",
"dictionary"
] |
Access kivy popup parent | 40,074,004 | <p>The way popups are implemented in kivy, the popup seems to get attached to the window and not the parent object which created the popup. Popup comes with self.dismiss() to close the popup but I can't figure out any way to access the 'parent' object since despite creating the popup, it seems to exist outside of it.</p>
<p>Example snippets:</p>
<pre><code>class StartButton(ActionButton)
def on_release(self):
self.popup = StartPop(id='popid')
self.popup.open()
class StartPop(Popup):
def close(self):
self.dismiss()
def start(self):
print(self)
print(self.parent)
</code></pre>
<p>The result of the print commands is</p>
<pre><code><__main__.StartPop object at 0x00000000037BBCE0>
<kivy.core.window.window_sdl2.WindowSDL object at 0x000000000373B0B0>
</code></pre>
<p>So rather than the parent being StartButton, whose parent I would also expect to access etc. the parent is the Window. </p>
<p>I don't see how I could bind any function that thus interact with the widget I used to create the popup from. I need to be able to get the parent object and its parents to do things based on what I click within the popup but I can't figure out how this could be implemented.</p>
<p>In the .kv file</p>
<pre><code><StartPop>:
title: 'Popup'
auto_dismiss: True
size_hint: None,None
size: 400,250
BoxLayout:
orientation: 'vertical'
Label:
text: 'sample text here'
text_size: self.size
halign: 'center'
valign: 'middle'
BoxLayout:
orientation: 'horizontal'
Button:
size_hint: 1,0.5
text: 'Cancel'
on_release: root.close()
Button:
size_hint: 1,0.5
text: 'Start Testing'
on_release: root.start()
</code></pre>
| 2 | 2016-10-16T18:37:28Z | 40,074,127 | <p>It's implemented like that because it needs to be hidden most of the time, yet still active, so that <code>open()</code> could be called. Kivy doesn't seem to handle hiding of the widgets other way that actually <em>removing</em> it and keeping a reference somewhere (there's no <code>hide</code> property), so maybe even because of that. Or because it was easier to implement it this way. It's not bad implementation however and the way OO programming works you can do some fancy stuff with it too. The thing you want can be handled simply with <code>kwargs</code> in <code>__init__</code>:</p>
<p>Inherit from Popup and get a custom keyword argument:</p>
<pre><code>class StartPop(Popup):
def __init__(self, **kwargs):
self.caller = kwargs.get('caller')
super(StartPop, self).__init__(**kwargs)
print self.caller
</code></pre>
<p>Then create an instance of that custom <code>Popup</code> and set the parent:</p>
<pre><code>pop = StartPop(caller=self)
pop.open()
</code></pre>
<p>The <code>caller</code> keyword isn't limited only to Kivy widgets. Put there any object you want to do stuff with and you can then access it inside the <code>StartPop</code> object via <code>self.caller</code></p>
| 2 | 2016-10-16T18:49:37Z | [
"python",
"python-2.7",
"popup",
"kivy"
] |
Python Trouble getting cursor position (x, y) on desktop | 40,074,054 | <p>I've been looking for ways to find my cursor position and put it on to two variables, x and y. But most answers are outdated and i can't seem to make them work. I would rather if it is in pythons standard librarys or pywinauto. I would also prefer in python 2.7. Thanks.</p>
| 3 | 2016-10-16T18:41:46Z | 40,074,079 | <p>You can do this with <a href="https://pypi.python.org/pypi/PyMouse" rel="nofollow">PyMouse</a>.</p>
<pre><code>>>> import pymouse;
>>> mouse = pymouse.PyMouse()
>>> mouse.position()
(288.046875, 396.15625)
>>> mouse.position()
(0.0, 0.0)
>>> mouse.position()
(1439.99609375, 861.2890625)
</code></pre>
| 2 | 2016-10-16T18:44:42Z | [
"python",
"windows-7",
"cursor-position",
"pywinauto"
] |
Target WSGI script cannot be loaded as Python module + no module named Django | 40,074,088 | <p><em>I know that the question has already been asked here. I've read tons of answers, but nothing helped.</em></p>
<p>I'm using virtualenv (/root/eb-virt); my Django project is called mediar. All public files are stored in /var/www/html/xxx.com/public_html/</p>
<p>From error log:</p>
<pre><code>[Sun Oct 16 18:40:11.737747 2016] [:error] [pid 27659] [client 128.75.240.205:60486] mod_wsgi (pid=27659): Target WSGI script '/var/www/html/xxx.com/django.wsgi' cannot be loaded as Python module.
[Sun Oct 16 18:40:11.737808 2016] [:error] [pid 27659] [client 128.75.240.205:60486] mod_wsgi (pid=27659): Exception occurred processing WSGI script '/var/www/html/xxx.com/django.wsgi'.
[Sun Oct 16 18:40:11.745983 2016] [:error] [pid 27659] [client 128.75.240.205:60486] Traceback (most recent call last):
[Sun Oct 16 18:40:11.746153 2016] [:error] [pid 27659] [client 128.75.240.205:60486] File "/var/www/html/xxx.com/django.wsgi", line 9, in <module>
[Sun Oct 16 18:40:11.746165 2016] [:error] [pid 27659] [client 128.75.240.205:60486] import django.core.handlers.wsgi
[Sun Oct 16 18:40:11.746191 2016] [:error] [pid 27659] [client 128.75.240.205:60486] ImportError: No module named 'django'
</code></pre>
<p>My apache2.conf:</p>
<pre><code>Mutex file:${APACHE_LOCK_DIR} default
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 5
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
Include ports.conf
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
#<Directory /srv/>
# Options Indexes FollowSymLinks
# AllowOverride None
# Require all granted
#</Directory>
AccessFileName .htaccess
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf
<IfModule mpm_prefork_module>
StartServers 4
MinSpareServers 20
MaxSpareServers 40
MaxClients 200
MaxRequestsPerChild 4500
</IfModule>
LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so
WSGIScriptAlias / /var/www/html/xxx.com/public_html/mediar/mediar/wsgi.py
WSGIPythonPath /var/www/html/xxx.com/public_html:/root/eb-virt/lib/python3.4/site-packages/
<Directory /var/www/html/xxx.com/public_html/mediar/mediar/>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
</code></pre>
<p>My xxx.com.conf:</p>
<pre><code><VirtualHost *:80>
ServerAdmin xxx@xxx.com
ServerName xxx.com
ServerAlias www.xxx.com
# Index file and Document Root (where the public files are located)
DirectoryIndex index.html index.php
DocumentRoot /var/www/html/xxx.com/public_html
# Log file locations
LogLevel warn
ErrorLog /var/www/html/xxx.com/log/error.log
CustomLog /var/www/html/xxx.com/log/access.log combined
WSGIScriptAlias / /var/www/html/xxx.com/django.wsgi
</VirtualHost>
</code></pre>
<p>And, finally, my django.wsgi:</p>
<pre><code>#!/usr/bin/python
import os, sys
PROJECT_ROOT = '/var/www/html/xxx.com/'
sys.path.append(PROJECT_ROOT)
os.environ['DJANGO_SETTINGS_MODULE'] = 'mediar.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code></pre>
<p>I've tried </p>
<pre><code>$ sudo apt-get remove libapache2-mod-python libapache2-mod-wsgi
$ sudo apt-get install libapache2-mod-wsgi-py3
</code></pre>
<p>, it didn't help. </p>
<p>What should I do?</p>
| 0 | 2016-10-16T18:45:36Z | 40,074,311 | <p>I would first try using the right python shebang in your wsgi file. Shouldnât it be something like the following?</p>
<pre><code>#!/root/eb-virt/bin/python
</code></pre>
<p>And then the second thing would be to explicitly add the virtualenv to the <code>sys.path</code> append in the wsgi file</p>
<pre><code>sys.path.append('/root/eb-virt/lib/python3.4/site-packages')
</code></pre>
| 0 | 2016-10-16T19:07:25Z | [
"python",
"django",
"apache",
"mod-wsgi"
] |
How to improve distance function in python | 40,074,155 | <p>I am trying to do a classification exercise on email docs (strings containing words). </p>
<p>I defined the distance function as following:</p>
<pre><code>def distance(wordset1, wordset2):
if len(wordset1) < len(wordset2):
return len(wordset2) - len(wordset1)
elif len(wordset1) > len(wordset2):
return len(wordset1) - len(wordset2)
elif len(wordset1) == len(wordset2):
return 0
</code></pre>
<p>However, the accuracy in the end is pretty low (0.8). I guess this is because of the not so accurate distance function. How can I improve the function? Or what are other ways to calculate the "distance" between email docs?</p>
| 3 | 2016-10-16T18:51:18Z | 40,074,306 | <p>One common measure of similarity for use in this situation is the <a href="https://nickgrattan.wordpress.com/2014/02/18/jaccard-similarity-index-for-measuring-document-similarity/" rel="nofollow">Jaccard similarity</a>. It ranges from 0 to 1, where 0 indicates complete dissimilarity and 1 means the two documents are identical. It is defined as </p>
<pre><code>wordSet1 = set(wordSet1)
wordSet2 = set(wordSet2)
sim = len(wordSet1.intersection(wordSet2))/len(wordSet1.union(wordSet2))
</code></pre>
<p>Essentially, it is the ratio of the intersection of the sets of words to the ratio of the union of the sets of words. This helps control for emails that are of different sizes while still giving a good measure of similarity. </p>
| 2 | 2016-10-16T19:06:49Z | [
"python",
"distance",
"knn"
] |
How to improve distance function in python | 40,074,155 | <p>I am trying to do a classification exercise on email docs (strings containing words). </p>
<p>I defined the distance function as following:</p>
<pre><code>def distance(wordset1, wordset2):
if len(wordset1) < len(wordset2):
return len(wordset2) - len(wordset1)
elif len(wordset1) > len(wordset2):
return len(wordset1) - len(wordset2)
elif len(wordset1) == len(wordset2):
return 0
</code></pre>
<p>However, the accuracy in the end is pretty low (0.8). I guess this is because of the not so accurate distance function. How can I improve the function? Or what are other ways to calculate the "distance" between email docs?</p>
| 3 | 2016-10-16T18:51:18Z | 40,075,652 | <p>You didn't mention the type of <code>wordset1</code> and <code>wordset2</code>. I'll assume they are both <code>strings</code>.</p>
<p>You defined your distance as the word counting and got a bad score. It's obvious text length is not a good dissimilarity measure: two emails with different sizes can talk about the same thing, while two emails of same size be talking about completely different things.</p>
<p>So, as suggested above, you could try and check for SIMILAR WORDS instead:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def distance(wordset1, wordset2):
wordset1 = set(wordset1.split())
wordset2 = set(wordset2.split())
common_words = wordset1 & wordset2
if common_words:
return 1 / len(common_words)
else:
# They don't share any word. They are infinitely different.
return np.inf
</code></pre>
<p>The problem with that is that two big emails are more likely to share words than two small ones, and this metric would favor those, making them "more similar to each other" in comparison to the small ones. How do we solve this? Well, we normalize the metric somehow:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def distance(wordset1, wordset2):
wordset1 = set(wordset1.split())
wordset2 = set(wordset2.split())
common_words = wordset1 & wordset2
if common_words:
# The distance, normalized by the total
# number of different words in the emails.
return 1 / len(common_words) / (len(wordset1 | wordset2))
else:
# They don't share any word. They are infinitely different.
return np.inf
</code></pre>
<p>This seems cool, but completely ignores the FREQUENCY of the words. To account for this, we can use the <a href="https://en.wikipedia.org/wiki/Bag-of-words_model" rel="nofollow">Bag-of-words</a> model. That is, create a list of all possible words and histogram their appearance in each document. Let's use <a href="http://scikit-learn.org/stable/modules/feature_extraction.html" rel="nofollow">CountVectorizer</a> implementation from scikit-learn to make our job eaiser:</p>
<pre class="lang-py prettyprint-override"><code>from sklearn.feature_extraction.text import CountVectorizer
def distance(wordset1, wordset2):
model = CountVectorizer()
X = model.fit_transform([wordset1, wordset2]).toarray()
# uses Euclidean distance between bags.
return np.linalg.norm(X[0] - X[1])
</code></pre>
<p>But now consider two pairs of emails. The emails in the first pair are composed by perfectly written English, full of "small" words (e.g. <code>a</code>, <code>an</code>, <code>is</code>, <code>and</code>, <code>that</code>) necessary for it to be grammatically correct. The emails in the second pair are different: only containing the keywords, it's extremely dry. You see, chances are the first pair will be more similar than the second one. That happens because we are currently accounting for all words the same, while we should be prioritizing the MEANINGFUL words in each text. To do that, let's use <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" rel="nofollow">term frequencyâinverse document frequency</a>. Luckly, there's a very similar implementation in scikit-learn:</p>
<pre class="lang-py prettyprint-override"><code>from sklearn.feature_extraction.text import TfidfVectorizer
def distance(wordset1, wordset2):
model = TfidfVectorizer()
X = model.fit_transform([wordset1, wordset2]).toarray()
similarity_matrix = X.dot(X.T)
# The dissimilarity between samples wordset1 and wordset2.
return 1-similarity_matrix[0, 1]
</code></pre>
<p>Read more about this in this <a href="http://stackoverflow.com/questions/8897593/similarity-between-two-text-documents">question</a>. Also, duplicate?</p>
<p>You should now have a fairly good accuracy. Try it out. If it's still not as good as you want, then we have to go deeper... (get it? Because... Deep-learning). The first thing is that we need either a dataset to train over or an already trained model. That's required because networks have many parameters that MUST be adjusted in order to provide useful transformations.</p>
<p>What's been missing so far is UNDERSTANDING. We histogrammed the words, striping them from any context or meaning. Instead, let's keep them where they are and try to recognize blocks of patterns. How can this be done?</p>
<ol>
<li>Embed the words into numbers, which will deal with the different sizes of words.</li>
<li>Pad every number (word embed) sequence to a single length.</li>
<li>Use convolutional networks to extract meaninful features from sequences.</li>
<li>Use fully-connected networks to project the features extracted to a space that minimizes the distance between similar emails and maximizes the distance between non-similar ones.</li>
</ol>
<p>Let's use <a href="https://keras.io/" rel="nofollow">Keras</a> to simply our lives. It should look something like this:</p>
<pre class="lang-py prettyprint-override"><code># ... imports and params definitions
model = Sequential([
Embedding(max_features,
embedding_dims,
input_length=maxlen,
dropout=0.2),
Convolution1D(nb_filter=nb_filter,
filter_length=filter_length,
border_mode='valid',
activation='relu',
subsample_length=1),
MaxPooling1D(pool_length=model.output_shape[1]),
Flatten(),
Dense(256, activation='relu'),
])
# ... train or load model weights.
def distance(wordset1, wordset2):
global model
# X = ... # Embed both emails.
X = sequence.pad_sequences(X, maxlen=maxlen)
y = model.predict(X)
# Euclidean distance between emails.
return np.linalg.norm(y[0]-y[1])
</code></pre>
<p>There's a practical example on sentence processing which you can check <a href="https://github.com/fchollet/keras/blob/master/examples/imdb_cnn.py" rel="nofollow">Keras github repo</a>. Also, someone solves this exact same problem using a siamese recurrent network in this <a href="http://stackoverflow.com/questions/39289050/sentence-similarity-using-keras">stackoverflow question</a>.</p>
<p>Well, I hope this gives you some direction. :-)</p>
| 1 | 2016-10-16T21:24:22Z | [
"python",
"distance",
"knn"
] |
"TypeError: 'str' does not support the buffer interface" when writing to a socket | 40,074,315 | <pre><code>import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host, port))
filename = input("Filename? -> ")
if filename != 'q':
s.send(filename)
data = s.recv(1024)
if data[:6] == 'EXISTS':
filesize = long(data[6:])
message = input("File Exists, " + str(filesize) +\
"Bytes, download? (Y/N) -> ")
if message == 'Y':
s.send('OK')
f = open('new_' + filename, 'wb')
data = s.recv(1024)
totalRecv = len(data)
f.write(data)
while totalRecv < filesize:
data = s.recv(1024)
totalRecv += len(data)
f.write(data)
print("{0:.2f}".format((totalRecv/float(filesize))*100)+\
"% Done")
print("Download complete!")
else:
print("File doedn't exist!")
s.close()
if __name__ == '__main__':
Main()
</code></pre>
<p>The above python code is giving me this error: </p>
<pre class="lang-none prettyprint-override"><code>File "C:/Users/Mario/Networking/File Trasfering/fileClient.py", line 12, in Main
s.send(filename)
TypeError: 'str' does not support the buffer interface
</code></pre>
| 0 | 2016-10-16T19:07:31Z | 40,074,398 | <p>Python 3 makes a clean distinction between text strings (in the unicode character set, but conceptually independent of any encoding) and sequences of bytes. To write text to a file or socket, it must be "encoded" using a suitable encoding. In your case, you could use </p>
<pre><code>s.send(bytes(filename, encoding="..."))
</code></pre>
<p>or the equivalent</p>
<pre><code>s.send(filename.encode(encoding="..."))
</code></pre>
<p>Literal strings can simply be written as byte strings, e.g.,</p>
<pre><code>s.send(b'OK')
</code></pre>
| 0 | 2016-10-16T19:16:17Z | [
"python",
"sockets",
"python-3.x",
"networking"
] |
Is it possible to run program in python with additional HTTP server in infinite loop? | 40,074,378 | <p>I want to run program in infinite loop wich handles GPIO in raspberry PI and gets requests in infinite loop (as HTTP server). Is it possible? I tried Flask framework, but infinite loop waits for requests and then my program is executed. </p>
| 0 | 2016-10-16T19:14:17Z | 40,074,663 | <p>If I were to face with a problem like this right now, I wold do this:</p>
<p>1) First I'd try figuring out if I can use the event loop of the web framework to execute the code communicating with raspberry-pi asynchronously (i.e. inside of the event handlers).</p>
<p>2) If I failed to find a web framework extensible enough to do what I need or if it turned out that the raspberry-pi part can't be done asynchronously (e.g. it is taking to long to execute), I would figure out what is the difference between threads and processes in python, which of the two can I use in my specific situation and what tools can help me with that.</p>
<p>This answer is as specific as the question (at the time of writting).</p>
| 0 | 2016-10-16T19:43:05Z | [
"python",
"raspberry-pi"
] |
Python Split Variable Output to Multiple Variables | 40,074,385 | <p>First, I apologize for my ignorance here as I'm very new to Python and I may say things that really don't make sense.</p>
<p>I'm using the <code>youtube.search.list</code> API to create a variable <code>search_response</code>. This variable outputs the data on all searched videos in JSON format (I believe it's JSON anyways).</p>
<p>The search API is limited to 50 results per page but I've been able to use pagination to return up to 550 results (which is adequate for what I'm doing).</p>
<p>The <code>search.list</code> only provides me with details like the video title, date posted, video ID, etc. However, I'm hoping to access the view, like, and dislike counts for each video as well.</p>
<p>Using the <code>videos.list</code> API I have been able to pull in these variables (view, like, dislike) but it seems to be capped at 50 results as well and provides no pagination option.</p>
<p><a href="https://drive.google.com/open?id=0B-CXsNw4ZWO0Mm80clJqbDg3dkk" rel="nofollow">Here is a link</a> to the file in Jupyter Notebook (also attaching in .py).</p>
<p>So I'm thinking that if I can separate the JSON file (<code>search_response</code>) into segments of 50 posts I should be to run it 10 times and download views, likes, and dislikes for all videos. However, I have no idea how to separate the output of my <code>search_response</code> variable and appreciate any thoughts or suggestions on this!</p>
<p><strong>To summarize this issue:</strong></p>
<ul>
<li>I have a variable <code>search_response</code> outputting, in JSON format, hundreds of individual sections (one for each video)</li>
<li>The <code>videos.list</code> API to gather detailed stats (view, dis/like count) has a limit of 50 requests</li>
<li>I'm looking for a way to separate the <code>search_response</code> output into multiple variables of 50 sections each to run individually in the API</li>
</ul>
<p><strong>Code Used:</strong>
<em>Gather Data</em></p>
<pre><code>from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
DEVELOPER_KEY = "REPLACE ME"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def fetch_all_youtube_videos(channelId):
youtube = build(YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY)
res = youtube.search().list(
q="",
part="id,snippet",
channelId=channelId,
maxResults=50,
).execute()
nextPageToken = res.get('nextPageToken')
while ('nextPageToken' in res):
nextPage = youtube.search().list(
part="id,snippet",
channelId=channelId,
maxResults="50",
pageToken=nextPageToken
).execute()
res['items'] = res['items'] + nextPage['items']
if 'nextPageToken' not in nextPage:
res.pop('nextPageToken', None)
else:
nextPageToken = nextPage['nextPageToken']
return res
if __name__ == '__main__':
search_response = fetch_all_youtube_videos("UCp0hYYBW6IMayGgR-WeoCvQ")
videos = []
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos.append("%s (%s)" % (search_result["snippet"]["title"],
search_result["id"]["videoId"]))
</code></pre>
<p><strong>Code Used:</strong>
<em>Add Detailed Stats</em></p>
<pre><code>youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
videos = {}
for search_result in search_response.get("items", []):
if search_result["id"]["kind"] == "youtube#video":
videos[search_result["id"]["videoId"]] = search_result["snippet"]["title"]
video_ids_list = ','.join(videos.keys())
video_list_stats = youtube.videos().list(
id=video_ids_list,
part='id,statistics'
).execute()
</code></pre>
<p><strong>Ideal Output:</strong><em>This output corresponds to the first 50 etag sections (only have 25 or so displayed here because of character limits on this website but should be 50 sections) of the</em> <code>search_response</code> <em>variable and could be called</em> <code>search_response1</code> <em>where</em> <code>search_response2</code> <em>could encompass etag sections 51-100 and so on.</em></p>
<pre><code> search_response1 = {'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/hsQmFEqp1R_glFpcQnpnOLbbxCg"',
'id': {'kind': 'youtube#video', 'videoId': 'd8kCTPPwfpM'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "This incredible duo teamed up to perform an original song for Ellen! They may not have had a lot of rehearsal, but it's clear that this is one musical combo it ...",
'liveBroadcastContent': 'none',
'publishedAt': '2012-02-21T14:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/d8kCTPPwfpM/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/d8kCTPPwfpM/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/d8kCTPPwfpM/mqdefault.jpg',
'width': 320}},
'title': 'Taylor Swift and Zac Efron Sing a Duet!'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/LeKypRrnWWD6mRhK1wATZB5UQGo"',
'id': {'kind': 'youtube#video', 'videoId': '-l2KPjQ2lJA'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Harry, Liam, Louis and Niall played a round of Ellen's revealing game. How well do you know the guys of One Direction?",
'liveBroadcastContent': 'none',
'publishedAt': '2015-11-18T14:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/-l2KPjQ2lJA/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/-l2KPjQ2lJA/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/-l2KPjQ2lJA/mqdefault.jpg',
'width': 320}},
'title': 'Never Have I Ever with One Direction'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/qm7jX3gngQBYS7xv9sROxTpUtDU"',
'id': {'kind': 'youtube#video', 'videoId': 'Jr7bRw0NxQ4'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Ellen has always loved giving her guests a good thrill, and she put together this montage of some of her favorite scares from over the years!',
'liveBroadcastContent': 'none',
'publishedAt': '2015-11-19T14:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/Jr7bRw0NxQ4/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/Jr7bRw0NxQ4/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/Jr7bRw0NxQ4/mqdefault.jpg',
'width': 320}},
'title': "Ellen's Never-Ending Scares"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/dWDEID-z2CI4P-eh62pmTxWq0uc"',
'id': {'kind': 'youtube#video', 'videoId': 't5jw3T3Jy70'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Kristen Bell loves sloths. You might even say she's obsessed with them. She told Ellen about what happened when her boyfriend, Dax Shepard, introduced her ...",
'liveBroadcastContent': 'none',
'publishedAt': '2012-01-31T03:18:55.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/t5jw3T3Jy70/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/t5jw3T3Jy70/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/t5jw3T3Jy70/mqdefault.jpg',
'width': 320}},
'title': "Kristen Bell's Sloth Meltdown"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/ZSOfmz-dGZ3R0LNJ2n1LLQ4hEjg"',
'id': {'kind': 'youtube#video', 'videoId': 'fC_Z5HlK9Pw'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "The two incredibly handsome and talented stars got hilariously honest while playing one of Ellen's favorite games.",
'liveBroadcastContent': 'none',
'publishedAt': '2016-05-18T13:00:04.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/fC_Z5HlK9Pw/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/fC_Z5HlK9Pw/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/fC_Z5HlK9Pw/mqdefault.jpg',
'width': 320}},
'title': 'Drake and Jared Leto Play Never Have\xa0I\xa0Ever'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/M9siwkGRaHrf5ELg2R1JceH2KmA"',
'id': {'kind': 'youtube#video', 'videoId': '4aKteL3vMvU'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'The amazing Adele belted out her hit song for the first time since her Grammy performance.',
'liveBroadcastContent': 'none',
'publishedAt': '2016-02-18T14:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/4aKteL3vMvU/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/4aKteL3vMvU/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/4aKteL3vMvU/mqdefault.jpg',
'width': 320}},
'title': "Adele Performs\xa0'All\xa0I\xa0Ask'"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/od24uJeVxDWErhRWWtsSKHuD9oQ"',
'id': {'kind': 'youtube#video', 'videoId': 'WOgKIlvjlQ8'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Ellen, Johnny Depp, Gwyneth Paltrow and Paul Bettany all played an incredibly revealing round of "Never Have I Ever." You won\'t believe what they revealed!',
'liveBroadcastContent': 'none',
'publishedAt': '2015-01-23T14:00:13.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/WOgKIlvjlQ8/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/WOgKIlvjlQ8/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/WOgKIlvjlQ8/mqdefault.jpg',
'width': 320}},
'title': 'Never Have I Ever'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/Wu5vxAyQ5QGl6uO7eIodYHjaqVI"',
'id': {'kind': 'youtube#video', 'videoId': '07nXzFPHiGU'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "The two music icons played a revealing game with Ellen. You won't believe their responses.",
'liveBroadcastContent': 'none',
'publishedAt': '2015-03-19T13:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/07nXzFPHiGU/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/07nXzFPHiGU/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/07nXzFPHiGU/mqdefault.jpg',
'width': 320}},
'title': 'Never Have I Ever with Madonna and Justin Bieber'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/Z8HWp7YAzQPWcodFthhbxOU3l2U"',
'id': {'kind': 'youtube#video', 'videoId': 'Wh8m4PYlSGY'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Ellen challenged Jennifer Lopez to a round of her fun and revealing game.',
'liveBroadcastContent': 'none',
'publishedAt': '2015-05-18T19:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/Wh8m4PYlSGY/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/Wh8m4PYlSGY/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/Wh8m4PYlSGY/mqdefault.jpg',
'width': 320}},
'title': 'J.Lo and Ellen Play Never Have I Ever'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/3B4UvmeCI4Y9UZC2f6kF09wpmW8"',
'id': {'kind': 'youtube#video', 'videoId': 'QJY5VVQsFZ0'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Adele sure can sing, but can she beat the clock? Watch what happened when Ellen challenged her to a game of 5 Second Rule!',
'liveBroadcastContent': 'none',
'publishedAt': '2016-02-24T14:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/QJY5VVQsFZ0/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/QJY5VVQsFZ0/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/QJY5VVQsFZ0/mqdefault.jpg',
'width': 320}},
'title': '5 Second Rule with Adele'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/mYDa0rUVIvzHCbQfJGRq2VeZ2so"',
'id': {'kind': 'youtube#video', 'videoId': 'vEVrYx8-lys'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': '"Brave" may be the wrong word, but Ellen\'s Executive Producer, Andy Lassner, and his assistant, Jacqueline, made their way through a haunted house.',
'liveBroadcastContent': 'none',
'publishedAt': '2014-10-31T16:50:33.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/vEVrYx8-lys/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/vEVrYx8-lys/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/vEVrYx8-lys/mqdefault.jpg',
'width': 320}},
'title': 'Andy and Jacqueline Brave the Haunted House'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/kprvuH9aAXC-dIAlXMbwA3Klp14"',
'id': {'kind': 'youtube#video', 'videoId': 'wTAJSuhgZxA'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Adele's new single is a hit, thanks to a chat she had with Ellenâ¦",
'liveBroadcastContent': 'none',
'publishedAt': '2015-10-29T13:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/wTAJSuhgZxA/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/wTAJSuhgZxA/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/wTAJSuhgZxA/mqdefault.jpg',
'width': 320}},
'title': "Ellen Inspired Adele's New Song"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/Ge10B_3x9KSfQTWF5V-ZNHDuqwU"',
'id': {'kind': 'youtube#video', 'videoId': 'oJsYwehp_r4'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'She loves to scare her guests. Take a look at a few of these recent favorites!',
'liveBroadcastContent': 'none',
'publishedAt': '2015-05-27T13:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/oJsYwehp_r4/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/oJsYwehp_r4/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/oJsYwehp_r4/mqdefault.jpg',
'width': 320}},
'title': "Ellen's Favorite Scares"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/Em-6euVf5saohkrtNZzXR2jmaTo"',
'id': {'kind': 'youtube#video', 'videoId': 'Vap9SMRf8YE'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Ellen and Sofia played a hilarious game of 5 Second Rule! Check it out, plus all the fun we didn't have time for in the show!",
'liveBroadcastContent': 'none',
'publishedAt': '2015-12-03T14:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/Vap9SMRf8YE/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/Vap9SMRf8YE/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/Vap9SMRf8YE/mqdefault.jpg',
'width': 320}},
'title': '5 Second Rule with Sofia Vergara -- Extended!'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/o7GMiOOo84bHhNwHGc6qQZ1ebRc"',
'id': {'kind': 'youtube#video', 'videoId': 'ZXZ6K21wvZM'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Ellen's writer Amy scares pretty easily, but she's nothing compared to Ellen's Executive Producer, Andy. That's why he was the perfect person to join Amy in this ...",
'liveBroadcastContent': 'none',
'publishedAt': '2013-10-22T13:00:05.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/ZXZ6K21wvZM/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/ZXZ6K21wvZM/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/ZXZ6K21wvZM/mqdefault.jpg',
'width': 320}},
'title': "Andy and Amy's Haunted House"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/SyuA5bIoXdtQD_0SQUu1PyfvPP4"',
'id': {'kind': 'youtube#video', 'videoId': 'QrIrbeoDkT0'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Ellen met Noah Ritter after a video of him went viral. Nobody could have predicted what she was in for. Ellen Meets the 'Apparently' Kid, Part 2 ...",
'liveBroadcastContent': 'none',
'publishedAt': '2014-09-11T18:37:28.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/QrIrbeoDkT0/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/QrIrbeoDkT0/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/QrIrbeoDkT0/mqdefault.jpg',
'width': 320}},
'title': 'Ellen Meets the âApparentlyâ Kid, Part 1'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/Ag0Zp0Gg9tiWeBYr4k1p5W7EnLI"',
'id': {'kind': 'youtube#video', 'videoId': 'U8Gv83xiFP8'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Emma Stone, Jamie Foxx and Andrew Garfield all participated in a revealing round of the saucy question and answer game.',
'liveBroadcastContent': 'none',
'publishedAt': '2014-04-04T04:55:12.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/U8Gv83xiFP8/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/U8Gv83xiFP8/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/U8Gv83xiFP8/mqdefault.jpg',
'width': 320}},
'title': "'The Amazing Spider-Man 2' Cast Plays Never Have I Ever"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/EeSV1P1pL1VAVWYm27ev8YIWcTk"',
'id': {'kind': 'youtube#video', 'videoId': 'QyJ8rulYHpU'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Ellen had a star turn in Nicki's viral video. What did Nicki think? Find out!",
'liveBroadcastContent': 'none',
'publishedAt': '2014-09-10T05:38:21.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/QyJ8rulYHpU/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/QyJ8rulYHpU/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/QyJ8rulYHpU/mqdefault.jpg',
'width': 320}},
'title': 'Nicki Minaj Reacts to Ellenâs âAnacondaâ'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/lklEBOJbEqTsZhzFeWQDvaEaovo"',
'id': {'kind': 'youtube#video', 'videoId': '7nGz7xgGJzc'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "After Ellen saw Brielle's video on ellentube, she invited her to showcase her science smarts on the show!",
'liveBroadcastContent': 'none',
'publishedAt': '2015-11-23T14:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/7nGz7xgGJzc/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/7nGz7xgGJzc/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/7nGz7xgGJzc/mqdefault.jpg',
'width': 320}},
'title': 'Adorable 3-Year-Old Periodic Table Expert Brielle'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/lFfDdAriFOK6-7T-GqAaQrfZrL0"',
'id': {'kind': 'youtube#video', 'videoId': '2DYfLJrp1TQ'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Ellen loves scaring her executive producer, Andy Lassner, and "Modern Family" star Eric Stonestreet. So, of course she couldn\'t wait to send them both through ...',
'liveBroadcastContent': 'none',
'publishedAt': '2015-10-29T13:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/2DYfLJrp1TQ/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/2DYfLJrp1TQ/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/2DYfLJrp1TQ/mqdefault.jpg',
'width': 320}},
'title': 'Andy Goes to a Haunted House with Eric Stonestreet'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/UPK4p6u7VdWPSkW1Cnz5QKCxfXk"',
'id': {'kind': 'youtube#video', 'videoId': 'fNJI2A0v8yI'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Leonardo DiCaprio is quite the daredevil, and he told Ellen about a few of his close calls!',
'liveBroadcastContent': 'none',
'publishedAt': '2016-01-08T14:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/fNJI2A0v8yI/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/fNJI2A0v8yI/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/fNJI2A0v8yI/mqdefault.jpg',
'width': 320}},
'title': "Leo's Bad Luck"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/cdwuhXK78q9_SFeRcIdz2ZKxvy4"',
'id': {'kind': 'youtube#video', 'videoId': '3RLTanW1DGo'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'Their visit to the haunted house was so funny, Ellen had to send them again! This time Andy and Amy visited the Queen Mary Dark Harbor, and the results ...',
'liveBroadcastContent': 'none',
'publishedAt': '2013-10-31T13:00:03.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/3RLTanW1DGo/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/3RLTanW1DGo/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/3RLTanW1DGo/mqdefault.jpg',
'width': 320}},
'title': "Andy and Amy's Haunted Ship Adventure"}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/N1j-mxkND6apYO8kdjitbd3mOns"',
'id': {'kind': 'youtube#video', 'videoId': 'zcAQCTZ3TuQ'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Ellen held nothing back when when Mila Kunis was here, and asked her about what's going on between her and Ashton Kutcher. See how she responded!",
'liveBroadcastContent': 'none',
'publishedAt': '2013-02-13T17:14:14.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/zcAQCTZ3TuQ/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/zcAQCTZ3TuQ/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/zcAQCTZ3TuQ/mqdefault.jpg',
'width': 320}},
'title': 'Mila Kunis Blushes over Ashton'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/b7ZtfnV8spHzXmzgj_c0lN2dwJ0"',
'id': {'kind': 'youtube#video', 'videoId': 'pP-PF4nKb0I'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'It was a legendary meeting on The Ellen Show, Sophia Grace & Rosie and Russell Brand met for the very first time to discuss their hometown of Essex, England ...',
'liveBroadcastContent': 'none',
'publishedAt': '2012-05-17T02:57:04.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/pP-PF4nKb0I/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/pP-PF4nKb0I/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/pP-PF4nKb0I/mqdefault.jpg',
'width': 320}},
'title': 'Sophia Grace & Rosie Meet Russell Brand'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/U3UJ8UFIu4nRHqfysq91oHzinuw"',
'id': {'kind': 'youtube#video', 'videoId': 'mUr5KxtKZQk'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'After chatting with Sofia Vergara, Ellen sent her into a store on the WB lot for some hidden camera fun!',
'liveBroadcastContent': 'none',
'publishedAt': '2010-11-03T19:13:20.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/mUr5KxtKZQk/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/mUr5KxtKZQk/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/mUr5KxtKZQk/mqdefault.jpg',
'width': 320}},
'title': 'Sofia Vergara Plays a Hidden Camera Prank'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/B4kmiOv8FEBHoH3MRiahPrDEGxc"',
'id': {'kind': 'youtube#video', 'videoId': '5SZ_--mt4bk'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': 'They were staked out in the bathroom for this hilarious round of scares!',
'liveBroadcastContent': 'none',
'publishedAt': '2015-02-06T14:00:01.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/5SZ_--mt4bk/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/5SZ_--mt4bk/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/5SZ_--mt4bk/mqdefault.jpg',
'width': 320}},
'title': 'Justin Bieber and Ellen Scare Audience Members'}},
</code></pre>
<p>Thank you.</p>
| 2 | 2016-10-16T19:14:55Z | 40,074,709 | <p>Given the Jupyter notebook you referenced here's how you'd get the videoId from the data you've retrieved. Does this answer your question? </p>
<p>I'm not fully sure how the Youtube search API works but I might have time to explore it if this isn't a full answer.</p>
<pre><code>example = {
'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/EK5D70JgnA5Bec8tRSnEFfhIsv0"',
'items': [
{
'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/hsQmFEqp1R_glFpcQnpnOLbbxCg"',
'id': {
'kind': 'youtube#video', 'videoId': 'd8kCTPPwfpM'},
'kind': 'youtube#searchResult',
'snippet': {
'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "This incredible duo teamed up to perform an original song for Ellen! They may not have had a lot of rehearsal, but it's clear that this is one musical combo it ...",
'liveBroadcastContent': 'none',
'publishedAt': '2012-02-21T14:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/d8kCTPPwfpM/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/d8kCTPPwfpM/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/d8kCTPPwfpM/mqdefault.jpg',
'width': 320}},
'title': 'Taylor Swift and Zac Efron Sing a Duet!'}},
{'etag': '"I_8xdZu766_FSaexEaDXTIfEWc0/LeKypRrnWWD6mRhK1wATZB5UQGo"',
'id': {'kind': 'youtube#video', 'videoId': '-l2KPjQ2lJA'},
'kind': 'youtube#searchResult',
'snippet': {'channelId': 'UCp0hYYBW6IMayGgR-WeoCvQ',
'channelTitle': 'TheEllenShow',
'description': "Harry, Liam, Louis and Niall played a round of Ellen's revealing game. How well do you know the guys of One Direction?",
'liveBroadcastContent': 'none',
'publishedAt': '2015-11-18T14:00:00.000Z',
'thumbnails': {'default': {'height': 90,
'url': 'https://i.ytimg.com/vi/-l2KPjQ2lJA/default.jpg',
'width': 120},
'high': {'height': 360,
'url': 'https://i.ytimg.com/vi/-l2KPjQ2lJA/hqdefault.jpg',
'width': 480},
'medium': {'height': 180,
'url': 'https://i.ytimg.com/vi/-l2KPjQ2lJA/mqdefault.jpg',
'width': 320}},
'title': 'Never Have I Ever with One Direction'}},]}
import pprint
for video in example["items"]:
pprint.pprint(video["id"]["videoId"])
# Prints 'd8kCTPPwfpM'
# '-l2KPjQ2lJA'
</code></pre>
| 0 | 2016-10-16T19:47:10Z | [
"python",
"json",
"youtube",
"youtube-api",
"jupyter-notebook"
] |
Zipline Error: AttributeError: 'NoneType' object has no attribute 'fetch_csv' | 40,074,425 | <p>I just installed Zipline on Windows 10, Python 2.7 system using <code>conda</code>. When I <a href="http://www.zipline.io/appendix.html?highlight=fetch_csv#zipline.api.fetch_csv" rel="nofollow">tried to use a function <code>fetch_csv</code> from <code>zipline.api</code></a>, I get an error</p>
<pre><code>AttributeError: 'NoneType' object has no attribute 'fetch_csv'
</code></pre>
<p>Why can't I load the function <code>fetch_csv</code>?</p>
<pre><code>from zipline.api import fetch_csv
fetch_csv('./test.csv')
</code></pre>
| 2 | 2016-10-16T19:19:42Z | 40,074,559 | <p>The <a href="http://www.zipline.io/appendix.html?highlight=fetch_csv#zipline.api.fetch_csv" rel="nofollow">Zipline API reference</a> says that this methods is to "Fetch a csv from a remote url". For local files, I would suggest <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas</a>:</p>
<pre><code>pandas.read_csv('./test.csv')
</code></pre>
| 0 | 2016-10-16T19:32:04Z | [
"python",
"python-2.7",
"zipline"
] |
Heapify each sublist in a list of lists in python? | 40,074,472 | <p>I have a list of lists called opened which was declared like this: </p>
<pre><code>opened = [[] for i in range(5)]
</code></pre>
<p>Now <code>opened = [[], [], [], [], []]</code><br>
How can I heapify each of the sublists using the <code>heapq.heapify()</code> function? i.e, opened[0], opened[1], opened[2], opened[3], opened[4] should be heapified. </p>
<p>Thanks in advance.</p>
| 0 | 2016-10-16T19:24:44Z | 40,074,586 | <p>Each of those sub-lists is a list, so just use <code>heapify()</code> directly on each of them:</p>
<pre><code>import heapq
for j in range(5):
heapq.heapify(opened[j])
</code></pre>
<p>Of course, if you know that each of those sub-lists is empty, there is no need to do this: an empty list is already a heap. There are no extra variables or other storage to make them heaps, since a Python heap is just a list with a condition on the order of the elements.</p>
| 3 | 2016-10-16T19:35:26Z | [
"python",
"data-structures",
"heap"
] |
Python: Select particular characters from a file and add them to a new variable | 40,074,474 | <p>I'm fairly new to python and I'm not sure why what I'm doing is wrong.</p>
<pre><code>numberOfOrders = 0
numberOfProducts = 0
allOrders = open("file.txt", "r") #A .txt file in the same directory as the .py file.
#file.txt:
#(A->[a:20,a:20,b:10,c:25,c:25])
#(B->[d:100,e:70])
#(C->[f:10000,g:200000])
while True:
theline = allOrders.readline()
for theline in allOrders:
for char in theline: #Iterate over each character of a line.
listProducts = "" #Empty string, will be the concatenation of the wanted characters.
if char == "[": #Wanted character.
listProducts = listProducts + "["
elif char == ":": #To keep count of no. of products in a list.
numberOfProducts += 1
elif is_number(char) == True: #Function that checks whether char is a number.
listProducts = listProducts + str(char) #Add to the string "listProducts".
elif char == ",": #Wanted character.
listProducts = listProducts + str(char)
elif char == "]":#Wanted character, to end the string.
listProducts = listProducts +str(char)
break
numberOfOrders += 1 #To keep track of no. of orders. Each line of file is an order.
if len(theline) == 0:
break
allOrders.close()
print(numberOfProducts)
print(numberOfOrders)
print(listProducts)
</code></pre>
<p>I basically only want the numbers and commas within brackets. That's my biggest issue here.
The output I get for</p>
<pre><code> print(listProducts)
</code></pre>
<p>is</p>
<pre><code> ]
</code></pre>
<p>Thank you.</p>
| 0 | 2016-10-16T19:24:48Z | 40,074,935 | <p>You can keep the digits and commas by stripping everything else out using a regular expression. Then you have a string of decimals and commas that you can split to give a list of products in each order line.</p>
<pre><code>import re
with open('file.txt') as all_orders:
# substitute '' for all non-digit non-comma then split
orders = [re.sub(r'[^\d,]', '', line).split(',')
for line in all_orders]
number_of_orders = len(orders)
number_of_products = sum(map(len, orders))
print('orders', number_of_orders, 'products', number_of_products)
</code></pre>
| 0 | 2016-10-16T20:09:32Z | [
"python",
"file",
"python-3.x",
"if-statement",
"for-loop"
] |
Python: Select particular characters from a file and add them to a new variable | 40,074,474 | <p>I'm fairly new to python and I'm not sure why what I'm doing is wrong.</p>
<pre><code>numberOfOrders = 0
numberOfProducts = 0
allOrders = open("file.txt", "r") #A .txt file in the same directory as the .py file.
#file.txt:
#(A->[a:20,a:20,b:10,c:25,c:25])
#(B->[d:100,e:70])
#(C->[f:10000,g:200000])
while True:
theline = allOrders.readline()
for theline in allOrders:
for char in theline: #Iterate over each character of a line.
listProducts = "" #Empty string, will be the concatenation of the wanted characters.
if char == "[": #Wanted character.
listProducts = listProducts + "["
elif char == ":": #To keep count of no. of products in a list.
numberOfProducts += 1
elif is_number(char) == True: #Function that checks whether char is a number.
listProducts = listProducts + str(char) #Add to the string "listProducts".
elif char == ",": #Wanted character.
listProducts = listProducts + str(char)
elif char == "]":#Wanted character, to end the string.
listProducts = listProducts +str(char)
break
numberOfOrders += 1 #To keep track of no. of orders. Each line of file is an order.
if len(theline) == 0:
break
allOrders.close()
print(numberOfProducts)
print(numberOfOrders)
print(listProducts)
</code></pre>
<p>I basically only want the numbers and commas within brackets. That's my biggest issue here.
The output I get for</p>
<pre><code> print(listProducts)
</code></pre>
<p>is</p>
<pre><code> ]
</code></pre>
<p>Thank you.</p>
| 0 | 2016-10-16T19:24:48Z | 40,075,115 | <p>Regarding your code, the solution is to:</p>
<ol>
<li>Removing the "for theline in allOrders" which is not coherent</li>
<li>Moving the initialization of listProducts before the while loop </li>
</ol>
<p>Of course this can be widely optimized using regex for example, as suggested by tdelaney.</p>
| 0 | 2016-10-16T20:29:17Z | [
"python",
"file",
"python-3.x",
"if-statement",
"for-loop"
] |
PyQt5 port: how do I hide a window and let it appear at the same position | 40,074,637 | <p>I'm porting a PyQt4 program to PyQt5. One part of it is hiding the window, taking a screenshot of the area behind the window and showing the window again, which worked just fine with PyQt4.</p>
<p>With my PyQt5 port, everything works fine, but the window appears on the position where it was when the program was started, and not at the position where it was before calling the hide() method.</p>
<p>I'm testing this on a Linux box. The relevant code strips down to:</p>
<pre><code>import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
QGridLayout, QPushButton)
class demo(QMainWindow):
def __init__(self):
super().__init__()
mainWidget = QWidget(self)
layout = QGridLayout(mainWidget)
self.setCentralWidget(mainWidget)
self.testButton = QPushButton(self)
self.testButton.setText('Test')
self.testButton.clicked.connect(self.hideMe)
layout.addWidget(self.testButton, 0, 0)
def hideMe(self):
self.hide()
QTimer.singleShot(300, self.showMe)
def showMe(self):
self.show()
self.move(self.pos())
app = QApplication(sys.argv)
mainWindow = demo()
mainWindow.show()
sys.exit(app.exec_())
</code></pre>
<p>In showMe(), self.pos() actually contains the right coordinates, but the window isn't moved there (but to it's "original" position it had right after starting).</p>
<p>When I e. g. do a self.move(10, 10) instead, the window is actually moved there. But as soon as I use a variable (I also tried to save the x and y of self.pos in a variable and to use this instead) the window is shown at the position it had after starting.</p>
<p>Why does a move() call with integers actually move the window, but a move() call with variables doesn't? How do I move the window to the position it had before hiding?</p>
<p>Thanks for all help!</p>
<p>Edit (perhaps to find out what's the difference):</p>
<p>The very same code using PyQt4 works:</p>
<pre><code>import sys
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import (QApplication, QMainWindow, QWidget,
QGridLayout, QPushButton)
class demo(QMainWindow):
def __init__(self):
super().__init__()
mainWidget = QWidget(self)
layout = QGridLayout(mainWidget)
self.setCentralWidget(mainWidget)
self.testButton = QPushButton(self)
self.testButton.setText('Test')
self.testButton.clicked.connect(self.hideMe)
layout.addWidget(self.testButton, 0, 0)
def hideMe(self):
self.hide()
QTimer.singleShot(300, self.showMe)
def showMe(self):
self.show()
self.move(self.pos())
app = QApplication(sys.argv)
mainWindow = demo()
mainWindow.show()
sys.exit(app.exec_())
</code></pre>
<p>so why behaves Qt5 different to Qt4 in this case?</p>
| 2 | 2016-10-16T19:40:10Z | 40,074,761 | <p>If I use <code>self.old_pos</code> in <code>hideMe</code> and <code>showMe</code> then it works for me (Linux).</p>
<pre><code>def hideMe(self):
self.old_pos = self.pos()
self.hide()
QTimer.singleShot(300, self.showMe)
def showMe(self):
self.show()
self.move(self.old_pos)
</code></pre>
| 0 | 2016-10-16T19:54:12Z | [
"python",
"pyqt4",
"porting",
"pyqt5"
] |
PyQt5 port: how do I hide a window and let it appear at the same position | 40,074,637 | <p>I'm porting a PyQt4 program to PyQt5. One part of it is hiding the window, taking a screenshot of the area behind the window and showing the window again, which worked just fine with PyQt4.</p>
<p>With my PyQt5 port, everything works fine, but the window appears on the position where it was when the program was started, and not at the position where it was before calling the hide() method.</p>
<p>I'm testing this on a Linux box. The relevant code strips down to:</p>
<pre><code>import sys
from PyQt5.QtCore import QTimer
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget,
QGridLayout, QPushButton)
class demo(QMainWindow):
def __init__(self):
super().__init__()
mainWidget = QWidget(self)
layout = QGridLayout(mainWidget)
self.setCentralWidget(mainWidget)
self.testButton = QPushButton(self)
self.testButton.setText('Test')
self.testButton.clicked.connect(self.hideMe)
layout.addWidget(self.testButton, 0, 0)
def hideMe(self):
self.hide()
QTimer.singleShot(300, self.showMe)
def showMe(self):
self.show()
self.move(self.pos())
app = QApplication(sys.argv)
mainWindow = demo()
mainWindow.show()
sys.exit(app.exec_())
</code></pre>
<p>In showMe(), self.pos() actually contains the right coordinates, but the window isn't moved there (but to it's "original" position it had right after starting).</p>
<p>When I e. g. do a self.move(10, 10) instead, the window is actually moved there. But as soon as I use a variable (I also tried to save the x and y of self.pos in a variable and to use this instead) the window is shown at the position it had after starting.</p>
<p>Why does a move() call with integers actually move the window, but a move() call with variables doesn't? How do I move the window to the position it had before hiding?</p>
<p>Thanks for all help!</p>
<p>Edit (perhaps to find out what's the difference):</p>
<p>The very same code using PyQt4 works:</p>
<pre><code>import sys
from PyQt4.QtCore import QTimer
from PyQt4.QtGui import (QApplication, QMainWindow, QWidget,
QGridLayout, QPushButton)
class demo(QMainWindow):
def __init__(self):
super().__init__()
mainWidget = QWidget(self)
layout = QGridLayout(mainWidget)
self.setCentralWidget(mainWidget)
self.testButton = QPushButton(self)
self.testButton.setText('Test')
self.testButton.clicked.connect(self.hideMe)
layout.addWidget(self.testButton, 0, 0)
def hideMe(self):
self.hide()
QTimer.singleShot(300, self.showMe)
def showMe(self):
self.show()
self.move(self.pos())
app = QApplication(sys.argv)
mainWindow = demo()
mainWindow.show()
sys.exit(app.exec_())
</code></pre>
<p>so why behaves Qt5 different to Qt4 in this case?</p>
| 2 | 2016-10-16T19:40:10Z | 40,075,769 | <p>It seems that in Qt5 the geometry won't be re-set if it is exactly the same - but I don't know why this behaviour has changed, or whether it is a bug. And note that it is not just the position that is affected - resizing is also ignored.</p>
<p>Here is a hack to work around the problem:</p>
<pre><code>from PyQt5.QtCore import QMargins
class demo(QMainWindow):
...
def hideMe(self):
print('hide:', self.geometry())
self.hide()
QTimer.singleShot(300, self.showMe)
def showMe(self):
print('show1:', self.geometry())
hack = QMargins(0, 0, 0, 1)
self.setGeometry(self.geometry() + hack)
self.show()
self.setGeometry(self.geometry() - hack)
print('show2:', self.geometry())
</code></pre>
| 0 | 2016-10-16T21:37:15Z | [
"python",
"pyqt4",
"porting",
"pyqt5"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.