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
How to create a dictionary with multiple values inside another dictionary in python
39,923,198
<p>I want to simulate a graph using dictionaries in Python.</p> <pre><code>G = {'a':{'b':3, 'c':4}, 'b':{'a':3, 'c':5}, 'c':{'a':4,'b':5}, } </code></pre> <p>G is a dictionary where each value is a dictionary which represents adjacent nodes with its weight.</p> <p>I have the following code:</p> <pre><code>def Graph(nodes): list_nodes = [] list_adjacent_nodes = [] graph = {} for i in range(nodes): node = raw_input(" ID Node %d:" %(i+1)) list_nodes.append(node) num_adjacent_nodes = input(" Num adjacent nodes '%s':" %(list_nodes[i])) list_adjacent_nodes.append([]) for j in range(num_adjacent_nodes): adjacent_node = raw_input(" ID adjacent nodes %d:" %(j+1)) list_adjacent_nodes.append[i].append(adjacent_node) weight = input(" Wight (Nodes(%s,%s) ): " %(list_nodes[i],list_adjacent_nodes[i][j] ) ) graph[list_nodes[i]] = {} graph[lista_nodes[i]][list_adjacent_nodes[i][j]] = weight return graph </code></pre> <p>However, I get the following result:</p> <pre><code>G = {'a':{'c':4}, 'b':{'c':5}, 'c':{'b':5}, } </code></pre> <p>Where have I gone wrong and how can I return my desired output?</p>
2
2016-10-07T17:51:28Z
39,923,251
<p>You overwrite the "inner" dictionary in each iteration of the loop with an empty dictionary. You should do so only if it's missing:</p> <pre><code>if not graph[list_nodes[i]]: # Here! graph[list_nodes[i]] = {} graph[list_nodes[i]][list_adjacent_nodes[i][j]] = weight </code></pre>
2
2016-10-07T17:54:48Z
[ "python", "dictionary" ]
Variable scope in case of an exception in python
39,923,315
<pre><code>while True: try: 2/0 except Exception as e: break print e </code></pre> <p>Gives: integer division or modulo by zero</p> <p>I thought scope of <code>e</code> is within the <code>while</code> block and it will not be accessible in the outside <code>print</code> statement. What did I miss ?</p>
2
2016-10-07T17:59:46Z
39,923,802
<p>Simple: <code>while</code> does not create a scope in Python. Python has only the following scopes:</p> <ul> <li>function scope (may include closure variables)</li> <li>class scope (only while the class is being defined)</li> <li>global (module) scope</li> <li>comprehension/generator expression scope</li> </ul> <p>So when you leave the <code>while</code> loop, <code>e</code>, being a local variable (if the loop is in a function) or a global variable (if not), is still available.</p> <p>tl;dr: Python is not C.</p>
5
2016-10-07T18:33:49Z
[ "python", "python-2.7", "exception" ]
'str' object is not callable Django Rest Framework
39,923,384
<p>I'm trying to create an API view but I'm getting an error. Can anyone help?</p> <p>urls.py:</p> <pre><code>app_name = 'ads' urlpatterns = [ # ex: /ads/ url(r'^$', views.ListBrand.as_view(), name='brand_list'), ] </code></pre> <p>views.py:</p> <pre><code>from rest_framework.views import APIView from rest_framework.response import Response from . import models from . import serializers class ListBrand(APIView): def get(self, request, format=None): brands = models.Brand.objects.all() serializer = serializers.BrandSerializer(brands, many=True) data = serializer.data return Response(data) </code></pre> <p>UPDATE: HERE IS THE ERROR, it is a string error. And I can't seem to find where its coming from.</p> <pre><code>TypeError at /api/v1/ads/ 'str' object is not callable Request Method: GET Request URL: http://localhost/api/v1/ads/ Django Version: 1.10.2 Exception Type: TypeError Exception Value: 'str' object is not callable Exception Location: C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py in &lt;listcomp&gt;, line 264 Python Executable: C:\Users\Leon\Desktop\esriom\Scripts\python.exe Python Version: 3.5.2 Python Path: ['C:\\Users\\Leon\\Desktop\\esirom', 'C:\\Users\\Leon\\Desktop\\esriom\\lib\\site-packages\\setuptools-18.1-py3.5.egg', 'C:\\Users\\Leon\\Desktop\\esriom\\lib\\site-packages\\pip-7.1.0-py3.5.egg', 'C:\\Users\\Leon\\Desktop\\esriom\\Scripts\\python35.zip', 'C:\\Users\\Leon\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs', 'C:\\Users\\Leon\\AppData\\Local\\Programs\\Python\\Python35-32\\lib', 'C:\\Users\\Leon\\AppData\\Local\\Programs\\Python\\Python35-32', 'C:\\Users\\Leon\\Desktop\\esriom', 'C:\\Users\\Leon\\Desktop\\esriom\\lib\\site-packages'] Server time: Fri, 7 Oct 2016 12:44:04 -0500 </code></pre> <p>HERE IS THERE TRACEBACK TOO</p> <pre><code>Environment: Request Method: GET Request URL: http://localhost/api/v1/ads/ Django Version: 1.10.2 Python Version: 3.5.2 Installed Applications: ['rest_framework', 'ads.apps.AdsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\core\handlers\exception.py" in inner 39. response = get_response(request) File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "C:\Users\Leon\Desktop\esriom\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in dispatch 457. request = self.initialize_request(request, *args, **kwargs) File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in initialize_request 364. authenticators=self.get_authenticators(), File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in get_authenticators 264. return [auth() for auth in self.authentication_classes] File "C:\Users\Leon\Desktop\esriom\lib\site-packages\rest_framework\views.py" in &lt;listcomp&gt; 264. return [auth() for auth in self.authentication_classes] Exception Type: TypeError at /api/v1/ads/ Exception Value: 'str' object is not callable </code></pre>
0
2016-10-07T18:04:41Z
39,924,164
<p>My problem was in my settings.py file:</p> <p>It should've been:</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticatedOrReadOnly', ), } </code></pre> <p>Instead of:</p> <pre><code>REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': { 'rest_framework.authentication.SessionAuthentication', }, 'DEFAULT_PERMISSION_CLASSES': { 'rest_framework.permissions.IsAuthenticatedOrReadOnly', }, } </code></pre>
1
2016-10-07T19:00:14Z
[ "python", "django", "python-3.x", "django-rest-framework" ]
Compare length of values of a column
39,923,519
<p>I have a data frame with 20 columns, two of the columns being Company1 and Company2. I want a resultant data frame with only those rows in which length of Company1 and Company2 don't differ by more than 5 characters. How do I accomplish this task using pandas? </p>
1
2016-10-07T18:15:03Z
39,923,711
<p>You can use <code>.str.len()</code> to get access to the number of characters in the <code>Company</code> columns, then calculate the difference with vectorized subtraction of pandas series and create a logic vector with the condition for subsetting:</p> <pre><code>df[abs(df.Company1.str.len() - df.Company2.str.len()) &lt;= 5] </code></pre>
2
2016-10-07T18:27:26Z
[ "python", "pandas" ]
Python Load csv file to Oracle table
39,923,540
<p>I'm a python beginner. I'm trying to insert records into a Oracle table from a csv file. csv file format : Artist_name, Artist_type, Country . I'm getting below error:</p> <pre><code>Error: File "artist_dim.py", line 42, in &lt;module&gt; cur.execute(sqlquery) cx_Oracle.DatabaseError: ORA-00917: missing comma import cx_Oracle as cx import csv import sys ##### Step 1 : Connect to Oracle Database######### conn_str=u'hr/hr@localhost:1521/PDBORCL' conn= cx.connect(conn_str) cur=conn.cursor() ####################################### #### Step 2: FETCH LATEST ROW ID FROM ARTIST_DIM### query="SELECT nvl(max(row_id)+1,1) from artist_dim" cur.execute(query) rownum=cur.fetchone() x=rownum[0] with open('D:\python\Artist.csv') as f: reader=csv.DictReader(f,delimiter=',') for row in reader: sqlquery="INSERT INTO ARTIST_DIM VALUES (%d,%s,%s,%s)" %(x,row['Artist_name'],row['Artist_type'],row['Country']) cur.execute(sqlquery) x=x+1 conn.commit() </code></pre> <p>When I try to read the file it is working correctly.</p> <pre><code> ##### Just to Read CSV File############################ with open('D:\python\Artist.csv') as f: reader = csv.DictReader(f, delimiter=',') for row in reader: a="row_id %d Artist : %s type : %s Country : %s " %(x,row['Artist_name'],row['Artist_type'],row['Country']) print(a) x=x+1 print(row['Artist_name'],",",row['Artist_type'],",",row['Country']) Also, when I try to insert using hard coded values it is working sqlquery1="INSERT INTO ARTIST_DIM VALUES (%d,'Bob','Bob','Bob')" %x cur.execute(sqlquery1) </code></pre>
0
2016-10-07T18:16:29Z
39,923,627
<p>Put quotes around the values:</p> <pre><code>sqlquery="INSERT INTO ARTIST_DIM VALUES (%d,'%s','%s','%s')" %(x,row['Artist_name'],row['Artist_type'],row['Country']) </code></pre> <p>Without the quotes it translates to:</p> <pre><code>sqlquery="INSERT INTO ARTIST_DIM VALUES (1, Bob, Bob, Bob)" </code></pre>
1
2016-10-07T18:22:36Z
[ "python", "oracle", "python-3.x" ]
Python read CSV file, and write to another skipping columns
39,923,595
<p>I have CSV input file with 18 columns I need to create new CSV file with all columns from input except column 4 and 5</p> <p>My function now looks like</p> <pre><code>def modify_csv_report(input_csv, output_csv): begin = 0 end = 3 with open(input_csv, "r") as file_in: with open(output_csv, "w") as file_out: writer = csv.writer(file_out) for row in csv.reader(file_in): writer.writerow(row[begin:end]) return output_csv </code></pre> <p>So it reads and writes columns number 0 - 3, but i don't know how skip column 4,5 and continue from there</p>
0
2016-10-07T18:20:35Z
39,923,631
<p>You can add the other part of the row using <em>slicing</em>, like you did with the first part:</p> <pre><code>writer.writerow(row[:4] + row[6:]) </code></pre> <p>Note that to include column 3, the stop index of the first slice should be 4. Specifying start index 0 is also usually not necessary.</p> <p>A more general approach would employ a <em>list comprehension</em> and <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a>:</p> <pre><code>exclude = (4, 5) writer.writerow([r for i, r in enumerate(row) if i not in exclude]) </code></pre>
2
2016-10-07T18:22:49Z
[ "python", "csv" ]
Python read CSV file, and write to another skipping columns
39,923,595
<p>I have CSV input file with 18 columns I need to create new CSV file with all columns from input except column 4 and 5</p> <p>My function now looks like</p> <pre><code>def modify_csv_report(input_csv, output_csv): begin = 0 end = 3 with open(input_csv, "r") as file_in: with open(output_csv, "w") as file_out: writer = csv.writer(file_out) for row in csv.reader(file_in): writer.writerow(row[begin:end]) return output_csv </code></pre> <p>So it reads and writes columns number 0 - 3, but i don't know how skip column 4,5 and continue from there</p>
0
2016-10-07T18:20:35Z
39,923,807
<p>This is what you want:</p> <pre><code>import csv def remove_csv_columns(input_csv, output_csv, exclude_column_indices): with open(input_csv) as file_in, open(output_csv, 'w') as file_out: reader = csv.reader(file_in) writer = csv.writer(file_out) writer.writerows( [col for idx, col in enumerate(row) if idx not in exclude_column_indices] for row in reader) remove_csv_columns('in.csv', 'out.csv', (3, 4)) </code></pre>
0
2016-10-07T18:34:11Z
[ "python", "csv" ]
Python read CSV file, and write to another skipping columns
39,923,595
<p>I have CSV input file with 18 columns I need to create new CSV file with all columns from input except column 4 and 5</p> <p>My function now looks like</p> <pre><code>def modify_csv_report(input_csv, output_csv): begin = 0 end = 3 with open(input_csv, "r") as file_in: with open(output_csv, "w") as file_out: writer = csv.writer(file_out) for row in csv.reader(file_in): writer.writerow(row[begin:end]) return output_csv </code></pre> <p>So it reads and writes columns number 0 - 3, but i don't know how skip column 4,5 and continue from there</p>
0
2016-10-07T18:20:35Z
39,923,823
<p>If your CSV has meaningful headers an alternative solution to slicing your rows by indices, is to use the <code>DictReader</code> and <code>DictWriter</code> classes.</p> <pre><code>#!/usr/bin/env python from csv import DictReader, DictWriter data = '''A,B,C 1,2,3 4,5,6 6,7,8''' reader = DictReader(data.split('\n')) # You'll need your fieldnames first in a list to ensure order fieldnames = ['A', 'C'] # We'll also use a set for efficient lookup fieldnames_set = set(fieldnames) with open('outfile.csv', 'w') as outfile: writer = DictWriter(outfile, fieldnames) writer.writeheader() for row in reader: # Use a dictionary comprehension to iterate over the key, value pairs # discarding those pairs whose key is not in the set filtered_row = dict( (k, v) for k, v in row.iteritems() if k in fieldnames_set ) writer.writerow(filtered_row) </code></pre>
0
2016-10-07T18:35:36Z
[ "python", "csv" ]
Models referring to each other - how can I most efficiently fix this issue?
39,923,649
<p>I have a Django application that contains two models - <code>Company</code> and <code>User</code>. These are each in separate files. Each <code>User</code> has a <code>Company</code> by a <code>model.ForeignKey</code> field:</p> <p>company.py:</p> <pre><code>class Company(models.Model): name = models.CharField(max_length=32) is_admin = models.BooleanField(default=False) </code></pre> <p>user.py:</p> <pre><code># Ignore the clumsy in this import for a moment from package.models.company import Company class User(models.Model): name = models.CharField(max_length=32) company = models.ForeignKey(Company) </code></pre> <p>Now, one thing I want to do is to add a method <code>list_admins</code> to <code>Company</code> (<em>not</em> <code>User</code>), whereby it would give me a list of all users who happen to have <code>is_admin</code> set to <code>True</code>:</p> <pre><code> def list_admins(self): return User.object.filter(is_admin=True); </code></pre> <p>But of course that would require me to import <code>User</code> in Company, which I can't, as I can't import <code>User</code> in <code>Company</code> and <code>Company</code> in <code>User</code> at the same time owing to its circularity.</p> <p>So how does one resolve this in a Pythonic/Djangoic way?</p>
0
2016-10-07T18:23:50Z
39,923,761
<pre><code>def list_admins(self): return User.object.filter(company__is_admin=True); </code></pre>
-1
2016-10-07T18:30:48Z
[ "python", "django", "django-models" ]
Models referring to each other - how can I most efficiently fix this issue?
39,923,649
<p>I have a Django application that contains two models - <code>Company</code> and <code>User</code>. These are each in separate files. Each <code>User</code> has a <code>Company</code> by a <code>model.ForeignKey</code> field:</p> <p>company.py:</p> <pre><code>class Company(models.Model): name = models.CharField(max_length=32) is_admin = models.BooleanField(default=False) </code></pre> <p>user.py:</p> <pre><code># Ignore the clumsy in this import for a moment from package.models.company import Company class User(models.Model): name = models.CharField(max_length=32) company = models.ForeignKey(Company) </code></pre> <p>Now, one thing I want to do is to add a method <code>list_admins</code> to <code>Company</code> (<em>not</em> <code>User</code>), whereby it would give me a list of all users who happen to have <code>is_admin</code> set to <code>True</code>:</p> <pre><code> def list_admins(self): return User.object.filter(is_admin=True); </code></pre> <p>But of course that would require me to import <code>User</code> in Company, which I can't, as I can't import <code>User</code> in <code>Company</code> and <code>Company</code> in <code>User</code> at the same time owing to its circularity.</p> <p>So how does one resolve this in a Pythonic/Djangoic way?</p>
0
2016-10-07T18:23:50Z
39,923,892
<p>You can use the reverse <code>ForeignKey</code> relation on each <code>Company</code> to access their respective <code>Users</code>:</p> <pre><code>def list_admins(self): return self.user_set.filter(is_admin=True) </code></pre> <hr> <p>Doc. reference: <a href="https://docs.djangoproject.com/en/1.10/topics/db/queries/#following-relationships-backward" rel="nofollow">Following relationships “backward”</a></p>
2
2016-10-07T18:40:05Z
[ "python", "django", "django-models" ]
Measure how much activity is occurring within certain frequency values in Python
39,923,741
<p>I'm trying to find a way to obtain frequency values (in Hz) of an audio file, and measure how often these frequency values occur in proportion to the rest of the frequency values in that file. </p> <p>For example, in an audio file, I'd like to see what proportion of the audio activity occurs within the 300 - 500 Hz range.</p> <p>This would be simple if I could somehow get a list or an array filled with all frequency values of a given audio file, but I don't know how to do that.</p> <p>Thank you.</p>
0
2016-10-07T18:29:12Z
39,923,974
<p>You may be looking for a <a href="https://en.wikipedia.org/wiki/Fourier_transform" rel="nofollow">Fourier Transform</a> or <a href="https://en.wikipedia.org/wiki/Fast_Fourier_transform" rel="nofollow">Fast Fourier Transform</a>.</p> <p>From Wikipedia:</p> <p><a href="http://i.stack.imgur.com/QWXIG.png" rel="nofollow"><img src="http://i.stack.imgur.com/QWXIG.png" alt="Fourier Transform"></a></p> <p>On the left would be your normal signal, and on the right is your frequency-domain signal. Of course, you can just cut out the 300-500 Hz range, take the integral over that area, then divide by the total area to get the proportion...</p> <p>Not really my specialty, but consider a <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.fft.html#scipy.fftpack.fft" rel="nofollow">scipy solution</a>?</p>
1
2016-10-07T18:46:19Z
[ "python", "audio", "frequency" ]
json array with in array returning error ?bad string
39,923,774
<p>i am parsing my json string file to python and always returning error . i used online json formatter and validators that also returning error so i want help to make my json correct and tell me error</p> <pre><code> [{ "sentence_id": "TR.00001", "sentence": { "text": "Bill was born 1986.", "annotation": { (1, "Bill", "bill", "NNP", "B-PERSON"), (2, "was", "be", "VBD", "O"), (3, "born", "bear", "VBN", "O"), (4, "1986", "BIL", "CD", "B-DATE"), (5, ".", ".", ".", "O"), }, "relations": { "subject": "bill", "predicate": "DATE of Birth", "object": "1986" } } }, ] </code></pre> <p>the above is my json string you can check online validators or online json format verifier here is the part of json that returns error</p> <pre><code>"annotation": { (1, "Bill", "bill", "NNP", "B-PERSON"), (2, "was", "be", "VBD", "O"), (3, "born", "bear", "VBN", "O"), (4, "1986", "BIL", "CD", "B-DATE"), (5, ".", ".", ".", "O"), }, </code></pre> <p>so can you please help me in sorting out the trouble of array with in array using json you can use these editors link <a href="http://www.jsoneditoronline.org/" rel="nofollow">link to json editor</a></p> <blockquote> <p>expecting property name <code>,</code> error in line 8</p> </blockquote>
0
2016-10-07T18:32:01Z
39,923,952
<p>JSON doesn't understand tuples, try changing to lists:</p> <pre><code>"annotation": [ [1, "Bill", "bill", "NNP", "B-PERSON"], [2, "was", "be", "VBD", "O"], [3, "born", "bear", "VBN", "O"], [4, "1986", "BIL", "CD", "B-DATE"], [5, ".", ".", ".", "O"] ] </code></pre> <p>You can do <code>tuple(list)</code> to convert back to tuples on the other end.</p> <p>Also, you had an extra comma on <code>[5, ".", ".", ".", "O"]</code>, I removed it.</p>
2
2016-10-07T18:45:12Z
[ "javascript", "php", "python", "arrays", "json" ]
json array with in array returning error ?bad string
39,923,774
<p>i am parsing my json string file to python and always returning error . i used online json formatter and validators that also returning error so i want help to make my json correct and tell me error</p> <pre><code> [{ "sentence_id": "TR.00001", "sentence": { "text": "Bill was born 1986.", "annotation": { (1, "Bill", "bill", "NNP", "B-PERSON"), (2, "was", "be", "VBD", "O"), (3, "born", "bear", "VBN", "O"), (4, "1986", "BIL", "CD", "B-DATE"), (5, ".", ".", ".", "O"), }, "relations": { "subject": "bill", "predicate": "DATE of Birth", "object": "1986" } } }, ] </code></pre> <p>the above is my json string you can check online validators or online json format verifier here is the part of json that returns error</p> <pre><code>"annotation": { (1, "Bill", "bill", "NNP", "B-PERSON"), (2, "was", "be", "VBD", "O"), (3, "born", "bear", "VBN", "O"), (4, "1986", "BIL", "CD", "B-DATE"), (5, ".", ".", ".", "O"), }, </code></pre> <p>so can you please help me in sorting out the trouble of array with in array using json you can use these editors link <a href="http://www.jsoneditoronline.org/" rel="nofollow">link to json editor</a></p> <blockquote> <p>expecting property name <code>,</code> error in line 8</p> </blockquote>
0
2016-10-07T18:32:01Z
39,924,089
<p>Your json string file is not proper it have some error ...</p> <ol> <li>you missed the key in annotation.</li> <li>your value must be in capital bracket because it is an array.</li> <li><p>you add extra comma at the end.</p> <pre><code> [ { "sentence_id" : "TR.00001", "sentence" : { "text" : "Bill was born 1986.", "annotation":{ "1": [1,"Bill" , "bill" , "NNP" ,"B-PERSON"], "2":[2, "was" , "be" , "VBD" , "O"], "3": [3 , "born" , "bear" , "VBN", "O"], "4":[4, "1986" , "BIL" , "CD" , "B-DATE"], "5":[5, "." , "." , ".","O"] }, "relations":{ "subject":"bill", "predicate":"DATE of Birth", "object":"1986" } } } ] </code></pre></li> </ol> <p>That means your annotation section must be like this:</p> <pre><code>"annotation":{ "1": [1,"Bill" , "bill" , "NNP" ,"B-PERSON"], "2":[2, "was" , "be" , "VBD" , "O"], "3": [3 , "born" , "bear" , "VBN", "O"], "4":[4, "1986" , "BIL" , "CD" , "B-DATE"], "5":[5, "." , "." , ".","O"] }, </code></pre>
1
2016-10-07T18:54:21Z
[ "javascript", "php", "python", "arrays", "json" ]
OpenCV Stereo confidence
39,923,798
<p>Is there a way to get out the confidence from OpenCV's Stereo matching algorithms in Python?</p> <p>I wish to eliminate points from the generated point cloud based on these confidence values.</p>
1
2016-10-07T18:33:28Z
39,927,027
<p>Unfortunately, OpenCV does not seem to provide correlation scores with the stereo matcher functions. If no correspondance is found, pixel appears black on disparity map but you have to trust the algorithms implementation.</p> <p>You can still compute your own error estimate with respect to your camera parameters, baseline and range (see <a href="https://siddhantahuja.wordpress.com/2009/07/24/how-to-select-the-proper-disparity-value-for-stereo-vision/" rel="nofollow">this</a> page) or if you really need precision or high confidence in your result, you could try to implement some subpixel accuracy correlation such as <a href="http://xanthippi.ceid.upatras.gr/people/evangelidis/encc/" rel="nofollow">this</a> one. Hope this helps.</p>
0
2016-10-07T23:19:31Z
[ "python", "opencv", "computer-vision" ]
Retrieving form data after setting initial value
39,923,814
<p>I wanted to populate my form fields with initial data, so I've set my view just like recommended by @ars in <a href="http://stackoverflow.com/questions/3833403/initial-populating-on-django-forms">this question</a>:</p> <pre><code>def update_member(request): if request.method == 'POST': urn = 'urn:publicid:myurn' member = Member(urn=urn) retrieved_members = member.search_member(filter_params=['urn', 'first_name', 'last_name']) # If search returns member if retrieved_members != []: member = retrieved_members[0] member_attributes = {'first_name': member.first_name, 'last_name': member.last_name} form = UpdateMemberForm(initial=member_attributes) </code></pre> <p>And it works properly. But when I manually fill in the fields in the template, my view still sets those initial values. I cannot reset the values as the ones passed via POST method. I know this happens because of the way I set the initial values, but I don't know how I could fix it. </p> <p>Does anyone has an idea of how I could solve this?</p>
0
2016-10-07T18:35:01Z
39,924,765
<p>If you check the POST data for values submitted, you can update member_attributes with those values before calling UpdateMemberForm()</p>
1
2016-10-07T19:45:17Z
[ "python", "django" ]
Merging two dictionaries together and adding None to the desired location
39,923,922
<p>I've scraped some <a href="http://www.richmond.com/data-center/salaries-local-government-employees-2014/?Agency=&amp;Last_Name=&amp;First_Name=&amp;Job_Title=PRINCIPAL&amp;appSession=82100926574322760625479516407609655632811717398403303845564132296054295099051816928601026788234447191565075848437884339109744304&amp;RecordID=29541&amp;PageID=8&amp;PrevPageID=2&amp;cpipage=1&amp;CPIsortType=&amp;CPIorderBy=&amp;cbCurrentRecordPosition=1&amp;Mod0LinkToDetails=True" rel="nofollow">data</a> and due to the way the website was structured I put the data into two dictionaries. </p> <pre><code>&gt;&gt;&gt;pprint(dict(data)) {u'Additional compensation': [u'$32,241'], u'Agency': [u'Chesterfield County Schools', u'City of Richmond Schools'], u'Bonuses or other allowances': [u'$12,500'], u'COMMENTS': [u'$28,088 - Board Paid Annuity; $4,153 - Excess Health Benefit Contribution;', u''], u'Full Name': [u'Marcus J. Newsome', u'Dana T. Bedden'], u'Total Compensation': [u'$282,258', u'']} &gt;&gt;&gt;pprint(dict(data2)) {u'Base Salary': [u'$229,758', u'$234,068'], u'COMMENTS': [u'12,500 CAR ALLOWANCE, 40,000 DEFFERRED COMPENSATION'], u'Deferred compensation': [u'$40,000'], u'Job Title': [u'SUPERINTENDENT', u'SUPERINTENDENT'], u'Total Compensation': [u'$266,309'], u'Work location': [u'Office Of Superintendent']} </code></pre> <p>I've combined the data into one master dictionary and I've attempted to put it into a csv file. </p> <pre><code>for d in data2, data: for k, v in d.iteritems(): master_data[k].append(v) with open('test2.csv', 'wb') as f: writer = csv.writer(f) writer.writerows(zip(*([k] + master_data[k] for k in sorted(master_data)))) </code></pre> <p>The problem is that only the first person's (<code>Marcus J. Newsome</code>) information is exported to the csv. I think this is due to fact that there are keys/values (for example <code>Additional compensation</code>) that belong to <code>Dana T. Bedden</code> that aren't present in <code>Marcus J Newsome</code>'s data. </p> <p>To address this I've tried adding <code>None</code> to the positions to fix this problem. </p> <pre><code>for d in data2, data: master_data.update((k, [None, master_data[k]]) for k in master_data if k not in d) &gt;&gt;&gt;pprint(dict(master_data)) {u'Additional compensation': [None, [[u'$32,241']]], u'Agency': [None, [[u'Chesterfield County Schools', u'City of Richmond Schools']]], u'Base Salary': [None, [[u'$229,758', u'$234,068']]], u'Bonuses or other allowances': [None, [[u'$12,500']]], u'COMMENTS': [[u'12,500 CAR ALLOWANCE, 40,000 DEFFERRED COMPENSATION'], [u'$28,088 - Board Paid Annuity; $4,153 - Excess Health Benefit Contribution;', u'']], u'Deferred compensation': [None, [[u'$40,000']]], u'Full Name': [None, [[u'Marcus J. Newsome', u'Dana T. Bedden']]], u'Job Title': [None, [[u'SUPERINTENDENT', u'SUPERINTENDENT']]], u'Total Compensation': [[u'$266,309'], [u'$282,258', u'']], u'Work location': [None, [[u'Office Of Superintendent']]]} </code></pre> <p>Unfortunately, this doesn't seem to work the way I want it to. Ultimately I would like to have my output look like this:</p> <p><strong>Desired Output</strong></p> <pre><code>{u'Additional compensation': [[None, [u'$32,241']]], u'Agency': [[u'Chesterfield County Schools'], [u'City of Richmond Schools']]], u'Base Salary': [[u'$229,758'], [u'$234,068']]], u'Bonuses or other allowances': [[u'$12,500'], None]], u'COMMENTS': [[u'12,500 CAR ALLOWANCE, 40,000 DEFFERRED COMPENSATION'], [u'$28,088 - Board Paid Annuity; $4,153 - Excess Health Benefit Contribution;', u'']], u'Deferred compensation': [[u'$40,000'], None]], u'Full Name': [[u'Marcus J. Newsome'], [u'Dana T. Bedden']]], u'Job Title': [[u'SUPERINTENDENT'], [u'SUPERINTENDENT']]], u'Total Compensation': [[u'$266,309'], [u'$282,258', u'']], u'Work location': [None, [u'Office Of Superintendent']]]} </code></pre> <p>Anyone have any ideas?</p>
2
2016-10-07T18:42:39Z
39,924,100
<p>I would restructure the data such that you have one dictionary for all relevant fields for each person. You can than easily use the dictwriter class of csv to export that data. </p>
0
2016-10-07T18:55:22Z
[ "python", "python-2.7", "csv", "dictionary" ]
Merging two dictionaries together and adding None to the desired location
39,923,922
<p>I've scraped some <a href="http://www.richmond.com/data-center/salaries-local-government-employees-2014/?Agency=&amp;Last_Name=&amp;First_Name=&amp;Job_Title=PRINCIPAL&amp;appSession=82100926574322760625479516407609655632811717398403303845564132296054295099051816928601026788234447191565075848437884339109744304&amp;RecordID=29541&amp;PageID=8&amp;PrevPageID=2&amp;cpipage=1&amp;CPIsortType=&amp;CPIorderBy=&amp;cbCurrentRecordPosition=1&amp;Mod0LinkToDetails=True" rel="nofollow">data</a> and due to the way the website was structured I put the data into two dictionaries. </p> <pre><code>&gt;&gt;&gt;pprint(dict(data)) {u'Additional compensation': [u'$32,241'], u'Agency': [u'Chesterfield County Schools', u'City of Richmond Schools'], u'Bonuses or other allowances': [u'$12,500'], u'COMMENTS': [u'$28,088 - Board Paid Annuity; $4,153 - Excess Health Benefit Contribution;', u''], u'Full Name': [u'Marcus J. Newsome', u'Dana T. Bedden'], u'Total Compensation': [u'$282,258', u'']} &gt;&gt;&gt;pprint(dict(data2)) {u'Base Salary': [u'$229,758', u'$234,068'], u'COMMENTS': [u'12,500 CAR ALLOWANCE, 40,000 DEFFERRED COMPENSATION'], u'Deferred compensation': [u'$40,000'], u'Job Title': [u'SUPERINTENDENT', u'SUPERINTENDENT'], u'Total Compensation': [u'$266,309'], u'Work location': [u'Office Of Superintendent']} </code></pre> <p>I've combined the data into one master dictionary and I've attempted to put it into a csv file. </p> <pre><code>for d in data2, data: for k, v in d.iteritems(): master_data[k].append(v) with open('test2.csv', 'wb') as f: writer = csv.writer(f) writer.writerows(zip(*([k] + master_data[k] for k in sorted(master_data)))) </code></pre> <p>The problem is that only the first person's (<code>Marcus J. Newsome</code>) information is exported to the csv. I think this is due to fact that there are keys/values (for example <code>Additional compensation</code>) that belong to <code>Dana T. Bedden</code> that aren't present in <code>Marcus J Newsome</code>'s data. </p> <p>To address this I've tried adding <code>None</code> to the positions to fix this problem. </p> <pre><code>for d in data2, data: master_data.update((k, [None, master_data[k]]) for k in master_data if k not in d) &gt;&gt;&gt;pprint(dict(master_data)) {u'Additional compensation': [None, [[u'$32,241']]], u'Agency': [None, [[u'Chesterfield County Schools', u'City of Richmond Schools']]], u'Base Salary': [None, [[u'$229,758', u'$234,068']]], u'Bonuses or other allowances': [None, [[u'$12,500']]], u'COMMENTS': [[u'12,500 CAR ALLOWANCE, 40,000 DEFFERRED COMPENSATION'], [u'$28,088 - Board Paid Annuity; $4,153 - Excess Health Benefit Contribution;', u'']], u'Deferred compensation': [None, [[u'$40,000']]], u'Full Name': [None, [[u'Marcus J. Newsome', u'Dana T. Bedden']]], u'Job Title': [None, [[u'SUPERINTENDENT', u'SUPERINTENDENT']]], u'Total Compensation': [[u'$266,309'], [u'$282,258', u'']], u'Work location': [None, [[u'Office Of Superintendent']]]} </code></pre> <p>Unfortunately, this doesn't seem to work the way I want it to. Ultimately I would like to have my output look like this:</p> <p><strong>Desired Output</strong></p> <pre><code>{u'Additional compensation': [[None, [u'$32,241']]], u'Agency': [[u'Chesterfield County Schools'], [u'City of Richmond Schools']]], u'Base Salary': [[u'$229,758'], [u'$234,068']]], u'Bonuses or other allowances': [[u'$12,500'], None]], u'COMMENTS': [[u'12,500 CAR ALLOWANCE, 40,000 DEFFERRED COMPENSATION'], [u'$28,088 - Board Paid Annuity; $4,153 - Excess Health Benefit Contribution;', u'']], u'Deferred compensation': [[u'$40,000'], None]], u'Full Name': [[u'Marcus J. Newsome'], [u'Dana T. Bedden']]], u'Job Title': [[u'SUPERINTENDENT'], [u'SUPERINTENDENT']]], u'Total Compensation': [[u'$266,309'], [u'$282,258', u'']], u'Work location': [None, [u'Office Of Superintendent']]]} </code></pre> <p>Anyone have any ideas?</p>
2
2016-10-07T18:42:39Z
39,924,128
<p>It'd be much better to change the way you store scraped data.</p> <p>Pseudocode:</p> <pre><code>data = [] for row in table: person = get_data_from_row(row) person.update(get_data_from_person_page(row)) data.append(person) </code></pre> <p>Then you can use <a href="https://docs.python.org/3/library/csv.html#csv.DictWriter" rel="nofollow"><code>csv.DictWriter</code></a> without any complex data manipulation:</p> <pre><code>with open('data.csv', 'w') as f: fieldnames = data[0].keys() writer = csv.DictWriter(f, fieldnames) writer.writeheader() for row in data: writer.writerow(row) </code></pre>
1
2016-10-07T18:57:18Z
[ "python", "python-2.7", "csv", "dictionary" ]
Pandas sklearn one-hot encoding dataframe or numpy?
39,923,927
<p>How can I transform a pandas data frame to sklearn one-hot-encoded (dataframe / numpy array) where some columns do not require encoding?</p> <pre><code>mydf = pd.DataFrame({'Target':[0,1,0,0,1, 1,1], 'GroupFoo':[1,1,2,2,3,1,2], 'GroupBar':[2,1,1,0,3,1,2], 'GroupBar2':[2,1,1,0,3,1,2], 'SomeOtherShouldBeUnaffected':[2,1,1,0,3,1,2]}) columnsToEncode = ['GroupFoo', 'GroupBar'] </code></pre> <p>Is an already label encoded data frame and I would like to only encode the columns marked by <code>columnsToEncode</code>? </p> <p>My problem is that I am unsure if a <code>pd.Dataframe</code> or the <code>numpy</code> array representation are better and how to re-merge the encoded part with the other one.</p> <p>My attempts so far:</p> <pre><code>myEncoder = OneHotEncoder(sparse=False, handle_unknown='ignore') myEncoder.fit(X_train) df = pd.concat([ df[~columnsToEncode], # select all other / numeric # select category to one-hot encode pd.Dataframe(encoder.transform(X_train[columnsToEncode]))#.toarray() # not sure what this is for ], axis=1).reindex_axis(X_train.columns, axis=1) </code></pre> <p>Notice: I am aware of <a href="http://stackoverflow.com/questions/36285155/pandas-get-dummies">Pandas: Get Dummies</a> / <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html</a> but that does not play well in a train / test split where I require such an encoding per fold.</p>
0
2016-10-07T18:42:54Z
39,930,275
<p>This library provides several categorical encoders which make sklearn / numpy play nicely with pandas <a href="https://github.com/wdm0006/categorical_encoding" rel="nofollow">https://github.com/wdm0006/categorical_encoding</a></p> <p>However, they do not yet support "handle unknown category"</p> <p>for now I will use</p> <pre><code>myEncoder = OneHotEncoder(sparse=False, handle_unknown='ignore') myEncoder.fit(df[columnsToEncode]) pd.concat([df.drop(columnsToEncode, 1), pd.DataFrame(myEncoder.transform(df[columnsToEncode]))], axis=1).reindex() </code></pre> <p>As this supports unknown datasets. For now, I will stick with half-pandas half-numpy because of the nice pandas labels. for the numeric columns.</p>
0
2016-10-08T08:21:05Z
[ "python", "pandas", "numpy", "scikit-learn", "dummy-variable" ]
Trying to create new variables by strings from a list
39,923,999
<p><p> I've been scouring the ends of the internet for this, and I am well aware of how discouraged what I am trying to do is. I just can't figure out another way to achieve what I want. Now, for my actual issue, I have been given a csv containing information of police shootings. The file contains the state of the case, with the city next to it. I want to a variable from each state's name recorded in the csv, and turn them into lists with the contents being the cities in that state. I've read some stuff about globals, but I'm just stumped about where to go from there. The language I'm using is python.</p> <p>Edit: As requested, here's what the format for the data and my current code:<p> State|City<p> Washington|Seattle<p> California|Los Angeles<p> Washington|Kirkland<p></p> <pre><code>PVC = open("PoliceViolence_city.csv", "r", errors="ignore"); KBP = open("KilledByPolice.csv", "r", errors="ignore"); def start(dparse, dparse2): cur = []; cur2 = []; for aa in dparse: cur.append(aa); for ab in dparse2: cur2.append(ab); del cur2[0]; del cur[0]; for ba in range(len(cur)): cur[ba] = cur[ba].split(","); sortloc(cur); for bb in range(len(cur2)): cur2[bb] = cur2[bb].split(","); def sortloc(dp): merge = []; state = []; city = []; s2 = []; for a in range(len(dp)): if dp[a][0] not in state: state.append(dp[a][0]); city.append(dp[a][1]); s2.append(dp[a][0]); for ba in range(len(city)): for bb in range(len(state)): if s2[ba] == state[bb]: print("Matched stuff!"); start(PVC, KBP); </code></pre> <p>Ideally, my output will be something like: Washington = ["Seattle", "Kirkland"].</p> <p>Thank you in advance for the help!</p>
-1
2016-10-07T18:47:56Z
39,924,159
<p>Use <code>csv.reader</code> and <code>collections.defaultdict</code>:</p> <pre><code>import csv import collections with open('states.csv') as f: result = collections.defaultdict(list) reader = csv.reader(f) for state,city in reader: result[state].append(city) </code></pre> <p>The file:</p> <pre><code>CA,San Francisco CA,Sacramento CA,San Francisco Idaho,Boise New York,New York City </code></pre> <p>The result:</p> <pre><code>&gt;&gt;&gt; import pprint &gt;&gt;&gt; pprint.pprint(result) {'CA': ['San Francisco', 'Sacramento', 'San Francisco'], 'Idaho': ['Boise'], 'New York': ['New York City']} </code></pre>
1
2016-10-07T18:59:41Z
[ "python", "list", "csv", "variables" ]
Trying to create new variables by strings from a list
39,923,999
<p><p> I've been scouring the ends of the internet for this, and I am well aware of how discouraged what I am trying to do is. I just can't figure out another way to achieve what I want. Now, for my actual issue, I have been given a csv containing information of police shootings. The file contains the state of the case, with the city next to it. I want to a variable from each state's name recorded in the csv, and turn them into lists with the contents being the cities in that state. I've read some stuff about globals, but I'm just stumped about where to go from there. The language I'm using is python.</p> <p>Edit: As requested, here's what the format for the data and my current code:<p> State|City<p> Washington|Seattle<p> California|Los Angeles<p> Washington|Kirkland<p></p> <pre><code>PVC = open("PoliceViolence_city.csv", "r", errors="ignore"); KBP = open("KilledByPolice.csv", "r", errors="ignore"); def start(dparse, dparse2): cur = []; cur2 = []; for aa in dparse: cur.append(aa); for ab in dparse2: cur2.append(ab); del cur2[0]; del cur[0]; for ba in range(len(cur)): cur[ba] = cur[ba].split(","); sortloc(cur); for bb in range(len(cur2)): cur2[bb] = cur2[bb].split(","); def sortloc(dp): merge = []; state = []; city = []; s2 = []; for a in range(len(dp)): if dp[a][0] not in state: state.append(dp[a][0]); city.append(dp[a][1]); s2.append(dp[a][0]); for ba in range(len(city)): for bb in range(len(state)): if s2[ba] == state[bb]: print("Matched stuff!"); start(PVC, KBP); </code></pre> <p>Ideally, my output will be something like: Washington = ["Seattle", "Kirkland"].</p> <p>Thank you in advance for the help!</p>
-1
2016-10-07T18:47:56Z
39,924,318
<p>It is possible by using <code>eval()</code>, but you should <strong>REALLY</strong> not do that... a much more structured and safe way to accomplish your task would be to take the state name and make that a key in a dictionary:</p> <pre class="lang-python prettyprint-override"> txt = '''state1, city1 state2, city2 state2, city3 state3, city4 state3, city4''' states = {} for line in txt.split('\n'): state, city = line.split(', ') if state not in states: states[state] = [] #create an empty list to hold all cities in a state if city not in states[state]: #don't put the same city in twice states[state].append(city) #insert the city into the list #resulting structure: #states = { # 'state1': ['city1'], # 'state2': ['city2', 'city3'], # 'state3': ['city4'] #}</pre>
0
2016-10-07T19:11:57Z
[ "python", "list", "csv", "variables" ]
Trying to create new variables by strings from a list
39,923,999
<p><p> I've been scouring the ends of the internet for this, and I am well aware of how discouraged what I am trying to do is. I just can't figure out another way to achieve what I want. Now, for my actual issue, I have been given a csv containing information of police shootings. The file contains the state of the case, with the city next to it. I want to a variable from each state's name recorded in the csv, and turn them into lists with the contents being the cities in that state. I've read some stuff about globals, but I'm just stumped about where to go from there. The language I'm using is python.</p> <p>Edit: As requested, here's what the format for the data and my current code:<p> State|City<p> Washington|Seattle<p> California|Los Angeles<p> Washington|Kirkland<p></p> <pre><code>PVC = open("PoliceViolence_city.csv", "r", errors="ignore"); KBP = open("KilledByPolice.csv", "r", errors="ignore"); def start(dparse, dparse2): cur = []; cur2 = []; for aa in dparse: cur.append(aa); for ab in dparse2: cur2.append(ab); del cur2[0]; del cur[0]; for ba in range(len(cur)): cur[ba] = cur[ba].split(","); sortloc(cur); for bb in range(len(cur2)): cur2[bb] = cur2[bb].split(","); def sortloc(dp): merge = []; state = []; city = []; s2 = []; for a in range(len(dp)): if dp[a][0] not in state: state.append(dp[a][0]); city.append(dp[a][1]); s2.append(dp[a][0]); for ba in range(len(city)): for bb in range(len(state)): if s2[ba] == state[bb]: print("Matched stuff!"); start(PVC, KBP); </code></pre> <p>Ideally, my output will be something like: Washington = ["Seattle", "Kirkland"].</p> <p>Thank you in advance for the help!</p>
-1
2016-10-07T18:47:56Z
39,925,002
<p>Time to bring this to a close. My friend helped me out by introducing me to dictionaries. The formatting is right for my data, and I have parented all the states to their respective cities. Thank you all for the help! While furas' answer was correct for what I needed, it wasn't very explanatory, so I think the most helpful overall was Aaron, as he went out of his way to try to help me understand. Hope y'all have a good one!</p>
0
2016-10-07T20:06:26Z
[ "python", "list", "csv", "variables" ]
IBM Bluemix user defined variables
39,924,006
<p>How can we access <code>USER-DEFINED</code> variables in IBM Bluemix in Python? I have made a token in IBM Bluemix, but I am unable to access it from my Python script. </p> <p>In the bluemix UI,</p> <p><code>token = &lt;actual value of token&gt;</code></p>
0
2016-10-07T18:48:20Z
39,925,339
<p>Solved it.</p> <p><code>os.getenv('name of the key')</code></p> <p>where <code>name of the key</code> is key defined in Bluemix UI. </p>
0
2016-10-07T20:30:15Z
[ "python", "ibm-bluemix", "ibm" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from for x in range(26):#loops through the random index of letter_count for i in range(letter_count[x]):#chooses the index bag_o_letters.append(letters[x])#appends the index of the letter to bag_o_letters rack = []#list for the person to see for a in range(7):#makes the list 7 letters long rack.append(bag_o_letters.pop(random.randint(0,len(letters)-1)))#appends the letter to rack(supposedly...) print(rack) </code></pre> <p>In this code that you just read it should choose random letters and put 7 of those letters in a rack that the person can see. It shows a error that I've looked over many times, but I just can't see what is wrong.</p> <blockquote> <p>I put comments on the side to understand the code.</p> </blockquote> <p><strong>It shows this error:</strong></p> <pre><code>rack.append(bag_of_letters.pop(random.randint(0,len(letters)-1))) IndexError: pop index out of range </code></pre> <blockquote> <p>Can someone please help?</p> <p>After this code, I am going to make a input statement for the user to make a word from those letters.</p> </blockquote>
0
2016-10-07T18:55:02Z
39,924,208
<p>You're selecting the <em>index</em> to <code>pop</code> for <code>bag_of_letters</code> from the length of <code>letters</code> which is obviously larger.</p> <p>You should instead do:</p> <pre><code>rack.append(bag_of_letters.pop(random.randint(0, len(bag_of_letters)-1))) # ^^^^^^^^^^^^^^ </code></pre> <hr> <p>However, there are likely to be more problems with your code. I'll suggest you use <a href="https://docs.python.org/2/library/random.html#random.sample" rel="nofollow"><code>random.sample</code></a> in one line of code or <a href="https://docs.python.org/2/library/random.html#random.shuffle" rel="nofollow"><code>random.shuffle</code></a> on a copy of the list, and then <em>slice</em> up till index 7. Both will give you 7 randomly selected letters:</p> <pre><code>import random print(random.sample(letters, 7)) # ['m', 'u', 'l', 'z', 'r', 'd', 'x'] </code></pre> <hr> <pre><code>import random letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letters_copy = letters[:] random.shuffle(letters_copy) print(letters_copy[:7]) # ['c', 'e', 'x', 'b', 'w', 'f', 'v'] </code></pre>
1
2016-10-07T19:04:18Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from for x in range(26):#loops through the random index of letter_count for i in range(letter_count[x]):#chooses the index bag_o_letters.append(letters[x])#appends the index of the letter to bag_o_letters rack = []#list for the person to see for a in range(7):#makes the list 7 letters long rack.append(bag_o_letters.pop(random.randint(0,len(letters)-1)))#appends the letter to rack(supposedly...) print(rack) </code></pre> <p>In this code that you just read it should choose random letters and put 7 of those letters in a rack that the person can see. It shows a error that I've looked over many times, but I just can't see what is wrong.</p> <blockquote> <p>I put comments on the side to understand the code.</p> </blockquote> <p><strong>It shows this error:</strong></p> <pre><code>rack.append(bag_of_letters.pop(random.randint(0,len(letters)-1))) IndexError: pop index out of range </code></pre> <blockquote> <p>Can someone please help?</p> <p>After this code, I am going to make a input statement for the user to make a word from those letters.</p> </blockquote>
0
2016-10-07T18:55:02Z
39,924,244
<p>The first time through the loop, you append one value to <code>bag_of_letters</code>, and then you try to pop an index of <code>random.randint(0,len(letters)-1)</code>. It doesn't have that many elements to pop from yet. Instead of this approach, you can make a list of the required length and sample from it:</p> <pre><code>letters = ['a', ...]#alphabet letter_count = [9, ...]#random indexes to chose from bag_of_letters = [l*c for l,c in zip(letters, letter_count)] ... rack = random.sample(bag_o_letters, 7) </code></pre>
2
2016-10-07T19:06:25Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from for x in range(26):#loops through the random index of letter_count for i in range(letter_count[x]):#chooses the index bag_o_letters.append(letters[x])#appends the index of the letter to bag_o_letters rack = []#list for the person to see for a in range(7):#makes the list 7 letters long rack.append(bag_o_letters.pop(random.randint(0,len(letters)-1)))#appends the letter to rack(supposedly...) print(rack) </code></pre> <p>In this code that you just read it should choose random letters and put 7 of those letters in a rack that the person can see. It shows a error that I've looked over many times, but I just can't see what is wrong.</p> <blockquote> <p>I put comments on the side to understand the code.</p> </blockquote> <p><strong>It shows this error:</strong></p> <pre><code>rack.append(bag_of_letters.pop(random.randint(0,len(letters)-1))) IndexError: pop index out of range </code></pre> <blockquote> <p>Can someone please help?</p> <p>After this code, I am going to make a input statement for the user to make a word from those letters.</p> </blockquote>
0
2016-10-07T18:55:02Z
39,924,246
<p>So I assume this is for something like scrabble? Your issue is that you're choosing a random index from your list of <code>letters</code>, not <code>bag_o_letters</code>. Maybe try this:</p> <pre><code>rack = [] for i in range(7): index = random.randint(0, len(bag_o_letter) - 1) rack.append(bag_o_letters.pop(index)) </code></pre>
0
2016-10-07T19:06:31Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from for x in range(26):#loops through the random index of letter_count for i in range(letter_count[x]):#chooses the index bag_o_letters.append(letters[x])#appends the index of the letter to bag_o_letters rack = []#list for the person to see for a in range(7):#makes the list 7 letters long rack.append(bag_o_letters.pop(random.randint(0,len(letters)-1)))#appends the letter to rack(supposedly...) print(rack) </code></pre> <p>In this code that you just read it should choose random letters and put 7 of those letters in a rack that the person can see. It shows a error that I've looked over many times, but I just can't see what is wrong.</p> <blockquote> <p>I put comments on the side to understand the code.</p> </blockquote> <p><strong>It shows this error:</strong></p> <pre><code>rack.append(bag_of_letters.pop(random.randint(0,len(letters)-1))) IndexError: pop index out of range </code></pre> <blockquote> <p>Can someone please help?</p> <p>After this code, I am going to make a input statement for the user to make a word from those letters.</p> </blockquote>
0
2016-10-07T18:55:02Z
39,924,260
<p>Why not do something like this:</p> <pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from from random import shuffle all_letters = list(''.join([l*c for l,c in zip(letters, letter_count)])) shuffle(all_letters) for i in range(int(len(all_letters)/7)): print all_letters[i*7:(i+1)*7] </code></pre>
0
2016-10-07T19:07:32Z
[ "python", "list", "random" ]
fPython : Making a new list from a random list of letters
39,924,096
<pre><code>letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']#alphabet bag_o_letters = []#letters to chose from letter_count = [9, 2, 2, 4, 12, 2, 3, 2, 9, 1, 1, 4, 2, 6, 8, 2, 1, 6, 4, 6, 4, 2, 2, 1, 2, 1]#random indexes to chose from for x in range(26):#loops through the random index of letter_count for i in range(letter_count[x]):#chooses the index bag_o_letters.append(letters[x])#appends the index of the letter to bag_o_letters rack = []#list for the person to see for a in range(7):#makes the list 7 letters long rack.append(bag_o_letters.pop(random.randint(0,len(letters)-1)))#appends the letter to rack(supposedly...) print(rack) </code></pre> <p>In this code that you just read it should choose random letters and put 7 of those letters in a rack that the person can see. It shows a error that I've looked over many times, but I just can't see what is wrong.</p> <blockquote> <p>I put comments on the side to understand the code.</p> </blockquote> <p><strong>It shows this error:</strong></p> <pre><code>rack.append(bag_of_letters.pop(random.randint(0,len(letters)-1))) IndexError: pop index out of range </code></pre> <blockquote> <p>Can someone please help?</p> <p>After this code, I am going to make a input statement for the user to make a word from those letters.</p> </blockquote>
0
2016-10-07T18:55:02Z
39,924,266
<p>The IndexError is expected:</p> <blockquote> <p>pop(...) L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or <strong>index is out of range</strong>.</p> </blockquote> <p>You need to subtract 1 from the bounds of the call to <code>random()</code> after each <code>pop()</code>. Right now you are doing this: </p> <pre><code>l = [1,2,3] random_idx = 2 l.pop(random_idx) &gt;&gt;&gt; l == [1,3] random_idx = 3 l.pop(random_idx) &gt;&gt;&gt;&gt; IndexError: pop index out of range </code></pre> <p>So instead, <code>pop()</code> based on <code>len(bag_o_letter)</code> rather than <code>len(letter)</code>.</p>
0
2016-10-07T19:07:42Z
[ "python", "list", "random" ]
I am writing a code which builds a decision tree and spits out the tree in the form of a code of if-else loops
39,924,168
<p>I am able to generate the correct if else loops. But i am not able to adjust the indentation. Is there any way of correctly indenting it?</p>
-4
2016-10-07T19:00:34Z
39,924,201
<p>If you have an indentation level that matches the decision tree depth, you should be able to just prepend four spaces for each level of indentation.</p>
0
2016-10-07T19:03:42Z
[ "python", "decision-tree" ]
How to make huge loops in python faster on mac?
39,924,176
<p>I am a computer science student and some of the things I do require me to run huge loops on Macbook with dual core i5. Some the loops take 5-6 hours to complete but they only use 25% of my CPU. Is there a way to make this process faster? I cant change my loops but is there a way to make them run faster?</p> <p>Thank you</p> <p>Mac OS 10.11 Python 2.7 (I have to use 2.7) with IDLE or Spyder on Anaconda</p> <p>Here is a sample code that takes 15 minutes:</p> <pre><code>def test_false_pos(): sumA = [0] * 1000 for test in range(1000): counter = 0 bf = BloomFilter(4095,10) for i in range(600): bf.rand_inserts() for x in range(10000): randS = str(rnd.randint(0,10**8)) if bf.lookup(randS): counter += 1 sumA[test] = counter/10000.0 avg = np.mean(sumA) return avg </code></pre>
0
2016-10-07T19:01:22Z
39,924,228
<p>Sure thing: Python 2.7 has to generate huge lists and waste a lot of memory <em>each time</em> you use <code>range(&lt;a huge number&gt;)</code>. </p> <p>Try to use the <code>xrange</code> function instead. It doesn't create that gigantic list at once, it produces the members of a sequence <em>lazily</em>. </p> <hr> <p>But if your were to use Python 3 (which is the modern version and the future of Python), you'll find out that there <code>range</code> is even cooler and faster than <code>xrange</code> in Python 2.</p>
4
2016-10-07T19:05:32Z
[ "python", "performance", "python-2.7", "loops", "cpu-usage" ]
How to make huge loops in python faster on mac?
39,924,176
<p>I am a computer science student and some of the things I do require me to run huge loops on Macbook with dual core i5. Some the loops take 5-6 hours to complete but they only use 25% of my CPU. Is there a way to make this process faster? I cant change my loops but is there a way to make them run faster?</p> <p>Thank you</p> <p>Mac OS 10.11 Python 2.7 (I have to use 2.7) with IDLE or Spyder on Anaconda</p> <p>Here is a sample code that takes 15 minutes:</p> <pre><code>def test_false_pos(): sumA = [0] * 1000 for test in range(1000): counter = 0 bf = BloomFilter(4095,10) for i in range(600): bf.rand_inserts() for x in range(10000): randS = str(rnd.randint(0,10**8)) if bf.lookup(randS): counter += 1 sumA[test] = counter/10000.0 avg = np.mean(sumA) return avg </code></pre>
0
2016-10-07T19:01:22Z
39,924,339
<p>You could split it up into 4 loops:</p> <pre><code>import multiprocessing def test_false_pos(i, pieces, q): sumA = [0] * 1000 for test in range((1000/pieces) * i, 250 + (1000/pieces)*i): counter = 0 bf = BloomFilter(4095,10) for i in range(600): bf.rand_inserts() for x in range(10000): randS = str(rnd.randint(0,10**8)) if bf.lookup(randS): counter += 1 sumA[test] = counter/10000.0 q.put(list(sumA)) def full_test(pieces): threads = [] q = multiprocessing.Queue() for i in range(pieces): threads.append(multiprocessing.Process(target=test_false_pos, args=(i, pieces, q))) [thread.start() for thread in threads] sums = [] for i in range(4): sums.append(q.get()) return np.mean(np.array(sums)) if __name__ == '__main__': full_test(4) </code></pre> <p>This will run 4 processes that each do ¼ of the work.</p>
3
2016-10-07T19:13:39Z
[ "python", "performance", "python-2.7", "loops", "cpu-usage" ]
How to make huge loops in python faster on mac?
39,924,176
<p>I am a computer science student and some of the things I do require me to run huge loops on Macbook with dual core i5. Some the loops take 5-6 hours to complete but they only use 25% of my CPU. Is there a way to make this process faster? I cant change my loops but is there a way to make them run faster?</p> <p>Thank you</p> <p>Mac OS 10.11 Python 2.7 (I have to use 2.7) with IDLE or Spyder on Anaconda</p> <p>Here is a sample code that takes 15 minutes:</p> <pre><code>def test_false_pos(): sumA = [0] * 1000 for test in range(1000): counter = 0 bf = BloomFilter(4095,10) for i in range(600): bf.rand_inserts() for x in range(10000): randS = str(rnd.randint(0,10**8)) if bf.lookup(randS): counter += 1 sumA[test] = counter/10000.0 avg = np.mean(sumA) return avg </code></pre>
0
2016-10-07T19:01:22Z
39,924,499
<p>Consider looking into Numba and Jit (just in time compiler). It works for functions that are Numpy based. It can handle some python routines, but is mainly for speeding up numerical calculations, especially ones with loops (like doing cholesky rank-1 up/downdates). I don't think it would work with a BloomFilter, but it is generally super helpful to know about. </p> <p>In cases where you must use other packages in your flow with numpy, separate out the heavy-lifting numpy routines into their own functions, and throw a @jit decorator on top of that function. Then put them into your flows with normal python stuff. </p>
1
2016-10-07T19:26:01Z
[ "python", "performance", "python-2.7", "loops", "cpu-usage" ]
Python parser ply matches wrong regex
39,924,181
<p>I'm trying to create a parser using Ply but I am confronted to a strange error. Here is a MCVE where the matching error occurs :</p> <p>Lexer</p> <pre><code>import ply.lex as lex tokens = ( 'IDENTIFIER', 'NAME', 'EQUALS' ) def t_IDENTIFIER(t): r'\* *[a-zA-Z_]+' print("identifier") return t def t_NAME(t): r"[a-zA-Z_]+" print("name") return t t_EQUALS = r"=" t_ignore = ' \t' def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) # Error handling rule def t_error(t): print("Illegal character '%s' at line' %s'" % (t.value[0] , t.lexer.lineno )) t.lexer.skip(1) # Build the lexer lexer = lex.lex() </code></pre> <p>Parser</p> <pre><code>import ply.yacc as yacc from l import tokens def p_main(p): ''' main : NAME EQUALS NAME ''' def p_error(p): if p is not None: print ("Line %s, illegal token %s" % (p.lineno, p.value)) else: print("Syntax error in input!") parser = yacc.yacc() with open('simple2','r') as f: result = parser.parse(f.read()) </code></pre> <p>My input file only contains this :</p> <pre><code>A = B </code></pre> <p>And what happens is that the first word <code>A</code> is matched by the token <code>IDENTIFIER</code> even if it is not supposed to do since the regex requires a <code>*</code> before the letters. After this the parser is unable to recognize the expression since the lexer does not return the right tokens.</p> <p>What is wrong ? The regex used for the token IDENTIFIER works perfectly in Python.</p>
1
2016-10-07T19:01:46Z
39,925,412
<p>I think I found problem and solution. </p> <p>Problem is <code>'*'</code> in <code>' *'</code> because it treats <code>'\* '</code> as one string - so <code>'\* *'</code> means <code>'\* '</code> many times or <strong>none</strong> (like <code>'abc*'</code> means <code>'abc'</code> many times or none).</p> <p>You need <code>'\*[ ]*'</code> or <code>'\*\s*'</code></p>
1
2016-10-07T20:35:55Z
[ "python", "regex", "parsing", "lexer", "ply" ]
Python parser ply matches wrong regex
39,924,181
<p>I'm trying to create a parser using Ply but I am confronted to a strange error. Here is a MCVE where the matching error occurs :</p> <p>Lexer</p> <pre><code>import ply.lex as lex tokens = ( 'IDENTIFIER', 'NAME', 'EQUALS' ) def t_IDENTIFIER(t): r'\* *[a-zA-Z_]+' print("identifier") return t def t_NAME(t): r"[a-zA-Z_]+" print("name") return t t_EQUALS = r"=" t_ignore = ' \t' def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) # Error handling rule def t_error(t): print("Illegal character '%s' at line' %s'" % (t.value[0] , t.lexer.lineno )) t.lexer.skip(1) # Build the lexer lexer = lex.lex() </code></pre> <p>Parser</p> <pre><code>import ply.yacc as yacc from l import tokens def p_main(p): ''' main : NAME EQUALS NAME ''' def p_error(p): if p is not None: print ("Line %s, illegal token %s" % (p.lineno, p.value)) else: print("Syntax error in input!") parser = yacc.yacc() with open('simple2','r') as f: result = parser.parse(f.read()) </code></pre> <p>My input file only contains this :</p> <pre><code>A = B </code></pre> <p>And what happens is that the first word <code>A</code> is matched by the token <code>IDENTIFIER</code> even if it is not supposed to do since the regex requires a <code>*</code> before the letters. After this the parser is unable to recognize the expression since the lexer does not return the right tokens.</p> <p>What is wrong ? The regex used for the token IDENTIFIER works perfectly in Python.</p>
1
2016-10-07T19:01:46Z
39,928,427
<p>According to the <a href="http://www.dabeaz.com/ply/ply.html#ply_nn6" rel="nofollow">PLY manual</a>: (emphasis added)</p> <blockquote> <p>Internally, <code>lex.py</code> uses the <code>re</code> module to do its pattern matching. <em>Patterns are compiled using the <code>re.VERBOSE</code> flag</em> which can be used to help readability. However, be aware that unescaped whitespace is ignored and comments are allowed in this mode. If your pattern involves whitespace, make sure you use <code>\s</code>. If you need to match the <code>#</code> character, use <code>[#]</code>.</p> </blockquote> <p>So the space character in your regular expression <code>\* *[a-zA-Z_]+</code> is ignored, making the regular expression, effectively, <code>\**[a-zA-Z_]+</code>; i.e., zero or more stars. If you really want it to be a star followed by one or more spaces, you would want something like: <code>\*\ [a-zA-Z_]+</code>. </p>
1
2016-10-08T03:39:06Z
[ "python", "regex", "parsing", "lexer", "ply" ]
tkinter widgets on one frame affecting another frame alignment
39,924,213
<p>this program works functionality wise so far anyway so that's not my issue. My issue is something to do with how the alignment works for widgets with multiple frames. If I make the widgets on one frame longer width wise, than the other frames, it will center all the frames based on the widest frame rather than each individual frame. The widest frame right now in this code is 'ChangePasswordPage' as it will almost always use a long string for the label; this causes all of the other frames to shift to the left. If I remove the 'sticky="nsew"' from frame.grid(column=0, row=0, sticky="nsew") it will allign everything properly but the frame doesn't fill outwards so you can see the other frames behind each other. </p> <p>I am not sure how to fix this and would love some help. I have been trying different ways such as unloading each widget and then reloading it but getting errors there too. Any help will be highly appreciated.</p> <p>Here's my condensed code:</p> <pre><code>import tkinter as tk from tkinter import ttk, messagebox class CCTV(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack() container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (LoginPage, ChangePasswordPage): frame = F(container, self) self.frames[F] = frame frame.grid(column=0, row=0, sticky="nsew") self.creatingAccount() def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() def creatingAccount(self): self.show_frame(LoginPage) class LoginPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.createView() def createView(self): self.labelPassword = ttk.Label(self, text="Password") self.entryPassword = ttk.Entry(self, show = "*") self.buttonLogin = ttk.Button(self, text="Login", command=lambda: self.controller.show_frame(ChangePasswordPage)) self.labelPassword.grid(row=2, column=3, sticky="w") self.entryPassword.grid(row=2, column=4, sticky="e") self.buttonLogin.grid(row=3, columnspan=6, pady=10) class ChangePasswordPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.createView() def createView(self): self.labelSecurityQuestion = ttk.Label(self, text="A very very very very very very very very very very long string") self.entrySecurityQuestion = ttk.Entry(self) self.buttonCreateAccount = ttk.Button(self, text="Change Password", command=lambda: self.controller.show_frame(LoginPage)) self.labelSecurityQuestion.grid(row=3, column=0, sticky="w") self.entrySecurityQuestion.grid(row=3, column=1, sticky="e") self.buttonCreateAccount.grid(row=5, columnspan=2, pady=10) app = CCTV() app.geometry("800x600") app.mainloop() </code></pre>
-1
2016-10-07T19:04:45Z
39,925,476
<p>There are usually many ways to solve layout problems. It all depends on what you actually want to do, what actual widgets you're using, and how you expect widgets react when their containing windows or frames change. </p> <p>When you use <code>grid</code>, by default it gives widgets only as much space as they need. Any extra space within the containing widget will go unused. If you want <code>grid</code> to use all available space you must tell it how to allocate the extra space by giving rows and columns "weight". You are not doing so, so extra space is not being used, and thus, your widgets aren't being centered. </p> <p>As a rule of thumb, for any container (typically, a Frame) that uses grid, you must give a weight to at least one row, and one column. If you have a canvas or text widget, usually the row and column it is in is the one you want to get the un-allocated space. If you have entry widgets that you want to grow and shrink, you'll often give a weight to the column(s) that contain the entry widgets. Often you'll have multiple rows and/or columns that you want to be given extra space, though there are also times where you want everything centered, with extra space being allocated along the edges.</p> <p>In your specific case, to center everything in the password screen there are several solutions. I will detail a couple. </p> <h2>Using only grid, and placing all widgets directly on the page</h2> <p>When you want to arrange absolutely all of your widgets in one frame and manage them with <code>grid</code>, and you want everything centered in the window, you can give all of the weight to rows and columns that surround your content.</p> <p>Here's an example. Notice that the widgets are in rows 1 and 2, and columns 1 and 2, and all extra space is being given to rows 0 and 3, and columns 0 and 3. </p> <pre><code>def createView(self): ... self.labelPassword.grid(row=1, column=1, sticky="e") self.entryPassword.grid(row=1, column=2, sticky="ew") self.buttonLogin.grid(row=2, column=1, columnspan=2) self.grid_rowconfigure(0, weight=1) self.grid_rowconfigure(3, weight=1) self.grid_columnconfigure(0, weight=1) self.grid_columnconfigure(3, weight=1) </code></pre> <h2>Using a nested frame</h2> <p>Another approach is to place the widgets into an inner frame that exactly fits its contents. When you do that, you only have to worry about centering that one frame within the "page" since, when you center the frame, by definition everything in the frame will also be centered relative to the window as a whole. </p> <p>When you do that you can skip worrying about row and column weights because you want the inner frame to shrink to fit the contents and thus not have to worry about un-allocated space. However, I personally think it's good to <em>always</em> give at least one row and one column weight. </p> <p>Here's an example using the inner frame technique. Notice how the widgets are placed in the inner frame rather than <code>self</code>, and the inner frame uses <code>pack</code> with no options which causes it to be centered at the top of its parent. You could also use <code>place</code>, which is particularly convenient if you want the password prompt centered vertically as well.</p> <pre><code>def createView(self): inner_frame = tk.Frame(self) inner_frame.pack(side="top", fill="none") self.labelPassword = ttk.Label(inner_frame, text="Password") self.entryPassword = ttk.Entry(inner_frame, show = "*") self.buttonLogin = ttk.Button(inner_frame, text="Login", command=lambda: self.controller.show_frame(ChangePasswordPage)) self.labelPassword.grid(row=1, column=1, sticky="e") self.entryPassword.grid(row=1, column=2, sticky="ew") self.buttonLogin.grid(row=2, column=1, columnspan=2) </code></pre> <h2>Summary</h2> <p>Layout out widgets requires a methodical approach. It helps to temporarily give each frame a distinct color so that you can see which frames are growing or shrinking to fit their contents and/or their parents. Often times that is enough to see whether the problem is with a frame, the contents in the frame, or the contents in the containing frame.</p> <p>Also, you should almost never use <code>pack</code>, <code>place</code> or <code>grid</code> without giving explicit arguments. When you use <code>grid</code>, always give at least one row and one column a weight.</p>
1
2016-10-07T20:40:28Z
[ "python", "tkinter", "alignment" ]
How to use Python requests to post form as curl PUT -F
39,924,303
<p>I'm trying to replicate the use of <code>curl PUT -F "file=@someFile"</code> using Python's requests. The Content-Type i'm required to use is: <code>multipart/form-data</code> I tried different variations like:</p> <p><code>r = requests.put(url, headers=headers, files={'file': (full_filename, open(full_filename, 'rb'), content_type)}, verify=False, stream=True)</code></p> <p><code>r = requests.put(url, headers=headers, data={'file': (full_filename, open(full_filename, 'rb'), content_type)}, verify=False, stream=True)</code></p> <p><code>r = requests.put(url, headers=headers, params={'file': (full_filename, open(full_filename, 'rb'), content_type)}, verify=False, stream=True)</code></p> <p>In all of the methods i tried i had <code>'Content-Type': 'multipart/form-data'</code> in my headers.</p> <p>But for all of the above i get <code>400</code> as a response.</p> <p>I saw some questions around stackoverflow but none of the answers answered my question, so i'm opening a new one.</p>
0
2016-10-07T19:10:25Z
39,931,294
<p>Thanks to <a href="http://stackoverflow.com/a/17438575/1659322">http://stackoverflow.com/a/17438575/1659322</a> i managed to work it out. I'm quoting his answer here because i find it extremely important:</p> <blockquote> <p>You should NEVER set that header yourself. We set the header properly with the boundary. If you set that header, we won't and your server won't know what boundary to expect (since it is added to the header). Remove your custom Content-Type header and you'll be fine.</p> </blockquote> <p>I love Requests but this is a very confusing implementation part for me.</p>
0
2016-10-08T10:29:36Z
[ "python", "curl", "python-requests", "multipartform-data", "put" ]
Redis management on Heroku
39,924,325
<p>I have provisioned Redis To Go addon in Heroku for use with <a href="http://python-rq.org/" rel="nofollow">Redis Queue python library</a>. My app is having some issue with the redis DB for the queue (namely max-memory problem). The memory use stays really high even when all the work has been finished. So I have been reading up on Redis and Redis Queue, and read all through <a href="https://devcenter.heroku.com/articles/heroku-redis" rel="nofollow">Heroku's Redis documentation</a>.</p> <p>I want to use the command line interface, so I tried installing:</p> <pre><code>heroku plugins:install heroku-redis </code></pre> <blockquote> <p>▸ Not installing heroku-redis because it is already installed as a core plugin.</p> </blockquote> <p>OK so the redis to go installed a redis server with the config var <code>REDISTOGO_URL</code>, which I can confirm with <code>heroku config | grep REDIS</code>. So then I tried to "promote" this instance:</p> <pre><code>heroku redis:promote REDISTOGO_URL </code></pre> <blockquote> <p>▸ No Redis instances found.</p> </blockquote> <p>and I get no results at all from <code>heroku redis:info -a appname</code></p> <p>The important thing I am trying to do is change my <code>maxmemory-policy</code>, which you are able to do using <code>heroku redis</code>, but still I can't figure out how to do that.</p> <p>Any help would be greatly appreciated.</p>
0
2016-10-07T19:12:35Z
39,924,543
<p>To give your Redis more RAM (i.e. increase max-memory) you just need to upgrade your plan - use <code>heroku addons:upgrade ...</code> to do that.</p>
0
2016-10-07T19:29:26Z
[ "python", "memory", "heroku", "redis" ]
Redis management on Heroku
39,924,325
<p>I have provisioned Redis To Go addon in Heroku for use with <a href="http://python-rq.org/" rel="nofollow">Redis Queue python library</a>. My app is having some issue with the redis DB for the queue (namely max-memory problem). The memory use stays really high even when all the work has been finished. So I have been reading up on Redis and Redis Queue, and read all through <a href="https://devcenter.heroku.com/articles/heroku-redis" rel="nofollow">Heroku's Redis documentation</a>.</p> <p>I want to use the command line interface, so I tried installing:</p> <pre><code>heroku plugins:install heroku-redis </code></pre> <blockquote> <p>▸ Not installing heroku-redis because it is already installed as a core plugin.</p> </blockquote> <p>OK so the redis to go installed a redis server with the config var <code>REDISTOGO_URL</code>, which I can confirm with <code>heroku config | grep REDIS</code>. So then I tried to "promote" this instance:</p> <pre><code>heroku redis:promote REDISTOGO_URL </code></pre> <blockquote> <p>▸ No Redis instances found.</p> </blockquote> <p>and I get no results at all from <code>heroku redis:info -a appname</code></p> <p>The important thing I am trying to do is change my <code>maxmemory-policy</code>, which you are able to do using <code>heroku redis</code>, but still I can't figure out how to do that.</p> <p>Any help would be greatly appreciated.</p>
0
2016-10-07T19:12:35Z
39,929,800
<p>Just for anyone using <a href="https://elements.heroku.com/addons/redistogo" rel="nofollow">Redis To Go</a>, I switched my Redis server to the free version of <a href="https://elements.heroku.com/addons/heroku-redis" rel="nofollow">Heroku Redis</a> and all the problems went away. </p> <p>Redis To Go was telling me in the console that it was using the <code>volatile-lru</code> eviction policy but it was still throwing errors for max memory and it wasn't clearing out max memory at all ( 8 MB memory use while doing nothing for hours ).</p> <p>Using Heroku Redis there were no memory errors while doing even more work on the free tier. At Rest the Redis memory usage went down to below 1MB which is what I would expect. Also no with Heroku Redis I am able to access the CLI using the <code>heroku redis</code> app.</p>
0
2016-10-08T07:18:23Z
[ "python", "memory", "heroku", "redis" ]
Python generating a lookup table of lambda expressions
39,924,360
<p>I'm building a game and in order to make it work, I need to generate a list of "pre-built" or "ready to call" expressions. I'm trying to do this with lambda expressions, but am running into an issue generating the lookup table. The code I have is similar to the following:</p> <pre><code>import inspect def test(*args): string = "Test Function: " for i in args: string += str(i) + " " print(string) funct_list = [] # The problem is in this for loop for i in range(20): funct_list.append(lambda: test(i, "Hello World")) for i in funct_list: print(inspect.getsource(i)) </code></pre> <p>The output I get is:</p> <pre><code>funct_list.append(lambda: test(i, "Hello World")) funct_list.append(lambda: test(i, "Hello World")) funct_list.append(lambda: test(i, "Hello World")) funct_list.append(lambda: test(i, "Hello World")) ... </code></pre> <p>and I need it to go:</p> <pre><code>funct_list.append(lambda: test(1, "Hello World")) funct_list.append(lambda: test(2, "Hello World")) funct_list.append(lambda: test(3, "Hello World")) funct_list.append(lambda: test(4, "Hello World")) ... </code></pre> <p>I tried both of the following and neither work</p> <pre><code>for i in range(20): funct_list.append(lambda: test(i, "Hello World")) for i in range(20): x = (i, "Hello World") funct_list.append(lambda: test(*x)) </code></pre> <p>My question is how do you generate lists of lambda expressions with some of the variables inside the lambda expression already set.</p>
0
2016-10-07T19:14:47Z
39,924,419
<p>As others have mentioned, Python's closures are <em>late binding</em>, which means that variables from an outside scope referenced in a closure (in other words, the variables <em>closed over</em>) are looked up at the moment the closure is called and <em>not</em> at the time of definition.</p> <p>In your example, the closure in question is formed when your lambda references the variable <code>i</code> from the outside scope. However, when your lambda is called later on, the loop has already finished and left the variable <code>i</code> with the value 19.</p> <p>An easy but not particularly elegant fix is to use a default argument for the lambda:</p> <pre><code>for i in range(20): funct_list.append(lambda x=i: test(x, "Hello World")) </code></pre> <p>Unlike closure variables, default arguments are bound early and therefore achieve the desired effect of capturing the value of the variable <code>i</code> at the time of lambda definition.</p> <p>A better way is use <code>functools.partial</code> which allows you to partially apply some arguments of the function, "fixing" them to a certain value:</p> <pre><code>from functools import partial for i in range(20): funct_list.append(partial(lambda x: test(x, "Hello World"), i)) </code></pre>
2
2016-10-07T19:19:46Z
[ "python", "function", "lambda", "functional-programming", "anonymous-function" ]
Crypto.Util import error in firebase_helper.py when deploying to Google App Flexible Engine
39,924,382
<p>I have been working to deploy the <a href="https://cloud.google.com/appengine/docs/python/authenticating-users-firebase-appengine" rel="nofollow">Authenticating Users on App Engine Using Firebase</a> tutorial, and can successfully deploy this to my local machine. </p> <p>As I wish to test some python modules that don't run on the standard Google App Engine, I have now tried to deploy this to the Flexible Environment via this setting in app.yaml</p> <pre><code>vm: true </code></pre> <p>the frontend deploys fine to the flexible app engine, but the backend throws an error during the import of firebase_helper.py. Specifically, it is choking on this line: </p> <pre><code>from Crypto.Util import asn1 </code></pre> <p>The raw stacktrace is listed here: </p> <pre><code>Traceback (most recent call last): File "/home/vmagent/python_vm_runtime/google/appengine/ext/vmruntime/meta_app.py", line 550, in GetUserAppAndServe app, mod_file = self.GetUserApp(script) File "/home/vmagent/python_vm_runtime/google/appengine/ext/vmruntime/meta_app.py", line 411, in GetUserApp app = _AppFrom27StyleScript(script) File "/home/vmagent/python_vm_runtime/google/appengine/ext/vmruntime/meta_app.py", line 271, in _AppFrom27StyleScript app, filename, err = wsgi.LoadObject(script) File "/home/vmagent/python_vm_runtime/google/appengine/runtime/wsgi.py", line 85, in LoadObject obj = __import__(path[0]) File "/home/vmagent/app/main.py", line 22, in &lt;module&gt; import firebase_helper File "/home/vmagent/app/firebase_helper.py", line 20, in &lt;module&gt; from Crypto.Util import asn1 ImportError: No module named Crypto.Util </code></pre> <p>Now, pycrypto is already included in the app.yaml:</p> <pre><code>libraries: - name: ssl version: 2.7.11 - name: pycrypto version: 2.6.1 </code></pre> <p>I have SSH'd into the server, and Crypto is installed. I can also load it into a python console on the VM, without problems. </p> <p>Any idea why I get this error during deployment? </p>
1
2016-10-07T19:17:25Z
39,925,886
<p>According to the <a href="https://cloud.google.com/appengine/docs/flexible/python/migrating-an-existing-app" rel="nofollow">Google App engine documentation</a>, the libraries section of app.yaml is no longer supported in flexible VM. You will need to declare dependencies in requirements.txt.</p> <p>So, you need to add this line to your <code>requirements.txt</code> :</p> <pre><code>pycrypto==2.6.1 </code></pre> <p>Make sure you delete the <code>libraries</code> directive from your app.yaml</p> <p>Make sure your runtime is set to <code>runtime: python-compat</code>.</p> <p>Delete the appengine_cfg.py file, since the flexible vm automatically installs all dependencies in the <code>requirements.txt</code>.</p>
2
2016-10-07T21:13:17Z
[ "python", "google-app-engine", "firebase" ]
How do I post this HTML form using Python?
39,924,501
<p>This is the form that I want to post in Python:</p> <pre><code> &lt;FORM METHOD="POST" ACTION="http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run" ENCTYPE="multipart/form-data"&gt; &lt;INPUT NAME="formtype" TYPE="HIDDEN" value="simple"&gt; &lt;p&gt;&lt;b&gt;Upload a sentence corpus file&lt;/b&gt;:&lt;br&gt; &lt;INPUT NAME="corpus" TYPE="FILE" SIZE=60 VALUE="empty"&gt; &lt;/p&gt; &lt;INPUT TYPE="submit" VALUE="COMPILE KNOWLEDGE BASE"&gt; &lt;/form&gt; </code></pre> <p>i tried it with requests</p> <pre><code>import requests url = "http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run" #url = "http://httpbin.org/post" files = {'file': open('testfile', 'rb')} payload = {'NAME': 'fromtype', 'TYPE': 'HIDDEN', 'value': 'simple', 'NAME': 'corpus', 'TYPE': 'FILE', 'SIZE': '60', 'VALUE': 'empty'} r = requests.post(url, data=payload) print r.text </code></pre> <p>and the response</p> <pre><code>Running: /home/darthtoker/programs/post.py (Fri Oct 7 15:19:21 2016) &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"&gt; &lt;head&gt; &lt;title&gt;LMTool Error&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;/head&gt; &lt;body&gt; &lt;pre&gt;Something went wrong. This is all I know: formtype &lt;/pre&gt; &lt;/body&gt; &lt;/html&gt;Content-Type: text/html; charset=ISO-8859-1 &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US"&gt; &lt;head&gt; &lt;title&gt;LMTool Error&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt; &lt;/head&gt; &lt;body&gt; &lt;pre&gt;Something went wrong. This is all I know: corpus &lt;/pre&gt; &lt;/body&gt; &lt;/html&gt;Status: 302 Found Location: http://www.speech.cs.cmu.edu/tools/product/1475867962_31194 </code></pre> <p>I need to automate this form for a project I'm working on, please help!</p>
0
2016-10-07T19:26:02Z
39,924,729
<p>There might be other errors, but the error message you get is clear enough:</p> <p>What the form expects:</p> <pre><code>&lt;INPUT NAME="formtype" ...&gt; </code></pre> <p>what you send:</p> <pre><code>'NAME': 'fromtype', ... </code></pre> <p>You see the difference between <strong>formtype</strong> and <strong>fromtype</strong>?</p> <hr> <p>According to the documentations of <a href="http://docs.python-requests.org/en/master/" rel="nofollow">Requests</a> (<a href="http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests" rel="nofollow">More complicated POST requests</a>, <a href="http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file" rel="nofollow">POST a Multipart-Encoded File</a>) your code should be:</p> <pre><code>import requests url = "http://www.speech.cs.cmu.edu/cgi-bin/tools/lmtool/run" #url = "http://httpbin.org/post" files = {'corpus': open('testfile', 'rb')} payload = {'formtype': 'simple' } r = requests.post(url, data=payload, files=files) print r.text </code></pre>
0
2016-10-07T19:42:53Z
[ "python", "html", "post", "python-requests" ]
Limiting integer width in python
39,924,510
<p>I'm practicing python, I came across a situation where I wanted to limit the character width of a field but it wasn't working.(I hope I'm saying that right) I want to truncate the sum of 2 integers to 5 spaces. eg: the sum of 88888 + 22222 has 6 characters. Is it possible to limit it to 5?</p>
0
2016-10-07T19:26:46Z
39,924,549
<p>You can easily truncate the value of these integers. Simply convert the result into a string and then use the Python index to select the first five characters:</p> <pre><code>&gt;&gt;&gt; str(88888 + 22222)[:5] '11111' </code></pre> <p>You can also convert this value back to an integer using <code>int()</code> if necessary.</p>
1
2016-10-07T19:30:08Z
[ "python", "python-2.7", "python-3.x" ]
Limiting integer width in python
39,924,510
<p>I'm practicing python, I came across a situation where I wanted to limit the character width of a field but it wasn't working.(I hope I'm saying that right) I want to truncate the sum of 2 integers to 5 spaces. eg: the sum of 88888 + 22222 has 6 characters. Is it possible to limit it to 5?</p>
0
2016-10-07T19:26:46Z
39,924,566
<p>To limit the number of decimal characters by throwing away the upper digits, you can use a remainder:</p> <pre><code>(88888 + 22222) % 100000 </code></pre> <p>To do the same for a binary number, which is more commonly required, you can use a bit-wise and. Here's an example limited to 16 bits.</p> <pre><code>(88888 + 22222) &amp; 0xffff </code></pre>
1
2016-10-07T19:31:03Z
[ "python", "python-2.7", "python-3.x" ]
How to read a compressed (gz) CSV file inro a dask Dataframe?
39,924,518
<p>Is there a way to read a .csv file that is compressed via gz into a dask dataframe?</p> <p>I've tried it directly with</p> <pre><code>import dask.dataframe as dd df = dd.read_csv("Data.gz" ) </code></pre> <p>but get an unicode error (probably because it is interpreting the compressed bytes) There is a <code>"compression"</code> parameter but <code>compression = "gz"</code> won't work and I can't find any documentation so far.</p> <p>With pandas I can read the file directly without a problem other than the result blowing up my memory ;-) but if I restrict the number of lines it works fine.</p> <pre><code>import pandas.Dataframe as pd df = pd.read_csv("Data.gz", ncols=100) </code></pre>
1
2016-10-07T19:27:03Z
39,924,970
<p>Without the file it's difficult to say. what if you set the encoding <code>like # -*- coding: latin-1 -*-</code>? or since <code>read_csv</code> is based off of Pandas, you may even <code>dd.read_csv('Data.gz', encoding='utf-8')</code>. Here's the list of Python encodings: <a href="https://docs.python.org/3/library/codecs.html#standard-encodings" rel="nofollow">https://docs.python.org/3/library/codecs.html#standard-encodings</a></p>
1
2016-10-07T20:04:42Z
[ "python", "csv", "pandas", "dask" ]
Python add quotes to all elements in list?
39,924,531
<p>I have a several list with in a dictionary. How do I add quotes around every element in each list?</p> <pre><code>native_american={ "A2" : ["Native, Eskimo Volodko, Apache, Mexico, Central America, Guarani, Rio das Cobras, Katuana, Poturujara, Surui, Waiwai, Yanomama, Zoro, Arsario, Cayapa, Kogui, Inupiat, Lauricocha"], "A2a" : ["Aleut, Eskimo, Apache, Siberian Eskimo, Chukchi, Dogrib, Innuit, Naukan Na-Dene, Chukchis, Athabaskan"], "A2b" : ["Paleo Eskimo"]} </code></pre> <p>I would like it to look like....</p> <pre><code>"Native", "Eskimo Volodko", "Apache", "Mexico" </code></pre>
1
2016-10-07T19:28:07Z
39,924,570
<p>Do you mean something like <code>"Native", "Eskimo Volodko", "Apache"</code>?</p> <p>If so: <code>[item.strip() for item in list.split(',')]</code></p>
0
2016-10-07T19:31:11Z
[ "python" ]
Python add quotes to all elements in list?
39,924,531
<p>I have a several list with in a dictionary. How do I add quotes around every element in each list?</p> <pre><code>native_american={ "A2" : ["Native, Eskimo Volodko, Apache, Mexico, Central America, Guarani, Rio das Cobras, Katuana, Poturujara, Surui, Waiwai, Yanomama, Zoro, Arsario, Cayapa, Kogui, Inupiat, Lauricocha"], "A2a" : ["Aleut, Eskimo, Apache, Siberian Eskimo, Chukchi, Dogrib, Innuit, Naukan Na-Dene, Chukchis, Athabaskan"], "A2b" : ["Paleo Eskimo"]} </code></pre> <p>I would like it to look like....</p> <pre><code>"Native", "Eskimo Volodko", "Apache", "Mexico" </code></pre>
1
2016-10-07T19:28:07Z
39,924,576
<pre><code>native_american = {key: value[0].split(',') for key, value in native_american.items()} </code></pre> <p>What you have at the moment is a list of one long string. This splits it into a list of many smaller strings</p>
3
2016-10-07T19:31:34Z
[ "python" ]
Sum from 1 to n in one line Python
39,924,547
<p>Given number <code>n</code>, I need to find the sum of numbers from <code>1</code> to <code>n</code>. Sample input and output:</p> <pre><code>100 5050 </code></pre> <p>So I came up with <code>print(sum(range(int(input())+1)))</code> which solves the problem in one line but takes a long time since it's <code>O(n)</code>. Clearly, if we know the number <code>n</code> then the answer can be given in one line too: <code>print(n * (n+1) / 2)</code> but how to replace <code>n</code> with <code>input()</code> to still make program work?</p>
1
2016-10-07T19:30:00Z
39,924,672
<p>Act as if it's Javascript; create a function that takes a parameter <code>n</code>, then immediately call it with the result of <code>input()</code>:</p> <pre><code>(lambda n: n * (n + 1) / 2)(int(input())) </code></pre>
10
2016-10-07T19:38:46Z
[ "python" ]
Sum from 1 to n in one line Python
39,924,547
<p>Given number <code>n</code>, I need to find the sum of numbers from <code>1</code> to <code>n</code>. Sample input and output:</p> <pre><code>100 5050 </code></pre> <p>So I came up with <code>print(sum(range(int(input())+1)))</code> which solves the problem in one line but takes a long time since it's <code>O(n)</code>. Clearly, if we know the number <code>n</code> then the answer can be given in one line too: <code>print(n * (n+1) / 2)</code> but how to replace <code>n</code> with <code>input()</code> to still make program work?</p>
1
2016-10-07T19:30:00Z
39,925,314
<p>Python 3, one line, and shorter than the currently accepted answer:</p> <pre><code>n=int(input());print(n*(n+1)/2) </code></pre>
0
2016-10-07T20:28:35Z
[ "python" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Send raw Ethernet packet on interface.""" assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses assert(len(eth_type) == 2) # 16-bit ethernet type #s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) # From the docs: "For raw packet # sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])" s.bind((interface, 0)) return s.send(src + dst + eth_type + payload) if __name__ == "__main__": print("Sent %d-byte Ethernet packet on eth0" % sendeth("\xFE\xED\xFA\xCE\xBE\xEF", "\xFE\xED\xFA\xCE\xBE\xEF", "\x7A\x05", "hello")) </code></pre> <p>I was having issues with the way the socket was being created. AF_PACKET is not recognized so I'm assuming that only works for Linux. I commented it out and added a new line below it. I ran it again and I started getting an error shown below.</p> <pre><code>Traceback (most recent call last): File "eth.py", line 27, in &lt;module&gt; "hello")) File "eth.py", line 19, in sendeth s.bind((interface, 0)) File "C:\Python27\lib\socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.gaierror: [Errno 11001] getaddrinfo failed </code></pre> <p>Does anyone know why this is happening?</p>
0
2016-10-07T19:30:51Z
39,924,831
<p>Looks like you don't get access to ethernet with this socket:</p> <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) </code></pre> <p><code>socket.IPPROTO_RAW</code> gives you access to Level 3 protocol (IP), whereas ethernet is on Level 1 and 2. At level 3 an ethernet frame is already analyzed and its headers discarded. You need to get to Level 2 and <code>ETH_P_ALL</code> protocol seems to be a nice place to start. I don't believe python <code>socket</code> module implements it on that low level, but you can interact with WinAPI via <code>ctypes</code> module.</p>
0
2016-10-07T19:50:27Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Send raw Ethernet packet on interface.""" assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses assert(len(eth_type) == 2) # 16-bit ethernet type #s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) # From the docs: "For raw packet # sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])" s.bind((interface, 0)) return s.send(src + dst + eth_type + payload) if __name__ == "__main__": print("Sent %d-byte Ethernet packet on eth0" % sendeth("\xFE\xED\xFA\xCE\xBE\xEF", "\xFE\xED\xFA\xCE\xBE\xEF", "\x7A\x05", "hello")) </code></pre> <p>I was having issues with the way the socket was being created. AF_PACKET is not recognized so I'm assuming that only works for Linux. I commented it out and added a new line below it. I ran it again and I started getting an error shown below.</p> <pre><code>Traceback (most recent call last): File "eth.py", line 27, in &lt;module&gt; "hello")) File "eth.py", line 19, in sendeth s.bind((interface, 0)) File "C:\Python27\lib\socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.gaierror: [Errno 11001] getaddrinfo failed </code></pre> <p>Does anyone know why this is happening?</p>
0
2016-10-07T19:30:51Z
39,924,857
<p>This example from the docs seems instructive. <a href="https://docs.python.org/2/library/socket.html" rel="nofollow">https://docs.python.org/2/library/socket.html</a></p> <pre><code>import socket # the public network interface HOST = socket.gethostbyname(socket.gethostname()) # create a raw socket and bind it to the public interface s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) s.bind((HOST, 0)) # Include IP headers s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # receive all packages s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) # receive a package print s.recvfrom(65565) # disabled promiscuous mode s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) </code></pre> <p>I think the key is socket.gethostbyname(socket.gethostname()). "eth0" as used in your example won't be supported on Windows.</p>
0
2016-10-07T19:52:52Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Send raw Ethernet packet on interface.""" assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses assert(len(eth_type) == 2) # 16-bit ethernet type #s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) # From the docs: "For raw packet # sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])" s.bind((interface, 0)) return s.send(src + dst + eth_type + payload) if __name__ == "__main__": print("Sent %d-byte Ethernet packet on eth0" % sendeth("\xFE\xED\xFA\xCE\xBE\xEF", "\xFE\xED\xFA\xCE\xBE\xEF", "\x7A\x05", "hello")) </code></pre> <p>I was having issues with the way the socket was being created. AF_PACKET is not recognized so I'm assuming that only works for Linux. I commented it out and added a new line below it. I ran it again and I started getting an error shown below.</p> <pre><code>Traceback (most recent call last): File "eth.py", line 27, in &lt;module&gt; "hello")) File "eth.py", line 19, in sendeth s.bind((interface, 0)) File "C:\Python27\lib\socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.gaierror: [Errno 11001] getaddrinfo failed </code></pre> <p>Does anyone know why this is happening?</p>
0
2016-10-07T19:30:51Z
39,926,417
<p>DHCP is a UDP protocol. You shouldn't need a raw socket to implement a DHCP server.</p> <p>Use an AF_INET/SOCK_DGRAM socket, and bind to address 255.255.255.255 in order to implement your server.</p>
0
2016-10-07T22:02:47Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python Raw Socket to Ethernet Interface (Windows)
39,924,563
<p>I'm trying to create a DHCP Server and the first step is for me to send packets through my ethernet port. I'm trying to send packets to my Ethernet interface and having an error popping up.</p> <p>The code is below.</p> <pre><code>import socket def sendeth(src, dst, eth_type, payload, interface = "eth0"): """Send raw Ethernet packet on interface.""" assert(len(src) == len(dst) == 6) # 48-bit ethernet addresses assert(len(eth_type) == 2) # 16-bit ethernet type #s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW) s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) # From the docs: "For raw packet # sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])" s.bind((interface, 0)) return s.send(src + dst + eth_type + payload) if __name__ == "__main__": print("Sent %d-byte Ethernet packet on eth0" % sendeth("\xFE\xED\xFA\xCE\xBE\xEF", "\xFE\xED\xFA\xCE\xBE\xEF", "\x7A\x05", "hello")) </code></pre> <p>I was having issues with the way the socket was being created. AF_PACKET is not recognized so I'm assuming that only works for Linux. I commented it out and added a new line below it. I ran it again and I started getting an error shown below.</p> <pre><code>Traceback (most recent call last): File "eth.py", line 27, in &lt;module&gt; "hello")) File "eth.py", line 19, in sendeth s.bind((interface, 0)) File "C:\Python27\lib\socket.py", line 224, in meth return getattr(self._sock,name)(*args) socket.gaierror: [Errno 11001] getaddrinfo failed </code></pre> <p>Does anyone know why this is happening?</p>
0
2016-10-07T19:30:51Z
39,926,458
<p>Approaching your question from another direction: why do you need to work with ethernet at all? DHCP is usually implemented via UDP.</p> <ol> <li>DHCP server always has some IP address (and a pool of addresses it can lease).</li> <li>If a client wants and IP (DHCP actually can do much more than just assign IPs but let's stop on this use case for now), it sends a broadcast DHCPREQUEST with source IP 0.0.0.0 and destination IP 255.255.255.255. The servers answer him via UDP broadcast as well, but with his own source IP.</li> </ol> <p>If you want to create an implementation of DHCP, starting with OSI Level 2 (ethernet) will just give you headache of maintaining Level 3 (IP) and 4 (UDP). I don't see any benefit in this.</p> <p>If you'd like to create a DHCP-like protocol based on ethernet be ready to work on the following issue: routers don't forward broadcast packets unless asked to do so. For instance, for Cisco routers it looks like this:</p> <pre><code>router(config)# interface ethernet 0/0 router(config-if)# ip helper-address 10.1.23.5 router(config-if)# end router# </code></pre> <p>Thus we configure router so it knows there's something helpful connected to ethernet 0/0 port with IP 10.1.23.5 that needs broadcasts (<a href="https://supportforums.cisco.com/document/13916/router-not-forwarding-dhcp-requests-hosts-are-unable-obtain-ip-address-dhcp-server" rel="nofollow">source</a>). </p>
0
2016-10-07T22:08:07Z
[ "python", "windows", "python-2.7", "sockets", "dhcp" ]
Python - wxPython Sequence of Command Execution
39,924,586
<p>I have a properly working code, I understand I am not pasting enough code - but I will explain each command with proper comments. My question here is why is the code behaving rather than what I expected it to behave. </p> <p>My code: </p> <pre><code> def OnReset(self, event): # A function event which works after a button is pressed self.reset_pump.Disable() # Disables the button so it is clicked self.WriteToController([0x30],'GuiMsgIn') # Sends the reset command self.flag_read.set() # Set Event of the thread time.sleep(0.25) self.tr.join() # Joining a Thread self.MessageBox('Pump RESET going on Click OK \n') # Having the above step is useful # The question I have is based on the commands from here: self.offset_text_control.Clear() self.gain_text_control.Clear() self.firmware_version_text_control.Clear() self.pump_rpm_text_control.Clear() self.pressure_text_control.Clear() self.last_error_text_control.Clear() self.error_count_text_control.Clear() self.pump_model_text_control.Clear() self.pump_serial_number_text_control.Clear() self.on_time_text_control.Clear() self.job_on_time_text_control.Clear() # The above commands clear various widgets on my GUI. self.ser.close() # Closes my serial connection to MCU time.sleep(5) self.OnCorrectComPort(event) # An external function which gets executed. This function has a Message BOX - which says - PORT IS OPENED. return </code></pre> <p>I expect, once the thread is joined - my commands will clear the GUI. Then close the serial connection using (ser.close()). Then the self.OnCorrectComPort(event) gets executed. </p> <p>This is what I am seeing: Thread joins with tr.join() then self.OnCorrecComPort(event) gets executed as I can see the Message box with "PORT OPENED" appears, I click OK, then my GUI gets CLEARED. To my understanding this is wrong, anyone please correct me. </p>
2
2016-10-07T19:32:26Z
39,924,782
<p>The problem is that you're calling <code>time.sleep(5)</code> and <code>self.OnCorrectComPort()</code> in the callback, <em>before</em> returning to the mainloop where the events will be processed.</p> <p>The widgets will not reflect the effects of your <code>Clear</code> calls until you exit of the callback into the wx mainloop.</p> <p>What happens is, the routines you call are executed (takes several seconds because of the <code>time.sleep</code> call, <em>then</em> wx gets to process the graphical commands, and the widgets are cleared at this very moment (which is too late and the GUI seems stuck with the previous state)</p> <p>If you want it the other way round, you can use <code>wx.CallAfter()</code> to leave wx a chance to process its events before you call your routines.</p> <p>In your case, since you want to wait 5 seconds, the risk is to freeze your interface again. It's even better to call <code>wx.CallLater()</code> with a 5 second delay in that case, leaving the time to wx to refresh all the widgets.</p> <p>Modified code:</p> <pre><code> def OnReset(self, event): # A function event which works after a button is pressed self.reset_pump.Disable() # Disables the button so it is clicked self.WriteToController([0x30],'GuiMsgIn') # Sends the reset command self.flag_read.set() # Set Event of the thread time.sleep(0.25) self.tr.join() # Joining a Thread self.MessageBox('Pump RESET going on Click OK \n') # Having the above step is useful # The question I have is based on the commands from here: self.offset_text_control.Clear() self.gain_text_control.Clear() self.firmware_version_text_control.Clear() self.pump_rpm_text_control.Clear() self.pressure_text_control.Clear() self.last_error_text_control.Clear() self.error_count_text_control.Clear() self.pump_model_text_control.Clear() self.pump_serial_number_text_control.Clear() self.on_time_text_control.Clear() self.job_on_time_text_control.Clear() # The above commands clear various widgets on my GUI. self.ser.close() # Closes my serial connection to MCU # will call calledAfter after 5 seconds wx.CallLater(5000,self.calledAfter,[ser,event]) def calledAfter(self,ser,event): self.OnCorrectComPort(event) # An external function which gets executed. This function has a Message BOX - which says - PORT IS OPENED. </code></pre>
1
2016-10-07T19:46:19Z
[ "python", "multithreading", "wxpython" ]
Multilanguage site with Python Django
39,924,596
<p>We are making a site for multiple users, using Python Django.</p> <p>We need to set language of system messages (such as indications of user's errors, labels of control elements, etc.) different for different registered users.</p> <p>What is the best way to do this?</p>
-2
2016-10-07T19:33:29Z
39,924,680
<p>There is <code>activate</code> function in <code>django.utils.translation</code>, to set the language for current session.</p>
-1
2016-10-07T19:39:25Z
[ "python", "django" ]
Multilanguage site with Python Django
39,924,596
<p>We are making a site for multiple users, using Python Django.</p> <p>We need to set language of system messages (such as indications of user's errors, labels of control elements, etc.) different for different registered users.</p> <p>What is the best way to do this?</p>
-2
2016-10-07T19:33:29Z
39,924,726
<p>Django has a very mature and standard internationalization framework. The <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/" rel="nofollow">documentation</a> is extensive and well organized.</p> <p>Unless you want to avoid using Django's own facilities for translation, which could be the case for applications heavy in client-side code, this is the way to go.</p>
0
2016-10-07T19:42:50Z
[ "python", "django" ]
Adding variable number of controls to DropDown - weakly-referenced object no longer exists
39,924,598
<p>I have a dropdown with a list of the months in it. When the Month is selected, I'm trying to dynamically populate buttons in a second dropdown with the correct number of days. When I do so, I get:</p> <pre><code>ReferenceError: weakly-referenced object no longer exists </code></pre> <p>Here are my files for reference:</p> <p>main.py:</p> <pre><code>from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button globIDs = {} class appScreen(BoxLayout): def dayDropPop(self, num): globIDs['dayDropDown'].populate(num) class ExtDropDown(BoxLayout): heldValue = '' def setID(self, key): globIDs[key] = self def changeValue(self, sentText, parent): self.heldValue = sentText parent.text = sentText class PriorityDropDown(ExtDropDown): pass class MonthDropDown(ExtDropDown): def __init__(self, **kwargs): super(MonthDropDown, self).__init__(**kwargs) self.setID('monthDropDown') def monthSelect(self, month): monthDay = {'Jan': 31, 'Feb': 29, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31} numOfDays = monthDay[month] appScreen().dayDropPop(numOfDays) def testingFurther(self): print() class DayDropDown(ExtDropDown): def __init__(self, **kwargs): super(DayDropDown, self).__init__(**kwargs) self.setID('dayDropDown') def populate(self, num): for i in range(0, num): newButt = Button(text=str(num + 1)) self.ids.drop.add_widget(newButt) class schedulerApp(App): def build(self): return appScreen() if __name__ == '__main__': schedulerApp().run() </code></pre> <p>scheduler.kv:</p> <pre><code>&lt;PriorityDropDown&gt;: Button: id: ddRoot text: 'Priority' on_release: drop.open(ddRoot) size_hint_y: None height: root.height DropDown: id: drop on_parent: self.dismiss() on_select: root.changeValue(args[1], ddRoot) Button: text: 'Top' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'High' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Medium' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Low' size_hint_y: None height: root.height on_release: drop.select(self.text) &lt;MonthDropDown&gt;: Button: id: ddRoot text: 'Month' on_release: drop.open(ddRoot) size_hint_y: None height: root.height DropDown: id: drop on_parent: self.dismiss() on_select: root.monthSelect(args[1]) Button: text: 'Jan' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Feb' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Mar' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Apr' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'May' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Jun' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Jul' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Aug' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Sep' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Oct' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Nov' size_hint_y: None height: root.height on_release: drop.select(self.text) Button: text: 'Dec' size_hint_y: None height: root.height on_release: drop.select(self.text) &lt;DayDropDown&gt;: height: root.height Button: id: ddRoot text: 'Day' on_release: drop.open(ddRoot) size_hint_y: None height: root.height DropDown: id: drop on_parent: self.dismiss() on_select: root.changeValue(args[1], ddRoot) &lt;appScreen&gt;: orientation: 'vertical' Label: size_hint_y: .1 text: 'Hello World' GridLayout: size_hint_y:.1 width: root.width cols: 3 Button: Button: Button: ScrollView: canvas.before: Color: rgba: .3, .3, .3, 5 Rectangle: pos: self.pos size: self.size GridLayout: cols: 3 Label: id: textReceiver text: 'Words' text_size: self.size halign: 'left' valign: 'top' Label: Label: BoxLayout: size_hint_y: .125 TextInput: size_hint_x: .7 PriorityDropDown: size_hint_x: .3 BoxLayout: size_hint_y: .125 MonthDropDown: size_hint_x: .35 DayDropDown: id: 'dayDrop' size_hint_y: 1 size_hint_x: .2 TextInput: size_hint_x: .45 </code></pre> <p>I think the issue stems from the controls in question being created in Kivy code, rather than in Python. What testing I've done leads me to believe that I'm referencing my DayDropDown widget incorrectly. However, I don't know how else I would do so. With that in mind, how would I go about referencing my DayDropDown using what I already have? If that isn't my issue, what else might be causing the ReferenceError to be thrown?</p> <p><strong>Edit:</strong></p> <p>Messed with my code a little bit. I created a new class "globAddable" with methods "getID" - a simple return self - and put setID in there instead. I then set my setID now assigns self.getID() to a variable, then uses that variable as the object to be added to the globObjects (formerly globIDs) dictionary.</p> <p>I also created a new class for my DropDown object, called ExtDropArray, which lives in my DayDropDown. I moved the populate() method to this new class so that it can be called directly by the Dropdown, rather than its parent BoxLayout. I made the ExtDropArray and ExtDropDown inherit from globAddable to expose the setID (and implicitly getID) methods.</p> <p>The net result of all this is exactly the same. I still don't see my day DropDown when clicking the button on DayDropDown, and after testing with different values on the MonthDropDown, again I get the 'ReferenceError: weakly-referenced object no longer exists' error. However, I am noticing that the offending line is actually the method that opens the dropdown (drop.open(ddRoot), which is called on line 114 of my .kv file). This still doesn't quite give me enough information to know which part of the process is causing the error, be it the adding of the buttons to the DropDown or simply the calling of the open method. Given this new information, is anyone able to deduce what needs to change?</p>
1
2016-10-07T19:33:32Z
40,050,644
<p>Alright, I finally figured this one out.</p> <p>My ReferenceError was not a result of my methods, but rather a fundamental misunderstanding on my part of the implementation of DropDown objects. The fix was simply </p> <pre><code>&lt;DayDropDown&gt;: drop: drop.__self__ ... </code></pre> <p>This took me one heck of a long time to find, but came in the form of <a href="https://media.readthedocs.org/pdf/kivy/latest/kivy.pdf" rel="nofollow">this</a> documentation. Seeing as no other posts mentioning these ReferenceErrors makes any mention to this document, I'm leaving it here for others to use in case they run into a similar issue.</p>
0
2016-10-14T19:25:53Z
[ "python", "kivy" ]
Python logging: Best way to organize logs in different files?
39,924,599
<p>I have different loggers (log1, log2, log3, ..., logN) which are being logged to "registry.log" for a big N. I would like to divide "registry.log" into N different files as "registry.log" can become really large.</p> <p>Is there a way to accomplish this automatically, for instance, with a rotating handler?</p>
0
2016-10-07T19:33:35Z
39,930,135
<p>Create a <code>logging.Handler</code> subclass which determines which file to write to based on the details of the event being logged, and write the formatted event to that file.</p>
0
2016-10-08T08:01:01Z
[ "python", "logging", "rotation", "handler", "hierarchy" ]
Mezzanine overextends() template tag examples?
39,924,647
<p>I've been searching but there no examples of Mezzanine overextends()template tag, which allows you to extend a template with the same name. Does anybody know?</p>
0
2016-10-07T19:37:10Z
39,924,841
<p>While we still support django-1.8, note that <code>overextends</code> is deprecated because starting in django-1.9, <code>extends</code> supports recursive template extension.</p> <p>There are several examples you can check out in my project <a href="https://github.com/ryneeverett/cartridge-downloads" rel="nofollow">cartridge-downloads</a>, but unless you're stuck on django-1.8 or writing a reusable app that supports django-1.8, there is no reason to use the <code>overextends</code> template tag.</p>
1
2016-10-07T19:51:10Z
[ "python", "django", "django-templates", "mezzanine" ]
regex match space forward slash and space ' / '
39,924,654
<p>Here is my string 'something / something else' I would like to match with regex everything up to <code>/</code> i.e space forward slash space again. Here is what I tried =<code>/.+?(?=\s//\s)/</code>, but it does not work. It says: 'pattern contains no capture groups'. I am using it with pandas extract function.</p>
2
2016-10-07T19:37:48Z
39,924,709
<p>Not sure if I understand your requirements exactly, but this should do the trick:</p> <pre><code>(.*?)(?= \/ ) </code></pre> <p><a href="https://regex101.com/r/JJYyg0/1" rel="nofollow">Try it here</a></p> <p>You can replace the <code>*</code> with a <code>+</code> if there must be at least one character before <code>/</code>.</p> <p>The problem with your code is that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>pd.Series.str.extract</code></a> expects a "regular expression pattern <strong>with capturing groups</strong>." Your regex includes a positive lookahead (<code>?=</code>) but does not have a captured group (something between parentheses). If you surround <code>.+?</code> with parentheses in your example, it should work, but note that <code>\s</code> captures <em>any</em> whitespace, not just spaces.</p>
3
2016-10-07T19:41:52Z
[ "python", "regex", "pandas" ]
regex match space forward slash and space ' / '
39,924,654
<p>Here is my string 'something / something else' I would like to match with regex everything up to <code>/</code> i.e space forward slash space again. Here is what I tried =<code>/.+?(?=\s//\s)/</code>, but it does not work. It says: 'pattern contains no capture groups'. I am using it with pandas extract function.</p>
2
2016-10-07T19:37:48Z
39,924,755
<p>Do:</p> <pre><code>r'^([^/]+) / ' </code></pre> <ul> <li><code>^([^/]+)</code> matches everything upto the <code>/</code>, then <code>/</code> matches a space, then <code>/</code>, and then a space again. SO the captured group 1 will only have the portion upto the space before <code>/</code></li> </ul> <p><strong>Example:</strong></p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = 'something / something else' &gt;&gt;&gt; re.search(r'^([^/]+) / ', s).group(1) 'something' </code></pre>
2
2016-10-07T19:44:26Z
[ "python", "regex", "pandas" ]
Initializing a list and appending in one line
39,924,711
<p>How can I initialize a list, if it is not already initialized and append to it in one line. For example,</p> <pre><code>function example(a=None): a = a or [] a.append(1) return another_function(a) </code></pre> <p>How can I combine those two statements in the function into one?</p> <p>I am looking for something like this, but that does not work:</p> <pre><code>function example(a): a = (a or []).append(1) return another_function(a) </code></pre> <p>EDIT: I don't reference <code>a</code> elsewhere, it is just being passed from function to function. Practically just value is important, so it is OK if it is another object with the right value. I also added a default value of None. </p>
0
2016-10-07T19:41:54Z
39,924,739
<pre><code>def example(a): return a + [1] if a else [1] &gt;&gt;&gt; example([1,2,3]) [1, 2, 3, 1] &gt;&gt;&gt; example([]) [1] </code></pre>
3
2016-10-07T19:43:16Z
[ "python" ]
PYSPARK : casting string to float when reading a csv file
39,924,742
<p>I'm reading a csv file to dataframe</p> <pre><code>datafram = spark.read.csv(fileName, header=True) </code></pre> <p>but the data type in datafram is String, I want to change data type to float. Is there any way to do this efficiently?</p>
0
2016-10-07T19:43:33Z
39,925,215
<p>The most straightforward way to achieve this is by casting.</p> <pre><code>dataframe = dataframe.withColumn("float", col("column").cast("double")) </code></pre>
1
2016-10-07T20:21:00Z
[ "python", "apache-spark", "pyspark" ]
Is there a way to send (python) code to a server to compile and run but display the results on the computer that sent them?
39,924,750
<p>I just bought a server and was wondering if there was a way to run the code remotely but store/display the results locally. For example, I write some code to display a graph, the positions on the graph are computed by the (remote) server, but the graph is displayed on the (local) tablet. </p> <p>I would like to do this because the tablet I carry around with me on a day-to-day basis is very slow for computational physics simulations. I understand that I can setup some kind of communications protocol that allows the server to compute things and then sends the computations to my tablet for a script on my tablet to handle the data. However, I would like to avoid writing a possibly new set of communications scripts (to handle different formats of data) every single time I run a new simulation.</p>
0
2016-10-07T19:44:07Z
39,924,860
<p>This is a complete "<a href="http://therussiansusedapencil.com/post/175863624/the-pencil" rel="nofollow">The Russians used a pencil</a>" solution, but have you considered running a VNC server on the machine that is doing the computations? </p> <p>You could install a VNC client onto your tablet/phone/PC and view it that way, there are tons of them available. No need to go about creating anything from scratch.</p>
0
2016-10-07T19:53:20Z
[ "python", "remote-access" ]
Is there a way to send (python) code to a server to compile and run but display the results on the computer that sent them?
39,924,750
<p>I just bought a server and was wondering if there was a way to run the code remotely but store/display the results locally. For example, I write some code to display a graph, the positions on the graph are computed by the (remote) server, but the graph is displayed on the (local) tablet. </p> <p>I would like to do this because the tablet I carry around with me on a day-to-day basis is very slow for computational physics simulations. I understand that I can setup some kind of communications protocol that allows the server to compute things and then sends the computations to my tablet for a script on my tablet to handle the data. However, I would like to avoid writing a possibly new set of communications scripts (to handle different formats of data) every single time I run a new simulation.</p>
0
2016-10-07T19:44:07Z
39,924,876
<p>With ssh, you can do this with a python script or a shell script:</p> <p><code>ssh machine_name "python" &lt; ~/script/path/script.py</code></p> <p>REF: <a href="http://unix.stackexchange.com/questions/87405/how-can-i-execute-local-script-on-remote-machine-and-include-arguments">http://unix.stackexchange.com/questions/87405/how-can-i-execute-local-script-on-remote-machine-and-include-arguments</a></p>
0
2016-10-07T19:55:05Z
[ "python", "remote-access" ]
Code is correct, teacher approved, but it's not working. How do I make it run? (Python random module)
39,924,763
<p>This code is absolutely, 100% correct. It works on the teacher's computer and runs perfectly, but on mine it does not. I have no clue why that would be. The issue is the same on Mac and Windows (someone else had the same problem). I have Windows 8.1, if that's relevant, and I save all of my python files in Documents. I have Python 3.5, and I have the same issues in the Shell and in the command window. </p> <p>It does work to a point - it prints the student names it's supposed to, but then it prints the ending message twice and freaks out.</p> <p>I've imported the turtle module before with 0 issues. I haven't imported anything other than it and random, so I'm not sure if it's JUST random or if it's other modules too.</p> <p>Here's the code. It's to randomly pick students for activities:</p> <pre><code>def addlist(): maxLengthList = int(input("How many students?")) turtle.title("Class Chooser") while len(kids) &lt; maxLengthList: name = turtle.textinput("Students", "Enter a name") kids.append(name) nextturn() def nextturn(): turn = random.choice(kids) kids.remove(turn) print("Next " + turn) again=len(kids) while again&gt;0: nextturn() again=again-1 else: print("Have a nice day!") import random import turtle kids = [] addlist() </code></pre> <p>And here's the error message. I've inputted lucy, alex, jake, and bro for the students' names:</p> <pre><code>How many students?4 Next lucy Next alex Next jake Next bro Have a nice day! Have a nice day! Traceback (most recent call last): File "C:\Users\Seren\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 253, in choice i = self._randbelow(len(seq)) File "C:\Users\Seren\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 230, in _randbelow r = getrandbits(k) # 0 &lt;= r &lt; 2**k ValueError: number of bits must be greater than zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 24, in &lt;module&gt; addlist() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 7, in addlist nextturn() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 16, in nextturn nextturn() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 16, in nextturn nextturn() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 10, in nextturn turn = random.choice(kids) File "C:\Users\Seren\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 255, in choice raise IndexError('Cannot choose from an empty sequence') IndexError: Cannot choose from an empty sequence </code></pre> <p>Do any of you have a fix for this? If I can't import random properly, my assignments will be nearly impossible to do.</p> <p>EDIT: I think it's a problem with my computer, or my operating system, or the version of python I've downloaded. Anything outside the code that would cause the random module to go weird.</p> <p>UPDATE: If I put quit() after print("Have a nice day!"), no error message pops up and the program seems to run as intended. I'm not sure if this is so much a solution as a band-aid, though. </p>
0
2016-10-07T19:45:12Z
39,924,986
<p>The reason of this weird behavior is the use of recursion and a while loop to call the same function.</p> <p>There are many ways to solve this; however, I recommend to get rid of the while loop entirely as it is confusing:</p> <pre><code>def addlist(): maxLengthList = int(input("How many students?")) turtle.title("Class Chooser") while len(kids) &lt; maxLengthList: name = turtle.textinput("Students", "Enter a name") kids.append(name) nextturn() def nextturn(): turn = random.choice(kids) kids.remove(turn) print("Next " + turn) again=len(kids) if again&gt;0: nextturn() again=again-1 else: print("Have a nice day!") import random import turtle kids = [] addlist() </code></pre> <p>I would also standarize the code a bit, to make it more readable:</p> <pre><code>import random import turtle kids = [] def addlist(): maxLengthList = int(input("How many students?")) turtle.title("Class Chooser") while len(kids) &lt; maxLengthList: name = turtle.textinput("Students", "Enter a name") kids.append(name) nextturn() def nextturn(): turn = random.choice(kids) kids.remove(turn) print("Next " + turn) if kids: nextturn() else: print("Have a nice day!") addlist() </code></pre> <p><strong>Update:</strong></p> <p>This is the long explanation of what your code was doing:</p> <p>Suppose you have a list with <code>[ann, bob, charlie]</code>.</p> <ul> <li><p>On Call #1 to <code>nextturn</code>: you remove a kid so the variables are like this: (global kids=['ann', 'bob'], local again=2) before entering the loop.</p></li> <li><p>On Call #2 to <code>nextturn</code> your variables are like this before entering the loop(global kids=[ann], local again=1)</p></li> <li><p>On Call #3 it will be (global kids=[empty], local again=0) before (not) entering the loop. This will simply print "Have a nice day" and exit successfully</p></li> </ul> <p>Call 3 will end leaving the list empty. BUT Call 1 and 2 are still active. After the first iteration of the while loop on Call #2 the local variable <code>again</code> is 0, so it prints "Have a nice day" (again) and exits.</p> <p>But then in Call 1: the local variable <code>again</code> is 1, which means the loop will execute again on an empty list!!!.</p> <p>And that caused the problem.</p>
1
2016-10-07T20:05:46Z
[ "python", "random", "module", "python-module" ]
Code is correct, teacher approved, but it's not working. How do I make it run? (Python random module)
39,924,763
<p>This code is absolutely, 100% correct. It works on the teacher's computer and runs perfectly, but on mine it does not. I have no clue why that would be. The issue is the same on Mac and Windows (someone else had the same problem). I have Windows 8.1, if that's relevant, and I save all of my python files in Documents. I have Python 3.5, and I have the same issues in the Shell and in the command window. </p> <p>It does work to a point - it prints the student names it's supposed to, but then it prints the ending message twice and freaks out.</p> <p>I've imported the turtle module before with 0 issues. I haven't imported anything other than it and random, so I'm not sure if it's JUST random or if it's other modules too.</p> <p>Here's the code. It's to randomly pick students for activities:</p> <pre><code>def addlist(): maxLengthList = int(input("How many students?")) turtle.title("Class Chooser") while len(kids) &lt; maxLengthList: name = turtle.textinput("Students", "Enter a name") kids.append(name) nextturn() def nextturn(): turn = random.choice(kids) kids.remove(turn) print("Next " + turn) again=len(kids) while again&gt;0: nextturn() again=again-1 else: print("Have a nice day!") import random import turtle kids = [] addlist() </code></pre> <p>And here's the error message. I've inputted lucy, alex, jake, and bro for the students' names:</p> <pre><code>How many students?4 Next lucy Next alex Next jake Next bro Have a nice day! Have a nice day! Traceback (most recent call last): File "C:\Users\Seren\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 253, in choice i = self._randbelow(len(seq)) File "C:\Users\Seren\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 230, in _randbelow r = getrandbits(k) # 0 &lt;= r &lt; 2**k ValueError: number of bits must be greater than zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 24, in &lt;module&gt; addlist() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 7, in addlist nextturn() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 16, in nextturn nextturn() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 16, in nextturn nextturn() File "C:\Users\Seren\Documents\~School~\Computer Programming\isolated code ex.py", line 10, in nextturn turn = random.choice(kids) File "C:\Users\Seren\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 255, in choice raise IndexError('Cannot choose from an empty sequence') IndexError: Cannot choose from an empty sequence </code></pre> <p>Do any of you have a fix for this? If I can't import random properly, my assignments will be nearly impossible to do.</p> <p>EDIT: I think it's a problem with my computer, or my operating system, or the version of python I've downloaded. Anything outside the code that would cause the random module to go weird.</p> <p>UPDATE: If I put quit() after print("Have a nice day!"), no error message pops up and the program seems to run as intended. I'm not sure if this is so much a solution as a band-aid, though. </p>
0
2016-10-07T19:45:12Z
39,925,088
<p>Maybe use the <code>random.randint(0,x)</code> to define what student you want, e.g. </p> <pre><code>print(students[random.randint(0,3)] </code></pre> <p>Not sure if this helps, another suggestion may be trying a simpler <code>print(random.randint(1,4)</code> in another project just to see if it is working?</p> <p>(Also you should probably put the <code>import random</code> stuff at the very front.</p>
-1
2016-10-07T20:12:30Z
[ "python", "random", "module", "python-module" ]
Pygame: Creating a border
39,924,776
<p>I've been working on my school project which is a 2D game with a moveable player. I wish to create a border around the edge of the screen. I have read through several other articles but can't seem to wrap my mind around it. It would be great if someone could help me. Here is my program</p> <pre><code>import pygame import os black = (0,0,0) white = (255,255,255) blue = (0,0,255) class Player(object): def __init__(self): self.image = pygame.image.load("player1.png") self.image2 = pygame.transform.flip(self.image, True, False) self.coffee = pygame.image.load("coffee.png") self.computer = pygame.image.load("computer.png") self.background = pygame.image.load("background.png") self.flipped = False self.x = 0 self.y = 0 def handle_keys(self): """ Movement keys """ key = pygame.key.get_pressed() dist = 5 if key[pygame.K_DOWN]: self.y += dist elif key[pygame.K_UP]: self.y -= dist if key[pygame.K_RIGHT]: self.x += dist self.flipped = False elif key[pygame.K_LEFT]: self.x -= dist self.flipped = True def draw(self, surface): if self.flipped: image = self.image2 else: image = self.image surface.blit(self.background,(0,0)) surface.blit(self.coffee, (725,500)) surface.blit(self.computer,(15,500)) surface.blit(image, (self.x, self.y)) pygame.init() screen = pygame.display.set_mode((800, 600)) #creates the screen player = Player() clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() # quit the screen running = False player.handle_keys() # movement keys screen.fill((255,255,255)) # fill the screen with white player.draw(screen) # draw the player to the screen pygame.display.update() # update the screen clock.tick(60) # Limits Frames Per Second to 60 or less </code></pre>
0
2016-10-07T19:45:36Z
39,924,952
<p>What you can do is that you can add 20 pixels to each width and height and draw a series of squares all around.</p> <pre><code>screen = pygame.display.set_mode((800 + 20, 600 + 20)) for x in range(0, 810, 10) pygame.draw.rect(surface, BLACK, [x, 0, 10, 10]) pygame.draw.rect(surface, BLACK, [x, 610, 10, 10]) for x in range(0, 610, 10) pygame.draw.rect(screen, BLACK, [0, x, 10, 10]) pygame.draw.rect(screen, BLACK, [810, x, 10, 10]) </code></pre>
1
2016-10-07T20:03:00Z
[ "python", "python-2.7", "pygame" ]
Pygame: Creating a border
39,924,776
<p>I've been working on my school project which is a 2D game with a moveable player. I wish to create a border around the edge of the screen. I have read through several other articles but can't seem to wrap my mind around it. It would be great if someone could help me. Here is my program</p> <pre><code>import pygame import os black = (0,0,0) white = (255,255,255) blue = (0,0,255) class Player(object): def __init__(self): self.image = pygame.image.load("player1.png") self.image2 = pygame.transform.flip(self.image, True, False) self.coffee = pygame.image.load("coffee.png") self.computer = pygame.image.load("computer.png") self.background = pygame.image.load("background.png") self.flipped = False self.x = 0 self.y = 0 def handle_keys(self): """ Movement keys """ key = pygame.key.get_pressed() dist = 5 if key[pygame.K_DOWN]: self.y += dist elif key[pygame.K_UP]: self.y -= dist if key[pygame.K_RIGHT]: self.x += dist self.flipped = False elif key[pygame.K_LEFT]: self.x -= dist self.flipped = True def draw(self, surface): if self.flipped: image = self.image2 else: image = self.image surface.blit(self.background,(0,0)) surface.blit(self.coffee, (725,500)) surface.blit(self.computer,(15,500)) surface.blit(image, (self.x, self.y)) pygame.init() screen = pygame.display.set_mode((800, 600)) #creates the screen player = Player() clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() # quit the screen running = False player.handle_keys() # movement keys screen.fill((255,255,255)) # fill the screen with white player.draw(screen) # draw the player to the screen pygame.display.update() # update the screen clock.tick(60) # Limits Frames Per Second to 60 or less </code></pre>
0
2016-10-07T19:45:36Z
39,926,876
<p>Try adding this to your main part before <code>player.draw(screen)</code>:</p> <pre><code>pygame.init() line_width = 10 width = 800 height = 600 #creates the screen screen = pygame.display.set_mode((width+line_width, height+line_width),0,32) screen.fill(white) # fill the screen with white # top line pygame.draw.rect(screen, black, [0,0,width,line_width]) # bottom line pygame.draw.rect(screen, black, [0,height,width,line_width]) # left line pygame.draw.rect(screen, black, [0,0,line_width, height]) # right line pygame.draw.rect(screen, black, [width,0,line_width, height+line_width]) </code></pre>
0
2016-10-07T23:01:16Z
[ "python", "python-2.7", "pygame" ]
python multiprocessing returning error 'module' object has no attribute 'myfunc'
39,924,862
<p>First off, I am very new to multiprocessing, and I can't seem to make a very simple and straightforward example work. This is the example I working with:</p> <pre><code>import multiprocessing def worker(): """worker function""" print 'Worker' return if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) p.start() </code></pre> <p>everytime I run a code I am getting this error multiple times :</p> <pre><code>C:\Anaconda2\lib\site-packages\IPython\utils\traitlets.py:5: UserWarning: IPython.utils.traitlets has moved to a top-level traitlets package. warn("IPython.utils.traitlets has moved to a top-level traitlets package.") Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Anaconda2\lib\multiprocessing\forking.py", line 381, in main self = load(from_parent) File "C:\Anaconda2\lib\pickle.py", line 1384, in load return Unpickler(file).load() File "C:\Anaconda2\lib\pickle.py", line 864, in load dispatch[key](self) File "C:\Anaconda2\lib\pickle.py", line 1096, in load_global klass = self.find_class(module, name) File "C:\Anaconda2\lib\pickle.py", line 1132, in find_class klass = getattr(mod, name) AttributeError: 'module' object has no attribute 'worker' </code></pre> <p>I know that this question is very vague but I if anyone could point me in the right direction I would appreciate it.</p> <p>I am on Windows, I run it in Anaconda with python 2.7, the code is exactly the same as above, nothing more nothing less! I run it directly in the console in the IDE</p> <p>EDIT: It looks like when I run the code directly in command prompt it works just fine, but doing it the console using Anaconda won't work. anybody knows why?</p>
0
2016-10-07T19:53:51Z
39,925,567
<p>Anaconda doesn't like multiprocessing as explained <a href="http://stackoverflow.com/questions/32489352/multiprocessing-program-has-attributeerror-in-anaconda-notebook">in this</a> answer.</p> <p>From the answer:</p> <blockquote> <p>This is because of the fact that multiprocessing does not work well in the interactive interpreter. The main reason is that there is no fork() function applicable in windows. It is explained on their web page itself.</p> </blockquote> <p>Thank you!</p>
0
2016-10-07T20:47:50Z
[ "python", "multiprocessing", "python-2.x" ]
Finding if member function exists in a Boost python::object
39,924,912
<p>I'm using Boost Python to make C++ and Python operate together and I have a code that looks like this, creating an instance of a python object and calling one of its member functions.</p> <pre><code>bp::object myInstance; // ... myInstance is initialized bp::object fun = myInstance.attr("myfunction"); fun(); </code></pre> <p>I would like to check if the member function exists before calling it. If it does not exist, I don't want to call.</p> <p>The problem is: the call to myInstance.attr("myfunction") is successful even if the function does not exist. Hence, the only way to test if the function exists in my current code is by trying to call it, and catching an exception.</p> <p>Is there any way to check if the function exists without involving exception or calling the function?</p>
2
2016-10-07T19:59:08Z
39,925,047
<blockquote> <p>the call to <code>myInstance.attr("myfunction")</code> is successful even if the function does not exist</p> </blockquote> <p>Pretty sure it throws an <code>AttributeError</code>. </p> <blockquote> <p>Is there any way to check if the function exists without involving exception or calling the function?</p> </blockquote> <p>One of the strange holes in Boost.Python is that it doesn't have a <code>hasattr()</code> function. It's easy enough to add:</p> <pre><code>namespace boost { namespace python { bool hasattr(object o, const char* name) { return PyObject_HasAttrString(o.ptr(), name); } } } </code></pre> <p>and then you can just use it:</p> <pre><code>if (hasattr(myInstance, "myfunction")) { bp::object fun = myInstance.attr("myfunction"); fun(); // ... } </code></pre>
2
2016-10-07T20:09:33Z
[ "python", "c++", "boost", "boost-python" ]
Importing default sublime text commands into a custom command
39,924,917
<p>I'm writing a command that needs to copy the current file's path. Sublime Text already has a <a href="https://github.com/cj/sublime/blob/master/Default/copy_path.py" rel="nofollow">copy_path command</a> that achieves this. Is it possible to import that command into my command's file? I have tried <code>import copy_path</code> and <code>import CopyPathCommand</code>. I have also tried calling the command as if it were a method on the <code>sublime</code> module, i.e. <code>sublime.copy_path()</code> but all of these attempts have resulted in errors.</p>
0
2016-10-07T19:59:20Z
39,925,204
<p>To import the command you can write <code>from Default.copy_path import CopyPathCommand</code>. <em>However</em> it sounds as if you run the command for which you don't need to import it. Just write <code>self.view.run_command("copy_path")</code> inside your <code>TextCommand</code> and it will be executed.</p>
0
2016-10-07T20:20:19Z
[ "python", "sublimetext3", "sublimetext", "sublime-text-plugin" ]
How would I do a detailed walk-through of a factorial?
39,924,924
<pre><code>def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1) print(factorial(3)) </code></pre> <p>How would I do a detailed walk-through with information on the stack at every call and show the data at every return?</p> <p>I know I have to draw 3 boxes to show what happens at every call, and the data at every return; I just don't know how the function actually works, and how to implement it. This does not require any coding, but an explanation?</p> <p>***** Update **** So something like this?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>N = 3 4 * factorial (3): 24 N = 2 5 * factorial (4): 120 // and so on....</code></pre> </div> </div> </p>
0
2016-10-07T20:00:14Z
39,925,010
<p>You can try to add some <code>print</code> lines to know what's happening inside a function call. Such as the following:</p> <pre><code>def factorial(x): print("factorial({}) is called".format(x)) if x == 0: print("Reached base branch") return 1 else: print("Reached recursive branch") result = x * factorial(x - 1) print("Exitted recursive branch") return result print(factorial(3)) </code></pre> <p>This should let you see how the call to <code>factorial(3)</code> eventually calls <code>factorial(2)</code>, <code>factorial(1)</code>, and <code>factorial(0)</code> and then goes up the recursive hierarchy when the based case is reached.</p>
0
2016-10-07T20:07:09Z
[ "python", "recursion", "stack", "factorial" ]
Programming error column does not exist
39,924,967
<p>models.py </p> <pre><code>class PlansToLodge(models.Model): sm_sequence = models.IntegerField() sm_year = models.IntegerField() location = models.TextField(blank=True, null=True) car_number = models.CharField(max_length=100, blank=True, null=True) client_or_owner = models.TextField(blank=True, null=True) date_received = models.DateField(blank=True, null=True) date_lodged = models.DateField(blank=True, null=True) remarks = models.TextField(blank=True, null=True) sent_or_received = models.TextField(blank=True, null=True) receipt_number = models.TextField(blank=True, null=True) class Meta: managed = False db_table = 'plans_to_lodge' unique_together = (('sm_sequence', 'sm_year'),) </code></pre> <p>view.py</p> <pre><code>def searchPlanInfo(request): logger = logging.getLogger(__name__) if request.user.is_authenticated(): if request.method =='POST': if request.POST['smYear'] is not '': searchPlan = request.POST['smYear'] logger.error('lets see here') foundPlan = PlansToLodge.objects.filter(sm_year=searchPlan) logger.error(foundPlan[0]) context = {'parcel_list': foundPlan} return render(request,'parcelmanager/index2.html',context) return HttpResponse("once again") </code></pre> <p>traceback</p> <p>Traceback:</p> <pre><code>File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Sites\Landregistry\surveyplanmanager\views.py" in searchPlanInfo 39. logger.error(foundPlan[0]) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in __getitem__ 201. return list(qs)[0] File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in __iter__ 162. self._fetch_all() File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in _fetch_all 965. self._result_cache = list(self.iterator()) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\query.py" in iterator 238. results = compiler.execute_sql() File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 829. cursor.execute(sql, params) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\backends\utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\utils.py" in __exit__ 97. six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\utils\six.py" in reraise 658. raise value.with_traceback(tb) File "C:\Users\yfevrier\Envs\landregtry1\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) Exception Type: ProgrammingError at /surveyplanmanager/searchPlanInfo/ Exception Value: column plans_to_lodge.id does not exist LINE 1: SELECT "plans_to_lodge"."id", "plans_to_lodge"."sm_sequence"... ^ </code></pre> <p>now before i used sqlite but we moved into what database we will be using Postgresql and i knew in sqlite it made these "id" fields but i dont know why its doing this for postgresql ive migrated and all so that shouldnt be happening </p>
0
2016-10-07T20:04:20Z
39,926,597
<p>Actually this error occure because your database is not migrated</p> <p>So run following command to migrate database</p> <pre><code>python manage.py migrate </code></pre> <p>If this is not run then run following command</p> <pre><code>python manage.py makemigrations python manage.py migrate </code></pre>
1
2016-10-07T22:23:55Z
[ "python", "django", "postgresql", "object", "models" ]
How to run Threads synchronously with Python?
39,924,981
<p>I need to use 3 threads to print array items sequentially using Python.</p> <p>Each Thread will print one array item.</p> <p>I need the threads to sleep for a random number of seconds and then print the item.</p> <p>This function will be executed N times. This N value is given by the user.</p> <p>The items must be printed on a specific order, which means I have to somehow block the other threads to execute while the previous one is not done. I've been trying a lot of different solutions but I can't figure out how to make it work.</p> <p>I've tried to use Semaphores, Lock and Events but without success on the synchronization. In all cases it would print the sequence randomly, according to the time.sleep and not with the sequence itself. How can I block the thread from executing the function and check if the previous thread was finished in order to allow the sequence to work?</p> <p>Which tool should I use to make it work? Any help is appreciated.</p> <pre><code>class myThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): super(myThread,self).__init__() self.target = target self.name = name return def run(self): while True: if not q.empty(): semaphore.acquire() try: time_sleep = random.randrange(0,10) print "thread " + self.name + ". Dormir por " + str(time_sleep) + " segundos" time.sleep(time_sleep) print cores[int(self.name)] if int(self.name) == len(cores) - 1: item = q.get() print 'Executou sequencia ' + str(item + 1) + ' vezes. Ainda irá executar ' + str(q.qsize()) + ' vezes' e.set() finally: semaphore.release() if int(self.name) != len(cores) - 1: e.wait() return if __name__ == '__main__': for i in range(2): q.put(i) for i in range(3): t = myThread(name=i) t.start() </code></pre>
-1
2016-10-07T20:05:29Z
39,925,055
<p>There are many, many approaches to this. A simple one is to use a shared <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">Queue</a> of numbers.</p> <p>Each thread can sleep for however long it wants to, take a number from the queue when it wakes up, and print it. They will come out in the order they were pushed to the queue.</p> <p>If your numbers are sequential, or can generated dynamically, you can also do it in constant-memory using a shared counter, <a href="http://stackoverflow.com/questions/35088139/how-to-make-a-thread-safe-global-counter-in-python">as described in this answer</a>.</p>
1
2016-10-07T20:09:51Z
[ "python", "multithreading" ]
How to run Threads synchronously with Python?
39,924,981
<p>I need to use 3 threads to print array items sequentially using Python.</p> <p>Each Thread will print one array item.</p> <p>I need the threads to sleep for a random number of seconds and then print the item.</p> <p>This function will be executed N times. This N value is given by the user.</p> <p>The items must be printed on a specific order, which means I have to somehow block the other threads to execute while the previous one is not done. I've been trying a lot of different solutions but I can't figure out how to make it work.</p> <p>I've tried to use Semaphores, Lock and Events but without success on the synchronization. In all cases it would print the sequence randomly, according to the time.sleep and not with the sequence itself. How can I block the thread from executing the function and check if the previous thread was finished in order to allow the sequence to work?</p> <p>Which tool should I use to make it work? Any help is appreciated.</p> <pre><code>class myThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): super(myThread,self).__init__() self.target = target self.name = name return def run(self): while True: if not q.empty(): semaphore.acquire() try: time_sleep = random.randrange(0,10) print "thread " + self.name + ". Dormir por " + str(time_sleep) + " segundos" time.sleep(time_sleep) print cores[int(self.name)] if int(self.name) == len(cores) - 1: item = q.get() print 'Executou sequencia ' + str(item + 1) + ' vezes. Ainda irá executar ' + str(q.qsize()) + ' vezes' e.set() finally: semaphore.release() if int(self.name) != len(cores) - 1: e.wait() return if __name__ == '__main__': for i in range(2): q.put(i) for i in range(3): t = myThread(name=i) t.start() </code></pre>
-1
2016-10-07T20:05:29Z
39,925,289
<p>If you didn't care about order you could just use a lock to synchronize access. In this case, though, how about a list of events. Each thread gets its own event slot and hands it to the next event in the list when done. This scheme could be fancied up by returning a context manager so that you don't need to release explicitly.</p> <pre><code>import threading class EventSlots(object): def __init__(self, num_slots): self.num_slots = num_slots self.events = [threading.Event() for _ in range(num_slots)] self.events[0].set() def wait_slot(self, slot_num): self.events[slot_num].wait() self.events[slot_num].clear() def release_slot(self, slot_num): self.events[(slot_num + 1) % self.num_slots].set() def worker(event_slots, slot_num): for i in range(5): event_slots.wait_slot(slot_num) print('slot', slot_num, 'iteration', i) event_slots.release_slot(slot_num) NUM = 3 slots = EventSlots(NUM) threads = [] for slot in range(NUM): t = threading.Thread(target=worker, args=(slots, slot)) t.start() threads.append(t) for t in threads: t.join() </code></pre>
0
2016-10-07T20:26:45Z
[ "python", "multithreading" ]
Having problems parsing numerical command-line arguments
39,925,069
<p>I am making a super simple program that strips even or odd numbers from a string given on the command line. For example:</p> <pre><code>$ test.py 1 1234 13 $ test.py 2 1234 24 </code></pre> <p>The problem is I can't get it to work. It prints the usage instead of the expected numbers.</p> <pre><code>$ test.py 1 1234 Usage: test.py [option] [number], etc.. </code></pre> <p>Also, this should print out the usage, but instead does nothing:</p> <pre><code>$ python2.7 test.py 1 $ </code></pre> <p>Why doesn't the program output the usage? <code>len(sys.argv)</code> is <code>&lt; 2</code> so it should print usage, correct?</p> <pre><code>def oddtarray(num): tlist = map(int, str(num)) tnum = [x for x in tlist if (x % 2) != 0] return tnum def eventarray(num): tlist = map(int, str(num)) tnum = [x for x in tlist if (x % 2) == 0] return tnum def transform(): try: odd = int(''.join(map(str, eventarray(sys.argv[2])))) even = int(''.join(map(str, oddtarray(sys.argv[2])))) if len(sys.argv) == 3: if sys.argv[1] == 1: print odd elif sys.argv[1] == 2: print even else: usage() else: usage() except IndexError: if len(sys.argv) &lt; 2: usage() def usage(): print 'Usage: test.py [option] [number]' print 'Options: \n[1] - Remove even numbers\n[2] - Remove odd numbers' transform() </code></pre>
-2
2016-10-07T20:11:13Z
39,925,134
<p><code>sys.argv[1] == 1</code> is not possible. You mean: <code>sys.argv[1] == "1"</code>. Those are strings, not numbers.</p> <p>Your argument parsing would require some cleaning. No need for all those checks and exceptions to do such a simple task.</p> <p>Allow me to "code review" &amp; fix your code (I focused on the arg parsing part, protecting the integer parsing by a try/except <code>ValueError</code> printing usage and testing the number of arguments):</p> <pre><code>import sys def oddtarray(num): tlist = map(int, str(num)) tnum = [x for x in tlist if (x % 2) != 0] return tnum def eventarray(num): tlist = map(int, str(num)) tnum = [x for x in tlist if (x % 2) == 0] return tnum def transform(): if len(sys.argv) &lt; 3: # not enough arguments: print usage and that's it! usage() else: try: command = int(sys.argv[1]) # convert to integer odd = int(''.join(map(str, eventarray(sys.argv[2])))) even = int(''.join(map(str, oddtarray(sys.argv[2])))) if command == 1: print(odd) elif command == 2: print(even) else: usage() except ValueError as e: # some string to integer went wrong: display detailed exception # just in case, then usage print(str(e)) usage() def usage(): print('Usage: test.py [option] [number]') print('Options: \n[1] - Remove even numbers\n[2] - Remove odd numbers') transform() </code></pre> <p>now it's really "super simple", and as a bonus, it works :)</p>
4
2016-10-07T20:15:41Z
[ "python" ]
Having problems parsing numerical command-line arguments
39,925,069
<p>I am making a super simple program that strips even or odd numbers from a string given on the command line. For example:</p> <pre><code>$ test.py 1 1234 13 $ test.py 2 1234 24 </code></pre> <p>The problem is I can't get it to work. It prints the usage instead of the expected numbers.</p> <pre><code>$ test.py 1 1234 Usage: test.py [option] [number], etc.. </code></pre> <p>Also, this should print out the usage, but instead does nothing:</p> <pre><code>$ python2.7 test.py 1 $ </code></pre> <p>Why doesn't the program output the usage? <code>len(sys.argv)</code> is <code>&lt; 2</code> so it should print usage, correct?</p> <pre><code>def oddtarray(num): tlist = map(int, str(num)) tnum = [x for x in tlist if (x % 2) != 0] return tnum def eventarray(num): tlist = map(int, str(num)) tnum = [x for x in tlist if (x % 2) == 0] return tnum def transform(): try: odd = int(''.join(map(str, eventarray(sys.argv[2])))) even = int(''.join(map(str, oddtarray(sys.argv[2])))) if len(sys.argv) == 3: if sys.argv[1] == 1: print odd elif sys.argv[1] == 2: print even else: usage() else: usage() except IndexError: if len(sys.argv) &lt; 2: usage() def usage(): print 'Usage: test.py [option] [number]' print 'Options: \n[1] - Remove even numbers\n[2] - Remove odd numbers' transform() </code></pre>
-2
2016-10-07T20:11:13Z
39,925,357
<p>Unlike the OP and one other answer so far, I don't see why you would compute both the odd and even lists knowing you'll only need one of them -- it's short distance from "simple" to "simply inefficient". How about we delay the "hard work" of thinning the lists until we've finished the "easy work" of decoding the arguments:</p> <pre><code>import sys def oddtarray(digits): tlist = map(int, digits) tnum = [x for x in tlist if (x % 2) != 0] return int(''.join(map(str, tnum))) def eventarray(digits): tlist = map(int, digits) tnum = [x for x in tlist if (x % 2) == 0] return int(''.join(map(str, tnum))) def transform(): if len(sys.argv) == 3: try: if sys.argv[1] == "1": print oddtarray(sys.argv[2]) elif sys.argv[1] == "2": print eventarray(sys.argv[2]) else: usage() except ValueError: usage() else: usage() def usage(): print 'Usage: test.py [option] [number]' print 'Options: \n[1] - Remove even numbers\n[2] - Remove odd numbers' transform() </code></pre> <p>Specific issues with the original program: the <code>odd</code> and <code>even</code> variables are reversed; command line arguments are being treated as numbers instead of as strings that look like numbers; the validity of the length of the command line argument list is being tested <strong>after</strong> items have already been extracted from it -- it should be tested before; the possibility of an IndexError exception is more likely due to programmer error than user error -- a ValueError exception is more likely due to user error (entering non-digits).</p>
1
2016-10-07T20:31:08Z
[ "python" ]
Why SQLAlchemy send extra SELECTs when accessing a persisted model property
39,925,074
<p>Given a simple declarative based class;</p> <pre><code>class Entity(db.Model): __tablename__ = 'brand' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) </code></pre> <p>And the next script</p> <pre><code>entity = Entity() entity.name = 'random name' db.session.add(entity) db.session.commit() # Just by accessing the property name of the created object a # SELECT statement is sent to the database. print entity.name </code></pre> <p>When I enable <code>echo</code> mode in SQLAlchemy, I can see in the terminal the <strong><code>INSERT</code></strong> statement and an extra <strong><code>SELECT</code></strong> just when I access a property (column) of the model (table row).</p> <p>If I don't access to any property, the query is not created.</p> <p>What is the reason for that behavior? In this basic example, We already have the value of the <code>name</code> property assigned to the object. So, Why is needed an extra query? It to secure an up to date value, or something like that?</p>
0
2016-10-07T20:11:45Z
39,926,948
<p>By default, SQLAlchemy expires objects in the session when you commit. This is controlled via the <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.params.expire_on_commit" rel="nofollow"><code>expire_on_commit</code></a> parameter.</p> <p>The reasoning behind this is that the row behind the instance could have been modified outside of the transaction, so if you are not careful you could run into data races, but if you know what you are doing you can safely turn it off.</p>
0
2016-10-07T23:09:58Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Flask web development. No module named 'MySQLdb'
39,925,076
<p>I'm working with Flask following Miguel Grinberg's book at the moment. i've reached the part where i need to interact with MySQL. i've checked everything and yet when i try to create the actual database with the command:</p> <p>db.create_all()</p> <p>i get an error saying "No module named 'MySQLdb'". i've tried installing mySQL-python in my virtual environment and i get another error - "No module named 'ConfigParser'". i tried installing that module with pip, but the same error occurs like i didn't install the ConfigParser module at all. any advice? i'm using python version 3.4. i've read a couple of times that MySQLdb doesn't work with python 3, a statement which contradicts what was written in Miguels book, that Flask is compatible both with python 2 and 3.</p>
-1
2016-10-07T20:11:55Z
39,926,237
<p>solved it. needed to install mysqlclient via pip in the virtual environment. mySQL-python apparently doesn't work with python3</p>
0
2016-10-07T21:45:54Z
[ "python", "mysql", "flask" ]
Problems while applying a function to each element's content of a directory in python?
39,925,118
<p>I am trying to obtain the content of several .pdf files from a directory in order to transform them to text with tika library, however I believe that I am not reading the .pdf file objects correctly. This is what I tried so far:</p> <p>Input:</p> <pre><code>for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): with open(filename,"rb") as f: print(f) text = parser.from_file(f) </code></pre> <p>Output: </p> <pre><code>&lt;_io.BufferedReader name='/Users/user/Downloads/pdf-files/a_pdf_file.pdf'&gt; AttributeError: '_io.BufferedReader' object has no attribute 'decode' </code></pre> <p>Which is the most efficient way of walking through the content of the files in python?.</p>
1
2016-10-07T20:14:24Z
39,925,250
<p>The tika parser receives a path and opens the file itself:</p> <pre><code>for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): parsed = parser.from_file(filename) text = parsed['content'] </code></pre>
1
2016-10-07T20:23:19Z
[ "python", "python-3.x", "pdf", "io", "ipython-parallel" ]
Running a python program with cron, Docker and Supervisor
39,925,138
<p>When I run build the container with the CMD as <code>CMD /usr/bin/python3 /app/test.py</code> everything runs fine and I see an output, but when I run the CMD as <code>CMD ["/usr/bin/supervisord", "-n"]</code> which runs supervisor and cron, I see not output. It seems like the python file is not running, or i'm not properly setup to see logging.</p> <p>How can I ensure the python file is running and how can I see the output?</p> <p>My Dockerfile is:</p> <pre><code>FROM ubuntu:16.04 RUN apt-get update RUN apt-get install -y apt-utils -y cron -y liblapack3 -y build-essential \ -y python3-dev -y python3-setuptools -y python3-numpy \ -y python3-scipy -y python3-pip -y libatlas-dev \ -y supervisor COPY . /app # install requirements (early and on their own to leverage caching) COPY ./requirements.txt /app/requirements.txt RUN pip3 install -r /app/requirements.txt # make script executable RUN chmod +x /app/test.py # do cron stuff COPY ./crontab /etc/cron.d/crontab RUN chmod 0644 /etc/cron.d/crontab CMD cron &amp;&amp; tail -f /var/log/cron.log COPY ./supervisord.conf /etc/supervisor/conf.d/supervisord.conf # CMD ["/usr/bin/supervisord", "-n"] CMD /usr/bin/python3 /app/test.py </code></pre> <p>supervisord.conf is:</p> <pre><code>[supervisord] nodaemon=true loglevel=debug [program:cron] command = cron -f -L 15 autostart=true autorestart=true stdout_logfile=/var/log/supervisor/%(program_name)s.log stdout_logfile=/dev/stdout stdout_logfile_maxbytes=0 </code></pre> <p>crontab is:</p> <pre><code>* * * * * root /usr/bin/python3 /app/test.py * * * * * root echo "hello world" &gt;&gt; /var/log/cron.log 2&gt;&amp;1 </code></pre> <p>and test.py is:</p> <pre><code>#!/usr/bin/env python import logging from lib.rig import settings #set logging level to INFO logging.getLogger().setLevel(settings.get('logging_level')) logging.info('LOLOLOL') print('this is a print') </code></pre>
-1
2016-10-07T20:16:13Z
40,108,168
<p>You're missing the <code>PATH</code> environment variable declaration, which is causing your Python app to not run. Editing your Dockerfile to the following should fix the issue for you:</p> <pre><code>FROM ubuntu:16.04 ENV PATH /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin # This is the line that matters ^^ RUN apt-get update ... </code></pre> <p>See more on the <code>ENV</code> variable <a class='doc-link' href="http://stackoverflow.com/documentation/docker/3161/dockerfile/11006/env-directive#t=201610181215353951059">here</a>.</p>
0
2016-10-18T12:23:10Z
[ "python", "docker", "cron", "supervisord" ]
obtaining pre-signed request from heroku
39,925,157
<p>I'm looking at the heroku documentation (<a href="https://devcenter.heroku.com/articles/s3-upload-python" rel="nofollow">https://devcenter.heroku.com/articles/s3-upload-python</a>) about making a direct upload to S3 using a pre-signed request from heroku. </p> <p>For the code below, are you expected to send the actual file to Heroku to obtain the pre-signed request or can you just send the file info (name, type, etc.)?</p> <pre><code>@app.route('/sign_s3/') def sign_s3(): S3_BUCKET = os.environ.get('S3_BUCKET') file_name = request.args.get('file_name') file_type = request.args.get('file_type') s3 = boto3.client('s3') presigned_post = s3.generate_presigned_post( Bucket = S3_BUCKET, Key = file_name, Fields = {"acl": "public-read", "Content-Type": file_type}, Conditions = [ {"acl": "public-read"}, {"Content-Type": file_type} ], ExpiresIn = 3600 ) return json.dumps({ 'data': presigned_post, 'url': 'https://%s.s3.amazonaws.com/%s' % (S3_BUCKET, file_name) }) </code></pre>
0
2016-10-07T20:17:16Z
39,934,319
<p>The code you posted uses only the file name and type to generate an S3 pre-signed URL, so it's not using the file.</p> <p>Once the server generates this S3 URL, it will send it to the client so it can use this URL to upload the file.</p> <p>So the answer is no, your file is not sent to Heroku, just the file info. The file will be directly sent from the client side to S3.</p> <p>More information on S3 pre-signed URLs can be found <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/PresignedUrlUploadObject.html" rel="nofollow">here</a></p>
0
2016-10-08T15:47:16Z
[ "python", "heroku", "amazon-s3" ]
Try Statement Error
39,925,214
<p>I am new to Python and I am importing Excel data into postgreSQL. I have blank whitespaces in my Excel for the columns for Traffic and Week_Ending. The Try statement seems to function fine for the Week_Ending but for the Traffic it throws out an error. I checked the Excel and the error is showing up due to the single blank whitespace in one of the cells. I thought it would work for both the columns but it doesn't for the Traffic. Can anyone provide assistance please.</p> <pre><code>import psycopg2 import xlrd import datetime book = xlrd.open_workbook("T:\DataDump\8888.xlsx") sheet = book.sheet_by_name("Builder_Traffic") database = psycopg2.connect (database = "***", user="*") cursor = database.cursor() delete = """Drop table if exists "Python".buildertraffic""" print (delete) mydata = cursor.execute(delete) cursor.execute('''CREATE TABLE "Python".buildertraffic (Builder_Name varchar(55), Traffic integer, Week_Ending date, Project_ID integer );''') print "Table created successfully" query = """INSERT INTO "Python".buildertraffic (Builder_Name, Traffic, Week_Ending, Project_ID) VALUES (%s, %s, %s, %s)""" for r in range(1, sheet.nrows): Builder_Name = sheet.cell(r,0).value Traffic = None try: Traffic = (sheet.cell(r,1).value) except: pass Week_Ending = None try: Week_Ending = xlrd.xldate.xldate_as_datetime(sheet.cell(r,2).value,book.datemode) except: pass Project_ID = sheet.cell(r,3).value values = (Builder_Name, Traffic, Week_Ending, Project_ID) cursor.execute(query, values) cursor.close() database.commit() database.close() print "" print "All Done! Bye, for now." print "" columns = str(sheet.ncols) rows = str(sheet.nrows) print "I just imported Excel into postgreSQL" </code></pre> <p>And the error shows up as :</p> <pre><code>Traceback (most recent call last): File "C:\Users\aqureshi\Desktop\Programming\PythonSQLNew\BuilderTraffic.py", line 47, in &lt;module&gt; DataError: invalid input syntax for integer: " " LINE 2: VALUES ('American Legend Homes', ' ', NULL, 2.0) ^ </code></pre>
0
2016-10-07T20:20:59Z
39,925,440
<p>You should be checking for a blank or empty string in that column:</p> <pre><code>traffic = sheet.cell(r, 1).value </code></pre> <p>I don't see in your code how you're actually executing the query but you should wrap traffic in int to parse an integer from a string: <a href="http://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python">How to convert strings into integers in Python?</a></p> <pre><code>try: traffic = int(sheet.cell(r, 1).value) except: traffic = -1 # or 0? some value to indicate this has NO traffic. </code></pre>
0
2016-10-07T20:37:48Z
[ "python", "excel" ]
AttributeError: module 'pkg_resources' has no attribute 'safe_name' oauthlib install
39,925,227
<p>I'm trying to install tweepy (and by extension oauthlib), and I'm getting the following error when attempting to install:</p> <pre><code>Collecting requests-oauthlib&gt;=0.4.1 (from tweepy) Using cached requests_oauthlib-0.7.0-py2.py3-none-any.whl Collecting oauthlib&gt;=0.6.2 (from requests-oauthlib&gt;=0.4.1-&gt;tweepy) Using cached oauthlib-2.0.0.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/t7/751h0y1102z99ysr6659yjcr0000gn/T/pip-build-aoklhwtw/oauthlib/setup.py", line 70, in &lt;module&gt; 'Topic :: Software Development :: Libraries :: Python Modules', File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/setuptools/dist.py", line 263, in __init__ self.patch_missing_pkg_info(attrs) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/setuptools/dist.py", line 246, in patch_missing_pkg_info key = pkg_resources.safe_name(str(attrs['name'])).lower() AttributeError: module 'pkg_resources' has no attribute 'safe_name' </code></pre> <p>Interestingly, the <code>/private/var/folders/t7/751h0y1102z99ysr6659yjcr0000gn/T/pip-build-aoklhwtw/oauthlib/</code> folder does not exist, so I can t even delete that/look at it closer.</p> <p>Any ideas what might cause this?</p>
1
2016-10-07T20:22:05Z
39,930,983
<p>Found the solution. I had to upgrade setuptools, so: </p> <pre><code>$ sudo pip install --upgrade setuptools </code></pre>
0
2016-10-08T09:50:24Z
[ "python" ]
Extracting multiple lines of strings
39,925,258
<h2>Update:</h2> <p>I spoke to a colleague about this and we came up with the following solution...</p> <pre><code>#!/usr/bin/python python in_file = open("small-output.txt", "rt") with open("output-new.txt", "wt") as txtfile: sentence = "" hit = False for each in in_file: if each.strip() == "Description": hit = False txtfile.write(sentence + "\n") sentence = "" if hit == True: sentence += " " + each.strip() if each.strip() == "Title": hit = True txtfile.close() in_file.close() </code></pre> <p>It's not a perfect/elegant solution in that there are problems writing out to a .csv file with all the inline commas. So, what I ended up doing was just writing out to a text file using the script above and then importing that into a .csv.</p> <p>Ideally, the output would look like </p> <blockquote> <p>This is the title of the thing, also foo.</p> </blockquote> <p>With that in mind, can anyone improve the code so that each captured sentence is a row in a spreadsheet? Or does anyone have a more elegant solution using Python 2.7?</p> <h2>End update:</h2> <p>I have been looking through StackExchange all morning and, while I have seen many similar solutions, I have yet to find one that exactly fits my parameters. I am attempting to write a script that parses a text file, copies multiple lines of text between two delimiters, and then pastes each string set into a .csv file. The lines in the text file look like:</p> <pre><code>a string ...... a string another string, a string Title This is the title of the thing, also foo. Description a string .......... another string </code></pre> <p>Specifically, I am looking to capture everything between 'Title' and 'Description', then write it out to a .csv file. </p> <p>This started off as a very large PDF (10,000+ pages) that has been exported to a text file using pdfminer and there are lots of instances of the delimeters; so, ideally, the output would be lots of rows of cells with some sentences in them.</p> <p>So far, I have used Python 2.7 and regular expressions, but am open to other *nix methods, e.g. awk, sed, grep, etc. </p> <p>Here are some of the non-working snippets I have tried...</p> <pre><code>#!/usr/bin/python python import re, csv text_file = open('test_file.txt') with open(text_file, 'wb') as fout: for result in re.findall('Description(.*?)Family', enb_document.read(), re.S): # fout.write(result) fout.close() </code></pre> <hr> <pre><code>def extractData(): filename = ("test_file.txt") infile = open(filename,'r') startdelim = 'Description' enddelim = 'Family' for x in infile.readlines(): x = x.strip() if x.startswith(startdelim): print &gt;&gt; sequence else: sequence = x if delim1.startswith(enddelim): infile.close() extractData() </code></pre> <p>Any ideas? Thanks in advance!</p>
1
2016-10-07T20:23:52Z
39,926,295
<pre><code>sed -n '/^Title$/,/^Description$/{//d;p}' file </code></pre> <p>outputs</p> <pre><code>This is the title of the thing. </code></pre>
0
2016-10-07T21:51:55Z
[ "python", "csv", "awk", "sed" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like this</p> <p>[ 'html', 'head', 'meta' ]</p> <p>However when I run the function below it returns an empty list []</p> <pre><code>def getTag(htmlList): tagList=[] for iterate, character in enumerate(htmlList): tagAppend = '' if character=='&lt;': for index, word in enumerate(htmlList): if index&gt;iterate: if character=='&gt;': tagList.append(tagAppend) break tagAppend += character return tagList </code></pre> <p>The program seem make sense to me? It creates an empty list (tagList) then it iterates through the list(htmlList) like the first list I posted.</p> <p>When iterating if it comes across a '&lt;' it then adds all characters above the index where it found the '&lt;' to a string called tagAppend. It then stops when it reaches a '>' which ends the tag. The tagAppend is then added to the tagList. It then clears tagList and redoes to the loop.</p>
0
2016-10-07T20:24:12Z
39,925,312
<p>I'm going to assume this is just an exercise for the sake of learning. Python has much better tools for parsing HTML (<a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/</a>) or strings (<a href="https://docs.python.org/2/library/re.html" rel="nofollow">https://docs.python.org/2/library/re.html</a>) in general.</p> <pre><code>def getTag(htmlList): tagList=[] for iterate, character in enumerate(htmlList): tagAppend = '' if character=='&lt;': for index, word in enumerate(htmlList): if index&gt;iterate: # use word here otherwise this will never be True if word=='&gt;': tagList.append(tagAppend) break # and here tagAppend += word return tagList </code></pre> <p>The key bug is the use of character instead of word. I think it will work fine otherwise. Although it is inefficient.</p> <p>We can also simplify. No need for nested for loops.</p> <pre><code>def getTag(htmlList): tagList=[] tag = "" for character in htmlList: if character == "&lt;": tag = "" elif character == "&gt;": tagList.append(tag) else: tag.append(character) return tagList </code></pre> <p>The above has some serious issues depending on what constraints are on the input data. It might be instructive to think through it and see if you can find them.</p> <p>We can also use built-ins like split and join to great affect as mentioned in the other answer.</p>
0
2016-10-07T20:28:29Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like this</p> <p>[ 'html', 'head', 'meta' ]</p> <p>However when I run the function below it returns an empty list []</p> <pre><code>def getTag(htmlList): tagList=[] for iterate, character in enumerate(htmlList): tagAppend = '' if character=='&lt;': for index, word in enumerate(htmlList): if index&gt;iterate: if character=='&gt;': tagList.append(tagAppend) break tagAppend += character return tagList </code></pre> <p>The program seem make sense to me? It creates an empty list (tagList) then it iterates through the list(htmlList) like the first list I posted.</p> <p>When iterating if it comes across a '&lt;' it then adds all characters above the index where it found the '&lt;' to a string called tagAppend. It then stops when it reaches a '>' which ends the tag. The tagAppend is then added to the tagList. It then clears tagList and redoes to the loop.</p>
0
2016-10-07T20:24:12Z
39,925,315
<p>That looks too complicated. Instead, join the list into a string, remove the opening angle brackets, and split on the closing angle brackets, remembering to discard the empty strings:</p> <pre><code>def get_tag(l): return [item for item in ''.join(l).replace('&lt;','').split('&gt;') if item] </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; l = ['&lt;', 'h', 't', 'm', 'l', '&gt;', '&lt;', 'h', 'e', 'a', 'd', '&gt;', '&lt;', 'm', 'e', 't', 'a', '&gt;'] &gt;&gt;&gt; get_tag(l) ['html', 'head', 'meta'] </code></pre>
1
2016-10-07T20:28:43Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like this</p> <p>[ 'html', 'head', 'meta' ]</p> <p>However when I run the function below it returns an empty list []</p> <pre><code>def getTag(htmlList): tagList=[] for iterate, character in enumerate(htmlList): tagAppend = '' if character=='&lt;': for index, word in enumerate(htmlList): if index&gt;iterate: if character=='&gt;': tagList.append(tagAppend) break tagAppend += character return tagList </code></pre> <p>The program seem make sense to me? It creates an empty list (tagList) then it iterates through the list(htmlList) like the first list I posted.</p> <p>When iterating if it comes across a '&lt;' it then adds all characters above the index where it found the '&lt;' to a string called tagAppend. It then stops when it reaches a '>' which ends the tag. The tagAppend is then added to the tagList. It then clears tagList and redoes to the loop.</p>
0
2016-10-07T20:24:12Z
39,925,436
<p>I think <code>re</code> would be a good choice.</p> <pre><code>def get_tag(l): return re.findall(r'&lt;([a-z]+)&gt;', ''.join(l)) get_tag(l) ['html', 'head', 'meta'] </code></pre>
0
2016-10-07T20:37:41Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Python Loop that gets html tags returning empty list instead of tags
39,925,262
<p>So I'm trying to make a function that will go through a list of html tags in a list as characters and return the tags. An example would be it would go through a list like below</p> <p>['&lt;', 'h', 't', 'm', 'l', '>', '&lt;', 'h', 'e', 'a', 'd', '>', '&lt;', 'm', 'e', 't', 'a', '>']</p> <p>and return a list like this</p> <p>[ 'html', 'head', 'meta' ]</p> <p>However when I run the function below it returns an empty list []</p> <pre><code>def getTag(htmlList): tagList=[] for iterate, character in enumerate(htmlList): tagAppend = '' if character=='&lt;': for index, word in enumerate(htmlList): if index&gt;iterate: if character=='&gt;': tagList.append(tagAppend) break tagAppend += character return tagList </code></pre> <p>The program seem make sense to me? It creates an empty list (tagList) then it iterates through the list(htmlList) like the first list I posted.</p> <p>When iterating if it comes across a '&lt;' it then adds all characters above the index where it found the '&lt;' to a string called tagAppend. It then stops when it reaches a '>' which ends the tag. The tagAppend is then added to the tagList. It then clears tagList and redoes to the loop.</p>
0
2016-10-07T20:24:12Z
39,925,449
<p>Your code is <strong>nearly correct</strong>, you only need to replace all appearance of <code>character</code> in the inner loop with <code>word</code>; <code>word</code> was never used in that inner loop:</p> <pre><code> ... for index, word in enumerate(htmlList): if index &gt; iterate: if word == '&gt;': # here tagList.append(tagAppend) break tagAppend += word # here ... </code></pre> <hr> <p>You could do without <code>enumerate</code> and a nested for loop with the following:</p> <pre><code>def get_tag(htmlList): tag_list = [] for x in htmlList: if x == '&lt;': tag = '' continue elif x == '&gt;': tag_list.append(tag) continue tag += x return tag_list </code></pre>
0
2016-10-07T20:38:37Z
[ "python", "html", "list", "if-statement", "for-loop" ]
Flask test doesn't populate request.authorization when username and password are URL encoded
39,925,335
<p>I'm trying to use the following test: </p> <pre><code>def post_webhook(self, payload, **kwargs): webhook_username = 'test' webhook_password = 'test' webhook_url = 'http://{}:{}@localhost:8000/webhook_receive' webhook_receive = self.app.post( webhook_url.format(webhook_username, webhook_password), referrer='http://localhost:8000', json=payload) return webhook_receive.status_code </code></pre> <p>However the main issue is <code>request.authorization</code> is <code>None</code>. Though if I launch the server and use <code>curl -X POST &lt;webhook_url&gt;</code> or <code>requests.post(&lt;webhook_url&gt;)</code>, then <code>request.authorization</code> is properly populated. </p> <p>Trying to figure out the main issue of how to fix this problem. </p>
0
2016-10-07T20:29:54Z
39,925,521
<p>Using the <a href="http://flask.pocoo.org/snippets/8/" rel="nofollow">snippet</a> code and the <a href="http://flask.pocoo.org/docs/0.11/testing/#testing" rel="nofollow">Flask Test Client</a>, the next pytest code works for me. The way I send the HTTP Basic Auth is the same way curl and HTTPie send it; in the <strong><code>Authorization</code></strong> header with the user and password encoded in <strong>base64</strong>.</p> <pre><code>import base64 from app import app def test_secret_endpoint(): client = app.test_client() # testing a route without authentication required rv = client.get('/') assert rv.status_code == 200 # testing a secured route without credentials rv = client.post('/secret-page') assert rv.status_code == 401 # testing a secured route with valid credentials value = base64.encodestring('admin:secret').replace('\n', '') headers = {'Authorization': 'Basic {}'.format(value)} rv = client.post('/secret-page', headers=headers) assert rv.status_code == 200 assert 'This is secret' in rv.data </code></pre> <p>The route definitions are:</p> <pre><code>@app.route('/') def index(): return 'Hello World :)' @app.route('/secret-page', methods=['POST']) @requires_auth def secret_page(): return 'This is secret' </code></pre> <p>The request header sending the credentials looks something like this:</p> <pre><code>POST /secret-page HTTP/1.1 Accept: */* Authorization: Basic YWRtaW46c2VjcmV0 Connection: keep-alive Content-Length: 0 Host: localhost:5000 ... </code></pre>
1
2016-10-07T20:43:40Z
[ "python", "testing", "flask" ]
Django: Dynamic inline forms with filter upon user selection
39,925,382
<p>I have created these models:</p> <pre><code>class Service(models.Model): name = models.CharField(blank=False, max_length=200)code here class Monitor(models.Model): name = models.CharField(blank=False, max_length=100) services = models.ManyToManyField(Service, related_name='monitors') class Student(models.Model): name = models.CharField(blank=False, max_length=100) class ServiceMonitors(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) service = models.ForeignKey(Service, on_delete=models.CASCADE) monitors = models.ManyToManyField(Monitor) </code></pre> <p>These models represent a company that offer many services to students. Monitors that work for this company are assigned to students who need the service they offer. A monitor can offer many services and have many students for every one of them. Also, a student can have many services and monitors. </p> <p>Let's suppose the we have 3 services, s1, s2 and s3. When we create a new Monitor we assign him/her some of these services, let's say s1 and s3. Then, when we create a new Student, we should be able to choose which services and monitors the student will have.</p> <p>My problem here is that I need a form to create the student (name, phone, etc...) that allows me to:</p> <ol> <li>Select a service from a dropdown control </li> <li>Once a service is selected, the form must show the Monitors that offer that service, so I can choose one or more of them (checkboxes). </li> <li>A + button to create/show a new form to repeat the process, so I can choose a new service and the related Monitors.</li> </ol> <p>I'm very new to Django. I've been able to create an inline form in the user creation form, but i'm stuck here. I have now a dropdown control to select a service, and a ModelMultipleChoiceField with a CheckboxSelectMultiple widget which shows all Monitors. From here I need to know how to filter these Monitors when the user selects a service, and how to add new forms to select new services/monitors.</p>
1
2016-10-07T20:34:01Z
39,925,507
<p>This likely can not be managed within the Django forms framework which is very limited in functionality. It allows you to use a filtered queryset for selections in a ModelChoiceDropDown (I think that's the name) but filtering after a selection isn't possible this way. Django's forms are generated and sent as HTML which can not be made to filter without many modifications.</p> <p>The way you would likely do this is to set up a REST interface (See Django Rest Framework or Django-Tastypie) and link your dropdowns to that using a front end framework of your choosing (I prefer Backbone.js, but there are many options). The idea being that once you select a service the subsequent dropdowns will add a filter to their requests to only show the Monitors that offer that service. </p> <p>If you wish to keep using Django Forms you can, but you'll need to extend the default fields to get this sort of functionality.</p> <p>This is a fairly big rabbit hole and I don't have any resources off the cuff to point you toward. But reading up about REST interfaces is a good start.</p>
0
2016-10-07T20:43:02Z
[ "python", "django", "forms", "inline-formset" ]
Bizzare matplotlib behaviour in displaying images cast as floats
39,925,420
<p>When a regular RGB image in range (0,255) is cast as float, then displayed by matplotlib, the image is displayed as negative. If it is cast as uint8, it displays correctly (of course). It caused me some trouble to figure out what was going on, because I accidentally cast one of images as float. </p> <p>I am well aware that when cast as float, the image is expected to be in range (0,1), and sure enough, when divided by 255 the image displayed is correct. But, why would an image in range (0,255) that is cast as float displayed as negative? I would have expected either saturation (all white) or automatically inferred the range from the input (and thus correctly displayed)? If either of those expected things happened, I would have been able to debug my code quicker. I have included the required code to reproduce the behaviour. Does anyone have insight on why this happens?</p> <pre><code> import numpy as np import matplotlib.pyplot as plt a = np.random.randint(0,127,(200,400,3)) b = np.random.randint(128,255,(200,400,3)) img=np.concatenate((a,b)) # Top should be dark ; Bottom should be light plt.imshow(img) # Inverted plt.figure() plt.imshow(np.float64(img)) # Still Bad. Added to address sascha's comment plt.figure() plt.imshow(255-img) # Displayed Correctly plt.figure() plt.imshow(np.uint8(img)) # Displayed Correctly plt.figure() plt.imshow(img/255.0) # Displays correctly </code></pre>
2
2016-10-07T20:36:31Z
39,925,945
<p>I think you are on a wrong path here as you are claiming, that <code>np.random.randint()</code> should return an float-based array. <strong>It does not!</strong> (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html" rel="nofollow">docs</a>)</p> <p><strong>This means</strong>:</p> <p>Your first plot is calling imshow with an <strong>numpy-array of dtype=int64</strong>. This is not allowed as seen <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">here</a>!</p> <p>The only allowed dtypes for your dimensions are described as: (<a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.imshow" rel="nofollow">see docs</a>):</p> <pre><code>MxNx3 – RGB (float or uint8 array) # there are others # -&gt; this one applies to your dims! </code></pre> <p>The only valid calls to imshow in your example are number 3 and 4 (while 1 and 2 are invalid)!</p> <p>Listing:</p> <ul> <li><code>plt.imshow(img)</code> <strong>not ok</strong> as dtype=int64</li> <li><code>plt.imshow(255-img)</code> <strong>not ok</strong> as dtype=int64</li> <li><code>plt.imshow(np.uint8(img))</code> <strong>ok</strong> as dtype=uint8 (and compatible dims)</li> <li><code>plt.imshow(img/255.0)</code> <strong>ok</strong> as dtype=float (and compatible dims)</li> </ul> <p><strong>Remark:</strong></p> <p>If this makes you nervous, you could checkout <a href="http://scikit-image.org/" rel="nofollow">scikit-image</a> which is by design a bit more cautious about the internal representation of images (during custom-modifications and the resulting types). The internal data-structures are still numpy-arrays!</p>
1
2016-10-07T21:18:38Z
[ "python", "matplotlib" ]
Bizzare matplotlib behaviour in displaying images cast as floats
39,925,420
<p>When a regular RGB image in range (0,255) is cast as float, then displayed by matplotlib, the image is displayed as negative. If it is cast as uint8, it displays correctly (of course). It caused me some trouble to figure out what was going on, because I accidentally cast one of images as float. </p> <p>I am well aware that when cast as float, the image is expected to be in range (0,1), and sure enough, when divided by 255 the image displayed is correct. But, why would an image in range (0,255) that is cast as float displayed as negative? I would have expected either saturation (all white) or automatically inferred the range from the input (and thus correctly displayed)? If either of those expected things happened, I would have been able to debug my code quicker. I have included the required code to reproduce the behaviour. Does anyone have insight on why this happens?</p> <pre><code> import numpy as np import matplotlib.pyplot as plt a = np.random.randint(0,127,(200,400,3)) b = np.random.randint(128,255,(200,400,3)) img=np.concatenate((a,b)) # Top should be dark ; Bottom should be light plt.imshow(img) # Inverted plt.figure() plt.imshow(np.float64(img)) # Still Bad. Added to address sascha's comment plt.figure() plt.imshow(255-img) # Displayed Correctly plt.figure() plt.imshow(np.uint8(img)) # Displayed Correctly plt.figure() plt.imshow(img/255.0) # Displays correctly </code></pre>
2
2016-10-07T20:36:31Z
39,936,311
<p>In the sources, in <code>image.py</code>, in the <code>AxesImage</code> class (what <code>imshow</code> returns) a method <code>_get_unsampled_image</code> is called at some point in the drawing process. The relevant code starts on line 226 for me (matplotlib-1.5.3):</p> <pre><code>if A.dtype == np.uint8 and A.ndim == 3: im = _image.frombyte(A[yslice, xslice, :], 0) im.is_grayscale = False else: if self._rgbacache is None: x = self.to_rgba(A, bytes=False) # Avoid side effects: to_rgba can return its argument # unchanged. if np.may_share_memory(x, A): x = x.copy() # premultiply the colors x[..., 0:3] *= x[..., 3:4] x = (x * 255).astype(np.uint8) self._rgbacache = x </code></pre> <p>So the type and size of the input <code>A</code> get checked:</p> <pre><code>if A.dtype == np.uint8 and A.ndim == 3: </code></pre> <p>in which case there is no preprocessing. Otherwise, without checking the range of the input, you ultimately have a multiplication by 255 and a cast to <code>uint8</code>:</p> <pre><code>x = (x * 255).astype(np.uint8) </code></pre> <p>And we know what to expect if <code>x</code> is from 0 to 255 instead of 0 to 1:</p> <pre><code>In [1]: np.uint8(np.array([1,2,128,254,255])*255) Out[1]: array([255, 254, 128, 2, 1], dtype=uint8) </code></pre> <p>So light becomes dark. That this inverts the image is probably not a planned behavior as I think you assume.</p> <p>You can compare the values of <code>_rgbacache</code> in the object returned from <code>imshow</code> for each of your input cases to observe the result, e.g. <code>im._rbacache</code> where <code>im = plt.imshow(np.float64(img))</code>.</p>
1
2016-10-08T19:09:28Z
[ "python", "matplotlib" ]
join/search/sum in Pandas Python
39,925,423
<p>i'm new to Panda and trying to learn it, I have a DataFrame in Panda with 3 different columns:</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 2 ' ' Bob 7/18/2014 1 ' ' Alice 5/5/2014 3 ' ' Bob 8/10/2014 5 ' ------------------------------ </code></pre> <p>I want to sum up the 'C' columns for each person per month, so the desired result would be like :</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 5 ' ' Bob 7/18/2014 1 ' ' Bob 8/10/2014 5 ' ------------------------------ </code></pre> <p>what is the best way to do this in Panda.</p> <p>if my question is repeated please re-direct me to other question i couln't find it maybe because i wasn't sure what to look for. thank you</p>
2
2016-10-07T20:36:47Z
39,925,456
<p>add a column specifying the month</p> <pre><code>df['month'] = df['b'].month # assuming it's a datetime object </code></pre> <p>then groupby and sum</p> <pre><code>df.groupby(['a','month']).sum() </code></pre>
0
2016-10-07T20:39:07Z
[ "python", "pandas" ]
join/search/sum in Pandas Python
39,925,423
<p>i'm new to Panda and trying to learn it, I have a DataFrame in Panda with 3 different columns:</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 2 ' ' Bob 7/18/2014 1 ' ' Alice 5/5/2014 3 ' ' Bob 8/10/2014 5 ' ------------------------------ </code></pre> <p>I want to sum up the 'C' columns for each person per month, so the desired result would be like :</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 5 ' ' Bob 7/18/2014 1 ' ' Bob 8/10/2014 5 ' ------------------------------ </code></pre> <p>what is the best way to do this in Panda.</p> <p>if my question is repeated please re-direct me to other question i couln't find it maybe because i wasn't sure what to look for. thank you</p>
2
2016-10-07T20:36:47Z
39,925,482
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">groupby</a> function like:</p> <pre><code>df.groupby(['a', 'b']).sum() </code></pre> <blockquote> <p>Group series using mapper (dict or key function, apply given function to group, return result as series) or by a series of columns.</p> </blockquote>
0
2016-10-07T20:40:55Z
[ "python", "pandas" ]
join/search/sum in Pandas Python
39,925,423
<p>i'm new to Panda and trying to learn it, I have a DataFrame in Panda with 3 different columns:</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 2 ' ' Bob 7/18/2014 1 ' ' Alice 5/5/2014 3 ' ' Bob 8/10/2014 5 ' ------------------------------ </code></pre> <p>I want to sum up the 'C' columns for each person per month, so the desired result would be like :</p> <pre><code> a b c ----------------------------- ' Alice 5/5/2014 5 ' ' Bob 7/18/2014 1 ' ' Bob 8/10/2014 5 ' ------------------------------ </code></pre> <p>what is the best way to do this in Panda.</p> <p>if my question is repeated please re-direct me to other question i couln't find it maybe because i wasn't sure what to look for. thank you</p>
2
2016-10-07T20:36:47Z
39,925,716
<p>The most efficient way is to first make sure your date column is of a <code>datetime</code> type:</p> <pre><code>&gt;&gt;&gt; df2 a b c 0 Alice 5/5/2014 2 1 Bob 7/18/2014 1 2 Alice 5/9/2014 3 3 Bob 8/10/2014 5 &gt;&gt;&gt; df2['b'] = pd.to_datetime(df2.b) </code></pre> <p>Then, index the <code>DataFrame</code> by the date column:</p> <pre><code>&gt;&gt;&gt; df2.set_index('b',inplace=True) &gt;&gt;&gt; df2 a c b 2014-05-05 Alice 2 2014-07-18 Bob 1 2014-05-09 Alice 3 2014-08-10 Bob 5 </code></pre> <p>Then use <code>groupby</code>:</p> <pre><code>&gt;&gt;&gt; df2.groupby(['a',df2.index.month]).sum() c a Alice 5 5 Bob 7 1 8 5 &gt;&gt;&gt; </code></pre> <p>And you can always go back to your original index:</p> <pre><code>&gt;&gt;&gt; df2.reset_index(inplace=True) &gt;&gt;&gt; df2 b a c 0 2014-05-05 Alice 2 1 2014-07-18 Bob 1 2 2014-05-09 Alice 3 3 2014-08-10 Bob 5 </code></pre>
3
2016-10-07T20:59:08Z
[ "python", "pandas" ]
Keras custom metric gives incorrect tensor shape
39,925,462
<p>I want to monitor the dimension of <code>y_pred</code> by defining my own custom metric (using the Theano backend)</p> <pre><code>def shape_test(y_true, y_pred): return K.shape(y_pred)[0] </code></pre> <p>I was assuming that the dimension of <code>y_pred</code> in the custom metric function is equal to the mini batch size. However, I get weird output. See a small reproducible example below.</p> <pre><code>#imports and definitions import numpy numpy.random.seed(1234) import keras.backend as K from keras.models import Sequential from keras.layers import Dense from keras.optimizers import SGD neuron_num=20 dim_input=2 #batch size will be important below! batch_size=2048 TT=int(1e4) #sample data X=numpy.random.randn(TT,dim_input) eps=numpy.random.randn(TT) Y=0.3*X[:,0]+0.5*X[:,1]+eps x={"is":X[:(TT/2),:],"os":X[(TT/2+1):,:]} y={"is":Y[:(TT/2)],"os":Y[(TT/2+1):]} </code></pre> <p>This is the custom metric as given above</p> <pre><code>def shape_test(y_true, y_pred): return K.shape(y_pred)[0] </code></pre> <p>Now define a simple NN</p> <pre><code>sgd=SGD(lr=1e-2,nesterov=True) model=Sequential() model.add(Dense(neuron_num, input_dim=x["is"].shape[1], init="glorot_normal", activation="tanh")) model.add(Dense(neuron_num,init="glorot_normal",activation="tanh")) model.add(Dense(1,init="glorot_normal",activation="linear")) model.compile(loss="mean_squared_error", optimizer=sgd, metrics=["mean_squared_error",shape_test]) model.fit(x["is"], y["is"], validation_data=(x["os"],y["os"]), nb_epoch=1, batch_size=batch_size, verbose=False).history </code></pre> <p>This gives</p> <pre><code>#{'loss': [1.834826689338684], # 'mean_squared_error': [1.834826689338684], # 'shape_test': [1841], # 'val_loss': [1.4931119817522769], # 'val_mean_squared_error': [1.4931119817522769], # 'val_shape_test': [1841.1716343268654]} </code></pre> <p>I would have expected to see <code>'shape_test': [2048]</code> instead of <code>'shape_test': [1841]</code>, as the batch size is 2048.</p> <p>This seems very weird. Is this possibly a bug? I am using <code>Python 2.7.6</code>, <code>Keras==1.0.8</code>, <code>Theano==0.8.2</code> and the CPU.</p>
1
2016-10-07T20:39:25Z
39,930,509
<p>Using <code>neuron_num=2000</code> and <code>verbose=True</code>, here is what I was able to produce with your example:</p> <pre><code>Epoch 1/1 2048/5000 [========&gt;............] - ETA: 9s - loss: 1.4507 - shape_test: 2048.000 4096/5000 [=================&gt;...] - ETA: 3s - loss: 1.3577 - shape_test: 2048.000 5000/5000 [=====================] - 26s - loss: 1.3087 - shape_test: 1841.1648 - val_shape_test: 1841.1716 </code></pre> <p>As you can see, your shape function seems to work fine. But since batch_size is not a divisor of the training set size, the last batch only contains 904 examples. I can't seem to be able to guess how Keras comes up with 1841 at the minute, but it's probably not complicated.</p> <p>Another try with <code>batch_size=2500</code> looks better:</p> <pre><code>2500/5000 [==========&gt;..........] - ETA: 9s - loss: 1.4292 - shape_test: 2500.0000 5000/5000 [=====================] - 24s - loss: 1.3311 - shape_test: 2500.0000 - val_shape_test: 2499.5001 </code></pre>
1
2016-10-08T08:54:26Z
[ "python", "python-2.7", "theano", "keras" ]
Indexing a ndarray - 1 item is stored differently to >1
39,925,512
<p>I'm using <code>genfromtxt</code> to import data from a txt file.</p> <p>This data is imported into an ndarray, as per <code>genfromtxt</code></p> <p>Normally, this text file has many lines of data to inport, meaning that the ndarray is like this:</p> <pre><code>array([ ('2016-04-17T00:08:42.273000Z', '2016-04-17T00:08:50.595000Z', '2016-04-17T00:08:58.378391Z', '2016-04-17T00:08:58.840273Z', '2016-04-17T00:09:05.670000Z', '2016-04-17T00:09:06.115000Z', '2016-04-17T00:09:07.155000Z', '2016-04-17T00:09:06.804999Z', '2016-04-17T00:09:08.488391Z', '2016-04-17T00:09:14.890273Z', '2016-04-17T00:09:11.648393Z', 1.702756, 10, 3.959), ('2016-04-17T01:11:11.393000Z', '2016-04-17T01:11:19.715000Z', '2016-04-17T01:11:27.498391Z', '2016-04-17T01:11:27.960273Z', '2016-04-17T01:11:34.790000Z', '2016-04-17T01:11:35.235000Z', '2016-04-17T01:11:36.275000Z', '2016-04-17T01:11:35.924999Z', '2016-04-17T01:11:37.608391Z', '2016-04-17T01:11:44.010273Z', '2016-04-17T01:11:40.768393Z', 3.084912, 10, 3.423), ('2016-05-20T19:10:42.883000Z', '2016-05-20T19:10:51.205000Z', '2016-05-20T19:10:58.978393Z', '2016-05-20T19:10:59.441114Z', '2016-05-20T19:11:06.280000Z', '2016-05-20T19:11:06.705000Z', '2016-05-20T19:11:07.725000Z', '2016-05-20T19:11:07.405000Z', '2016-05-20T19:11:09.108393Z', '2016-05-20T19:11:15.481160Z', '2016-05-20T19:11:12.258393Z', 1.956513, 10, 3.078)], dtype=[('origintime', 'S27'), ('JAMA', 'S27'), ('FLF1', 'S27'), ('MAG1', 'S27'), ('AV18', 'S27'), ('AV21', 'S27'), ('AMA1', 'S27'), ('BV15', 'S27'), ('PPLP', 'S27'), ('HPAL', 'S27'), ('ILLI', 'S27'), ('stackedcorr', '&lt;f8'), ('totalstations', '&lt;i8'), ('magestimate', '&lt;f8')]) </code></pre> <p>But when the text file only has one line, the ndarray is like this (note the lack of square-brackets like the previous example):</p> <pre><code>array(('2016-05-08T03:13:02.841000Z', '2016-05-08T03:13:10.705000Z', '1900-01-01T00:00:00.000000Z', '2016-05-08T03:13:14.099997Z', '2016-05-08T03:13:14.938393Z', '2016-05-08T03:13:29.228391Z', '2016-05-08T03:13:31.868393Z', '2016-05-08T03:13:31.909995Z', '2016-05-08T03:13:36.920000Z', '2016-05-08T03:13:37.080000Z', '2016-05-08T03:13:37.635000Z', 9.0, 9, 3.41), dtype=[('origintime', 'S27'), ('JAMA', 'S27'), ('CABP', 'S27'), ('MAG1', 'S27'), ('FLF1', 'S27'), ('PAC1', 'S27'), ('GGPT', 'S27'), ('PINO', 'S27'), ('SUCR', 'S27'), ('BNAS', 'S27'), ('SLOR', 'S27'), ('stackedcorr', '&lt;f8'), ('totalstations', '&lt;i8'), ('magestimate', '&lt;f8')]) </code></pre> <p><strong>The difference is that the multi-line input is an array, while the one-line input is not.</strong> </p> <p>This messes up indexing as I cannot loop over <code>results['origintime'][i]</code> because of the one-line input possibility.</p> <p><em>How can I convert the ndarray of the one-line input (no square-brackets) to be a len=1 list, meaning it has the same format as the multi-line ndarrays?</em></p> <p>Thanks</p>
0
2016-10-07T20:43:07Z
39,925,958
<p>Numpy actually is loading in the file as an array, but it is a "0-dimensional" array. That is, <code>results.ndim</code> will return <code>0</code>. You can convert it to a 1-dimensional array with 1 element by doing <code>results.reshape((1,))</code>.</p> <p>If you are reading in a file and you don't know whether it will have one or multiple lines beforehand, you can do:</p> <pre><code>results = np.genfromtxt(filename) if results.ndim==0: results.reshape((1,)) </code></pre>
1
2016-10-07T21:19:53Z
[ "python", "multidimensional-array", "indexing", "genfromtxt" ]
How to use regex to replace a particular field in a formatted file
39,925,562
<p>I have a file with following formatted file I need to parse</p> <pre><code>field_1 { field_2 { .... } field_i_want_to_replace { .... } .... } .... </code></pre> <p>I need a pre-processor in python to parse those files and delete the content of some particular fields. In the above example, the processed file will look like:</p> <pre><code>field_1 { field_2 { .... } field_i_want_to_replace {} .... } .... </code></pre> <p>So the preprocessor needs to locate the particular field "field_i_want_to_replace" and then delete the contents between the brackets. I'm trying to do the following but the regex can't parse the file correctly.</p> <pre><code>regex = r'(field_i_want_to_replace )\{.*?\}' print re.sub(regex,'field_i_want_to_replace {}', file_in_string) </code></pre> <p>Is there sth wrong with the regex I'm using?</p>
0
2016-10-07T20:47:31Z
39,925,787
<p>Your <code>.</code> character is not matching any newlines, so it will not continue after the left curly bracket.</p> <p>To change this behavior, just add the <a href="https://docs.python.org/2/library/re.html#re.DOTALL" rel="nofollow"><code>re.DOTALL</code> flag</a> (or <code>re.S</code>) as a keyword arg to your <code>re.sub</code>:</p> <pre><code>&gt;&gt;&gt; regex = r'(field_i_want_to_replace )\{.*?\}' &gt;&gt;&gt; print re.sub(regex,'field_i_want_to_replace {}', file_in_string, flags=re.DOTALL) field_1 { field_2 { .... } field_i_want_to_replace {} .... } </code></pre>
2
2016-10-07T21:05:11Z
[ "python", "regex" ]
Server/Client application TimeoutError on LAN
39,925,658
<p>I have two programs: server.py and client.py. I need to be able to use server.py in my main PC, and client.py from my laptop. When I run them, I get the following error from client.py:</p> <pre><code>TimeoutError: [WinError 10060] </code></pre> <p>I have disabled firewalls in both my PC (that runs Windows 7) and my laptop (that runs Windows 8).</p> <p>How do I get them to connect?</p> <p>Some things that I have tried:</p> <ul> <li>Creating Firewall port rules, on the PC.</li> <li>Disabling the firewall in both computers.</li> <li>Using different ports.</li> <li>Changing the server address from "localhost" to socket.gethostname(), this changes the error from <code>TimeoutError</code> to <code>ConnectionRefusedError</code>.</li> </ul> <p>The IP for my PC is 192.168.0.2, and I am sure of this because I have an Apache server running in port 80, and that one works (I can access that from my laptop).</p> <p>Python versions: PC: 3.5.2, Laptop: 3.4.1</p> <h2>Code</h2> <p>server.py:</p> <pre><code>import socket import threading server_port = 2569 server_address = "localhost" class ClientThread(threading.Thread): def __init__(self, client_info): super(ClientThread, self).__init__() self.client_info = client_info def run(self): socket = self.client_info[0] bytes_received = socket.recv(100) print(bytes_received.decode("utf-8")) server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.bind((server_address, server_port)) server_socket.listen(5) while True: new_client = server_socket.accept() ClientThread(new_client).run() </code></pre> <p>client.py:</p> <pre><code>import socket server_port = 2569 server_address = "192.168.0.2" server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.connect((server_address, server_port)) server_socket.send(b"message") </code></pre>
1
2016-10-07T20:54:36Z
39,925,933
<p>You just need to change the <code>localhost</code> or <code>socket.gethostname()</code> in the <code>server.py/client.py</code> scripts to the actual <strong>internal ip</strong> address of the server. Then it will work! </p> <p>If you want to learn more why this happens I recommend reading <a href="http://superuser.com/questions/196893/difference-between-localhost-and-the-ip-address">this post</a> which explains in deep the differences between <code>localhost/127.0.0.1</code> and the <code>internal ip</code> of a machine, which are falsely considered to be the same thing, but in fact they are not.</p>
1
2016-10-07T21:17:18Z
[ "python", "sockets", "networking", "lan" ]
Subprocess call bash script
39,925,659
<p>Im trying to call a python class which contains a subprocess call for a bashscript.</p> <pre><code>def downloadURL(self,address): call(['bash youtube2mp3_2.sh', str(address)],shell=True) </code></pre> <p>This is the bash script:</p> <pre><code>#!/bin/bash # Script for grabbing the audio of youtube videos as mp3. address=$1 user_name=$2 # todo path_music=/home/pi/music_loaded echo Address : $address #title=$(youtube-dl --get-title $address) youtube-dl --no-playlist -x --audio-format mp3 -o $path_music/'%(title)s.% (ext)s' $address echo ----Download finshed---- </code></pre> <p>When calling the method downloadURl I pass a static youtube link. Printing him in the python method returns it correctly.</p> <p>But the echo in the script return "" in consonsole. So I think the Argument which I`am trying to pass is not passed to the script. </p> <p>Does anyone have a Idea?</p>
0
2016-10-07T20:54:38Z
39,925,706
<p>either you pass the arguments as a string</p> <pre><code>def downloadURL(self,address): call('bash youtube2mp3_2.sh '+address) </code></pre> <p>or as a list</p> <pre><code>def downloadURL(self,address): call(['bash','youtube2mp3_2.sh',address]) </code></pre> <p>both work, but the latter is better so space chars are quoted if necessary.</p> <p>(BTW since you prefix your command by <code>bash</code> you don't need the <code>shell=True</code>)</p> <p>Third alternative: let the system choose which interpretor to use according to the shebang:</p> <pre><code>def downloadURL(self,address): call(['youtube2mp3_2.sh',address],shell=True) </code></pre> <p>PS: The args you're passing <code>['bash youtube2mp3_2.sh', str(address)]</code> make <code>call</code> add quotes to the first one because it contains spaces, well I don't know what the hell happens on Linux, but I tested on windows and I got a "syntax error", nothing got executed. (Works with the fixed code, I have MSYS <code>bash</code> in my path)</p> <p>PS2: why calling such a simple bash script from python. Do it in python:</p> <pre><code>def downloadURL(self,address): path_music="/home/pi/music_loaded" rc=call(["youtube-dl","--no-playlist","-x","--audio-format","mp3","-o",os.path.join(path_music,'%(title)s.% (ext)s'),address]) if rc==0: print("Download OK") </code></pre>
2
2016-10-07T20:58:07Z
[ "python", "bash", "youtube-dl" ]