title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python user input for def function
39,803,996
<p>How to do a number input by user first then only display the answer?</p> <pre><code>a = int(raw_input("Enter number: "),twoscomp) def tobin(x, count = 8): return "".join(map(lambda y:str((x&gt;&gt;y)&amp;1), range(count-1, -1, -1))) def twoscomp(bin_str): return tobin(-int(bin_str,2),len(bin_str)) print ...
0
2016-10-01T07:16:22Z
39,804,041
<p>I believe this is what you're trying to do?</p> <pre><code>def tobin(x, count = 8): return "".join(map(lambda y:str((x&gt;&gt;y)&amp;1), range(count-1, -1, -1))) def twoscomp(bin_str): return tobin(-int(bin_str,2),len(bin_str)) a = twoscomp(raw_input("Enter number: ")) print a </code></pre> <p>Things to...
3
2016-10-01T07:22:19Z
[ "python", "bit-manipulation", "twos-complement" ]
Python scraping of javascript web pages fails for https pages only
39,804,034
<p>I'm using PyQt5 to scrape web pages, which works great for http:// URLs, but not at all for https:// URLs.</p> <p>The relevant part of my script is below:</p> <pre><code>class WebPage(QWebPage): def __init__(self): super(WebPage, self).__init__() self.timerScreen = QTimer() self.timerS...
11
2016-10-01T07:21:39Z
39,858,556
<p>tested with PyQt4 and normally opened pages with HTTPS</p> <pre><code>import sys from PyQt4.QtGui import QApplication from PyQt4.QtCore import QUrl from PyQt4.QtWebKit import QWebView class Browser(QWebView): def __init__(self): QWebView.__init__(self) self.loadFinished.connect(self._result_ava...
0
2016-10-04T17:39:51Z
[ "python", "https", "pyqt" ]
Can cPickle save reshaped numpy object reference?
39,804,175
<p>I have a class defined as:</p> <pre><code>class A(): def __init__(): self.a = np.array([0,1,2,3,4,5]) self.b = self.a.reshape((2, 3)) </code></pre> <p>now, b is in fact a reshaped reference of array a. If we change the first element of a:<code>a[0] = 10</code>, <code>b[0, 0]</code> will also ch...
2
2016-10-01T07:39:28Z
39,804,612
<p>You can use <code>__getstate__</code> and <code>__setstate__</code> to control the pickle:</p> <pre><code>import numpy as np class A: def __init__(self): self.a = np.array([0,1,2,3,4,5]) self.b = self.a.reshape((2, 3)) def __getstate__(self): return {"a":self.a, "b":self.b.shape} ...
0
2016-10-01T08:39:57Z
[ "python", "numpy", "pickle" ]
Can cPickle save reshaped numpy object reference?
39,804,175
<p>I have a class defined as:</p> <pre><code>class A(): def __init__(): self.a = np.array([0,1,2,3,4,5]) self.b = self.a.reshape((2, 3)) </code></pre> <p>now, b is in fact a reshaped reference of array a. If we change the first element of a:<code>a[0] = 10</code>, <code>b[0, 0]</code> will also ch...
2
2016-10-01T07:39:28Z
39,804,721
<p>the latest prerelease of jsonpickle does correctly serialize numpy views; pickle sadly does not.</p>
0
2016-10-01T08:52:03Z
[ "python", "numpy", "pickle" ]
Get HTTP 400 Bad Request when login using Python requests
39,804,202
<p>I'm trying to use <code>requests</code> to log into <a href="https://appleid.apple.com/cn" rel="nofollow">https://appleid.apple.com/cn</a> (/us should be the same, but get 400 Bad request returned.</p> <pre><code>session = requests.Session() productURL = &lt;the URL above&gt; headers = { "Accept": "te...
0
2016-10-01T07:42:59Z
39,805,564
<p>Since I'm new and can't comment (I don't quite understand the reputation system yet), I'll have to write an answer. </p> <p>I know that Google recently blocked the login via scripts (well, via most scripts) because it was rather easy to conduct brute force attacks against accounts. </p> <p>I am presuming that Appl...
0
2016-10-01T10:34:16Z
[ "python" ]
Get HTTP 400 Bad Request when login using Python requests
39,804,202
<p>I'm trying to use <code>requests</code> to log into <a href="https://appleid.apple.com/cn" rel="nofollow">https://appleid.apple.com/cn</a> (/us should be the same, but get 400 Bad request returned.</p> <pre><code>session = requests.Session() productURL = &lt;the URL above&gt; headers = { "Accept": "te...
0
2016-10-01T07:42:59Z
39,805,734
<p>When you are posting JSON you should use requests like:</p> <pre><code>r = requests.post(url, json=payload) </code></pre> <p>also, don't need to hardcode the <code>Content-Length</code> and <code>Content-Type</code> requests package takes care of that.</p>
0
2016-10-01T10:53:29Z
[ "python" ]
Hook in oauth2 code with DRF
39,804,235
<p>I am trying to build an app which has user login and signup functionality.<br>I can create login and signup both from django, and DRF but could not hook in oAuth2 with DRF to make it functional.<br>I have no idea where should i use it.<br><br>Should I generate token on signup or login?<br>How can I make it functiona...
0
2016-10-01T07:48:17Z
39,805,256
<p>Try using python social auth.</p> <p>Add <code>social.apps.django_app.default</code> to <code>INSTALLED_APPS</code></p> <p>Add <code>social.backends.facebook.FacebookOAuth2</code> to <code>AUTHENTICATION_BACKENDS</code></p> <p>Add <code>url(r'^auth/', include('social.apps.django_app.urls', namespace='social'))</c...
0
2016-10-01T09:59:06Z
[ "python", "django", "python-3.x", "oauth-2.0", "django-rest-framework" ]
How to query python list with multiple characters in each one
39,804,239
<p>I know the title is a little messy and if someone wants to fix it, they are more than welcome to.</p> <p>Anyways, I'm having trouble querying a python list with multiple values, I have looked on other Stackoverflow questions and none of seem to match what I'm looking for.</p> <p>So, this is the code I have so far,...
-2
2016-10-01T07:48:49Z
39,805,233
<p>If you loop over the input string, you should be able to get the solution you're looking for. How about something like this?</p> <pre><code>input_string = raw_input("What symbol character would you like to check? ") symbols = [' ', '!', '#', '$', '%', '&amp;', '"', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';',...
1
2016-10-01T09:56:25Z
[ "python", "list", "if-statement", "condition" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My questio...
0
2016-10-01T07:58:33Z
39,804,321
<p>If no path is given then the file is opened in the current working directory. This is returned by <code>os.getcwd()</code>.</p>
0
2016-10-01T08:01:12Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My questio...
0
2016-10-01T07:58:33Z
39,804,355
<p>You can use <code>os.getcwd()</code> for getting the current working directory:</p> <pre><code>import os os.getcwd() </code></pre> <p>Otherwise, you could also specify the full path for the file when opening it, e.g.</p> <pre><code>f.open('/path/to/the/folder/Hello.txt', 'w') </code></pre>
0
2016-10-01T08:04:35Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My questio...
0
2016-10-01T07:58:33Z
39,804,476
<p>Convert the relative path to absolute path:</p> <pre><code>path = os.path.abspath(filename) </code></pre> <p>Then take just the directory from the absolute path:</p> <pre><code>directory = os.path.dirname(path) </code></pre> <p>That will work regardless of what <code>filename</code> is. It could by just a filena...
1
2016-10-01T08:21:46Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My questio...
0
2016-10-01T07:58:33Z
39,805,188
<p>Using f.name provides the file name if you didn't supply it as a separate variable.<br> Using <code>os.path.abspath()</code> provides the full file name including it's directory path i.e. in this case "/home/rolf/def"<br> Using <code>os.path.dirname()</code> strips the file name from the path, as that you already kn...
0
2016-10-01T09:51:22Z
[ "python", "python-3.x" ]
Print directory where file is saved with Python
39,804,301
<p>how could do print the path directory of my file saved with python. For ad example, i start with idle3 (Fedora 24), i save the IDLE code on: /home/jetson/Desktop/Python/Programs and in the code is written:</p> <pre><code>f = open("Hello.txt","w") f.write("This is a test","\n") f.close() </code></pre> <p>My questio...
0
2016-10-01T07:58:33Z
39,826,797
<p>Thank's all! It's working, have a nice day!</p>
0
2016-10-03T07:51:41Z
[ "python", "python-3.x" ]
TclError: no display name and no $DISPLAY environment variable on Windows 10 Bash
39,804,366
<p>I tried to install matplotlib on Windows 10 Bash shell.</p> <p>After that, I ran following lines:</p> <pre><code>$ ipython3 </code></pre> <p>then</p> <pre><code>In[1]: %pylab </code></pre> <p>then it gives me a following error:</p> <pre><code>--------------------------------------------------------------------...
2
2016-10-01T08:06:40Z
39,805,613
<p>There is no official display environment for bash on Windows. </p> <ul> <li>You need to install unoffical display environment, i.e. xming (<a href="https://sourceforge.net/projects/xming/" rel="nofollow">https://sourceforge.net/projects/xming/</a>)</li> <li>After installing xming you need to export as <strong>DISPL...
2
2016-10-01T10:39:33Z
[ "python", "matplotlib" ]
Python - Sort a list of dics by value of dict`s dict value
39,804,375
<p>I have a list that looks like this:</p> <pre><code>persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/11/2016...}}}] </code></pre> <p>I need to sort the list of persons by their sub key of sub key - their birth_info date.</...
3
2016-10-01T08:07:57Z
39,804,441
<p>Try this</p> <pre><code>from datetime import datetime print(sorted(persons, key=lambda x: datetime.strptime(x['passport']['birth_info']['date'], "%d/%m/%Y"))) #reverse=True for descending order. </code></pre>
2
2016-10-01T08:16:27Z
[ "python", "list", "sorting", "quicksort" ]
Python - Sort a list of dics by value of dict`s dict value
39,804,375
<p>I have a list that looks like this:</p> <pre><code>persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/11/2016...}}}] </code></pre> <p>I need to sort the list of persons by their sub key of sub key - their birth_info date.</...
3
2016-10-01T08:07:57Z
39,804,445
<p>The function <code>sorted()</code> provides the <code>key</code> argument. One can define a callable which returns the key to compare the items:</p> <pre><code>sorted(persons, key=lambda x: x['passport']['birth_info']['date']) </code></pre> <p>The argument x is an item of the given list of persons. </p> <p>If the...
6
2016-10-01T08:17:01Z
[ "python", "list", "sorting", "quicksort" ]
No module named django-extensions
39,804,399
<p>I need help.I am trying to run a django project that requires django-extensions module.i did pip install django-extensions and also in settings.py</p> <pre><code>INSTALLED_APPS = ( .... 'django_extensions', ) </code></pre> <p>but when i try to run the server it says "Import Error,No module named django-ext...
0
2016-10-01T08:11:52Z
39,812,025
<p>Have you look to install this: apt-get install python-django-extensions</p>
0
2016-10-01T22:25:52Z
[ "python", "django" ]
'numpy.ndarray' object is not callable error in python
39,804,439
<p>I was converting LU decomposition matlab code into python.</p> <p>But while I was doing it I encountered with this error </p> <blockquote> <p><code>'numpy.ndarray' object is not callable</code></p> </blockquote> <p>this error occurs when I tried to test my code. Here is my code and can anyone help with this pro...
1
2016-10-01T08:16:20Z
39,804,508
<p>The error is occurring because you have used the wrong kind of braces on the 4th line of your function.</p> <pre><code>a[k+1:m-1,k]=a[k+1:m-1,k]/a(k,k) </code></pre> <p>should be corrected to </p> <pre><code>a[k+1:m-1,k]=a[k+1:m-1,k]/a[k,k] </code></pre> <p>i.e. the <code>()</code> braces should be replaced by <...
3
2016-10-01T08:26:25Z
[ "python", "numpy", "callable" ]
Assign field from related model as default in another model
39,804,478
<p>How can i assign the default value of current_amount as minimum_price?</p> <pre><code>class Auction(models.Model): minimum_price = models.PositiveIntegerField() ..... class Bid(models.Model): product = models.ForeignKey(Auction, related_name='auction') # i want to set this field's default to value ...
0
2016-10-01T08:21:55Z
39,804,499
<p>One solution is </p> <pre><code>class Bid(models.Model): product = models.ForeignKey(Auction, related_name='auction') current_amount = models.PositiveIntegerField() def save(self, *args, **kwargs): if not self.current_amount: self.current_amount = self.product.minimum_price ...
1
2016-10-01T08:24:51Z
[ "python", "django", "database", "sqlite", "django-models" ]
breadth first search optimisation in python
39,804,573
<p>I was solving a problem related to breadth first search. I solved the problem but my solution took the longest time to solve (0.12 as compared to 0.01 and 0.02 done by others). The question is a simple BFS on a graph.</p> <p>Here is how I have implemented BFS:</p> <pre><code>def bfs1(g, s): parent = {s: None} ...
0
2016-10-01T08:34:42Z
39,808,088
<p>The main problem performance-wise seem to be the fact that this is performing a full graph search and returning the distances of all nodes compared to the root node.</p> <p>That is much more than is needed for the problem at hand.</p> <p>In the <a href="http://www.spoj.com/problems/NAKANJ/" rel="nofollow">specific...
1
2016-10-01T15:02:08Z
[ "python", "algorithm", "graph-algorithm", "bfs" ]
breadth first search optimisation in python
39,804,573
<p>I was solving a problem related to breadth first search. I solved the problem but my solution took the longest time to solve (0.12 as compared to 0.01 and 0.02 done by others). The question is a simple BFS on a graph.</p> <p>Here is how I have implemented BFS:</p> <pre><code>def bfs1(g, s): parent = {s: None} ...
0
2016-10-01T08:34:42Z
39,817,118
<p>There has been some advice to implement a nice bfs. In two dimensional problems you can save half the time by searching from both ends simultanously.</p> <p>But when it comes to brute optimisation for timing you always go for lookup tables. In your case you have quite nice constraints: 64 positions to start and 64 ...
0
2016-10-02T12:41:57Z
[ "python", "algorithm", "graph-algorithm", "bfs" ]
How do i fix reshaping my dataset for cross validation?
39,804,629
<pre><code>x_train:(153347,53) x_test:(29039,52) y:(153347,) </code></pre> <p>I am working with sklearn. To cross validate and reshape my dataset i did:</p> <pre><code>x_train, x_test, y_train, y_test = cross_validation.train_test_split( x, y, test_size=0.3) x_train = np.pad(x, [(0,0)], mode='constant') x_test = np....
2
2016-10-01T08:41:48Z
39,805,142
<p>With the little we see here one, I believe the call to <code>cross_validation.train_test_split</code> dumps because the the length of the two vectors does not coincide. So for every X (the data tuple we you observe) you need a Y (the data-point that is observed as a result).</p> <p>At least this leads to the error ...
1
2016-10-01T09:45:22Z
[ "python", "numpy", "machine-learning", "scikit-learn", "cross-validation" ]
Scrapy: Problems installing on clean anaconda environment
39,804,652
<p>On a clean environment of anaconda, after running <code>conda install -c scrapinghub scrapy</code> which as of today install scrapy 1.1.2, on python 2.7 for some reason does not create the scrapy-script.py file and scrapy.exe file.</p> <p>Scrapy does not install correctly, command is unrecognized (obviously)..</p>
0
2016-10-01T08:44:32Z
39,804,676
<p>I solved the issue by installing a previous scrapy version:</p> <pre><code>conda install -c anaconda scrapy=1.1.1 </code></pre> <p>beware, this does not solve other issues with scrapy and anaconda, like pyopenssl issues:</p> <pre><code>ImportError: DLL load failed: the operating system cannot run %1. </code></pre...
0
2016-10-01T08:46:45Z
[ "python", "python-2.7", "scrapy", "anaconda" ]
detecting keyboard overrun in tkinter event handler when autorepeating to avoid lag
39,804,732
<p>In my app I want to allow the user to scroll through images by holding down an arrow key. Not surprisingly with larger images the pc can't keep up, and builds up a potentially large buffer that carries on being processed after the key is released.</p> <p>None of this is unexpected, and my normal answer is just to c...
-1
2016-10-01T08:53:37Z
39,870,990
<p>well it's nor very nice, but it isn't too tedious and seems to work quite well: (with a little bit of monitoring as well)</p> <pre><code> def checklag(self,p): if self.lasteventtime is None: #assume first event arrives with no significant delay self.lasteventtime = p.time self.lasteventrealti...
0
2016-10-05T10:01:21Z
[ "python", "events", "tkinter" ]
Dummy creation in pipeline with different levels in train and test set
39,804,733
<p>I'm currently exploring the scikit learn pipelines. I also want to preprocess the data with a pipeline. However, my train and test data have different levels of the categorical variable. Example: Consider:</p> <pre><code>import pandas as pd train = pd.Series(list('abbaa')) test = pd.Series(list('abcd')) </code></pr...
2
2016-10-01T08:53:53Z
39,805,740
<p>You can use categoricals as explained in <a href="http://stackoverflow.com/a/37451867/2285236">this answer</a>:</p> <pre><code>categories = np.union1d(train, test) train = train.astype('category', categories=categories) test = test.astype('category', categories=categories) pd.get_dummies(train) Out: a b c d...
2
2016-10-01T10:53:54Z
[ "python", "pandas", "scikit-learn" ]
Turning 4 metric coordinates of Vector into a Vector field
39,804,757
<p>I have four 3*3 matrices:</p> <pre><code>X1=[[2.276840271621883, 2.329662596474333, 2.3633290819729527], [2.276840271621883, 2.329662596474333, 2.3633290819729527], [2.276840271621883, 2.329662596474333, 2.3633290819729527]] X2=[[2.2698145746531786, 2.3308266405107805, 2.3594316100497643], [2.2698145746531786, 2.33...
0
2016-10-01T08:57:25Z
39,807,867
<p>When you want to plot a set of arrows using matplotlib's <code>quiver</code> function, that start at points <code>Pi = (X1i, Y1i)</code> and "end" at points <code>Qi = (X2i, Y2i)</code>, you call <code>quiver</code> like this:</p> <pre><code># creating demo data X1, X2, Y1, Y2 = [ np.random.random_integers(0, 9, (2...
0
2016-10-01T14:39:52Z
[ "python", "matplotlib", "arrow" ]
Stuck implementing simple neural network
39,804,774
<p>I've been bashing my head against this brick wall for what seems like an eternity, and I just can't seem to wrap my head around it. I'm trying to implement an autoencoder using only numpy and matrix multiplication. No theano or keras tricks allowed.</p> <p>I'll describe the problem and all its details. It is a bit ...
13
2016-10-01T08:59:04Z
39,921,537
<p>OK, here's a suggestion. In the vector case, if you have <em>x</em> as a vector of length <code>n</code>, then <code>g(x)</code> is also a vector of length <code>n</code>. However, <code>g'(x)</code> is not a vector, it's the <a href="https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant" rel="nofollow">Ja...
4
2016-10-07T16:04:28Z
[ "python", "algorithm", "numpy", "matrix", "derivative" ]
switch variable and write problems,python
39,804,800
<pre><code>import csv import sys def switch(): file1=open('enjoysport.csv','r') for line in file1: line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0] file1.close() origin=sys.stdout fil2=open("test.csv","w") sys.stdout=fi...
0
2016-10-01T09:03:03Z
39,804,875
<p>You need to actually write the updated row to the file, you can also use the <em>csv</em> lib to read and write your file content:</p> <pre><code>def switch(): with open('enjoysport.csv') as f, open("test.csv", "w") as out: wr = csv.writer(out) for row in csv.reader(f): row[0], row[...
2
2016-10-01T09:13:49Z
[ "python", "output" ]
switch variable and write problems,python
39,804,800
<pre><code>import csv import sys def switch(): file1=open('enjoysport.csv','r') for line in file1: line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0] file1.close() origin=sys.stdout fil2=open("test.csv","w") sys.stdout=fi...
0
2016-10-01T09:03:03Z
39,804,911
<p>The problem is with this line</p> <pre><code> line.split(",")[0],line.split(",")[-1]=line.split(",")[-1],line.split(",")[0] </code></pre> <p>You create four temporary lists by split, which are discarded after that line directly because they are not assigned to any variable.</p> <p>You have to process one line ...
1
2016-10-01T09:17:28Z
[ "python", "output" ]
Find nodes defined in corrupted namespace
39,804,844
<p>I've downloaded <a href="http://udcdata.info/udcsummary-skos.zip" rel="nofollow">this</a> XML file.</p> <p>I'm trying to get <code>includingNote</code> as follows:</p> <pre><code>... namespaces = { "skos" : "http://www.w3.org/2004/02/skos/core#", "xml" : "http://www.w3.org/XML/1998/namespace", "u...
0
2016-10-01T09:08:11Z
39,805,230
<p>It is true that the <code>skos</code> prefix is not declared in udc-scheme, but searching the XML document is not a problem. </p> <p>The following program extracts 639 <code>includingNote</code> elements:</p> <pre><code>from xml.etree import cElementTree as ET namespaces = {"udc" : "http://udcdata.info/udc-schema...
1
2016-10-01T09:56:14Z
[ "python", "xml", "xml-namespaces", "elementtree" ]
How do I iterate over the product of different lists?
39,804,860
<p>I have the following problem:</p> <p>I have a list <code>l1</code> and I want to iterate over the product with the function <code>itertools.product</code>, I also want to include the second list <code>l2</code> in the same way.</p> <p>For example:</p> <pre><code>l1 = [1, 2, 3, 4] l2 = ['a', 'b', 'c', 'd'] for i i...
2
2016-10-01T09:10:43Z
39,804,868
<p>By providing a <code>zip</code> of the lists to <code>product</code>:</p> <pre><code>for i in product(zip(l1,l2), repeat = 2): print(i) </code></pre> <p>Wrapping in a <code>list</code> isn't required, the for loop takes care of calling <code>next</code> on the iterator for you.</p> <p>If you want a new-line f...
3
2016-10-01T09:12:36Z
[ "python", "list", "python-3.x", "for-loop", "itertools" ]
Which is the better location to compress images ? In the browswer or on the server?
39,805,033
<p>I have a Django project and i allow users to upload images. I don't want to limit image upload size for users. But want to compress the image after they select and store them. I want to understand which is better:</p> <ol> <li>Compress using java-script on the browser.</li> <li>Back end server using python librarie...
0
2016-10-01T09:32:14Z
39,805,099
<p>I advice you to compress on the browser in order to :</p> <ul> <li>avoid loading the server with many CPU and RAM heavy consuming calculations (as numerous as number of clients)</li> <li>dwindle bandwith needed when transfert image threw the network</li> </ul>
1
2016-10-01T09:40:12Z
[ "javascript", "python", "html", "django", "image-compression" ]
Which is the better location to compress images ? In the browswer or on the server?
39,805,033
<p>I have a Django project and i allow users to upload images. I don't want to limit image upload size for users. But want to compress the image after they select and store them. I want to understand which is better:</p> <ol> <li>Compress using java-script on the browser.</li> <li>Back end server using python librarie...
0
2016-10-01T09:32:14Z
39,805,180
<p>I would compress in nginx (or apache) since this is the right place to do it. no need for python libraries to do this</p> <p>small example: </p> <pre><code>gzip on; gzip_static on; gzip_comp_level 9; gzip_min_length 1400; gzip_types image/png image/gif image/jpeg </code></pre> <p>more on it --> <a href="https:/...
1
2016-10-01T09:49:54Z
[ "javascript", "python", "html", "django", "image-compression" ]
RabbitMQ unacked messages
39,805,088
<p>I'm creating Tasks at a rate of 5 Tasks per second. I can see in RabbitMQ Message rates incoming an average of 5.2/s, I have 240 consumers distributed in 4 Virtual machines (60 per VM), each worker process a Task that last 20 seconds. In theory I'm supposed to handle 100K task without queuing.</p> <p>I see a large ...
0
2016-10-01T09:39:14Z
39,816,273
<p>Message acknowledgement acts like transaction in SQL like commit you have to acknowledge the message received from RabbitMq. This function help to avoid the message loss in your system.</p> <p>Navigate to <strong>Message acknowledgment</strong> title <a href="https://www.rabbitmq.com/tutorials/tutorial-two-python.h...
1
2016-10-02T10:57:24Z
[ "python", "rabbitmq", "celery" ]
In a list of lists how to get all the items except the last one for each list?
39,805,098
<p>So I have this list of lists. Each nested list has <code>n+1</code> element where the first element are floats and the last one is an integer. I need to get , for each nested list, all the floats (so n elements out of <code>n+1</code>). Which is the best way to achieve that?</p> <p>For example:</p> <pre><code>x = ...
0
2016-10-01T09:40:08Z
39,805,133
<p>If you are <em>certain</em> the <code>int</code> will always be last, slicing is an option whereby you trim off the last element from every sub-list <code>sub</code> in <code>x</code> with <code>sub[:-1]</code> (<code>[:-1]</code> means grab all except the last element):</p> <pre><code>out = [sub[:-1] for sub in x]...
2
2016-10-01T09:44:18Z
[ "python", "list", "python-3.x" ]
In a list of lists how to get all the items except the last one for each list?
39,805,098
<p>So I have this list of lists. Each nested list has <code>n+1</code> element where the first element are floats and the last one is an integer. I need to get , for each nested list, all the floats (so n elements out of <code>n+1</code>). Which is the best way to achieve that?</p> <p>For example:</p> <pre><code>x = ...
0
2016-10-01T09:40:08Z
39,805,134
<p>This is the shortest and easiest way:</p> <pre><code>output = [l[:-1] for l in x] </code></pre> <p>It is called a <a href="https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension </a>.</p>
4
2016-10-01T09:44:23Z
[ "python", "list", "python-3.x" ]
Jupyter Notebook: How to output chinese?
39,805,113
<p>The coloumn ['douban_info'] in my dataset is info about movies in Chinese which stored in JSON, so when I do <code>df['douban_info'][0]</code>, it returns</p> <p><a href="http://i.stack.imgur.com/6WCkU.png" rel="nofollow"><img src="http://i.stack.imgur.com/6WCkU.png" alt="enter image description here"></a></p> <p>...
0
2016-10-01T09:42:29Z
39,805,228
<p>Call <code>json.dump</code> or <code>json.dumps</code> with <code>ensure_ascii=False</code> options, then you will get raw utf-8 encoded string.</p> <p>referenced by <a href="https://docs.python.org/2/library/json.html" rel="nofollow">https://docs.python.org/2/library/json.html</a></p> <p><code>json.dump(obj, fp,...
-1
2016-10-01T09:56:13Z
[ "python", "unicode", "jupyter-notebook" ]
Jupyter Notebook: How to output chinese?
39,805,113
<p>The coloumn ['douban_info'] in my dataset is info about movies in Chinese which stored in JSON, so when I do <code>df['douban_info'][0]</code>, it returns</p> <p><a href="http://i.stack.imgur.com/6WCkU.png" rel="nofollow"><img src="http://i.stack.imgur.com/6WCkU.png" alt="enter image description here"></a></p> <p>...
0
2016-10-01T09:42:29Z
39,812,356
<p>This is how Python 2 works. It by default displays the <code>repr()</code> when generating display strings for lists and strings. You have to <code>print</code> strings to see the Unicode characters:</p> <pre><code>&gt;&gt;&gt; D = {u'aka': [u'2019\u730e\u8840\u90fd\u5e02(\u6e2f)', u'\u9ece\u660e\u65f6\u5206']} &...
1
2016-10-01T23:15:47Z
[ "python", "unicode", "jupyter-notebook" ]
How to go about incremental scraping large sites near-realtime
39,805,237
<p>I want to scrape a lot (a few hundred) of sites, which are basically like bulletin boards. Some of these are very large (up to 1.5 million) and also growing very quickly. What I want to achieve is:</p> <ul> <li>scrape all the existing entries</li> <li>scrape all the new entries near real-time (ideally around 1 hour...
-1
2016-10-01T09:56:48Z
39,805,342
<blockquote> <p>For example: I have a site with 100 pages and 10 records each. So I scrape page 1, and then go to page 2. But on fast growing sites, at the time I do the request for page 2, there might be 10 new records, so I would get the same items again. Nevertheless I would get all items in the end. BUT next time...
1
2016-10-01T10:08:50Z
[ "python", "postgresql", "web-scraping", "scrapy" ]
plot 2d lines by line equation in Python using Matplotlib
39,805,258
<p>Lets say I have 2d line equations (y = Ax + B) , i.e: </p> <pre><code>[[A_1, B_1] , [A_2, B_2], .. ] </code></pre> <p>and I want to plot the lines in 2d range, for example from point (-100,-100) to point (100,100).</p> <p>as I understand the range limit can achieved with <code>xlim</code> and <code>ylim</code>, ...
2
2016-10-01T09:59:25Z
39,805,466
<p>To plot two straight lines within some specified range in x and y, you would do something like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt A1,B1 = 1.,1. A2,B2 = 2.,2. x = np.linspace(-100.,100.) fig,ax = plt.subplots() ax.plot(x,A1*x+B1) ax.plot(x,A2*x+B2) ax.set_xlim((-100.,100.)) ...
3
2016-10-01T10:22:36Z
[ "python", "matplotlib" ]
Intersection and Difference of two dictionaries
39,805,266
<p>Given two dictionaries, I want to look at their intersction and difference and perform f function on the elements that intersect and perform g on the unique elements, Here's how I found out what the unique and intersecting elements are where d1 and d2 are two dictionaries, How do i print out the d_intersection and d...
0
2016-10-01T10:00:22Z
39,805,458
<p>Here's one way of doing it, though there may be a more efficient method.</p> <pre><code>d1 = {1:30, 2:20, 3:30, 5:80} d2 = {1:40, 2:50, 3:60, 4:70, 6:90} d_intersect = {} # Keys that appear in both dictionaries. d_difference = {} # Unique keys that appear in only one dictionary. # Get all keys from both dictionar...
0
2016-10-01T10:21:57Z
[ "python", "dictionary" ]
Intersection and Difference of two dictionaries
39,805,266
<p>Given two dictionaries, I want to look at their intersction and difference and perform f function on the elements that intersect and perform g on the unique elements, Here's how I found out what the unique and intersecting elements are where d1 and d2 are two dictionaries, How do i print out the d_intersection and d...
0
2016-10-01T10:00:22Z
39,805,600
<p>You get a <em>KeyError</em> for <em>4</em> as <code>^</code> looks for the <em>symmetric difference</em> which means keys <em>unique to either</em>, the keys are <em>not in</em> both. You also don't need to create sets, you can use the <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects"...
1
2016-10-01T10:38:19Z
[ "python", "dictionary" ]
selecting correct form while iterating all forms
39,805,391
<p>I want to submit forms in multiple websites with mechanize. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p> <p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "...
7
2016-10-01T10:15:06Z
39,816,690
<p>Your problem is that you aren't storing what form you are working on. I would simply assign 0 into a variable and add 1 to it after every iteration. So your code should be:</p> <pre><code>currentForm = 0 for form in br.forms(): if not forms.find_control(name = "email"): currentForm += 1 ...
0
2016-10-02T11:49:33Z
[ "python", "mechanize" ]
selecting correct form while iterating all forms
39,805,391
<p>I want to submit forms in multiple websites with mechanize. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p> <p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "...
7
2016-10-01T10:15:06Z
39,948,965
<p>One solution would be to select the form by passing list form into br.form without using br.select_form. </p> <p>Contents of test.html:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Stuff&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="POST" &gt; &lt;input type="text" n...
0
2016-10-09T21:58:54Z
[ "python", "mechanize" ]
Python ignore character and print next character from list in for loop
39,805,409
<p>I am using BeautifulSoup4 and requests to scrape information from a website.</p> <p>I then store the required information in lists, there are two lists for two different types of information I scraped from the page.</p> <pre><code> try: for i in range(0,1000): location = dive_data1[((9*i)-7)...
1
2016-10-01T10:16:51Z
39,805,531
<p>Like @yedpodtriztko noted. You can just leave the characters that it cannot decode with following:</p> <p>instead of doing:</p> <pre><code>soup = BeautifulSoup(r.content) </code></pre> <p>you could use this:</p> <pre><code>soup = BeautifulSoup(r.content.decode('utf-8', 'ignore')) </code></pre>
-1
2016-10-01T10:30:54Z
[ "python", "beautifulsoup", "export-to-csv" ]
Python ignore character and print next character from list in for loop
39,805,409
<p>I am using BeautifulSoup4 and requests to scrape information from a website.</p> <p>I then store the required information in lists, there are two lists for two different types of information I scraped from the page.</p> <pre><code> try: for i in range(0,1000): location = dive_data1[((9*i)-7)...
1
2016-10-01T10:16:51Z
39,805,872
<p>You need to encode to <em>utf-8</em> in the loop when you write:</p> <pre><code>for i in range(len(locations)): writer.writerow((locations[i].encode("utf-8"), depths[i].encode("utf-8")) ) </code></pre>
0
2016-10-01T11:09:55Z
[ "python", "beautifulsoup", "export-to-csv" ]
Dealing with timezone dates in MongoDB and pymongo
39,805,453
<p>I do not seem to be able to query records and get what I expect. For example I am searching </p> <pre><code>today = datetime.datetime.today() past = today + timedelta(days=-200) results = mongo.stuff.find({"date_added": {"gt": past}}, {"id":1}) </code></pre> <p>I have the following date specified in MongoDB:</p> ...
0
2016-10-01T10:21:19Z
39,805,496
<p>Use an aware datetime object (with timezone info). </p> <pre><code># E.g. with UTC timezone : import pytz import datetime today = datetime.datetime.today() past = today + timedelta(days=-200) pytc.utc.localize(past) results = mongo.stuff.find({"date_added": {"gt": past}}, {"id":1}) </code></pre> <p>To use a di...
1
2016-10-01T10:25:53Z
[ "python", "mongodb", "pymongo" ]
Dealing with timezone dates in MongoDB and pymongo
39,805,453
<p>I do not seem to be able to query records and get what I expect. For example I am searching </p> <pre><code>today = datetime.datetime.today() past = today + timedelta(days=-200) results = mongo.stuff.find({"date_added": {"gt": past}}, {"id":1}) </code></pre> <p>I have the following date specified in MongoDB:</p> ...
0
2016-10-01T10:21:19Z
39,826,995
<p>This is just a typing error:</p> <p>Try with the following code:</p> <pre><code>results = mongo.stuff.find({"date_added": {"$gt": past}}, {"id":1}) </code></pre> <p>You forgot about the $ sign in $gt.</p>
1
2016-10-03T08:04:08Z
[ "python", "mongodb", "pymongo" ]
Εxtract data in between paratheses and append at the end of the line
39,805,590
<p>File.txt:</p> <pre><code>first_name NVARCHAR2(15) NOT NULL, middle_name NVARCHAR2(20) NOT NULL, last_name NVARCHAR2(11) NOT NULL, output i need:-&gt;output.txt first_name NVARCHAR2(15) NOT NULL,15 middle_name NVARCHAR2(20) NOT NULL,20 last_name NVARCHAR2(11) NOT NULL,11 </code></pre> <p>How can I extract data in ...
-2
2016-10-01T10:36:46Z
39,810,895
<p>Use regex - something like:</p> <pre><code>import re for line in input: m=re.search('\((\d+)\)',line) output.write(line.rstrip('\n')+m.group(1)+'\n') </code></pre> <p>The search content should match what you are looking for (<code>\d+</code> in my example - matches any number). If you expect more then one ...
-1
2016-10-01T19:56:39Z
[ "python", "python-3.x" ]
Django /admin/ Page not found (404)
39,805,624
<p>I have the following error:</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Raised by: nw.views.post_detail </code></pre> <p>But I can enter in example to <a href="http://127.0.0.1:8000/admin/nw/" rel="nofollow">http://127.0.0.1:8000/admin/nw/</a></p> <p>A...
0
2016-10-01T10:40:28Z
39,805,687
<p>The <code>admin</code> <em>url</em> should come first:</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('nw.urls', namespace='posts')), ] </code></pre> <p>Or else, it will be intercepted by another matching regex in your posts app <code>urlpatterns</code>, viz.:</p> <pre><...
1
2016-10-01T10:47:37Z
[ "python", "django" ]
Django /admin/ Page not found (404)
39,805,624
<p>I have the following error:</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Raised by: nw.views.post_detail </code></pre> <p>But I can enter in example to <a href="http://127.0.0.1:8000/admin/nw/" rel="nofollow">http://127.0.0.1:8000/admin/nw/</a></p> <p>A...
0
2016-10-01T10:40:28Z
39,805,748
<p>In your case this route working <code>url(r'^(?P&lt;slug&gt;[\w-]+)/$', post_detail, name='detail'),</code> and this function called <code>instance = get_object_or_404(Post, slug=slug)</code></p> <p>You can replace route like this</p> <pre><code>urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', includ...
1
2016-10-01T10:55:26Z
[ "python", "django" ]
ValueError: Could not find a default download directory of nltk
39,805,675
<p>I have problem on import nltk. I configured apache and run some sample python code, it worked well on the browser. The URL is : /localhost/cgi-bin/test.py. When I import the nltk in test.py its not running. The execution not continue after the "import nltk" line.And it gives me that error ValueError: Could not find ...
1
2016-10-01T10:46:11Z
39,805,804
<p>The environment in which your CGI script is executed is not the same as when you run it in from a terminal or similar. Specifically, environment variables like <code>$PYTHONPATH</code> might not be set to what you need.</p> <p>An ugly but safe work-around is adding the needed directories inside the script, before a...
0
2016-10-01T11:02:00Z
[ "python", "nltk" ]
ValueError: Could not find a default download directory of nltk
39,805,675
<p>I have problem on import nltk. I configured apache and run some sample python code, it worked well on the browser. The URL is : /localhost/cgi-bin/test.py. When I import the nltk in test.py its not running. The execution not continue after the "import nltk" line.And it gives me that error ValueError: Could not find ...
1
2016-10-01T10:46:11Z
39,807,691
<p>The problem is that on being imported, the <code>nltk</code> tries to initialize a <code>Downloader</code> object (even though you have not tried to download any resources), and fails to identify a usable download location. The easiest way to make it happy is to define <code>NLTK_DATA</code> in the environment, init...
0
2016-10-01T14:19:06Z
[ "python", "nltk" ]
ValueError: Could not find a default download directory of nltk
39,805,675
<p>I have problem on import nltk. I configured apache and run some sample python code, it worked well on the browser. The URL is : /localhost/cgi-bin/test.py. When I import the nltk in test.py its not running. The execution not continue after the "import nltk" line.And it gives me that error ValueError: Could not find ...
1
2016-10-01T10:46:11Z
39,810,288
<p>The Problem is raised probably because you don't have a default directory created for your ntlk downloads. If you are on a Windows Platform, All you need to do is to create a directory named "nltk_data" in any of your root directory and grant write permissions to that directory. The Natural Language Tool Kit initial...
-1
2016-10-01T18:47:43Z
[ "python", "nltk" ]
Write values to a particular cell in a sheet in pandas in python
39,805,677
<p>I have an excel sheet, which already has some values in some cells.</p> <p>For ex :- </p> <pre><code> A B C D 1 val1 val2 val3 2 valx valy </code></pre> <p><strong>I want pandas to write to specific cells without touching any other cells,sheet etc</stron...
2
2016-10-01T10:46:17Z
39,806,879
<p><strong>UPDATE2:</strong> appending data to existing Excel sheet, preserving other (old) sheets:</p> <pre><code>import pandas as pd from openpyxl import load_workbook fn = r'C:\Temp\.data\doc.xlsx' df = pd.read_excel(fn, header=None) df2 = pd.DataFrame({'Data': [13, 24, 35, 46]}) writer = pd.ExcelWriter(fn, engi...
1
2016-10-01T12:58:18Z
[ "python", "excel", "pandas" ]
Write values to a particular cell in a sheet in pandas in python
39,805,677
<p>I have an excel sheet, which already has some values in some cells.</p> <p>For ex :- </p> <pre><code> A B C D 1 val1 val2 val3 2 valx valy </code></pre> <p><strong>I want pandas to write to specific cells without touching any other cells,sheet etc</stron...
2
2016-10-01T10:46:17Z
40,060,480
<p>I was not able to do what was asked by me in the question by using pandas, but was able to solve it by using <code>Openpyxl</code>. </p> <p>I will write few code snippets which would help in achieving what was asked.</p> <pre><code>import openpyxl srcfile = openpyxl.load_workbook('docname.xlsx',read_only=False, k...
0
2016-10-15T14:51:41Z
[ "python", "excel", "pandas" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </...
0
2016-10-01T10:49:35Z
39,806,165
<p>This WILL take too long, since is a kind of geometric progression which tends to infinity.</p> <p>Example:</p> <pre><code>a=0 b=1 c=1*1 = 1 a=1 b=1 c=2*2 = 4 a=1 b=4 c=5*5 = 25 a=4 b=25 c= 29*29 = 841 a=25 b=841 . . . </code></pre>
0
2016-10-01T11:39:13Z
[ "python", "loops", "recurrence" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </...
0
2016-10-01T10:49:35Z
39,806,258
<p>You can check if c%10==0 and then divide it, and in the end multiplyit number of times you divided it but in the end it'll be the same large number. If you really need to do this calculation try using C++ it should run it faster than Python.</p> <hr> <p>Here's your code written in C++</p> <pre><code>#include &lt;...
0
2016-10-01T11:47:23Z
[ "python", "loops", "recurrence" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </...
0
2016-10-01T10:49:35Z
39,807,447
<p>I don't think this is a tractable problem with programming. The reason why your code is slow is that the numbers within grow <em>very</em> rapidly, and python uses infinite-precision integers, so it takes its time computing the result.</p> <p>Try your code with double-precision floats:</p> <pre><code>a=0.0 b=1.0 f...
2
2016-10-01T13:53:52Z
[ "python", "loops", "recurrence" ]
For loop computing recurrence relation takes very long
39,805,705
<pre><code>Q(x)=[Q(x−1)+Q(x−2)]^2 Q(0)=0, Q(1)=1 </code></pre> <p>I need to find Q(29). I wrote a code in python but it is taking too long. How to get the output (any language would be fine)?</p> <p>Here is the code I wrote:</p> <pre><code>a=0 b=1 for i in range(28): c=(a+b)*(a+b) a=b b=c print(b) </...
0
2016-10-01T10:49:35Z
39,823,636
<p>This can be solved with brute force but it is still an interesting problem since it uses two different "slow" operations and there are trade-offs in choosing the correct approach.</p> <p>There are two places where the native Python implementation of algorithm is slow: the multiplication of large numbers and the con...
1
2016-10-03T02:00:20Z
[ "python", "loops", "recurrence" ]
PIL crop image give incorrect height result
39,805,750
<pre><code>import PIL from PIL import Image img = Image.open('0009_jpg.jpg') width, height = img.size #height is 720 and width is 480 if height &gt; width: rm_height = abs(height - width) # rm_height = 240 x_offset = 0 y_offset = rm_height/2 # y_offset = 120 tall = height-rm_height # tall = 480 i...
1
2016-10-01T10:55:58Z
39,805,788
<p>OK after i search for more. Now i get it from this <a href="http://labb.in/s/ZCwU" rel="nofollow">post</a></p> <p>Chris Clarke's (<a href="http://labb.in/s/ZCqu" rel="nofollow">edited</a> by San4ez) answer:</p> <pre><code>import Image im = Image.open(&lt;your image&gt;) width, height = im.size # Get dimensions ...
-1
2016-10-01T11:00:13Z
[ "python", "python-2.7", "python-imaging-library" ]
The difference of gevent and multiprocess
39,805,780
<p>I am learning how to make my script run faster. I think parallel is a good way. So I try gevent and multiprocessing. But I am confused by it's different result. Let me show two examples I met,</p> <p>ex 1:</p> <pre><code>a=np.zeros([3]) def f(i): a[i]=1 print a def f_para(): p=multiprocessing.Pool() ...
2
2016-10-01T10:59:05Z
39,805,884
<p>ex1:</p> <p>when you use multiprocess each process has separate memory(unlike threads)</p> <p>ex2:</p> <p>gevent does not create threads, it creates Greenlets(coroutines)!</p> <blockquote> <p>Greenlets all run inside of the OS process for the main program but are scheduled cooperatively.</p> <p><strong>On...
1
2016-10-01T11:11:56Z
[ "python", "python-2.7", "parallel-processing", "multiprocessing", "gevent" ]
keep on getting str object has no attribute 'punctuation'
39,805,837
<p>Im trying to make a code that identifies punctuation in a word this is all I got up to:</p> <pre><code>word=input('enter a word: ') punctuation=set(word.punctuation) for each in word: if each==punctuation: print('yes') </code></pre> <p>but it keeps on saying 'str' object has no attribute 'punctuation' how...
-2
2016-10-01T11:06:32Z
39,805,864
<p><code>str</code> objects do not have a punctuation attribute. You can instead use <a href="https://docs.python.org/2/library/string.html#string.punctuation" rel="nofollow"><code>string.punctuation</code></a> to check for any punctuation in your word:</p> <pre><code>import string # string.punctuation '!"#$%&amp;\'(...
5
2016-10-01T11:08:59Z
[ "python" ]
Refer a global variable that has same name as the local variable in Python
39,805,893
<p>I am new to python, how can we refer a global variable that has the same name as local one. </p> <pre><code>spam = 'global spam' def scope_test(): spam = 'local spam' print(spam) # access global spam and print or assign to the local spam # print(global.spam) # local.spam = global.spam (something...
0
2016-10-01T11:13:02Z
39,808,103
<p>It's something not recommended, I am answering it for the sake if you're curious to ask/do it:</p> <pre><code>Python 3.5.2 &gt;&gt;&gt; spam = 'global spam' &gt;&gt;&gt; def scope_test(): .. spam = 'local spam' .. print(spam) .. # access global spam and print or assign to the local spam .. prin...
1
2016-10-01T15:03:22Z
[ "python" ]
pandas remove seconds from datetime index
39,805,961
<p>I have a pandas dataFrame called 'df' as follows</p> <pre><code> value 2015-09-27 03:58:30 1.0 2015-09-27 03:59:30 1.0 2015-09-27 04:00:30 1.0 2015-09-27 04:01:30 1.0 </code></pre> <p>I just want to strip out the seconds to get this</p> <pre><code> ...
0
2016-10-01T11:19:45Z
39,806,178
<p>You could use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.replace" rel="nofollow"><code>datetime.replace</code></a> to alter the second's attribute as shown:</p> <pre><code>df.index = df.index.map(lambda x: x.replace(second=0)) </code></pre> <p><a href="http://i.stack.imgur.com/xO9gu...
3
2016-10-01T11:40:22Z
[ "python", "pandas", "indexing", "seconds" ]
Open a file inside the package directory instead of opening from current directory
39,806,088
<p>I have created a Python package and installed locally. With using the command <code>pip install .</code> .In my package it's necessary to open a file like this.</p> <pre><code>open('abc.txt','r+') </code></pre> <p>But my problem is it's try to open the file in the working directory instead of package installed dir...
0
2016-10-01T11:31:21Z
39,806,187
<p>Try: </p> <pre><code>import os import inspect def open_file(filename): pkg_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) return open(pkg_dir + "/" + filename,'r+') </code></pre>
1
2016-10-01T11:41:10Z
[ "python", "python-packaging" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0...
0
2016-10-01T11:32:04Z
39,806,237
<p>What you are probably looking for is a <strong>for-loop</strong>.</p> <p>Using a for-loop your code could look like this:</p> <pre><code>word = "computer" for letter in word: index = ord(letter)-97 if (index&lt;0) or (index&gt;25): print ("'{}' is not in the lowercase alphabet.".format(letter)) else: ...
2
2016-10-01T11:45:21Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0...
0
2016-10-01T11:32:04Z
39,806,314
<p>Use for loop for loop,</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" for l in word: print '{} = {}'.format(l,alpha.index(l.lower())) </code></pre> <p><strong>Result</strong></p> <pre><code>c = 2 o = 14 m = 12 p = 15 u = 20 t = 19 e = 4 r = 17 </code></pre>
0
2016-10-01T11:53:54Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0...
0
2016-10-01T11:32:04Z
39,806,396
<p>Start with a <code>dict</code> that maps each letter to its number.</p> <pre><code>import string d = dict((c, ord(c)-ord('a')) for c in string.lowercase) </code></pre> <p>Then pair each letter of your string to the appropriate index.</p> <pre><code>result = [(c, d[c]) for c in word] </code></pre>
0
2016-10-01T12:02:42Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0...
0
2016-10-01T11:32:04Z
39,806,691
<p>thanks for the help managed to solve it myself in a different way using a function and a while loop, not as short but will work for all lower case words:</p> <pre><code>alpha = map(chr, range (97,123)) word = "computer" count = 0 y = 0 def indexfinder (number): o = word[number] i = str(alpha.index(o)) ...
0
2016-10-01T12:39:20Z
[ "python", "string", "list" ]
Python: Converting word to list of letters, then returning indexes of the letters against lower case alphabet
39,806,097
<p>I have already completed the task but in its most basic form looking for help shortening it and so it can apply to any word not just one with eight letters, here's what I've got so far (bit long for what it does):</p> <pre><code>alpha = map(chr, range(97, 123)) word = "computer" word_list = list(word) one = word[0...
0
2016-10-01T11:32:04Z
39,806,942
<p>Just an alternative way:</p> <pre><code>for w in word: print (w+" = "+str((ord(w.lower())-96))) if w not in '., !' else "" </code></pre> <p>This way is not case sensitive, for example for <code>Computer</code> you will get the same results as with <code>computer</code>, but the output is case sensitive (I mean...
0
2016-10-01T13:03:40Z
[ "python", "string", "list" ]
Python - multiprocessing while writing to a single result file
39,806,110
<p>I am really new to the multiprocessing package and I am failing to get the task done.</p> <p>I have lots of calculations to do on a list of objects. </p> <p>The results I need to write down are saved in those objects, too.</p> <p>The results should be written in a single file as soon as the process finished the c...
0
2016-10-01T11:33:29Z
39,806,402
<p>You can use <a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.imap_unordered" rel="nofollow">imap_unordered</a></p> <pre><code>def mp_handler(data_list): p = multiprocessing.Pool(4) with open('results.csv', 'a') as f: writer= csv.writer(f, lineterminator = '\n...
3
2016-10-01T12:03:34Z
[ "python", "multiprocessing" ]
Scrapy not going to next page (follow links) when the url is constructed from a csv file
39,806,177
<p>Hi I have this simple scrapy file. As you can see, I am adding ship imo number to the response.url(). But when i run the programme i do not get any results (no error messages as well). I have set the USER AGENT in settings.py.</p> <pre><code>import re import csv import scrapy from mcdetails.items import Mcdetail...
0
2016-10-01T11:40:10Z
39,808,074
<p>The traceback speaks for itself:</p> <pre><code>2016-10-01 15:37:53 [scrapy] DEBUG: Filtered offsite request to 'maritime-connector.com': &lt;GET http://maritime-connector.com/ship/8986080&gt; </code></pre> <p>Your <code>allowed_domains</code> are wrong. You should use:</p> <pre><code>allowed_domains = ["maritime...
1
2016-10-01T15:00:35Z
[ "python", "scrapy" ]
Convert List of List of Tuples Into 2d Numpy Array
39,806,259
<p>I have a list of list of tuples:</p> <pre><code>X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]] </code></pre> <p>and would like to convert it to a 2D numpy array. I trie...
0
2016-10-01T11:47:28Z
39,806,711
<p>Dont know if you are working on python 2.x or 3.x but in 3.x you could try:</p> <pre><code>&gt;&gt; import numpy as np &gt;&gt; X = [(....)] # Your list &gt;&gt; array = np.array([*X]) &gt;&gt; print(array) array([[[ 0.5 , 0.5 , 0.5 ], [ 1. , 1. , 1. ]], [[ 0.5 , 0.5 , 0.52], [ 1. , 1. , 1....
0
2016-10-01T12:41:30Z
[ "python", "numpy" ]
Convert List of List of Tuples Into 2d Numpy Array
39,806,259
<p>I have a list of list of tuples:</p> <pre><code>X = [[(0.5, 0.5, 0.5), (1.0, 1.0, 1.0)], [(0.5, 0.5, 0.52), (1.0, 1.0, 1.0)], [(0.5, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)], [(0.52, 0.52, 0.52), (1.0, 1.0, 1.0)]] </code></pre> <p>and would like to convert it to a 2D numpy array. I trie...
0
2016-10-01T11:47:28Z
39,808,449
<p>If I do the normal thing to your list I get a 3d array:</p> <pre><code>In [38]: np.array(X) Out[38]: array([[[ 0.5 , 0.5 , 0.5 ], [ 1. , 1. , 1. ]], [[ 0.5 , 0.5 , 0.52], [ 1. , 1. , 1. ]], [[ 0.5 , 0.52, 0.52], [ 1. , 1. , 1. ]], [[ 0.52, 0.52,...
0
2016-10-01T15:37:50Z
[ "python", "numpy" ]
convert a fasta file to a tab-delimited file using python script
39,806,301
<p>I am student currently learning how to write scripts in python. I have been giving the following exercise. I have to convert a fasta file in the following format: </p> <pre><code>&gt;header 1 AATCTGTGTGATAT ATATA AT &gt;header 2 AATCCTCT </code></pre> <p>into this: </p> <pre><code>&gt;header 1 AATCTGTGTGAT...
0
2016-10-01T11:52:18Z
39,806,591
<p>This creates a new string based on the <code>&gt;</code> character and combines the string until the next <code>&gt;</code>. It then appends to a running list.</p> <pre><code># open file and iterate through the lines, composing each single line as we go out_lines = [] temp_line = '' with open('path/to/file','r') a...
0
2016-10-01T12:26:26Z
[ "python", "parsing" ]
convert a fasta file to a tab-delimited file using python script
39,806,301
<p>I am student currently learning how to write scripts in python. I have been giving the following exercise. I have to convert a fasta file in the following format: </p> <pre><code>&gt;header 1 AATCTGTGTGATAT ATATA AT &gt;header 2 AATCCTCT </code></pre> <p>into this: </p> <pre><code>&gt;header 1 AATCTGTGTGAT...
0
2016-10-01T11:52:18Z
39,807,390
<p>I am trying to understand the script posted above, line by line. I have posted what I think it is doing below: </p> <pre><code># open file and iterate through the lines, composing each single line as we go. out_lines = [] temp_line = '' with open('sequences.fa','r') as fp: for line in fp: if line.st...
0
2016-10-01T13:47:43Z
[ "python", "parsing" ]
Why does a python program not interrupt with Ctlr+d or Ctrl+c?
39,806,392
<p>This is a client code from my server-client chat program but when i'm trying to close this program with sending a letter <em>q</em>, it simply doesn't work. It stucks in the terminal and waits for something.</p> <p>What did i do wrong here?</p> <pre><code>import socket import threading import time receiving = Fal...
0
2016-10-01T12:02:10Z
39,806,416
<p>Because you have a exception block that excepts on everything. In this case it also catches keyboard interrupt and overrides your termination call.</p> <p>You should probably add a separate catch block for the KeyboardInterrupt:</p> <pre><code>except KeyboardInterrupt: raise </code></pre>
3
2016-10-01T12:05:16Z
[ "python" ]
Why does a python program not interrupt with Ctlr+d or Ctrl+c?
39,806,392
<p>This is a client code from my server-client chat program but when i'm trying to close this program with sending a letter <em>q</em>, it simply doesn't work. It stucks in the terminal and waits for something.</p> <p>What did i do wrong here?</p> <pre><code>import socket import threading import time receiving = Fal...
0
2016-10-01T12:02:10Z
39,806,418
<p>Because in python ctrl+C triggers KeyboardInterrupt exception to be thrown. This allows you to gracefully shut down your program. And you catch this exception with </p> <pre><code> except: pass </code></pre>
0
2016-10-01T12:05:28Z
[ "python" ]
Comparing items of case-insensitive list
39,806,410
<p>So I have two lists, with items in varying cases. Some of the items are the same but are lowercase/uppercase. How can I create a loop to run through all the items and do something with each item, that also ignores what case the item may have?</p> <pre><code>fruits = ['Apple','banana','Kiwi','melon'] fruits_add = ['...
2
2016-10-01T12:04:15Z
39,806,435
<p>I wouldn't use the lower() function there. Use lower like this:</p> <pre><code>for fruit in fruits_add: if fruit.lower() in fruits: print("already in list") </code></pre>
-1
2016-10-01T12:07:18Z
[ "python", "list", "python-3.x", "compare", "case-insensitive" ]
Comparing items of case-insensitive list
39,806,410
<p>So I have two lists, with items in varying cases. Some of the items are the same but are lowercase/uppercase. How can I create a loop to run through all the items and do something with each item, that also ignores what case the item may have?</p> <pre><code>fruits = ['Apple','banana','Kiwi','melon'] fruits_add = ['...
2
2016-10-01T12:04:15Z
39,806,444
<p><code>fruit.lower()</code> in the for loop won't work as the error message implies, you can't assign to a function call..</p> <p>What you could do is create an auxiliary structure (<code>set</code> here) that holds the lowercase items of the existing fruits in <code>fruits</code>, and, <code>append</code> to <code>...
1
2016-10-01T12:08:36Z
[ "python", "list", "python-3.x", "compare", "case-insensitive" ]
Why does this Python Tkinter stopwatch script crash?
39,806,420
<p>I have this script I wrote as a timer, but it crashes whenever I press the start button. (Sorry, I'm very much so of a noob) <a href="http://pastebin.com/BWDaRTYv" rel="nofollow">http://pastebin.com/BWDaRTYv</a> Thanks, Sam</p>
-4
2016-10-01T12:05:37Z
39,835,322
<p>I can't see your code but I am willing to bet that you are using time.sleep to delay your time. DONT. Use the Tkinter .after method to schedule a function to be called periodically to update your timer.</p> <p><a href="http://effbot.org/tkinterbook/widget.htm" rel="nofollow">See here</a> or <a href="http://stackove...
0
2016-10-03T15:36:54Z
[ "python", "button", "timer", "tkinter", "crash" ]
Flask: differences between request.form["xxxxx"], request.form.get("xxxxxx") and request.args.get("xxxxx")?
39,806,433
<p>What are the differences between <code>flask.request.form["xxx"]</code> , <code>flask.request.form.get("xxx")</code> and <code>flask.request.args.get("xxx")</code> ? </p> <p>I have this question because I am using flask-login to handle authentication.<br> In particular in the following code (taken from the flask-l...
0
2016-10-01T12:06:51Z
39,807,501
<p>The proper use-case get() is to return a default value when the key you are looking for doesn't exist in a dictionary.</p> <p>For example, if you have a dictionary d such that :</p> <pre><code>d = {'foo': 'bar'} </code></pre> <p>Doing the following will return None:</p> <pre><code>d.get('baz', None) </code></pre...
0
2016-10-01T13:59:12Z
[ "python", "flask", "flask-login" ]
How do I return the value from each iteration of a loop to the function it is running within?
39,806,486
<p>I'm making a program that scrapes local bus times from a real time information server and prints them. In order to return all the bus times, it does this:</p> <pre><code>while i &lt; len(info["results"]): print "Route Number:" + " " + info['results'][i]['route'] print "Due in" + " " + info["results"][i]["du...
0
2016-10-01T12:14:06Z
39,806,531
<p>Can you not just make a list and return the list? </p> <pre><code>businfo = list() while i &lt; len(info["results"]): businfo.append("Route Number:" + " " + str(info['results'][i]['route']) + "\n" + "Due in" + " " + str(info["results"][i]["duetime"]) + " " + "minutes." + "\n") i = i + 1 return businfo </...
3
2016-10-01T12:20:43Z
[ "python", "json", "function", "loops" ]
How do I return the value from each iteration of a loop to the function it is running within?
39,806,486
<p>I'm making a program that scrapes local bus times from a real time information server and prints them. In order to return all the bus times, it does this:</p> <pre><code>while i &lt; len(info["results"]): print "Route Number:" + " " + info['results'][i]['route'] print "Due in" + " " + info["results"][i]["du...
0
2016-10-01T12:14:06Z
39,806,577
<p>I would suggest you to use the yield statement instead return in fetchtime function.</p> <p>Something like:</p> <pre><code>def fetchtime(stopnum): data = "?stopid={}".format(stopnum)+"&amp;format=json" content = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation" req = urllib2.urlopen(conte...
1
2016-10-01T12:24:54Z
[ "python", "json", "function", "loops" ]
How do I draw a table of squares on tkinter canvas based on a table (list of lists)?
39,806,552
<p>it's me again :) I'm carrying on on my game project. I'm stuck (as the beginner I am) on this thing: I have a table (list of 4 lists of 4 elements each. The length is flexible though, this is only a simple example for the question). so here is my code:</p> <pre><code>from tkinter import* l=[[0,0,0,0],[0,0,0,0],[0,0...
0
2016-10-01T12:22:03Z
39,806,855
<p>Here's how to draw a square grid of squares on a Canvas.</p> <pre><code>import tkinter as tk l = [[0,0,0,0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] n = len(l) #this is the length of the list l lngt = 400 // n #this is the dimension of the squares that I want fen = tk.Tk() fen.geometry("600x400") #I would...
1
2016-10-01T12:55:30Z
[ "python", "list", "canvas", "tkinter", "tkinter-canvas" ]
how to have "city" fields depending on "country" field in Django models, without creating their tables
39,806,588
<p>I know there are several questions asked like this (such as <a href="http://stackoverflow.com/questions/25706639/django-dependent-select">this one</a>), but non of them could help me with my problem.</p> <p>I wanna have a City and a Country field in my models, which the City choices is depended on Country; BUT I do...
0
2016-10-01T12:25:55Z
39,807,298
<p>the only way for it would be to define choices in your model: </p> <pre><code>class UserProfile(models.Model): CITIES = ( ('ny', 'New York'), ('sm', 'Santa Monica') # .. etc ) city = models.CharField(max_length=5, choices=CITIES, blank=True) </code></pre> <p><a href="https://doc...
0
2016-10-01T13:37:10Z
[ "python", "django", "django-countries" ]
how to have "city" fields depending on "country" field in Django models, without creating their tables
39,806,588
<p>I know there are several questions asked like this (such as <a href="http://stackoverflow.com/questions/25706639/django-dependent-select">this one</a>), but non of them could help me with my problem.</p> <p>I wanna have a City and a Country field in my models, which the City choices is depended on Country; BUT I do...
0
2016-10-01T12:25:55Z
39,807,588
<p>In order to do this you can use <a href="https://github.com/coderholic/django-cities" rel="nofollow">django-cities</a>. </p> <p>However, this will not resolve the issue with the input logic - if you need something like filtering the cities after selecting a country in your forms. You could use <a href="https://gith...
0
2016-10-01T14:08:45Z
[ "python", "django", "django-countries" ]
Ignore or sidestep a name error
39,806,706
<p>I feel like I'm turning a molehill into a mountain here but I can't think of or don't know of a better way to do this. </p> <p>In short, <strong>I have</strong> a list of lists that looks like: </p> <p><code>[ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]</code></p> <p>And <strong>I need</strong> a l...
0
2016-10-01T12:41:04Z
39,806,810
<p>If you want to solve "i have this and i want this" it can simply be done with <a href="https://docs.python.org/2/library/functions.html#map" rel="nofollow"><code>map</code></a></p> <pre><code>&gt;&gt;&gt; a = [ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ] &gt;&gt;&gt; map(lambda x: {'lat': x[0], 'lng'...
0
2016-10-01T12:51:00Z
[ "python", "string", "list", "set", "jinja2" ]
Ignore or sidestep a name error
39,806,706
<p>I feel like I'm turning a molehill into a mountain here but I can't think of or don't know of a better way to do this. </p> <p>In short, <strong>I have</strong> a list of lists that looks like: </p> <p><code>[ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]</code></p> <p>And <strong>I need</strong> a l...
0
2016-10-01T12:41:04Z
39,806,815
<p>Based on the provided data structures and what expected output you are looking to achieve, this can be done through a simple loop over your existing data structure and creating a new list of dictionaries:</p> <pre><code>coords = [ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ] new_list = [] for data in...
1
2016-10-01T12:51:14Z
[ "python", "string", "list", "set", "jinja2" ]
Ignore or sidestep a name error
39,806,706
<p>I feel like I'm turning a molehill into a mountain here but I can't think of or don't know of a better way to do this. </p> <p>In short, <strong>I have</strong> a list of lists that looks like: </p> <p><code>[ [4.54323, 5.4325], [7.235, 3.67543], [9.342543, 1.65323] ]</code></p> <p>And <strong>I need</strong> a l...
0
2016-10-01T12:41:04Z
39,807,063
<p>As an alternative to using dictionaries, consider using namedtuples to store your position data. They use less RAM, and the components can be accessed either by index or as attributes. Since namedtuples are a type of tuple they are immutable, but it generally make sense for (latitude, longitude) info of a place to b...
1
2016-10-01T13:14:03Z
[ "python", "string", "list", "set", "jinja2" ]
Using BeautifulSoup with multiple tags with the same name
39,806,817
<p>I have the below html</p> <pre><code>&lt;g class="1581 sqw_sv5" style="cursor: pointer;"&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#ffffff" style="stroke-width: 3.6; stroke-opacity: 0.5; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; &lt;pat...
0
2016-10-01T12:51:21Z
39,806,925
<p>You need to use find_all to first find all the <em>path's</em> and then extract the last one:</p> <pre><code>h = """&lt;g class="1581 sqw_sv5" style="cursor: pointer;"&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#ffffff" style="stroke-width: 3.6; stroke-opa...
2
2016-10-01T13:02:09Z
[ "python", "beautifulsoup" ]
Using BeautifulSoup with multiple tags with the same name
39,806,817
<p>I have the below html</p> <pre><code>&lt;g class="1581 sqw_sv5" style="cursor: pointer;"&gt; &lt;path d="M397.696,126.554C397.696,126.554,404.57504,140.2417375,404.57504,140.2417375" stroke="#ffffff" style="stroke-width: 3.6; stroke-opacity: 0.5; stroke-linecap: round; fill-opacity: 0;"&gt; &lt;/path&gt; &lt;pat...
0
2016-10-01T12:51:21Z
39,807,113
<p>Here's my solution to your question. My issue with my answer is that it may be overly specific. This will only work if the value of <code>style</code> is always <code>"stroke-width: 1.2; stroke-linecap: round; fill-opacity: 0;"</code> and if only one such <code>path</code> element is present in the entire document...
1
2016-10-01T13:20:05Z
[ "python", "beautifulsoup" ]
find all files matching exact name with and without an extension
39,806,895
<p>I'm using glob to scan a specified directory to find all files matching the specified name, but I can't seem to get it to work with files with no extension without finding files matching the name and then some...</p> <p>For example, here's some files:<br> - file<br> - file2<br> - file.dat</p> <p>The resulting list...
3
2016-10-01T12:59:36Z
39,812,454
<p>Shortly after posting this question, I thought of the answer, but gave up the phone before I could post it...</p> <p>So instead of relying on glob to find the royal all files, have it only look for files with extensions.</p> <p>Here's how to validate if glob is even needed:</p> <pre><code>path = 'subdirectory/fil...
0
2016-10-01T23:31:36Z
[ "python", "glob" ]
local and global variable usage in Python
39,806,949
<p>I am testing a reverse function. My code is as follow:</p> <pre><code>def deep_reverse(L): new_list = [] for element in L: new_list += [element[::-1]] L = new_list[::-1] L = [[1, 2], [3, 4], [5, 6, 7]] deep_reverse(L) print(L) </code></pre> <p>I expect my output L can be like [[7, 6, 5], [4,...
-1
2016-10-01T13:04:28Z
39,807,032
<p><code>L</code> is just a local variable, and assigning a new object to it won't change the original list; all it does is point the name <code>L</code> in the function to another object. See <a href="http://nedbatchelder.com/text/names.html" rel="nofollow">Ned Batchelder's excellent explanation about Python names</a>...
1
2016-10-01T13:11:56Z
[ "python", "list", "global-variables", "reverse", "local-variables" ]
shell script not executing a python file
39,806,957
<p>I am trying to run a script which in turn should execute a basic python script. This is the shell script:</p> <pre><code>#!usr/bin/bash mv ~/Desktop/source/movable.py ~/Desktop/dest cd ~/Desktop/dest pwd ls -lah chmod +x movable.py python movable.py echo "Just ran a python file from a shell script" </code></pre> <...
0
2016-10-01T13:05:15Z
39,822,085
<p>You are missing a '/' in the shebang line:</p> <pre><code>#!usr/bin/python </code></pre> <p>should be</p> <pre><code>#!/usr/bin/python </code></pre> <p>Another thing I noticed was, you are calling cd in os.system. Since that command would be executed in a sub shell, it won't change the current directory of the ...
0
2016-10-02T21:52:56Z
[ "python", "shell" ]
is comparison returns False with strings using same id
39,807,008
<p>I was playing around with Python <code>is</code> and <code>==</code> operator. As far as I know, is operator checks whether two objects have same id, but in my case operator returns False even if two substrings have the same id. </p> <p>Here is the code:</p> <pre><code>#! /usr/bin/python3 # coding=utf-8 string = "...
3
2016-10-01T13:10:37Z
39,807,198
<p>For me both:</p> <pre><code>print(id(string[0:5])) print(id(string[-10:-5])) </code></pre> <p>have different IDs, and as such, those answers:</p> <pre><code>print(string[0:5] == string[-10:-5]) #True print(string[0:5] is string[-10:-5]) #False </code></pre> <p>Are as they should be expected.</p> <p>Are ...
0
2016-10-01T13:27:19Z
[ "python", "string", "comparison" ]
How to parallelize 2 loops in python
39,807,026
<p>I need to make each iteration in different thread (for each of these 2 loops). </p> <pre><code>var = 5 a = -7 b = 7 for i in range(var): for j in range(a, b): print(i, " ", j) </code></pre> <p>How can I make it?</p> <p>UPD:</p> <pre><code>var = 5 a = -7 b = 7 max = 0 for i in range(var): for j ...
1
2016-10-01T13:11:43Z
39,807,254
<p>You can not run these two loops in different threads because the second loop have dependency to the data which is produced in first loop.</p> <p>One way is to run each iteration of first loop in a different thread like this:</p> <pre><code>from threading import Thread var = 5 a = -7 b = 7 def inner_loop(i): f...
1
2016-10-01T13:33:15Z
[ "python", "multithreading" ]
How to parallelize 2 loops in python
39,807,026
<p>I need to make each iteration in different thread (for each of these 2 loops). </p> <pre><code>var = 5 a = -7 b = 7 for i in range(var): for j in range(a, b): print(i, " ", j) </code></pre> <p>How can I make it?</p> <p>UPD:</p> <pre><code>var = 5 a = -7 b = 7 max = 0 for i in range(var): for j ...
1
2016-10-01T13:11:43Z
39,807,401
<p>If you want true multi-threading (which the 'threading' library doesn't do!) use the 'multiprocessing' library. The <a href="https://docs.python.org/2/library/multiprocessing.html#introduction" rel="nofollow">introduction section in the docs</a> has a good example.</p>
1
2016-10-01T13:49:10Z
[ "python", "multithreading" ]
Selenium seems not working properly with Firefox 49.0, Is anyone familiar with this?
39,807,042
<p>I have been trying to load my Firefox (Mozilla Firefox 49.0), with simple python script and with the assistance of selenium-2.53.6 on Ubuntu 16.04.1 LTS, but even <a href="https://pypi.python.org/pypi/selenium" rel="nofollow">selenium's basic example 0</a> doesn't work:</p> <blockquote> <p>from selenium import we...
0
2016-10-01T13:12:25Z
39,807,144
<p>For firefox 49.0 you need selenium 3(it's in beta stage, that's why you can't download it with <code>pip -U</code>) and geckodriver.</p> <p>try this:</p> <pre><code>wget https://github.com/mozilla/geckodriver/releases/download/v0.10.0/geckodriver-v0.10.0-linux64.tar.gz tar xzvf geckodriver-v0.10.0-linux64.tar.gz c...
3
2016-10-01T13:21:49Z
[ "python", "selenium", "firefox" ]