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
numpy ndarray with more that 32 dimensions
39,325,930
<p>When I try to create an numpy array with more than 32 dimensions I get an error: </p> <pre><code>import numpy as np np.ndarray([1] * 33) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-2-78103e...
2
2016-09-05T07:46:13Z
39,334,404
<p>How about maintaining the data in a 1d, and selectively reshaping to focus on a given dimension</p> <p>To illustrate</p> <pre><code>In [252]: x=np.arange(2*3*4*5) </code></pre> <p>With full reshape</p> <pre><code>In [254]: x.reshape(2,3,4,5).sum(2) Out[254]: array([[[ 30, 34, 38, 42, 46], [110, 114,...
0
2016-09-05T16:17:41Z
[ "python", "python-3.x", "numpy", "multidimensional-array", "python-2.x" ]
How to copy os image cross IDC with softlayer API?
39,326,006
<p>I have a VM in IDC A, and I have captured this VM as my custom image_A. Now I want to copy image_A to IDC B. Does the softlayer API support this operation?</p>
0
2016-09-05T07:51:41Z
39,355,079
<h2>To copy image across datacenters:</h2> <p>You can use: </p> <ul> <li><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest_Block_Device_Template_Group/addLocations" rel="nofollow">SoftLayer_Virtual_Guest_Block_Device_Template_Group::addLocations</a></li> </ul> <p>Here an example using RES...
1
2016-09-06T17:52:45Z
[ "python", "api", "softlayer" ]
How to uninstall django-watson library clearly
39,326,089
<p>I want use search library in django</p> <p>So i decide to use django-watson(it tell me easy install, easy use)</p> <p>I command</p> <pre><code>git clone https://github.com/etianen/django-watson.git </code></pre> <p>in my django projects</p> <p>and insert <code>watson</code> in my <code>settings.py. INSTALLED_AP...
1
2016-09-05T07:56:29Z
39,326,161
<p>Make sure you have removed it from INSTALLED_APPS in settings.py and that you have removed all imports related to it inside your project.</p>
1
2016-09-05T08:01:12Z
[ "python", "django", "environment-variables", "uninstall", "django-watson" ]
python3 global name 'SOL_SOCKET is not defined
39,326,220
<p>when I use <code>gevent</code>, I can not use <code>requests</code>, is my useage wrong?</p> <pre><code>from gevent import monkey; monkey.patch_all() import gevent, requests requests.get('https://haofly.net') </code></pre> <p>it raise the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt...
0
2016-09-05T08:04:46Z
39,333,822
<p>Install the Python 3.5 version can fix this problem.</p>
0
2016-09-05T15:34:28Z
[ "python", "python-3.x", "python-3.3" ]
python3 global name 'SOL_SOCKET is not defined
39,326,220
<p>when I use <code>gevent</code>, I can not use <code>requests</code>, is my useage wrong?</p> <pre><code>from gevent import monkey; monkey.patch_all() import gevent, requests requests.get('https://haofly.net') </code></pre> <p>it raise the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt...
0
2016-09-05T08:04:46Z
39,335,677
<p>This is really a bug in gevent. It is trying to import a <a href="https://docs.python.org/3/library/socket.html#constants" rel="nofollow"><code>socket</code> constant</a> from the <code>ssl</code> library.</p> <p>That specific constant <em>happens</em> to be imported into the <code>ssl</code> library because that l...
1
2016-09-05T18:01:45Z
[ "python", "python-3.x", "python-3.3" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(ema...
-1
2016-09-05T08:06:24Z
39,326,331
<p>I recommend you use for loop, so whatever be the number of values it will be appended to array, if there's no value none will be appended : </p> <pre><code>for single_name in name: allname.append(single_name) for single_tel in tel: alltel.append(single_tel) for single_email in email: allemail.append(sin...
0
2016-09-05T08:12:34Z
[ "python", "beautifulsoup", "append" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(ema...
-1
2016-09-05T08:06:24Z
39,326,735
<p>You can use a <code>try, except</code> to catch your exceptions as follows.</p> <pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(...
0
2016-09-05T08:39:30Z
[ "python", "beautifulsoup", "append" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(ema...
-1
2016-09-05T08:06:24Z
39,326,985
<p>soup.find() returns a None value if there is no match. An attribute error occurs when applying the .string method to a None value. You can catch it this way:</p> <pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='...
-1
2016-09-05T08:55:25Z
[ "python", "beautifulsoup", "append" ]
Append value to list with BeautifulSoup in Python
39,326,246
<pre><code>allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.find('a', class_='tel').string email = soup.find('a', class_='email').string allname.append(name) alltel.append(tel) allemail.append(ema...
-1
2016-09-05T08:06:24Z
39,327,346
<p>You can write your own function to verify the attribute, See below example.</p> <pre><code>def validate_string(attr): if attr.strip() == '': return 'NA' else: return attr.strip() allname = [] alltel = [] allemail = [] for link in docdetail: name = soup.h1.contents[1] tel = soup.fin...
0
2016-09-05T09:15:36Z
[ "python", "beautifulsoup", "append" ]
Django aggregate, use of AND/OR operators in when condition
39,326,289
<p>With the following queryset I would like to add and / or condition in the when clause, but I get syntax error. Is it possible to do it in a single queryset or should I split?</p> <pre><code>Game.objects.prefetch_related('schedule').filter(Q(team_home_id=625) | Q(team_away_id=625), schedule__date_time_start__lte=tim...
0
2016-09-05T08:09:32Z
39,326,325
<p>According to the <a href="https://docs.djangoproject.com/en/1.10/ref/models/conditional-expressions/#when" rel="nofollow">docs</a> you have to use <code>Q</code> objects when using complex conditions (just like you did in <code>filter</code>). An example:</p> <pre><code>When(Q(name__startswith="John") | Q(name__sta...
1
2016-09-05T08:11:47Z
[ "python", "django", "aggregate", "django-queryset" ]
AccessToken matching query does not exist
39,326,356
<p>I am creating a an API for registering user based on oauth token. My app has functionality like registration and login, adding restaurant etc. I created user registration part but i get error while login. I want login based on token. </p> <p>I have used django-oauth-toolkit for this and DRF. </p> <p>What i have do...
0
2016-09-05T08:14:22Z
39,326,999
<p>Try to use request.data instead of request.post in order to get the access_token(<a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses/" rel="nofollow">http://www.django-rest-framework.org/tutorial/2-requests-and-responses/</a>):</p> <pre><code>access_token = AccessToken.objects.get(token=...
0
2016-09-05T08:55:52Z
[ "python", "django", "python-3.x", "oauth", "django-rest-framework" ]
Run a module when module name is in a variable
39,326,482
<p>I'm trying to run modules from a directory. A simplified version of my project tree would be:</p> <pre><code>main.py modules/ |_ a/ | |_ a.py | |_ __init__.py |_ b/ | |_ b.py | |_ __init__.py |_ __init__.py </code></pre> <p>Each module in <code>modules/</code> has an empty <code>__init__.py</code> and a <code>...
0
2016-09-05T08:24:32Z
39,326,532
<p>You can do this with <a href="https://docs.python.org/3/library/importlib.html#importlib.import_module" rel="nofollow"><code>importlib</code></a>.</p> <pre><code>def run_module(module_name): mod = importlib.import_module(module_name) mod.run() </code></pre>
4
2016-09-05T08:27:51Z
[ "python" ]
Sort Multi-index pandas dataframe based on specific indexes
39,326,503
<p>I have the following dataframe:</p> <pre><code> x y a b c a b c kk ii jj kk jj ii kk jj ii ii jj kk jj kk ii kk ii jj 1 .1 .01 2 .5 .2 .4 .6 .01 .3 .5 .7 1. 1. 2 .3 .2 .01 .4 2 ...
1
2016-09-05T08:26:05Z
39,326,606
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>:</p> <pre><code>df = df.reindex(columns=['ii','kk','jj'], level=2) print (df) x y \ a ...
2
2016-09-05T08:31:47Z
[ "python", "sorting", "pandas", "dataframe", "multi-index" ]
How do I reshape array of images obtained from .h5 file in python?
39,326,635
<p>I'm new to python and I apologize in advance if my question seems trivial.</p> <p>I have a .h5 file containing pairs of images in greyscale organized in match and non-match groups. For my final purpose I need to consider each pair of images as a single image of 2 channels (where each channel is in fact an image). <...
3
2016-09-05T08:33:36Z
39,326,779
<p>I bet you need to first transpose your input matrix from <code>250000x2x4096</code> to <code>250000x4096x2</code>, after which you can do the <code>reshape</code>.</p> <p>Luckly, numpy offers the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.transpose.html" rel="nofollow">transpose</a> function...
2
2016-09-05T08:42:16Z
[ "python" ]
How can I use request.form in Flask/Python to get a variable textarea name?
39,326,729
<p>In my HTML template, I've added the following <code>&lt;textarea&gt;</code> into a flask for loop:</p> <pre><code>{% for message in messageList %} &lt;form action="/comment/{{ message['id'] }}" method='POST' id='createComment{{ message["id"] }}'&gt; &lt;textarea name='comment{{ message["id"] }}' id='com...
0
2016-09-05T08:39:09Z
39,357,714
<p>Should be <code>request.form["comment" + id]</code></p> <p>Better yet, to avoid a key error:</p> <p><code>request.form.get("comment" + id, 'oops, bad id')</code></p>
1
2016-09-06T20:57:00Z
[ "python", "html", "flask" ]
How can I use request.form in Flask/Python to get a variable textarea name?
39,326,729
<p>In my HTML template, I've added the following <code>&lt;textarea&gt;</code> into a flask for loop:</p> <pre><code>{% for message in messageList %} &lt;form action="/comment/{{ message['id'] }}" method='POST' id='createComment{{ message["id"] }}'&gt; &lt;textarea name='comment{{ message["id"] }}' id='com...
0
2016-09-05T08:39:09Z
39,554,079
<p>I solved this by creating a new variable:</p> <p><code>form = request.form</code></p> <p>and setting my dictionary value to:</p> <p><code>'comment' : form["comment" + id]</code></p> <p>[<em>EDIT</em>] I had sworn I'd tried <code>request.form['comment' + id]</code> as the @GAEfan noted, but I wasn't able to get i...
0
2016-09-18T04:23:38Z
[ "python", "html", "flask" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,078
<p>Try to sort items by creation time. Example below sorts files in a folder and gets first element which is latest.</p> <pre><code>import glob import os files_path = os.path.join(folder, '*') files = sorted( glob.iglob(files_path), key=os.path.getctime, reverse=True) print files[0] </code></pre>
1
2016-09-05T09:00:52Z
[ "python" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,156
<p>What ever assigned to your <code>files</code> variable is incorrect. Use the following code.</p> <pre><code>import glob import os list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv latest_file = max(list_of_files, key=os.path.getctime) print latest_file </code></pre>
0
2016-09-05T09:04:49Z
[ "python" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,174
<p>(Edited to improve answer)</p> <p>First define a function get_latest_file</p> <pre><code>def get_latest_file(path, *paths): fullpath = os.path.join(path, paths) ... get_latest_file('example', 'files','randomtext011.*.txt') </code></pre> <p>You may also use a docstring !</p> <pre><code>def get_latest_file...
0
2016-09-05T09:05:39Z
[ "python" ]
How to get the latest file in a folder using python
39,327,032
<p>i need to get the latest file of a folder using python. While using the code:</p> <pre><code>max(files, key = os.path.getctime) </code></pre> <p>I am getting the below error: </p> <blockquote> <p>FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'</p> </blockquote>
2
2016-09-05T08:58:23Z
39,327,252
<pre><code>max(files, key = os.path.getctime) </code></pre> <p>is quite incomplete code. What is <code>files</code>? It probably is a list of file names, coming out of <code>os.listdir()</code>.</p> <p>But this list lists only the filename parts (a. k. a. "basenames"), because their path is common. In order to use it...
0
2016-09-05T09:09:55Z
[ "python" ]
Combining Characters using lambda in python
39,327,068
<p>I want to result using 'str += ' style in the lambda function </p> <p>example (with error) : </p> <pre><code>t=lambda text text : [c for c in text str += c.upper()] t(['h','e','l','l','o']) </code></pre> <p>I expect to result as :</p> <pre><code>HELLO </code></pre> <p>How can i fix above lambda function with st...
-1
2016-09-05T09:00:24Z
39,327,112
<p>I think you mean this:</p> <pre><code>&gt;&gt;&gt; t = lambda text: ''.join(text).upper() &gt;&gt;&gt; t(['h','e','l','l','o']) 'HELLO' </code></pre> <p>Documentation: <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="nofollow">Lambda Expressions</a></p>
4
2016-09-05T09:02:32Z
[ "python", "lambda" ]
No visible text() when using matplotlib.pyplot
39,327,258
<p>matplotlib==1.5.2 pylab==0.1.3</p> <p>I am trying to reproduce a graph from the course <a href="http://cs224d.stanford.edu/syllabus.html" rel="nofollow">"CS224d Deep Learning for NLP"</a>, <a href="http://cs224d.stanford.edu/lectures/CS224d-Lecture2.pdf" rel="nofollow">Lecture 2</a>.</p> <p>It should look the foll...
1
2016-09-05T09:10:16Z
39,327,699
<p>It shows the words when you set axis limits to show the text as per this answer below. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt la = np.linalg words = ['I', 'like', 'enjoy', 'deep', 'learning', 'NLP', 'flying', '.'] X = np.array([[0,2,1,0,0,0,0,0], [2,0,0,1,0,1,0,0], ...
1
2016-09-05T09:35:53Z
[ "python", "matplotlib" ]
Python PIL: How can set to a png image the background to white?
39,327,265
<p>I have a png image with transparent background and I want to resize it to another image, but with white background instead of transparent one. How can I do that with PIL?</p> <p><strong>Here is my code:</strong></p> <pre><code>basewidth = 200 img = Image.open("old.png") wpercent = (basewidth/float(img.size[0])) h...
1
2016-09-05T09:10:37Z
39,327,366
<pre><code> import Image f = Image.open('old.png') from resizeimage import resizeimage alpha1 = 0 # Original value r2, g2, b2, alpha2 = 255, 255, 255,255 # Value that we want to replace it with red, green, blue,alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3] mask = (alpha==alpha...
0
2016-09-05T09:16:42Z
[ "python", "python-imaging-library" ]
Python PIL: How can set to a png image the background to white?
39,327,265
<p>I have a png image with transparent background and I want to resize it to another image, but with white background instead of transparent one. How can I do that with PIL?</p> <p><strong>Here is my code:</strong></p> <pre><code>basewidth = 200 img = Image.open("old.png") wpercent = (basewidth/float(img.size[0])) h...
1
2016-09-05T09:10:37Z
39,327,595
<p>You can check whether the alpha channel is set to less than 255 on each pixel (which means that it is not opaque) and then set it to white and opaque.</p> <p>It might not be an ideal solution if you have transparency in other parts of your image, besides the background.</p> <pre><code>... pixels = img.load() for ...
0
2016-09-05T09:29:29Z
[ "python", "python-imaging-library" ]
Python socket select.select. Using list of objects instead of connections
39,327,333
<p>Typically using <code>select.select()</code> will require a list of connection objects to work like this:</p> <p><code>read, write, error = select(self.all_connections, [], [], 0.1)</code></p> <p>Say I have the below object:</p> <pre><code>class remoteDevice(object) def __init___(self, connection): s...
0
2016-09-05T09:14:53Z
39,328,021
<p>According to the <a href="https://docs.python.org/3/library/select.html#select.select" rel="nofollow"><code>select.select()</code></a> documentation you can supply a sequence of objects that have a <code>fileno()</code> method. You can easily add that method to your class:</p> <pre><code>class RemoteDevice(object):...
3
2016-09-05T09:54:26Z
[ "python", "sockets", "python-3.x" ]
Is there a delay moving between libraries in Python?
39,327,361
<p>So recently I decided to write a program to draw the mandelbrot set using turtle, and it works very well, except for one thing; it's quite slow, and it slows down as it draws. The way it draws is, if I remember correctly, as follows:</p> <pre><code>def drawpoint(x,y,colour): t.color(colour) t.setpos(x,y) ...
1
2016-09-05T09:16:15Z
40,081,059
<p>Since you didn't give a clock value to <strong><em>quite slow</em></strong>, I have to make assumptions. (And I don't disagree with PM 2Ring that turtle.py may not be your best choice for this purpose.) I wrote a mandelbrot program, using generic turtle operations, which took nearly an hour to draw the 320 x 240 im...
0
2016-10-17T07:51:32Z
[ "python", "turtle-graphics" ]
Kivy canvas - fast drawing - polylines
39,327,575
<p>Tell me please, if drawing in Kivy Canvas fast, I get very acute, polylines figure, but if drawing very slow, then I get smooth lines.</p> <pre><code> ... def on_touch_down(self, touch): if Widget.on_touch_down(self, touch): return True print(touch.x, touch.y) with self....
1
2016-09-05T09:28:25Z
39,333,864
<p>i dont know why the lines dont look smooth when you draw fast in kivy, can you please test it on a different devices.</p>
0
2016-09-05T15:37:00Z
[ "android", "python", "canvas", "drawing", "kivy" ]
Kivy canvas - fast drawing - polylines
39,327,575
<p>Tell me please, if drawing in Kivy Canvas fast, I get very acute, polylines figure, but if drawing very slow, then I get smooth lines.</p> <pre><code> ... def on_touch_down(self, touch): if Widget.on_touch_down(self, touch): return True print(touch.x, touch.y) with self....
1
2016-09-05T09:28:25Z
39,340,288
<p>Actually I tested your code and couldn't produce the issue you are having. I mean it doesn't matter if I draw fast or slow in Kivy. Half of these 'e's I drew fast and half slow but no difference in output. I suggest you try <a href="https://kivy.org/docs/tutorials/firstwidget.html" rel="nofollow">https://kivy.org/do...
0
2016-09-06T03:39:20Z
[ "android", "python", "canvas", "drawing", "kivy" ]
Python: Problems in calling the function from the while loop
39,327,676
<p>I have a while loop which calls the function mainrt() on each iteration.</p> <pre><code>if __name__ == "__main__": inp = sys.stdin.read() inpList = inp.split('\n') inpList.pop() for n in inpList: i = 0 p = 0 n = int (n) while True: i += 1 p =...
0
2016-09-05T09:34:42Z
39,327,915
<p>In your <code>mainrt</code> function I do not see that you declare <code>diMon</code> list, so it looks like it is a global variable and you do not clean that list. That mean your <code>mainrt</code> return <code>False</code> at the first check of <code>if len(diMon) == 10:</code> for the second input. You should de...
1
2016-09-05T09:48:17Z
[ "python", "python-2.7" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><...
-1
2016-09-05T09:37:51Z
39,327,816
<p>What you are missing is that <code>value</code> is a single element string. Indexing at positions <code>!= 0</code> will result in an <code>IndexError</code>; during your first iteration that's what happens.</p> <p>If you want to create it with your for loop, just append the value immediately:</p> <pre><code>for k...
2
2016-09-05T09:42:19Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><...
-1
2016-09-05T09:37:51Z
39,327,823
<pre><code>name = 'Chris' my_list = list(name) print(my_list) </code></pre> <p>Input: ['C', 'h', 'r', 'i', 's']</p> <p>For one in each time:</p> <pre><code>for letter in name: print(letter) </code></pre>
0
2016-09-05T09:42:40Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><...
-1
2016-09-05T09:37:51Z
39,327,854
<p>You are enumerating over a string ("Chris") which means that key and value will hold the following values during the iteration:</p> <pre><code>0 "C" 1 "h" 2 "r" 3 "i" 4 "s" </code></pre> <p>value[key] in the first iteration is ok, it returns 'C'. </p> <p>In the second iteration, the index 1 is out of range f...
0
2016-09-05T09:44:40Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><...
-1
2016-09-05T09:37:51Z
39,327,861
<p>change my_list.append(value[key]) to my_list.append(value) in your code</p>
0
2016-09-05T09:45:21Z
[ "python", "python-3.x" ]
IndexError: string index out of range (enumerate)
39,327,737
<p>Okay so I have no idea what the problem is here. Everything I've read basically addresses the range not ending, thus the error, but that doesn't make sense to me since this is a fixed loop. </p> <p>I'm simply trying to take a string, and throw each letter into a list one at a time. What am I missing?</p> <pre><...
-1
2016-09-05T09:37:51Z
39,327,964
<p>An alternative way, to reach your goal:</p> <pre><code>&gt;&gt;&gt;name ="Chris" &gt;&gt;&gt;list(name) ['C', 'h', 'r', 'i', 's'] </code></pre> <p>For your example: When iterating through a string in python, no enumeration is required.</p> <pre><code>&gt;&gt;&gt;name = "Chris" &gt;&gt;&gt;my_list = [] &gt;&gt;&gt...
0
2016-09-05T09:51:03Z
[ "python", "python-3.x" ]
I have two .py files. How can I get multi-lined output of one program into tkinter text of another program's GUI?
39,327,767
<p>GUI consists one Run Button which should run the first program as many times user wants &amp; display output in tkinter text.</p> <p>My code(2nd .py file):</p> <pre><code>from tkinter import* from tkinter import ttk import Random Game root = Tk() root.title("Random Game 1.0") quote = "Long \nRandom \nText \nGene...
2
2016-09-05T09:39:15Z
39,337,367
<p>Output first program to txt file.</p> <p>Read from that txt file into the tkinter GUI by checking when it was last modified so as to avoid mutex issues.</p> <p>Therefore:</p> <pre><code># Prog 1: file = open("log.txt", "w") # code that writes there # Prog 2: file = open("log.txt", "r") # use data to show in th...
1
2016-09-05T20:34:53Z
[ "python", "python-2.7", "python-3.x", "user-interface", "tkinter" ]
How to actively avoid duplicate rows from the angle of the code not database?
39,327,925
<p>I get a table called <code>tb_user_portrait</code> which saves customers' head portrait, its schema looks quite simple,</p> <pre><code>CREATE TABLE `tb_user_portrait` ( id BIGINT NOT NULL AUTO_INCREMENT COMMENT 'primary key', user_id BIGINT NOT NULL DEFAULT 0 COMMENT 'custormer id', portrait_hash CHAR(2...
1
2016-09-05T09:48:48Z
39,328,089
<p>From SQLAlchemy:</p> <blockquote> <p>autoflush – When True, all query operations will issue a flush() call to this Session before proceeding. This is a convenience feature so that flush() need not be called repeatedly in order for database queries to retrieve results. It’s typical that autoflush is used in co...
0
2016-09-05T09:58:00Z
[ "python", "mysql", "python-2.7", "sqlalchemy" ]
Python: listing variables from object
39,327,930
<p>So basically I need help with laziness.</p> <p>Is it possible in python to take an object, and then list off all it's variables</p> <p>For example</p> <pre><code>class some_object: def __init__(self): self.Name = None self.UUID = None </code></pre> <p>then call a magic function that lists all the varia...
-3
2016-09-05T09:49:09Z
39,328,282
<p>You can use vars():</p> <pre><code>class about_me: def __init__(self): self.name = "Lyend Victorian" self.age = "25" self.height = "180" me = about_me() &gt;&gt;&gt; vars(me) {'age': '25', 'name': 'Lyend Victorian', 'height': '180'} </code></pre>
2
2016-09-05T10:08:43Z
[ "python" ]
Python: listing variables from object
39,327,930
<p>So basically I need help with laziness.</p> <p>Is it possible in python to take an object, and then list off all it's variables</p> <p>For example</p> <pre><code>class some_object: def __init__(self): self.Name = None self.UUID = None </code></pre> <p>then call a magic function that lists all the varia...
-3
2016-09-05T09:49:09Z
39,328,340
<p>You can use the <a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow"><code>dir()</code></a> function to get a list of (some of) the attributes an object has, like so:</p> <pre><code>&gt;&gt;&gt; class Foo: ... def __init__(self): ... self.name = None ... self.uuid = None...
1
2016-09-05T10:11:40Z
[ "python" ]
How to install PythonMagick on Amazon Elastic Beanstalk
39,327,940
<p>Since PythonMagick is not available through PIP package manager, how can I install PythonMagick on Amazon Elastic Beanstalk?</p>
0
2016-09-05T09:49:38Z
39,328,898
<p>To install Python packages on Amazon Beanstalk, you have to run add a command in our .ebextension/*.config file. Amazon Linux AMIs in Beanstalk are not shipped with pip but easy_install.</p> <p>These commands run before the application and web server are set up and the application version file is extracted.</p> <p...
0
2016-09-05T10:43:24Z
[ "python", "pythonmagick" ]
Using PyMongo insert_many and empty/null values
39,328,142
<p>I'm in the process of populating a mongoDB database and and not sure what to do with null values when using the insert_many statement (I should state at this point that I'm new to both Python and MongoDB)</p> <p>The data I am inserting is two dimensional traditional SQL like data obtained from a text file, it looks...
0
2016-09-05T10:01:12Z
39,329,760
<p>When you have a datafile like containing:</p> <pre><code>1,'Bob','Owner',null 2,'Joe','Worker','Bob' 3,'Sergiu','Eng','Bob' </code></pre> <p>insert_many it accepts an array (an iterable), in youre code you are using it wrong; python code can look like this:</p> <pre><code># 1 - create a list, read data and insert...
0
2016-09-05T11:36:39Z
[ "python", "mongodb", null, "pymongo", "bulkinsert" ]
Restful API - passing cookie to subsequent POST requests
39,328,197
<p>The application I want to query requires Json format. Supported method is POST. I seemingly cannot find a good example of how to get a cookie from 1 query and pass it to another query (or make subsequent queries use it as part of a <code>base package</code>. Could you advise what I'm doing wrong?</p> <pre><code>imp...
0
2016-09-05T10:04:15Z
39,337,266
<p>This link may have the solution to your problem : <a href="http://stackoverflow.com/questions/4166129/apache-httpclient-4-0-3-how-do-i-set-cookie-with-sessionid-for-post-request">Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request</a>. <strong>Have a look at the cookie path adjustment part ...
-1
2016-09-05T20:25:30Z
[ "python", "jsessionid" ]
NumPy structured / regular array from ctypes pointer to array of structs
39,328,205
<p>Say I have the following <code>C</code> function:</p> <pre><code>void getArrOfStructs(SomeStruct** ptr, int* numElements) </code></pre> <p>And the following <code>C</code> struct:</p> <pre><code>typedef struct SomeStruct { int x; int y; }; </code></pre> <p>I am able to successfully get a Python list:</p>...
0
2016-09-05T10:04:37Z
39,334,720
<p>Views of numpy arrays share a data buffer</p> <pre><code>In [267]: x=np.arange(6).reshape(3,2) In [268]: x.tostring() Out[268]: b'\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x05\x00\x00\x00' In [269]: x.view('i,i') Out[269]: array([[(0, 1)], [(2, 3)], [(4, 5)]], ...
1
2016-09-05T16:42:01Z
[ "python", "numpy", "ctypes" ]
print cgi fieldstorage object to file instead of a html page python
39,328,254
<p>Thanks in advance. I have a dictionary that has been created from form post data. I want to print the contents of the dictionary to another file. I do not want to use it to output to a html page. </p> <pre><code>def cgiFieldStorageToDict( fieldStorage ): # Makes a dictionary from the http post data params = {...
0
2016-09-05T10:06:59Z
39,330,233
<p>I could not write to the file because it did not have the right permissions for all users to write to it. I chmod the file to 777 and some of the code and it now works the way I want it too. Here is the code:</p> <pre><code>form = cgi.FieldStorage() latitude = form.getvalue('latitude') s = open('any_read.py','w') s...
0
2016-09-05T12:05:38Z
[ "python", "forms", "file", "post", "cgi" ]
Python shapely: .equals function does not always work:
39,328,327
<p>I am having a few issues with the shapely library. Now the equals function seem not to always work:</p> <pre><code>poly1 = Polygon(([220.0, 400, 500], [220.0, 20, 500], [220.0, 20, 0], [220.0, 400, 0], [220.0, 400, 500])) poly2 = Polygon(([220.0, 20, 500], [220.0, 400, 500], [220.0, 400, 0], [220.0, 20, 0], [220....
1
2016-09-05T10:10:42Z
39,328,405
<p>From docs:</p> <blockquote> <p>The Polygon constructor takes two positional parameters. The first is an ordered sequence of (x, y[, z]) point tuples and is treated exactly as in the LinearRing case.</p> </blockquote> <p>So try to sort them first (tuples) before create <code>Polygon</code>:</p> <pre><code>&gt;&g...
2
2016-09-05T10:15:30Z
[ "python", "shapely" ]
Python shapely: .equals function does not always work:
39,328,327
<p>I am having a few issues with the shapely library. Now the equals function seem not to always work:</p> <pre><code>poly1 = Polygon(([220.0, 400, 500], [220.0, 20, 500], [220.0, 20, 0], [220.0, 400, 0], [220.0, 400, 500])) poly2 = Polygon(([220.0, 20, 500], [220.0, 400, 500], [220.0, 400, 0], [220.0, 20, 0], [220....
1
2016-09-05T10:10:42Z
39,408,439
<p>As @ewcz says in the comments, this is because Shapely only really works with 2D geometry in the XY plane. It is ignoring the Z coordinate here. These are not valid Polygons when projected into the XY plane so Shapely is not prepared to agree that they are equal. It works fine if you remove the (unnecessary) x co...
1
2016-09-09T09:37:07Z
[ "python", "shapely" ]
OR-tools consistently returns very sub-optimal TSP solution
39,328,358
<p>Generating some random Gaussian coordinates, I noticed the TSP-solver returns horrible solutions, however it also returns the same horrible solution over and over again for the same input.</p> <p>Given this code:</p> <pre><code>import numpy import math from ortools.constraint_solver import pywrapcp from ortools.co...
0
2016-09-05T10:12:45Z
39,329,754
<p>I think the problem is with the distance-measure :). I can remember a <code>kScalingFactor</code> in the C-code samples from or-tools, which was used to scale up distances, and then round (by casting) them to integers: or-tools expects distances to be integers.</p> <p>Or course, distances between standard Gaussian ...
0
2016-09-05T11:35:59Z
[ "python", "or-tools" ]
PUT Request fails on field rename
39,328,384
<p>Serializer.py</p> <pre><code>class CategorySerializer(serializers.ModelSerializer) : id = serializers.IntegerField(source='category_id') name = serializers.CharField(source='category_name') class Meta: model = Category fields = ['id', 'name'] </code></pre> <p>Above works fine for the G...
4
2016-09-05T10:14:03Z
39,328,526
<p>I think problem with <code>id</code> field, it is required. But you sent only <code>name</code> field, try to use <code>partial</code> key. </p> <pre><code>serializer = CategorySerializer(category, data=request.data, partial=True) </code></pre>
0
2016-09-05T10:22:47Z
[ "python", "django", "django-rest-framework" ]
PUT Request fails on field rename
39,328,384
<p>Serializer.py</p> <pre><code>class CategorySerializer(serializers.ModelSerializer) : id = serializers.IntegerField(source='category_id') name = serializers.CharField(source='category_name') class Meta: model = Category fields = ['id', 'name'] </code></pre> <p>Above works fine for the G...
4
2016-09-05T10:14:03Z
39,328,544
<p>You didn't attach your's serializer errors, but it looks like that you should set <code>partial</code> argument for <code>PUT</code> request method. Try </p> <pre><code>serializer = CategorySerializer(category, data=request.data, partial=True) </code></pre> <p>Documentation <a href="http://www.django-rest-framewor...
2
2016-09-05T10:23:43Z
[ "python", "django", "django-rest-framework" ]
Locking in dask.multiprocessing.get and adding metadata to HDF
39,328,398
<p>Performing an ETL-task in pure Python, I would like to collect error metrics as well as metadata for each of the raw input files considered (error metrics are computed from error codes provided in the data section of the files while metadata is stored in headers). Here's pseudo-code for the whole procedure:</p> <pr...
1
2016-09-05T10:15:19Z
39,330,077
<h3>Don't depend on Globals</h3> <p>Dask works best with <a href="http://toolz.readthedocs.io/en/latest/purity.html#function-purity" rel="nofollow">pure functions</a>. </p> <p>In particular, your case is a limitation in Python, in that it (correctly) doesn't share global data between processes. Instead, I recommend...
1
2016-09-05T11:55:40Z
[ "python", "pandas", "locking", "metadata", "dask" ]
Python-Sphinx documentation: link source code
39,328,463
<p>I have a dictionary that represent a schema (JSON-Schema to be more precise).</p> <p>Sometimes the schema gets complex and in the documentation I need to link to it in order to give a better picture.</p> <p>I have the <code>viewcode</code> extension enabled, I tried the following with no luck:</p> <pre><code>.. d...
1
2016-09-05T10:19:32Z
39,352,023
<p>Try this:</p> <pre><code>.. literalinclude:: your_json_filename.json :language: json </code></pre> <p>You can even select a part of this file to display by </p> <pre><code>.. literalinclude:: your_json_filename.json :language: json :lines: 18-43 </code></pre> <p>This displays the lines 18 to 43 of <e...
0
2016-09-06T14:51:52Z
[ "python", "python-sphinx" ]
Colorbar for seaborn.kdeplot
39,328,551
<p>I want to create a Kernel-Density-Estimation with Seaborn.kdeplot with a colorbar on the side.</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np; np.random.seed(10) import seaborn as sns; sns.set(color_codes=True) mean, cov = [0, 2], [(1, .5), (.5, 1)] x, y = np.random.multivar...
0
2016-09-05T10:24:04Z
39,332,225
<p>You'll have to call the scipy KDE and matplotlib contour function directly, but it's just a bit of extra code:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np; np.random.seed(10) import seaborn as sns; sns.set(color_codes=True) from scipy import stats mean, cov = [0, 2], [(1...
1
2016-09-05T13:58:13Z
[ "python", "matplotlib", "seaborn", "colorbar", "kernel-density" ]
Reading defined Data from SQL
39,328,634
<p>I have a Problem with reading data with Pandas.read_sql (...):</p> <p>My code Looks like this:</p> <pre><code>import psycopg2 as pg import pandas as pd con = pg.connect(host='db123', database='data', user='ortm', password='***') db = pd.read_sql_query('select calculationtime, state from stateresult WHERE ID = A1...
0
2016-09-05T10:28:36Z
39,329,186
<p>Why don't you try this once and inform the response you got. If your connection with database is correct.But I am not aware about python.Once check it and revert to me if it gives error message. </p> <pre><code> db = pd.read_sql_query("select calculationtime, state from stateresult WHERE ID = 'A123'", con) </code...
0
2016-09-05T11:00:40Z
[ "python", "sql", "pandas" ]
Run something only once in while loop without breaking the loop
39,328,690
<pre><code>import RPi.GPIO as g import time g.setmode(g.BOARD) g.setup(33, g.OUT) while True: tempfile = open("/sys/devices/w1_bus_master1/28-00152c2631ee/w1_slave") thetext = tempfile.read() tempfile.close() tempdata = thetext.split("\n") [1].split(" ")[9] temperature = float(tempdata[2:]) finaltemp = t...
-1
2016-09-05T10:31:56Z
39,329,087
<p>What you're currently doing is just checking the temperature and using a condition to keep switching the AC on and off, which as you have already figured out will not work.</p> <p>This is because your condition statements only look at the temperature and not and the current state of the AC, for example if you want ...
1
2016-09-05T10:54:27Z
[ "python" ]
Run something only once in while loop without breaking the loop
39,328,690
<pre><code>import RPi.GPIO as g import time g.setmode(g.BOARD) g.setup(33, g.OUT) while True: tempfile = open("/sys/devices/w1_bus_master1/28-00152c2631ee/w1_slave") thetext = tempfile.read() tempfile.close() tempdata = thetext.split("\n") [1].split(" ")[9] temperature = float(tempdata[2:]) finaltemp = t...
-1
2016-09-05T10:31:56Z
39,329,272
<p>You need to add both <a href="https://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow">state</a> and <a href="https://en.wikipedia.org/wiki/Hysteresis#Control_systems" rel="nofollow">hysteresis</a>.</p> <p>Pseudo-code for the on/off logic:</p> <pre><code>LIMIT_LOW = 21.5 LIMIT_HIGH = 22.5 AC_running = Fa...
1
2016-09-05T11:06:04Z
[ "python" ]
Show html generated by using json2html at webpage [Django] [Python]?
39,328,784
<p>Following is my code in view: </p> <pre><code> RESULTS= {} for k in RESULTS_LIST[0].iterkeys(): RESULTS[k] = list(results[k] for results in RESULTS_LIST) RESULTS.pop('_id',None) html_table = json2html.convert(json=RESULTS) return render(request,'homepage.html',{'html_table':html_table}) </code></pre> <p>he...
1
2016-09-05T10:36:52Z
39,330,777
<p>I have got solution to this problem in an easy way via using js, which is given below and it worked.</p> <pre><code> $http(search_req).success(function(response){ $(".search_results").append(response); }) </code></pre>
0
2016-09-05T12:36:33Z
[ "python", "json", "django" ]
Execute Gams in background on Python 2.7
39,328,807
<p>I need to call and run gams at background from a Python script.</p> <p>I'm using: </p> <pre><code>import subprocess subprocess.check_call([r"C:\GAMS\win64\24.4\gams.exe",r"F:\Otim\Interface\ElGr.gms"]) </code></pre> <p>And it gives me this error: </p> <blockquote> <p>Traceback (most recent call last): File ...
0
2016-09-05T10:38:08Z
39,349,060
<p>Here is a list of the meanings of the different exit codes: <a href="https://www.gams.com/help/index.jsp?topic=%2Fgams.doc%2Fuserguides%2Fuserguide%2F_u_g__g_a_m_s_return_codes.html" rel="nofollow">https://www.gams.com/help/index.jsp?topic=%2Fgams.doc%2Fuserguides%2Fuserguide%2F_u_g__g_a_m_s_return_codes.html</a></p...
0
2016-09-06T12:29:07Z
[ "python", "python-2.7", "subprocess", "gams-math" ]
Connecting to Google Cloud SQL from App Engine: access denied
39,328,869
<p>Trying to connect to Google Cloud SQL from App Engine. Getting an error 500 and the logs say: "Access denied for user 'root'@'cloudsqlproxy~' (using password: NO)"). The App Engine and cloud SQL are in the same project. The code I use to connect:</p> <pre><code>class MainPage(webapp2.RequestHandler): def get(self)...
0
2016-09-05T10:42:02Z
39,329,306
<p>Okay, so turns out there is some misinformation happening. Adding a password parameter solved my issue. But for some reason, there is no mention of this in Google Documentation and many posts on StackOverflow actually directly tell you the oppposite, saying that Cloud SQL will throw an error if you pass it a passwor...
1
2016-09-05T11:08:41Z
[ "python", "google-app-engine", "google-cloud-sql" ]
Connecting to Google Cloud SQL from App Engine: access denied
39,328,869
<p>Trying to connect to Google Cloud SQL from App Engine. Getting an error 500 and the logs say: "Access denied for user 'root'@'cloudsqlproxy~' (using password: NO)"). The App Engine and cloud SQL are in the same project. The code I use to connect:</p> <pre><code>class MainPage(webapp2.RequestHandler): def get(self)...
0
2016-09-05T10:42:02Z
39,489,787
<p>I would say this part is not well documented on <code>Google Developer Console</code>.</p> <p><code>Google Cloud SQL 2nd Gen</code> comes with a little modification required in the connection string which is not provided in your code.</p> <p>Please have a look at the original code after some modifications from my ...
0
2016-09-14T11:53:04Z
[ "python", "google-app-engine", "google-cloud-sql" ]
Python fails to compile a regex
39,328,878
<p>I'm trying to detect all <code>set</code> from a cmake file using a python regex, fo the file below:</p> <pre><code># Library to include set(LIB_TO_INCLUDE a b c) # comon code (inclusion in source code) set(SHARED_TO_INCLUDE d e f) # Library to include set(THIRD_PARTY g h) </code></pre> ...
0
2016-09-05T10:42:34Z
39,329,504
<p>This should do it: <code>set\(([^)]*?)\)</code></p> <p>The "single line" modifier is passed as an argument when you compile the regex:</p> <pre><code>&gt;&gt;&gt; t = """set(LIB_TO_INCLUDE ... a ... b ... c)""" &gt;&gt;&gt; &gt;&gt;&gt; pattern = r'set\(([^)]*?)\)' &gt;&gt;&gt; &gt;&gt;&...
1
2016-09-05T11:21:06Z
[ "python", "regex" ]
In python why is the "object" class all in lower case instead of first letter in capitals?
39,328,881
<p>Before I ask this question please note that I've tried searching online for this question but because the word "object" is so common I get lots of unrelated results instead of what I'm looking for. I also looked through the official doc here: <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">h...
1
2016-09-05T10:42:50Z
39,328,921
<p>All Python's built-in types have lower case: int, str, unicode, float, bool, etc. The object type is just another one of these.</p>
4
2016-09-05T10:44:53Z
[ "python", "class", "inheritance" ]
In python why is the "object" class all in lower case instead of first letter in capitals?
39,328,881
<p>Before I ask this question please note that I've tried searching online for this question but because the word "object" is so common I get lots of unrelated results instead of what I'm looking for. I also looked through the official doc here: <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">h...
1
2016-09-05T10:42:50Z
39,328,945
<p>The short and basic answer is, class is just a keyword used by the python interpreter to know when some thing needs to be seen as a class , like how you have "def" for defining a function. Its a keyword to describe what follows is all.</p>
-3
2016-09-05T10:46:23Z
[ "python", "class", "inheritance" ]
In python why is the "object" class all in lower case instead of first letter in capitals?
39,328,881
<p>Before I ask this question please note that I've tried searching online for this question but because the word "object" is so common I get lots of unrelated results instead of what I'm looking for. I also looked through the official doc here: <a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">h...
1
2016-09-05T10:42:50Z
39,329,013
<p>If you go to the python interpreter and do this:</p> <pre><code>&gt;&gt;&gt; object &lt;type 'object'&gt; </code></pre> <p>You'll see object is a built-in type, the other built-in types in python are also lowercase <code>type, int, bool, float, str, list, tuple, dict, ...</code>. For instance:</p> <pre><code>&gt;...
0
2016-09-05T10:50:27Z
[ "python", "class", "inheritance" ]
Elasticsearch delete_by_query wrong usage
39,328,892
<p> I am using 2 similar ES methods to load and delete documents:</p> <pre><code>result = es.search(index='users_favourite_documents', doc_type='favourite_document', body={"query": {"match": {'user': user}}}) </code></pre> <p>And:</p> <pre><code>result = es.delete_by_query(index...
0
2016-09-05T10:43:10Z
39,329,398
<p>If you're running ES 2.x, you need to make sure that you have installed the <a href="https://www.elastic.co/guide/en/elasticsearch/plugins/2.4/plugins-delete-by-query.html" rel="nofollow">delete-by-query plugin</a> first:</p> <p>In your ES_HOME folder, run this:</p> <pre><code>bin/plugin install delete-by-query </...
1
2016-09-05T11:14:26Z
[ "python", "elasticsearch", "elasticsearch-py" ]
regex that shouldn't work works
39,328,951
<p>im starting to learn regex and i tried to make a simple regex that doesn't make sense to match but it matched any way i tried in python</p> <pre><code>import re pattern = r'[a-z]+[a-z]' print re.findall(pattern,"adasdasad"); </code></pre> <p>it returned ['adasdasad'] where it shouldn't have worked because [a-...
1
2016-09-05T10:46:58Z
39,329,003
<p>The <code>+</code> is not a possessive quantifier and allows backtracking into the quantified subpattern.</p> <p>The <code>[a-z]+</code> matches <code>adasdasa</code> and <code>[a-z]</code> matches <code>d</code>, see <a href="https://regex101.com/r/fG5rS2/1">this demo</a>.</p> <p><a href="http://i.stack.imgur.com...
5
2016-09-05T10:49:57Z
[ "python", "regex" ]
How to identify unconnected siblings in a graph?
39,328,963
<p>I have a directed acyclic graph as shown in the figure below. <a href="http://i.stack.imgur.com/6NuA5.png" rel="nofollow"><img src="http://i.stack.imgur.com/6NuA5.png" alt="GRAPH WITH SIBLING NODES"></a></p> <p>I want to identify all such group of nodes in this graph that satisfy following conditions:</p> <ul> <li...
3
2016-09-05T10:47:47Z
39,338,249
<p>Note that first request is redundant because second request covers it. It is not possible to have same set of parents and children for two connected nodes. For connected nodes, one node has other node in parent set and vice verse in children set.</p> <p>So nodes in same group have same set of parent and children no...
2
2016-09-05T22:13:45Z
[ "python", "nodes", "graph-theory", "graph-algorithm", "networkx" ]
How to identify unconnected siblings in a graph?
39,328,963
<p>I have a directed acyclic graph as shown in the figure below. <a href="http://i.stack.imgur.com/6NuA5.png" rel="nofollow"><img src="http://i.stack.imgur.com/6NuA5.png" alt="GRAPH WITH SIBLING NODES"></a></p> <p>I want to identify all such group of nodes in this graph that satisfy following conditions:</p> <ul> <li...
3
2016-09-05T10:47:47Z
39,346,547
<p>Ante has provided an elegant solution to my question. I have modified his code a little to be used with networkx graphs in Python 3.5</p> <p>Given a directed acyclic graph <code>G</code>.</p> <pre><code>lineage = defaultdict(list) for node in G.nodes(): lineage[frozenset(G.predecessors(node)), frozenset(G.suc...
0
2016-09-06T10:19:02Z
[ "python", "nodes", "graph-theory", "graph-algorithm", "networkx" ]
how to find the consecutive items in the list that are in a specific range in python
39,329,141
<p>Having the following python list [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] I'd like to return the count of the longest consecutive sequence of items less than 0.5</p> <p>Expected result: [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] should give an output of 2</p>
-2
2016-09-05T10:58:23Z
39,329,636
<p>You can find the working sample down here:</p> <pre><code>list = [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] listDict = {} for idx, val in enumerate(list): for idx2, val2 in enumerate(list): if idx != idx2 and list[idx] != list[idx2] and abs(list[idx] - list[idx2]) &lt; 0.5: listDict[str(list...
0
2016-09-05T11:29:14Z
[ "python", "python-3.x" ]
how to find the consecutive items in the list that are in a specific range in python
39,329,141
<p>Having the following python list [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] I'd like to return the count of the longest consecutive sequence of items less than 0.5</p> <p>Expected result: [0.0, 5.0, 2.0, 0.0, 0.30000000000000004] should give an output of 2</p>
-2
2016-09-05T10:58:23Z
39,330,324
<p>Possible, but unstable approach:</p> <pre><code>def number_of_consecutive(data, min_threshold, max_threshold): sum_consec, max_value = 0,0 for element in data: if element &lt;= max_threshold and element &gt;= min_threshold: sum_consec += 1 if sum_consec &gt; max_value: ...
0
2016-09-05T12:10:22Z
[ "python", "python-3.x" ]
How to upload image file from django admin panel ?
39,329,196
<p>I am making a personal website using django 1.10 I want to upload my website logo from admin for why I can edit this in future. So that I have wrote website app and the models of website is :</p> <p>from <strong>future</strong> import unicode_literals</p> <p>from django.db import models</p> <pre><code># Create yo...
2
2016-09-05T11:01:32Z
39,329,622
<p>It saves inside project folder if I change this in settings.py:</p> <p>Before:</p> <pre><code>MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media_cdn") </code></pre> <p>After:</p> <pre><code>MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(PROJECT_ROOT), "media_cdn") ...
0
2016-09-05T11:28:17Z
[ "python", "django", "file-upload", "django-models", "django-admin" ]
How to upload image file from django admin panel ?
39,329,196
<p>I am making a personal website using django 1.10 I want to upload my website logo from admin for why I can edit this in future. So that I have wrote website app and the models of website is :</p> <p>from <strong>future</strong> import unicode_literals</p> <p>from django.db import models</p> <pre><code># Create yo...
2
2016-09-05T11:01:32Z
39,330,088
<p>Finally, I solved this problem, I had to change urls.py as like:</p> <pre><code>from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^', include("website.urls", namespace='home')), ...
0
2016-09-05T11:56:16Z
[ "python", "django", "file-upload", "django-models", "django-admin" ]
How does index assignment to nodes work in Spark with mapPartitionsWithIndex()?
39,329,216
<p>I am trying to coordinate GPU execution on a Spark cluster. In order to achieve this I need each task/partition to only use a specific GPU slot per system. Each system has 4 GPUs, and the easiest way I have found to achieve this is by doing a mapPartitionsWithIndex() on the rdd with the data, and then using the inde...
1
2016-09-05T11:02:35Z
39,619,957
<p>Short answer: No. In a cluster, the RessourceManager (YARN most of the time) will use a worker if it is available, and it is not always the case when your system is multi-user, or if you have already started a job in a subset of your cluster. So you can't bind a worker with an index. </p> <p>Thus, I am pretty sure ...
0
2016-09-21T14:54:04Z
[ "python", "apache-spark", "pyspark", "partitioning", "rdd" ]
Converting Python scripts to APIs
39,329,266
<p>I have a Python script that extracts certain consumer product aspects from customer reviews using LinearSVC, but I am trying to convert this script into some sort of API to use for new reviews. Is there an easy way to do this? I am very new to the whole concept of APIs.</p>
0
2016-09-05T11:05:40Z
39,329,314
<p>An API is just a library you import once it's reachable by the interpreter in your case. So any import in python is you calling on an library/API.</p> <p>So if you're script is called <em>foobar.py</em> for example, if it is in the same directory as other python files using</p> <pre><code>import foobar </code></pr...
1
2016-09-05T11:09:19Z
[ "python", "api", "python-textprocessing" ]
Insert data in specific columns in csv file
39,329,274
<p>I am trying to insert the data obtained from the date column. Columns headers are <code>date,day,month,year,pcp1,pcp2,pcp3,pcp4,pcp5,pcp6</code> in the csv file. The columns <code>day, month, year</code> are currently empty. </p> <p>I would like to insert the data obtained from the date by split method into these c...
1
2016-09-05T11:06:11Z
39,329,605
<p>Use pandas. You will be able to use most of your code which is not too far from working </p> <pre><code>import pandas as pd filename = "test.csv" data = pd.read_excel(filename) x = data["date"] dd=[] mm=[] yy=[] for date_str in x: day, month, year = date_str.split('.') dd.append(day) mm.append(mo...
0
2016-09-05T11:26:53Z
[ "python", "csv" ]
Insert data in specific columns in csv file
39,329,274
<p>I am trying to insert the data obtained from the date column. Columns headers are <code>date,day,month,year,pcp1,pcp2,pcp3,pcp4,pcp5,pcp6</code> in the csv file. The columns <code>day, month, year</code> are currently empty. </p> <p>I would like to insert the data obtained from the date by split method into these c...
1
2016-09-05T11:06:11Z
39,330,080
<p>You could just parse the CSV as follows. This reads all of your rows into a list, and then inserts the date componants into the empty columns.</p> <pre><code>import csv with open('output2.csv', newline='') as f_input: csv_input = csv.reader(f_input, delimiter=';', quotechar='|') header = next(csv_input) ...
2
2016-09-05T11:55:43Z
[ "python", "csv" ]
how to return object of matching subclass?
39,329,284
<p>I'm trying to write a method that is supposed to return me an object of a subclass depending on some input data. Let me try to explain</p> <pre><code>class Pet(): @classmethod def parse(cls,data): #return Pet() if all else fails pass class BigPet(Pet): size = "big" @classmethod ...
1
2016-09-05T11:06:57Z
39,434,087
<p>Why not pass the exact class name, look for that in the <code>globals()</code> and instantiate that?</p> <pre><code>def parse_pet(class_name, data): # will raise a KeyError exception if class_name doesn't exist cls = globals()[class_name] return cls(data) cat = parse_pet('Cat', 'meow') big_pet = parse_...
0
2016-09-11T08:07:49Z
[ "python", "parsing", "design-patterns" ]
Write a script that runs a command for you
39,329,309
<p>So, here is my doubt:</p> <p>I have some VPS with Ubuntu 15.04 headless that run a python script 24.7</p> <p>I'd like to reboot the process every 8 hours without restarting the machine and giving it a 60 seconds delay between stop and start.</p> <p>This may seem simple, but i'm struggling a bit on how to do this....
-4
2016-09-05T11:08:45Z
39,330,097
<p>I think it will be better (but not necessary) if you first daemonize your script so that it can be run as a service.</p> <p><a href="http://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux">How to make a Python script run like a service or daemon in Linux</a></p>...
0
2016-09-05T11:56:38Z
[ "python", "linux" ]
softlayer api: change root password and ssh-key operation
39,329,313
<p>I am a developer, my current work is writing a script to manage the softlayer VMs. The problems are about change Root Password and binding(remove binding) the SshKey. My questions are:</p> <ol> <li><p>I have a running softlayer vm, wihch softlayer api can help me to change the vm’s root password. </p></li> <li><p...
1
2016-09-05T11:09:04Z
39,353,450
<p>Regarding to your <strong>first question</strong>, change root password from vm, follow these steps:</p> <p>Retrieves the password's identifier from the vm</p> <pre><code>https://$user:$apiKey@api.softlayer.com/rest/v3.1/SoftLayer_Virtual_Guest/$vsiId/getSoftwareComponents?objectMask=mask[passwords] Method: Get <...
1
2016-09-06T16:09:42Z
[ "python", "api", "softlayer" ]
softlayer api: change root password and ssh-key operation
39,329,313
<p>I am a developer, my current work is writing a script to manage the softlayer VMs. The problems are about change Root Password and binding(remove binding) the SshKey. My questions are:</p> <ol> <li><p>I have a running softlayer vm, wihch softlayer api can help me to change the vm’s root password. </p></li> <li><p...
1
2016-09-05T11:09:04Z
39,355,839
<ol> <li>I have a running softlayer vm, wihch softlayer api can help me to change the vm’s root password.</li> </ol> <p>The answer Ruber Cuellar posted will change the password listed in the SoftLayer API, <strong><em>but will not change the password on your system</em></strong>, UNLESS you perform an OS reload. No ...
1
2016-09-06T18:43:24Z
[ "python", "api", "softlayer" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item =...
0
2016-09-05T11:12:30Z
39,329,399
<h3>Short answer:</h3> <p><code>'%s'</code> is a <em>string</em> by definition, while a list index should be an <em>integer</em> by definition. </p> <p>Use <code>int(string)</code> if you are sure the string can be an integer (if not, it will raise a <code>ValueError</code>)</p>
0
2016-09-05T11:14:39Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item =...
0
2016-09-05T11:12:30Z
39,329,447
<p>A list is made up of multiple data values that are referenced by an indice. So if i defined my list like so :</p> <pre><code>my_list = [apples, orange, peaches] </code></pre> <p>If I want to reference something in the list I do it like this</p> <pre><code>print(my_list[0]) </code></pre> <p>The expected output f...
0
2016-09-05T11:17:27Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item =...
0
2016-09-05T11:12:30Z
39,329,474
<p>I'd suggest wrapping around a function like this:</p> <pre><code>def get_item(index, list1, list2) if condition: return list1[index] else: return list2[index] print get_item(3) </code></pre>
0
2016-09-05T11:19:05Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item =...
0
2016-09-05T11:12:30Z
39,329,584
<p>You have a reasonably large misconception about how list slicing works. It will always happen at the time you call it, so inside your if loop itself Python will be trying to slice either of the lists by the literal string <code>"%s"</code>, which can't possibly work.</p> <p>There is no need to do this. You can just...
2
2016-09-05T11:25:39Z
[ "python", "list" ]
Python list - string formatting as list indices
39,329,368
<p>Depending on a condition I need to get a value from one or another function. I'm trying to put it inside a simple <code>If ... Else</code> statement. I tried to use <code>%s</code> string formatting but it won't work. Below code, so it will become more clear what I try to do:</p> <pre><code>if condition: item =...
0
2016-09-05T11:12:30Z
39,329,643
<p>Here is a compact way to do it:</p> <pre><code>source = my_list if condition else my_other_list print(source[2]) </code></pre> <p>This binds a variable <code>source</code> to either <code>my_list</code> or <code>my_other_list</code> depending on the condition. Then the 3rd element of the selected list is accessed ...
0
2016-09-05T11:29:35Z
[ "python", "list" ]
Matplotlib, usetex: Colorbar's font does not match plot's font
39,329,429
<p>I have a matplotlib plot with a colorbar and can't seem to figure out how to match the fonts of the plot and the colorbar.</p> <p>I try to use usetex for text handling, but it seems like only the ticks of the plot are affected, not the ticks of the colorbar. Also, I have searched for solution quite a bit, so in the...
1
2016-09-05T11:16:44Z
39,334,140
<p>The issue here is that MPL wraps ticklabels in <code>$</code> when <code>usetex=True</code>. This causes them to have different sizes than text that is not wrapped in <code>$</code>. When you force your ticks to be labeled with <code>[1,2,3,4,5]</code> these values are not wrapped in <code>$</code>, and are therefor...
1
2016-09-05T15:58:47Z
[ "python", "matplotlib", "fonts", "styles", "tex" ]
How to scattering a numpy array in python using comm.Scatterv
39,329,492
<p>I am tring to write a MPI-based code to do some calculation using python and MPI4py. However, following the example, I CANNOT scatter a numpy vector into cores. Here is the code and errors, is there anyone can help me? Thanks. </p> <pre><code>import numpy as np from mpi4py import MPI comm = MPI.COMM_WORLD size = c...
0
2016-09-05T11:20:14Z
39,345,364
<p>The data type is not correct. I should specify the type of the array:</p> <pre><code>d1 = np.arange(1, n+1, dtype='float64') </code></pre>
0
2016-09-06T09:25:11Z
[ "python", "numpy", "mpi", "mpi4py" ]
Stop counting time in django
39,329,649
<p>I've got a problem with take constant value from this function:</p> <pre><code>def get_time_left(self) now = timezone.now() time_left = self.deadline - now return time_left </code></pre> <p>self.deadline is value from model.</p> <p>For example I want to take time_left from 15.00 2.09.2016, save it and...
0
2016-09-05T11:29:44Z
39,329,875
<p>Maybe an easy workaround would be to have the value in the others function definition ? That way you are certain of what you send...</p> <p>Yet, if you set the result of get_time_left() in a variable, it should not change...</p> <p>More code would be helpfull indeed</p>
0
2016-09-05T11:42:59Z
[ "python", "django", "datetime", "timezone" ]
Unicode-encode issues while sending desktop notification using Python
39,329,709
<p>I am fetching latest football scores from a website and sending a notification on the desktop (OS X). I am using BeautifulSoup to scrape the data. I had issues with the unicode data which was generating this error</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal...
1
2016-09-05T11:33:18Z
39,329,859
<p>Use: ˋsys.getfilesystemencoding` to get your encoding</p> <p>Encode your string with it, ignore or replace errors:</p> <pre><code>import sys encoding = sys.getfilesystemencoding() msg = new_scorer[0].text.replace(",", "") print(msg.encode(encoding, errons="replace")) </code></pre>
-1
2016-09-05T11:42:01Z
[ "python", "unicode", "utf-8", "ascii" ]
Unicode-encode issues while sending desktop notification using Python
39,329,709
<p>I am fetching latest football scores from a website and sending a notification on the desktop (OS X). I am using BeautifulSoup to scrape the data. I had issues with the unicode data which was generating this error</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in position 2: ordinal...
1
2016-09-05T11:33:18Z
39,330,028
<p>You are formatting using <code>!r</code> which gives you the <em>repr</em> output, forget the terrible reload logic and either use unicode everywhere:</p> <pre><code>def notify (title, subtitle, message): t = u'-title {}'.format(title) s = u'-subtitle {}'.format(subtitle) m = u'-message {}'.format(mess...
1
2016-09-05T11:51:44Z
[ "python", "unicode", "utf-8", "ascii" ]
Python: How to manage multiple user?
39,329,746
<p>I have a list of users IDs and each user ID has a lot of friends IDs. I want to write a program to send message to user's friend. So how to manage these information ? I think I should using 1 single file and write this Json format into file:</p> <pre><code>{'id_user':1, 'id_friend': 123} {'id_user':1, 'id_friend':...
-1
2016-09-05T11:35:25Z
39,331,219
<p>I hope my answer is not too biased...</p> <p>Depending on what else you want to accomplish, there are several options:</p> <ul> <li>In standard library you have <a href="https://docs.python.org/3/library/sqlite3.html" rel="nofollow">sqlite3</a> which is a relational database engine (which can handle large amounts ...
1
2016-09-05T13:03:17Z
[ "python", "json", "database", "file", "dictionary" ]
How to find the maximum product of two elements in a list?
39,329,829
<p>I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:</p> <pre><code>import itertools l = [] for _ in range(int(input())): l.append(int(input())) max = l[0] * l[len(l)-1] for a,b in itertools.combinations(l,2): if max &lt; (...
2
2016-09-05T11:40:39Z
39,329,936
<p>Iterate over the list and find the following:</p> <p>Largest Positive number(a)</p> <p>Second Largest Positive number(b)</p> <p>Largest Negative number(c)</p> <p>Second Largest Negative number(d)</p> <p>Now, you will be able to figure out the maximum value upon multiplication, either <code>a*b</code> or <code>c...
13
2016-09-05T11:47:04Z
[ "python", "python-2.7", "python-3.x", "itertools" ]
How to find the maximum product of two elements in a list?
39,329,829
<p>I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:</p> <pre><code>import itertools l = [] for _ in range(int(input())): l.append(int(input())) max = l[0] * l[len(l)-1] for a,b in itertools.combinations(l,2): if max &lt; (...
2
2016-09-05T11:40:39Z
39,330,037
<p>Here is an implementation following @User_Targaryen's logic. <a href="https://docs.python.org/3.0/library/heapq.html" rel="nofollow"><code>heapq</code></a> returns the 2 largest and 2 smallest numbers in the list, <a href="https://docs.python.org/3/library/operator.html" rel="nofollow"><code>mul operator</code></a> ...
2
2016-09-05T11:52:42Z
[ "python", "python-2.7", "python-3.x", "itertools" ]
How to find the maximum product of two elements in a list?
39,329,829
<p>I was trying out a problem on hackerrank contest for fun, and there came this question. I used itertools for this, here is the code:</p> <pre><code>import itertools l = [] for _ in range(int(input())): l.append(int(input())) max = l[0] * l[len(l)-1] for a,b in itertools.combinations(l,2): if max &lt; (...
2
2016-09-05T11:40:39Z
39,330,487
<p>Just sort the list and select the largest of the products of the last 2 items in the list and the first 2 items in the list:</p> <pre><code>from operator import mul numbers = [10, 20, 1, -11, 100, -12] l = sorted(numbers) # or sort in place with numbers.sort() if you don't mind mutating the list max_product = m...
2
2016-09-05T12:19:31Z
[ "python", "python-2.7", "python-3.x", "itertools" ]
Scikit Image Marching Cubes
39,329,954
<p>I'm using the Scikit Image implementation of the marching cubes algorithm to generate an isosurface. </p> <pre><code>verts, faces,normals,values = measure.marching_cubes(stack,0) </code></pre> <p>generates the following error: </p> <blockquote> <p>ValueError: need more than 2 values to unpack</p> </blockquote> ...
0
2016-09-05T11:48:20Z
39,330,245
<p>The <a href="http://scikit-image.org/docs/dev/api/skimage.measure.html#marching-cubes" rel="nofollow">docs</a> of <code>marching_cubes</code> on the development version of scikit-image show that it should return <code>normals</code> and <code>values</code> as well. However it has only been introduced recently. They ...
2
2016-09-05T12:06:03Z
[ "python", "mesh", "scikit-image", "marching-cubes" ]
Time and Space Complexity Trouble
39,330,093
<p>I've seen so many time complexity problems but none seem to aid in my understanding of it - like really get it.</p> <p>What I have taken from my readings and attempts at practices all seems to come down to what was mentioned here <a href="http://stackoverflow.com/questions/13467674/determining-complexity-for-recurs...
0
2016-09-05T11:56:28Z
39,330,730
<blockquote> <p>Since the function calls the function 3 times</p> </blockquote> <p>This isn't really correct, but rather lets use examples that are more exact that your ad-hoc example.</p> <pre><code>def constant(n): return n*12301230 </code></pre> <p>This will always run in the same amount of time and is ther...
3
2016-09-05T12:33:48Z
[ "python", "recursion", "time-complexity" ]
recursively change file names in directories
39,330,127
<p>Starting with a source directory;</p> <p>&lt; C:/Users/Public/Env Defense/Projects/1_Earnings Calls/Quarterly Earnings Calls/1_IOUs by Quarter/2013 Q1/AAA Done/</p> <p>there are multiple subdirectories within the source directory; for example </p> <p>&lt; /Users/Public/Env Defense/Projects/1_Earnings Calls/Quart...
-1
2016-09-05T11:59:08Z
39,337,649
<p>The WinError was caused by the file path exceeding 260 characters. I edited the directory names to reduce the number of characters and the script worked as intended. It is very helpful to be able to quickly edit the names as I am working with 20 directories each of which contains about 40 subdirectories and each su...
1
2016-09-05T21:00:44Z
[ "python", "recursion" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip fi...
3
2016-09-05T12:00:02Z
39,330,766
<p>The example below will work directly! As suggested by @Padraic I replaced os.system with the more suitable subprocess.</p> <p>What about joining all the files in a single string and look for *.mkv within the string? </p> <pre><code>import os import re from subprocess import check_call from os.path import join rx ...
1
2016-09-05T12:36:08Z
[ "python", "loops" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip fi...
3
2016-09-05T12:00:02Z
39,331,468
<pre><code>import os import re regex = re.complile(r'(.*zip$)|(.*rar$)|(.*r00$)') path = "/mnt/externa/folder" for root, dirs, files in os.walk(path): for file in files: res = regex.match(file) if res: if res.group(1): print("Unzipping ",file, "...") os.system...
-2
2016-09-05T13:16:54Z
[ "python", "loops" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip fi...
3
2016-09-05T12:00:02Z
39,331,551
<p>Just use <em>any</em> to see if any files end in <code>.mkv</code> before going any further, you can also simplify to an <em>if/else</em> as you do the same thing for the last two matches. Also using <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_call" rel="nofollow">subprocess.check_cal...
2
2016-09-05T13:21:53Z
[ "python", "loops" ]
How to iterate through every directory specified and run commands on files (Python)
39,330,146
<p>I have been working on a script that will check through every subdirectory in a directory and match files using regex and then use different commands based on what kind of a file it is. </p> <p>So what i have finished is the use of different commands based on regex matching. Right now it checks for either a .zip fi...
3
2016-09-05T12:00:02Z
39,331,776
<p><code>re</code> is overkill for something like this. There's a library function for extracting file extensions, <code>os.path.splitext</code>. In the following example, we build an extension-to-filenames map and we use it both for checking the presence of <code>.mkv</code> files in constant time and for mapping each...
0
2016-09-05T13:33:03Z
[ "python", "loops" ]
how to avoid to being identified as spam when using smtplib in python
39,330,309
<pre><code>import smtplib smtp = smtplib.SMTP() smtp.connect('smtp.163.com', '25') from_addr = 'XXX@163.com' to_addr = 'XXX@qq.com' smtp.login(from_addr, 'XXXX') msg = ('From: %s\r\nTo: %s\r\n' % (from_addr, to_addr)) msg = msg + '''Subject: Test Hi, I just test this format!! Just python send mail test - -.''...
1
2016-09-05T12:09:38Z
39,330,501
<p>I had a similar issue and the work-around was to set a message ID:</p> <pre><code>from email.utils import make_msgid msg['Message-ID'] = make_msgid() </code></pre> <p>It is just a clue, I do not know if this fix will fit for you.</p>
0
2016-09-05T12:20:26Z
[ "python", "smtp", "spam" ]