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
Deleting row from database if value =? in SQLAlchemy
38,920,791
<p>I have 2 separate SQL tables in the same <code>.db</code> file. This is using SQLite.</p> <p><strong>table 1</strong></p> <pre><code>column1 column2 ggg values ttt values yyy values hhh values ddd values jjj values </code></pre> <p><strong>table 2</strong></p> <pre><code>col...
1
2016-08-12T14:47:52Z
38,921,048
<p>Thanks to Jon CLements, I realized my mistake of not opening the engine.. Thus getting errors for it. :( </p>
0
2016-08-12T15:02:17Z
[ "python", "sqlite", "sqlalchemy" ]
GNU/Linux - Python3 - PySerial: How to send data over USB connection?
38,920,876
<p>I have 2 questions about Python3 and PySerial (serial module).</p> <p>I must send data over USB port to my IC's stand-alone ATMega32. A possible snippet code:</p> <pre><code>import serial data=serial.Serial(port, speed) first_data=99.7 # Float point data. second_data=100 # Only int data like 10, 345, 2341 and so ...
1
2016-08-12T14:52:51Z
38,921,081
<ol> <li>converting float, int or most other non-strings to strings by using the <a href="https://docs.python.org/3/library/functions.html#func-str" rel="nofollow">string function</a>, e.g. in your case </li> </ol> <p><code>str(first_data)</code></p> <p>would output '99.7' (a string).</p> <ol start="2"> <li>by using...
1
2016-08-12T15:04:22Z
[ "python", "linux", "python-3.x", "pyserial" ]
Using the SuiteCRM/SugarCRM REST endpoint version 4.1
38,920,889
<p>I'm having a bad time trying to get the REST API to behave. Yes, the code is Python, but if you know PHP or anything else, I suspect you'll be able to help.</p> <p>I wrote two functions. 1 is a helper.</p> <pre><code>def post(self, method, parameters): args = collections.OrderedDict() args['method'] = me...
0
2016-08-12T14:53:35Z
38,931,338
<p>The reason for limit by 20 results is because it is limit on the list view of SuiteCRM and the list view is paginated for performance concerns. </p> <p>Typically, you would want to paginate. you really should only pull through the fields you need, as this reduces the bandwidth required to pull the data across. The ...
0
2016-08-13T09:35:23Z
[ "php", "python", "sugarcrm", "suitecrm" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delim...
0
2016-08-12T14:53:54Z
38,921,175
<p>If the spaces in <code>CheckList</code> are not going to be consistent (as indeed they are not in the example you gave), I would recommend first running <code>CheckList = CheckList.replace(" ","")</code> to eliminate all spaces. Otherwise be sure to <code>split</code> using <code>" | "</code> or <code>", "</code>.</...
1
2016-08-12T15:09:03Z
[ "python", "string", "list", "for-loop", "replace" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delim...
0
2016-08-12T14:53:54Z
38,921,252
<p>First of all, it looks like you're checking the wrong index in <code>i.split(",")</code>. Python is 0-indexed, so when you reference <code>i.split(",")[0]</code>, you are checking the left side of the comma (the key in this case), when it looks like you want it to check the right side (the fruit). </p> <p>Second, m...
1
2016-08-12T15:13:39Z
[ "python", "string", "list", "for-loop", "replace" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delim...
0
2016-08-12T14:53:54Z
38,921,707
<p>First, get a mapping from <code>CheckList</code>, then look up it from <code>box</code>:</p> <pre><code>box = ["apple","orange","banana", "water"] CheckList = "1, orange | 2, apple | 3,banana | 4,milk" d = dict(reversed(items.split(',')) for items in CheckList.replace(' ', '').split('|')) foundItems = [d[x] if x i...
2
2016-08-12T15:37:28Z
[ "python", "string", "list", "for-loop", "replace" ]
How to Access Each Item in A Delimited String to Find its Matching Item in a List?
38,920,896
<p>I have this list:</p> <pre><code>box = ["apple","orange","banana", "water"] </code></pre> <p>And this string: </p> <pre><code>CheckList = "1, orange | 2, apple | 3, banana | 4, milk" </code></pre> <p><strong>Note:</strong> The string has <code>"|"</code> and <code>","</code> delimiters. The <code>|</code> delim...
0
2016-08-12T14:53:54Z
38,922,181
<p>Good answers here, thought I'd offer this two-liner.</p> <pre><code>&gt;&gt;&gt; d = {i.split(',')[1].strip():i.split(',')[0] for i in checkList.split('|')} &gt;&gt;&gt; print [d[key].strip() if key in d else key for key in box] ['2', '1', '3', 'water'] </code></pre>
1
2016-08-12T16:02:14Z
[ "python", "string", "list", "for-loop", "replace" ]
How to only get the last directory from readlink
38,920,908
<p>I'm doing a project at work were I need to get the version of Java for 100's of servers. I been using readlink, but that gives me full path for the link. I'm trying to figured out a way to only get the last directory using Python.</p> <pre><code>&gt;&gt;&gt; f = os.system('readlink /dir/dir/dir/java') /dir/dir/dir...
0
2016-08-12T14:54:26Z
38,923,715
<p>After some further research I figured it out. Once I got the output from <code>os.readlink</code> I then took the output and got the basename:</p> <pre><code>&gt;&gt;&gt; f = os.readlink('/dir/dir/dir/java') &gt;&gt;&gt; java_version = os.path.basename(f) 'java' </code></pre>
0
2016-08-12T17:43:16Z
[ "python", "readlink" ]
Changing numpy structured array dtype names and formats
38,920,939
<p>I am doing some work with structured arrays in numpy (that I will eventually convert to a pandas dataframe).</p> <p>Now, I generate this structured array by reading in some data (actually memmapping some data) and then filtering it by user specified constraints. I then want to convert this data out of the form tha...
2
2016-08-12T14:55:46Z
38,922,842
<p>There is a library of functions designed to work with <code>recarray</code> (and thus structured arrays). It's kind of hidden so I'll have do a search to find it. It has functions for renaming fields, adding and deleting fields, etc. The general pattern of action is to make a new array with the target dtype, and ...
1
2016-08-12T16:41:58Z
[ "python", "python-3.x", "numpy", "structured-array" ]
How to use broadcasting to speed up this code?
38,920,957
<p>I have the following multi-dimensional array. The first axis denotes a 3-dimensional vector. I want to calculate the 3-by-3 matrix x⋅x' for each of those.</p> <p>My current solution:</p> <pre><code>arr.shape # (3, 64, 64, 33, 187) dm = arr.reshape(3,-1) dm.shape # (3, 25276416) cov = np.empty((3,3,dm.shape[1])...
0
2016-08-12T14:56:46Z
38,921,145
<p>Well you are not really reducing any axes with that matrix-multiplication using <code>np.dot</code> and it's just broadcasted elementwise multiplication there. So, you can simply use <code>NumPy broadcasting</code> for the whole thing, like so -</p> <pre><code>cov = dm[:,None]*dm </code></pre> <p>Or use it directl...
1
2016-08-12T15:07:27Z
[ "python", "numpy", "numpy-broadcasting" ]
django - python: failed using reverse : no reverse match
38,921,087
<p>I have the following Views:</p> <pre><code>def default_new (request): if request.method == "POST": post = EquipmentForm(request.POST) if form.is_valid(): post.save() return HttpResponseRedirect(reverse('calbase:default_detail', args=(id,))) else: form = Equipm...
1
2016-08-12T15:04:36Z
38,921,225
<p>The problem is you are using <a href="https://docs.python.org/3.5/library/functions.html#id" rel="nofollow"><code>id</code></a>, which is a built in function.</p> <p>When you call <code>form.save()</code>, it will return the <code>Post</code> instance. Use <code>post.id</code> (or <code>post.pk</code> if you prefer...
3
2016-08-12T15:12:19Z
[ "python", "django", "django-urls" ]
How to get a object from a view while using a django.test TestCase
38,921,202
<p>I am trying to access the object 'wines' that would be sent to a template. Basicaly, in this example I have wines that are sold by bottles, glasses or both. The first test I am on should be able to retrieve all 3 wines in a object called 'wines' that is sent to the template. (create_wine() is a custom Wine.objects.c...
1
2016-08-12T15:10:49Z
38,921,658
<p>You've misunderstood how the test client works. When you call <code>self.client.get("/wine/")</code>, it simulates a request to <code>/wine/</code>, and calls your <code>wine_list</code> view. You don't have to call <code>wine_list</code> manually.</p> <p>The <code>client.get()</code> call returns a response. You c...
2
2016-08-12T15:34:57Z
[ "python", "django", "unit-testing", "templates", "views" ]
Python Sockets - Keeping a connection to a server alive from the client
38,921,219
<p>I'm currently working with python's socket library for the first time and i'm not very experienced with computer networking.</p> <p>I'm able to connect to the server and the tcp handshake has happened as viewed by wireshark. After establishing a connection to the server(I have no control over the server), the conne...
1
2016-08-12T15:12:02Z
38,921,589
<p>For enabling keep alive there is a duplicate question at <a href="http://stackoverflow.com/questions/12248132/how-to-change-tcp-keepalive-timer-using-python-script">How to change tcp keepalive timer using python script?</a></p> <p>Keep in mind some servers and intermediate proxies forcibly close long lived connecti...
0
2016-08-12T15:31:38Z
[ "python", "sockets", "tcp", "network-programming", "tcp-ip" ]
How to disable showing visibility symbols in Tagbar for a specific filetype?
38,921,220
<p>I want <a href="https://github.com/majutsushi/tagbar/blob/master/doc/tagbar.txt" rel="nofollow"><code>g:tagbar_show_visibility</code></a> be set to <code>'0'</code> for Python files as there's no public/protected/private in Python. How can I configure Vim this way?</p>
2
2016-08-12T15:12:05Z
38,922,949
<p>To perform the operation manually execute this:</p> <pre><code>:TagbarClose :let g:tagbar_show_visibility = 0 :TagbarOpen </code></pre> <p>you can add the following line to your vimrc to make it automatically:</p> <pre><code>au BufRead *.py :let g:tagbar_show_visibility = 0 </code></pre> <p>The autocommand (au) ...
0
2016-08-12T16:50:05Z
[ "python", "vim", "tags", "tagbar" ]
How to disable showing visibility symbols in Tagbar for a specific filetype?
38,921,220
<p>I want <a href="https://github.com/majutsushi/tagbar/blob/master/doc/tagbar.txt" rel="nofollow"><code>g:tagbar_show_visibility</code></a> be set to <code>'0'</code> for Python files as there's no public/protected/private in Python. How can I configure Vim this way?</p>
2
2016-08-12T15:12:05Z
38,926,322
<p>You can customize <code>ctagsargs</code> for a particular filetype, making <code>ctags</code> not output the 'visibility' information for tags in the first place, e.g.:</p> <pre><code>let g:tagbar_type_python = { \ 'ctagsargs' : '-f - --excmd=pattern --fields=nksSmt' \ } </code></pre> <p>The important bit here...
1
2016-08-12T20:54:49Z
[ "python", "vim", "tags", "tagbar" ]
Define a function or loop, which restarts if given integer-parameter is less than X, or refuses to accept value less than 3
38,921,331
<p>I'm writing a simple program where a person can go on a trip, but the trip has to last <code>3</code> days <em>minimum</em>. The whole program has more parts which all work well, and the whole program works, but now I want to enhance it and set the minimal parameter value of function <code>hotel_cost(days)</code> to...
1
2016-08-12T15:18:17Z
38,921,607
<p>From my understanding of the question, you can do this: </p> <pre><code>def hotel_cost(days): if int(days) &gt;= 3: return 140 * int(days) else: return False </code></pre> <p>And then you can do:</p> <pre class="lang-py prettyprint-override"><code>while not hotel_cost(days): print("Ho...
0
2016-08-12T15:32:31Z
[ "python", "python-2.x" ]
Define a function or loop, which restarts if given integer-parameter is less than X, or refuses to accept value less than 3
38,921,331
<p>I'm writing a simple program where a person can go on a trip, but the trip has to last <code>3</code> days <em>minimum</em>. The whole program has more parts which all work well, and the whole program works, but now I want to enhance it and set the minimal parameter value of function <code>hotel_cost(days)</code> to...
1
2016-08-12T15:18:17Z
38,921,860
<p>Your can condense asking the user for the number of days, and giving them there price in in one function.</p> <pre><code>def ask_num_hotel_days(): i = int(input("Enter nuber of days: ")) while(i &lt; 3): print(str(i) + " is not a valid number of days") i = int(input("Enter nuber of days: "))...
0
2016-08-12T15:45:04Z
[ "python", "python-2.x" ]
Python - Display one line for each unique word
38,921,364
<p>I'm trying to write a python code that counts the frequency of each word in a text file. The code should display one line per unique word. The code I wrote is displaying duplicate words. </p> <pre><code>import string text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr...
1
2016-08-12T15:20:01Z
38,921,409
<p>The issue with your code is that you're creating a list of all the words and then looping over them. You want to create some sort of data structure that only stores unique words. A <code>dict</code> is a good way to do this, but it turns out there's a specialized collection in Python called a <code>Counter</code> th...
2
2016-08-12T15:22:53Z
[ "python", "python-2.7" ]
Python - Display one line for each unique word
38,921,364
<p>I'm trying to write a python code that counts the frequency of each word in a text file. The code should display one line per unique word. The code I wrote is displaying duplicate words. </p> <pre><code>import string text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr...
1
2016-08-12T15:20:01Z
38,922,090
<p>As another way to implement this, you could have taken your solution, added all of the entries as (word, count) tuples to a set, then printed the set. You should probably rethink your implementation anyway like @smarx points out but this will fix the issue using your native code.</p>
0
2016-08-12T15:57:17Z
[ "python", "python-2.7" ]
Python - Display one line for each unique word
38,921,364
<p>I'm trying to write a python code that counts the frequency of each word in a text file. The code should display one line per unique word. The code I wrote is displaying duplicate words. </p> <pre><code>import string text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr...
1
2016-08-12T15:20:01Z
39,030,802
<p>You can try something like this: </p> <pre><code>import string frequency = {} text = open('mary.txt','r') textr = text.read() for punc in string.punctuation: textr = textr.replace(punc, "") wordlist = textr.split() for word in wordlist: count = frequency.get(word,0) frequency[word] = count + 1 freq...
0
2016-08-19T03:48:36Z
[ "python", "python-2.7" ]
PyQT : Transfer between two TableView
38,921,398
<p>I would like to transfer data between two QtTableView. To do that, I first select the row to transfer then click on "to_X_table".</p> <p>But I don't understand how to fill the second tableview with the first one. I tried :</p> <pre><code>self.to_X_table.clicked.connect(self.to_X_tableView) def to_X_tableView(self)...
0
2016-08-12T15:22:09Z
39,017,619
<p>Finaly, I solve my problem. I didn't consider the model the first time. Here :</p> <pre><code> self.modelX = QtGui.QStandardItemModel() indexes = self.tableWidget_Input_Col.selectionModel().selectedIndexes() temp=self.tableWidget_Input_Col.selectionModel().model() # need to consider the model ! for ...
0
2016-08-18T11:56:51Z
[ "python", "pyqt5" ]
Create and write to new csv file during 'for' loop
38,921,486
<p>The code below is intended to create a csv file called 'file-0.csv' and start writing lines by iterating through the for loop until it reaches 100 lines. When the limit is reached, it should stop writing to 'file-0.csv', create 'file-1.csv', and <strong>continuing the for loop where it left off</strong>, start writi...
2
2016-08-12T15:26:45Z
38,921,779
<p>Leaving the <code>with</code> block closes with file. Therefore, the <code>new_file</code> function just opens and immediately closes a file.</p> <p>You could do somthing like the following:</p> <pre><code>import csv rowCounter = 0 fileCounter = 0 List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B...
2
2016-08-12T15:41:01Z
[ "python", "python-3.x", "csv", "for-loop" ]
Create and write to new csv file during 'for' loop
38,921,486
<p>The code below is intended to create a csv file called 'file-0.csv' and start writing lines by iterating through the for loop until it reaches 100 lines. When the limit is reached, it should stop writing to 'file-0.csv', create 'file-1.csv', and <strong>continuing the for loop where it left off</strong>, start writi...
2
2016-08-12T15:26:45Z
38,922,010
<p>Thanks @desiato!</p> <p>I accepted your answer, but ended up using lines 23-29 of your code and ended up with this (it works great!):</p> <pre><code>import csv rowCounter = 0 fileCounter = 0 List_A = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_B = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] List_C ...
0
2016-08-12T15:53:22Z
[ "python", "python-3.x", "csv", "for-loop" ]
Twitter data pull: How do i specify a range of date for Twitter data pull with specified keywords
38,921,489
<p>How do I search and pull data from Twitter containg specific keywords (or search terms) and in a specific data range.</p> <p>I see that I can use </p> <pre><code>import tweepy #override tweepy.StreamListener to add logic to on_status class MyStreamListener(tweepy.StreamListener): def on_status(self, status): ...
0
2016-08-12T15:27:03Z
38,989,823
<p>I searched in the web and found this library to be very useful <a href="https://github.com/Jefferson-Henrique/GetOldTweets-python" rel="nofollow">https://github.com/Jefferson-Henrique/GetOldTweets-python</a>. </p> <p>In Python,</p> <pre><code>tweetCriteria = got.manager.TweetCriteria().setQuerySearch('olympics').s...
0
2016-08-17T06:45:36Z
[ "python", "api", "twitter" ]
how to throttle a large number of task with out using all workers
38,921,531
<p>Imagine I have a dask grid with 10 workers &amp; 40 cores totals. This is a shared grid, so I don't want to fully saturate it with my work. I have 1000 tasks to do, and I want to submit (and have actively running) a maximum of 20 tasks at a time.</p> <p>To be concrete, </p> <pre><code>from time import sleep from r...
4
2016-08-12T15:28:41Z
38,921,763
<h3>Use <code>maxsize=</code></h3> <p>You're very close. All of <code>scatter</code>, <code>gather</code>, and <code>map</code> take the same <code>maxsize=</code> keyword argument that <code>Queue</code> takes. So a simple workflow might be as follows:</p> <h3>Example</h3> <pre><code>from time import sleep def i...
3
2016-08-12T15:40:15Z
[ "python", "dask" ]
Numpy choose shape mismatch
38,921,558
<p>I have a numpy problem with choose. I would like to choose certain indices as decribed in array a from array b.</p> <pre><code>a Out[54]: array([[3, 2, 2], [0, 0, 2]], dtype=int64) b Out[55]: array([[[ 6., 1., 8., 9., 3., 8., 5.], [ 6., 1., 5., 8., 2., 2., 10.], [ ...
2
2016-08-12T15:29:58Z
38,922,018
<p>It looks you want to use <code>choose</code> to select values from the dimension of length 7 in <code>b</code> (which is sized (2,3,7)). Your choosing array <code>a</code> will work for this, but only if the sequence dimension is the outermost dimension (as you quoted). The outermost dimension in Numpy is the <em>...
2
2016-08-12T15:53:46Z
[ "python", "numpy" ]
exporting a matrix to a text file in python
38,921,604
<p>I have a list of lists(matrix) in python and I want to export it to a text file. the inner lists have 3 elements. my file would have 3 columns. in other word, the first column would have the first element of inner list, the 2nd column would have the 2nd element of inner lists and the 3rd column would have the 3rd el...
0
2016-08-12T15:32:25Z
38,921,790
<p>The easiest way without using numpy, pandas or any other external package would be something like this:</p> <pre><code>data = [ ['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043] ] # builtin python functions data...
0
2016-08-12T15:41:33Z
[ "python", "file" ]
exporting a matrix to a text file in python
38,921,604
<p>I have a list of lists(matrix) in python and I want to export it to a text file. the inner lists have 3 elements. my file would have 3 columns. in other word, the first column would have the first element of inner list, the 2nd column would have the 2nd element of inner lists and the 3rd column would have the 3rd el...
0
2016-08-12T15:32:25Z
38,921,867
<p>Try the <code>csv.writer</code>:</p> <pre><code>import csv your_data=[['ENSG00000137288.5', 0.16721311, 0.13442624], ['ENSG00000116032.5', 0.094311371, 0.1444611], ['ENSG00000167578.12', 0.062894806, 0.10162043]] with open('output.txt', 'wb') as csvfile: w = csv.writer(csvfile, delimiter=' ') for row in you...
0
2016-08-12T15:45:29Z
[ "python", "file" ]
Python model targeting n variable prediction equation
38,921,636
<p>I am looking to build a predictive model and am working with our current JMP model. Our current approach is to guess an nth degree polynomial and then look at which terms are not significant model effects. Polynomials are not always the best and this leads to a lot of confusion and bad models. Our data can have betw...
1
2016-08-12T15:33:40Z
38,922,083
<p><a href="http://statsmodels.sourceforge.net/stable/anova.html" rel="nofollow">ANOVA (analysis of variance)</a> uses covariance to determine which effects are statistically significant... you shouldn't have to choose terms at random.</p> <p>However, if you are saying that your data is inhomogenous (i.e., you shouldn...
0
2016-08-12T15:56:55Z
[ "python", "pandas", "scikit-learn", "non-linear-regression" ]
Python model targeting n variable prediction equation
38,921,636
<p>I am looking to build a predictive model and am working with our current JMP model. Our current approach is to guess an nth degree polynomial and then look at which terms are not significant model effects. Polynomials are not always the best and this leads to a lot of confusion and bad models. Our data can have betw...
1
2016-08-12T15:33:40Z
39,363,619
<p>Try using other regression models instead of the vanilla Linear Model.</p> <p>You can use something like this for polynomial regression:</p> <pre><code>poly = PolynomialFeatures(degree=2) X_ = poly.fit_transform(input_data) </code></pre> <p>And you can constraint the weights through the Lasso Regression </p> <...
1
2016-09-07T07:21:42Z
[ "python", "pandas", "scikit-learn", "non-linear-regression" ]
Is there an accepted way to have a function pop a value from a parameter?
38,921,705
<p>Essentially, I would like to know if I should be attempting to avoid side effects in functions if possible, or if side effects are acceptable in certain situations. I would like to have a function which <code>pop</code>s and returns a key from a dictionary and am curious if the function should return just the key:<...
1
2016-08-12T15:37:25Z
38,921,823
<p>There is no need to return the parameter, since you already have a reference to it at the call site.</p> <p>If you choose to implement <code>pop_nearest</code> as a method in a <code>dict</code> subclass, then it's sometimes a good idea (depending on what you are trying to achieve) to return <code>self</code> so yo...
1
2016-08-12T15:43:18Z
[ "python", "dictionary", "side-effects" ]
Is there an accepted way to have a function pop a value from a parameter?
38,921,705
<p>Essentially, I would like to know if I should be attempting to avoid side effects in functions if possible, or if side effects are acceptable in certain situations. I would like to have a function which <code>pop</code>s and returns a key from a dictionary and am curious if the function should return just the key:<...
1
2016-08-12T15:37:25Z
38,922,011
<p>You don't need to return the modified dictionary. It is modified in the function like you would think since it is a reference/pointer to the actual object and not a deep copy and will exist in its modified form in the calling function after pop is called. Returning the key should be sufficient and work how you want ...
1
2016-08-12T15:53:23Z
[ "python", "dictionary", "side-effects" ]
Python - args an **kargs
38,921,813
<p>I have this global <code>function</code>:</p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, **kwargs): print (name, 'PLAYLIST') for i, x in enumerate(feature): if x &lt; value: track_name = sp.track(tids[i])['name'] xsongs.append(track_name) pri...
0
2016-08-12T15:43:01Z
38,922,047
<p><strong>test.py</strong></p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, **kwargs): print kwargs['value'] class Test(object): def __init__(self): energy = ['item 1', 'item2', 'item3' ] tids = [] xsongs = [] filterBelowThreshold('myname', energy, tids, xs...
0
2016-08-12T15:55:38Z
[ "python", "args", "kwargs" ]
Python - args an **kargs
38,921,813
<p>I have this global <code>function</code>:</p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, **kwargs): print (name, 'PLAYLIST') for i, x in enumerate(feature): if x &lt; value: track_name = sp.track(tids[i])['name'] xsongs.append(track_name) pri...
0
2016-08-12T15:43:01Z
38,922,347
<p>You should not use <code>**kwargs</code> if you call the function with a explicit parameter <code>value</code>, just use normal arguments:</p> <pre><code>def filterBelowThreshold(name, feature, tids, xsongs, value): print(name, 'PLAYLIST') for tid, x in zip(tids, feature): if x &lt; value: ...
0
2016-08-12T16:11:13Z
[ "python", "args", "kwargs" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... star...
0
2016-08-12T15:43:05Z
38,921,937
<p>When a generator hits its <code>return</code> statement (explicit or not) it raises <code>StopIteration</code>. So when you <code>return ingen</code> you end the iteration.</p> <p><code>check_v2</code> is not a generator, since it does not contain the <code>yield</code> statement, that's why it works.</p>
2
2016-08-12T15:49:31Z
[ "python", "python-3.x", "if-statement", "generator" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... star...
0
2016-08-12T15:43:05Z
38,921,939
<p>In Python, if <code>yield</code> is present in a function, then Python treats it as a generator. In a generator, any return will raise <code>StopIteration</code> with the returned value. This is a new feature in Python 3.3: see <a href="https://www.python.org/dev/peps/pep-0380/" rel="nofollow">PEP 380</a> and <a hre...
3
2016-08-12T15:49:33Z
[ "python", "python-3.x", "if-statement", "generator" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... star...
0
2016-08-12T15:43:05Z
38,921,984
<p>As others have said, if you return from a generator, it means the the generator has stopped yielding items, which raises a <code>StopIteration</code> whatever you return. </p> <p>This means that <code>check</code> actually returns an empty iterator.</p> <p>If you want to return the results of another generator, yo...
2
2016-08-12T15:52:17Z
[ "python", "python-3.x", "if-statement", "generator" ]
Unable to return a generator instance. why?
38,921,815
<p>I am using python 3.5. When I tried to return a generator function instance and i am getting a StopIteration error. Why?</p> <p>here is my code:</p> <pre><code>&gt;&gt;&gt; def gen(start, end): ... '''generator function similar to range function''' ... while start &lt;= end: ... yield start ... star...
0
2016-08-12T15:43:05Z
38,922,065
<p>See <a href="https://www.python.org/dev/peps/pep-0380/#formal-semantics" rel="nofollow">PEP 380</a>:</p> <blockquote> <p>In a generator, the statement</p> <pre><code>return value </code></pre> <p>is semantically equivalent to</p> <pre><code>raise StopIteration(value) </code></pre> <p>except that, as c...
0
2016-08-12T15:56:04Z
[ "python", "python-3.x", "if-statement", "generator" ]
python binary executable fails to execute on OS x: importerror no module named PyQt4
38,921,869
<p>I created a binary executable on Mac for a python script using <code>pyinstaller</code> and the following command:</p> <blockquote> <p>pyinstaller --onefile --windowed chatEdit.py</p> </blockquote> <p>also tried this:</p> <blockquote> <p>pyinstaller --windowed chatEdit.py</p> </blockquote> <p>In each case th...
0
2016-08-12T15:45:41Z
38,922,611
<p>It seems you missed PyQt in .spec file</p> <p>I hope my app.spec will help you. Pay attention to <strong>'PyQt4.QtCore', 'PyQt4.QtGui'</strong> in <em>hiddenimports</em> </p> <pre><code># -*- mode: python -*- a = Analysis(['app.py'], pathex=['d:\\4com\\consultant\\consultant'], hiddenimpo...
0
2016-08-12T16:26:19Z
[ "python", "osx", "pyqt4", "pyinstaller" ]
Setting Max Results in API v4 (python)
38,921,882
<p>In v3 of the API I'm seeing that there was a max-results parameter that could be passed to get more than 1000 records. I haven't been able to figure out how to pass that parameter in v4 of the API using python. </p> <p>My code looks something like below. I've commented out my best guess at max_result.</p> <pre><co...
0
2016-08-12T15:46:34Z
38,922,925
<p>The correct name of the parameter you are looking for is: <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/rest/v4/reports/batchGet#ReportRequest.FIELDS.page_size" rel="nofollow"><code>pageSize</code></a>. The <a href="https://developers.google.com/analytics/devguides/reporting/core/v4/re...
1
2016-08-12T16:47:28Z
[ "python", "google-analytics", "google-analytics-api", "google-analytics-v4" ]
Only show certain number of emails in imaplib
38,921,933
<p>The code I have below is working great but I am testing this on a test email and it only have around 5 emails. On my actual email account I have atleast 4k emails on my inbox.</p> <p>Is there a way for me to show for a certain number of emails. For example, only show the first 20 most recent emails? And then after...
0
2016-08-12T15:49:16Z
39,083,374
<p>I just realized that I already have the output that I want, which is to only output a specified number of emails.</p> <pre><code>ids = data[0] id_list = ids.split() for num in id_list[0:10]: rv, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) subj = msg['Subject'] to = ...
0
2016-08-22T15:26:11Z
[ "python", "email", "count", "imaplib" ]
Passing data mid-function back to function Python
38,921,940
<p>The below script works fine, until I added in "def test", I am trying to get rid of all global variables my programming in general and as I'm not a great programmer, I hope there is a way to do this. </p> <p>I want to pass "foo" from function "test" back to Function "work" but this does not work as its not a globa...
1
2016-08-12T15:49:33Z
38,922,005
<p>Add the following to the end of your <code>test()</code> function:</p> <pre><code>`return foo` </code></pre> <p>then you can print the variable in <code>work()</code> like this</p> <pre><code>print test(data) </code></pre>
4
2016-08-12T15:53:08Z
[ "python" ]
Passing data mid-function back to function Python
38,921,940
<p>The below script works fine, until I added in "def test", I am trying to get rid of all global variables my programming in general and as I'm not a great programmer, I hope there is a way to do this. </p> <p>I want to pass "foo" from function "test" back to Function "work" but this does not work as its not a globa...
1
2016-08-12T15:49:33Z
38,922,040
<p>Your <code>test</code> function should be written like</p> <pre><code>def test(data): if data == 3: return 'bar' elif data == 5: return 'barnone' </code></pre> <p>In a function that calls <code>test</code>, assign the result</p> <pre><code>something = test(data) </code></pre> <p>Note that...
1
2016-08-12T15:55:06Z
[ "python" ]
Passing data mid-function back to function Python
38,921,940
<p>The below script works fine, until I added in "def test", I am trying to get rid of all global variables my programming in general and as I'm not a great programmer, I hope there is a way to do this. </p> <p>I want to pass "foo" from function "test" back to Function "work" but this does not work as its not a globa...
1
2016-08-12T15:49:33Z
38,922,050
<p><code>foo</code> is only defined in the "scope" of the function <code>test()</code>, since that is where you created it. The function <code>work()</code> has no knowledge of the variable <code>foo</code>, as it is <em>undefined</em> outside of the function <code>test()</code>. So, <code>test()</code> has to <em>retu...
2
2016-08-12T15:55:42Z
[ "python" ]
Virtualenv Includes Global Packages / How do I clear my PYTHONPATH?
38,921,967
<p>I'm running a Virtualenv like this:</p> <pre><code>$ virtualenv --no-site-packages venv New python executable in .../venv/bin/python Installing setuptools, pip, wheel...done. $ source venv/bin/activate </code></pre> <p>But when I <code>pip freeze -l</code>, I don't get anything. So I double-checked my <a href="htt...
0
2016-08-12T15:51:20Z
38,922,666
<p>I don't know if this is a good fix, but I found a few statements in my .bashrc:</p> <pre><code>export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/dist-packages export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.7/site-packages export PYTHONPATH=$P...
0
2016-08-12T16:29:28Z
[ "python", "linux", "path", "virtualenv", "pythonpath" ]
How can I implement a dictionary with a NumPy array?
38,921,975
<p>I need to write a huge amount number-number pairs into a NumPy array. Since a lot of these pairs have a second value of 0, I thought of making something akin to a dictionary. The problem is that I've read through the NumPy documentation on structured arrays and it seems like dictionaries built like those on the page...
1
2016-08-12T15:51:53Z
38,924,069
<p>So you have an <code>(N,2)</code> array, and many values in <code>x[:,1]</code> are 0.</p> <p>What do you mean by <code>insertion</code>? Adding a value to the array to make it <code>(N+1,2)</code>? Or just changing <code>x[i,:]</code> to something new?</p> <p>And what about the search? <code>numpy</code> array ...
0
2016-08-12T18:07:45Z
[ "python", "arrays", "numpy", "dictionary", "red-black-tree" ]
How can I implement a dictionary with a NumPy array?
38,921,975
<p>I need to write a huge amount number-number pairs into a NumPy array. Since a lot of these pairs have a second value of 0, I thought of making something akin to a dictionary. The problem is that I've read through the NumPy documentation on structured arrays and it seems like dictionaries built like those on the page...
1
2016-08-12T15:51:53Z
38,924,162
<p>The most basic form of a dictionary is a structure called a <code>HashMap</code>. Implementing a hashmap relies on turning your key into a value that can be quickly looked up. A pathological example would be using <code>int</code>s as keys: The value for key <code>1</code> would go in <code>array[1]</code>, the v...
0
2016-08-12T18:14:53Z
[ "python", "arrays", "numpy", "dictionary", "red-black-tree" ]
I have a list of lists. I would like to make a new list of lists, but each new list will have the same indices of the old list
38,921,985
<p>Imagine my old list is:</p> <pre><code>old = [[card, towel, bus], [mouse, eraser, laptop], [pad, pen, bar]] </code></pre> <p>goal:</p> <pre><code>new = [[card, mouse, pad], [towel, eraser, pen], [bus, laptop, bar]] </code></pre> <p>Things I've tried:</p> <pre><code>new = dict(zip(old[i] for i in range(len(old))...
1
2016-08-12T15:52:20Z
38,922,042
<p>For your first question, this is the basic usage of <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a>:</p> <pre><code>&gt;&gt;&gt; old = [['card', 'towel', 'bus'], ['mouse', 'eraser', 'laptop'], ['pad', 'pen', 'bar']] &gt;&gt;&gt; zip(*old) [('card', 'mouse', 'pad'),...
3
2016-08-12T15:55:10Z
[ "python", "list" ]
I have a list of lists. I would like to make a new list of lists, but each new list will have the same indices of the old list
38,921,985
<p>Imagine my old list is:</p> <pre><code>old = [[card, towel, bus], [mouse, eraser, laptop], [pad, pen, bar]] </code></pre> <p>goal:</p> <pre><code>new = [[card, mouse, pad], [towel, eraser, pen], [bus, laptop, bar]] </code></pre> <p>Things I've tried:</p> <pre><code>new = dict(zip(old[i] for i in range(len(old))...
1
2016-08-12T15:52:20Z
38,922,257
<p><strong>Method 1:</strong> If you want reach your first goal in one line and want to use list comprehensions try:</p> <pre><code>old = [[1,2,3],[4,5,6],[7,8,9]] new = [[sublist[i] for sublist in old ] for i in (0,1,2)] </code></pre> <p>leads to <code>new = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]</code>.</p> <p><strong>...
0
2016-08-12T16:05:55Z
[ "python", "list" ]
I have a list of lists. I would like to make a new list of lists, but each new list will have the same indices of the old list
38,921,985
<p>Imagine my old list is:</p> <pre><code>old = [[card, towel, bus], [mouse, eraser, laptop], [pad, pen, bar]] </code></pre> <p>goal:</p> <pre><code>new = [[card, mouse, pad], [towel, eraser, pen], [bus, laptop, bar]] </code></pre> <p>Things I've tried:</p> <pre><code>new = dict(zip(old[i] for i in range(len(old))...
1
2016-08-12T15:52:20Z
38,923,097
<p>Thanks so much for the input everyone! zip(*old) worked like a charm, though I'm not entirely sure how...</p> <p>For the second problem, I used this: (I know this is not a good solution, but it worked)</p> <pre><code>for name in range(input_num): exec(list_names[name] + ' = arranged_list[name]') </code></pre>
0
2016-08-12T17:00:30Z
[ "python", "list" ]
how to pass askopenfilename() return value as a parameter to the builtin python function open
38,922,095
<p>I am a new user to Python.</p> <p><code>filename = askopenfilenames()</code> This prompts the user to select a file I want to use <code>file_selection = open(filename, "r")</code> with the file selected above.</p> <p>The issue I am running into is that when you use the <code>askopenfilenames()</code> (I think) t...
1
2016-08-12T15:57:29Z
38,924,797
<p><code>askopenfilenames()</code> allows the user to select multiple files; thus it returns a tuple of all the filenames selected.</p> <p>If you want to allow the user to select multiple files, just iterate over the returned tuple:</p> <pre><code>filenames = askopenfilenames() #filenames is a tuple of strings! for f...
2
2016-08-12T18:58:42Z
[ "python", "user-interface", "tkinter" ]
In Python, is it preferred to declare local variables to extract data from an object, or to just deal with the object directly?
38,922,101
<p>For example, say you have an object Dog with 3 different string attributes (bark, sleep, eat). Also assume you have a function where you will be accessing these variables several times repeatedly (dog.bark, dog.bark, dog.sleep). Is it preferred to declare these at the beginning of the function (bark = dog.bark) or j...
0
2016-08-12T15:57:48Z
38,922,174
<p>The first one is the one that you will see more often, but it depends on what your overall goal is. But more often than not, you are going to want to do it this way. </p> <p>I can't really think of a reason to do it the second way, other than sometimes it might make it more readable for you, if the variables get ha...
0
2016-08-12T16:01:37Z
[ "python", "coding-style" ]
In Python, is it preferred to declare local variables to extract data from an object, or to just deal with the object directly?
38,922,101
<p>For example, say you have an object Dog with 3 different string attributes (bark, sleep, eat). Also assume you have a function where you will be accessing these variables several times repeatedly (dog.bark, dog.bark, dog.sleep). Is it preferred to declare these at the beginning of the function (bark = dog.bark) or j...
0
2016-08-12T15:57:48Z
38,922,396
<p>If you're not going to use an attribute of the object, say <code>dog.bark</code>, more than once, then there is no point declaring an additional variable in order to do just one thing - except for readibility.</p> <p>This question can lead onto memory management topics; take a look at the "heap" and the "stack" and...
0
2016-08-12T16:14:02Z
[ "python", "coding-style" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&...
1
2016-08-12T15:58:34Z
38,922,153
<p>You create a new generator every time you recall it like so; so it starts from the initial value. What you want is:</p> <pre><code>&gt;&gt;&gt; n = nature() &gt;&gt;&gt; next(n) 0 &gt;&gt;&gt; next(n) 1 &gt;&gt;&gt; next(n) 2 &gt;&gt;&gt; next(n) 3 </code></pre>
1
2016-08-12T16:00:44Z
[ "python", "generator" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&...
1
2016-08-12T15:58:34Z
38,922,154
<p>You are creating a new generator each time, try creating it once and passing it to each next call</p>
1
2016-08-12T16:00:45Z
[ "python", "generator" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&...
1
2016-08-12T15:58:34Z
38,922,171
<p>Every time you call <code>nature()</code> you create a new generator. Instead do this:</p> <pre><code>n = nature() next(n) next(n) next(n) </code></pre>
6
2016-08-12T16:01:27Z
[ "python", "generator" ]
Infinite sequencing number generator not work in python?
38,922,122
<p>I am trying to implement a nature number generator which can generator infinite numbers, my code:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 </code></pre> <p>when I use <code>next(nature())</code>, I get a sequence of 0s, why this? and how to fix it?</p> <pre><code>&gt;&...
1
2016-08-12T15:58:34Z
38,922,226
<p>Don't instance your generator over and over, for example, instance one and use it several times like this:</p> <pre><code>def nature(): s = 0 while True: yield s s += 1 n = nature() for i in range(10): print next(n) print "Doing another stuff... Resuming the counting" for i in range(1...
0
2016-08-12T16:04:46Z
[ "python", "generator" ]
Specify download location in Django
38,922,176
<p>Is there a way to specify a download location in Django?</p> <p>My page allows the user to</p> <ul> <li>Click a button run to a EXE in the background</li> <li>Then gives the user a new page where the download option is available</li> <li>User clicks the download, and it downloads the latest file it generated</li> ...
1
2016-08-12T16:01:43Z
40,116,344
<p>After further research, I concluded that the reference <a href="http://stackoverflow.com/a/33612619/5104387">post</a> also reflects on Django. Django does not offer such feature, it is a security feature of the web browser that does not allow you to specify download location.</p> <p>Credit to <a href="http://Darren...
0
2016-10-18T19:20:11Z
[ "python", "django-1.9" ]
Remove string starting from specific characters in python
38,922,225
<p>I have the following data in a file:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585...
1
2016-08-12T16:04:42Z
38,922,308
<p>It may be easier to work with individual lines instead of whole file contents:</p> <pre><code>with open("file") as f: lines = [line for line in f if not line.startswith("CHN")] filtered = "".join(lines) </code></pre>
2
2016-08-12T16:08:56Z
[ "python", "string" ]
Remove string starting from specific characters in python
38,922,225
<p>I have the following data in a file:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585...
1
2016-08-12T16:04:42Z
38,922,323
<pre><code>for line in file: if not line[0:3] == "CHN": write_line else: remove_line </code></pre>
1
2016-08-12T16:09:38Z
[ "python", "string" ]
Remove string starting from specific characters in python
38,922,225
<p>I have the following data in a file:</p> <pre><code>Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585...
1
2016-08-12T16:04:42Z
38,922,327
<pre><code>file = """ Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.230.2.91 4 136041 0 0 35w6d 1178 CHN_RAY_901_1AC_CASR903R004# exit Neighbor V TblVer InQ OutQ Up/Down State/PfxRcd 10.229.5.239 4 890585 0 0 7w5d 1177 10...
2
2016-08-12T16:09:48Z
[ "python", "string" ]
How to delete an object from a list inside a list?
38,922,291
<p>Let's say there are three lists, the third being a list containing the first two:</p> <pre><code>Friendly_List = list() Enemy_List = list() Battle_Space = list([Friendly_List, Enemy_List]) </code></pre> <p>And a goblin class:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin...
2
2016-08-12T16:08:15Z
38,922,355
<p>If you know the index of the nested list, you can index from the parent list and call <code>remove</code>:</p> <pre><code>Battle_Space[0].remove(x) </code></pre> <p>To remove <code>x</code> from anywhere it appears, you can use a list comprehension:</p> <pre><code>Battle_Space = [[j for j in innerlist if j!=x] fo...
1
2016-08-12T16:11:44Z
[ "python", "python-3.x", "oop", "object" ]
How to delete an object from a list inside a list?
38,922,291
<p>Let's say there are three lists, the third being a list containing the first two:</p> <pre><code>Friendly_List = list() Enemy_List = list() Battle_Space = list([Friendly_List, Enemy_List]) </code></pre> <p>And a goblin class:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin...
2
2016-08-12T16:08:15Z
38,922,381
<p>The simple but maybe not-so-clean way is <code>Battle_Space[0].remove(x)</code>. You would have to ensure that the first list is the friendly list.</p> <p>My suggestion for readability would be to consider putting <code>friendly_list</code> and <code>enemy_list</code> in a <code>BattleSpace</code> object so you can...
4
2016-08-12T16:13:27Z
[ "python", "python-3.x", "oop", "object" ]
How to delete an object from a list inside a list?
38,922,291
<p>Let's say there are three lists, the third being a list containing the first two:</p> <pre><code>Friendly_List = list() Enemy_List = list() Battle_Space = list([Friendly_List, Enemy_List]) </code></pre> <p>And a goblin class:</p> <pre><code>class Goblin(object): def __init__(self): self.Name = "Goblin...
2
2016-08-12T16:08:15Z
38,922,481
<p>Just filter those damm goblins out, for instance:</p> <pre><code>import random class Goblin(object): def __init__(self): self.Name = "Goblin" self.HP = random.randint(15, 20) self.Damage = random.randint(5, 10) x = Goblin() Friendly_List = list() Enemy_List = list() Battle_Space = li...
1
2016-08-12T16:18:49Z
[ "python", "python-3.x", "oop", "object" ]
Ubuntu 16.04 default python environment in my user profile is Anaconda Python2, unable to run guake "anaconda2/bin/python2: No module named guake"
38,922,328
<p>I recently installed Ubuntu 16.04 and for ease of developing Machine Learning and other AI programs using Python2, I installed the Anaconda Python2 full distribution.</p> <p>I always use 'guake' terminal emulator which I find best for productivity. So I installed Guake in my Ubuntu and when I try to run it, I get t...
0
2016-08-12T16:09:50Z
38,958,052
<p>you don't execute the right Python execute: <code>/home/enlighter/anaconda2/bin/python2</code> while you installed in <code>/usr/lib/python2.7/dist-packages/guake/</code>.</p> <p>Use <code>/usr/bin/python2</code> as default interpreter or install in <code>/home/enlighter/anaconda2/lib/python2.7/dist-packages/guake/...
0
2016-08-15T15:23:49Z
[ "python", "ubuntu", "anaconda", "environment" ]
python print 3 first elements of list in reverse mode
38,922,333
<p>suppose i have a list like this:</p> <pre><code>my_list = [0,1,2,3,4,5] # range(5) </code></pre> <p>i want to print this:</p> <pre><code>[2,1,0] </code></pre> <p>my python script is:</p> <pre><code>print(my_list[2:-1:-1]) </code></pre> <p>but it <strong>prints an empty list!</strong></p> <p>is this a bug in p...
2
2016-08-12T16:10:26Z
38,922,363
<p>You could slice the <code>list</code> as shown:</p> <pre><code>print(my_list[2::-1]) # L[start:end:step] </code></pre> <p><strong>EDIT :</strong></p> <p>The result that you had obtained is not a <em>Bug</em>. </p> <p>Remember that traversal of the <code>list</code> elements takes place from left to right an...
5
2016-08-12T16:12:13Z
[ "python", "list" ]
python print 3 first elements of list in reverse mode
38,922,333
<p>suppose i have a list like this:</p> <pre><code>my_list = [0,1,2,3,4,5] # range(5) </code></pre> <p>i want to print this:</p> <pre><code>[2,1,0] </code></pre> <p>my python script is:</p> <pre><code>print(my_list[2:-1:-1]) </code></pre> <p>but it <strong>prints an empty list!</strong></p> <p>is this a bug in p...
2
2016-08-12T16:10:26Z
38,922,364
<p>You can also invert your list permanently for other uses:</p> <pre><code>my_list.reverse() print(my_list[-4:-1]) </code></pre>
1
2016-08-12T16:12:15Z
[ "python", "list" ]
New to Python (and programming) can't see where I'm going wrong
38,922,387
<p>I'm learning a bit of Phython in my spare time. Trying to make a phonebook, found one on this site; <a href="http://stackoverflow.com/questions/28910134/python-assignment-for-a-phonebook">Python assignment for a phonebook</a>. Have used that as a template but left out the print_menu function. That's the only differe...
3
2016-08-12T16:13:38Z
38,922,419
<p><code>input()</code> returns a string, not an integer.</p> <p>So</p> <pre><code>while action != 4: </code></pre> <p>should become:</p> <pre><code>while action != '4': </code></pre>
6
2016-08-12T16:15:14Z
[ "python" ]
New to Python (and programming) can't see where I'm going wrong
38,922,387
<p>I'm learning a bit of Phython in my spare time. Trying to make a phonebook, found one on this site; <a href="http://stackoverflow.com/questions/28910134/python-assignment-for-a-phonebook">Python assignment for a phonebook</a>. Have used that as a template but left out the print_menu function. That's the only differe...
3
2016-08-12T16:13:38Z
38,922,490
<p>You have two problems here. As Padraic and Leistungsabfall mention, <code>input</code> returns a string, but you <em>also</em> are only getting the input one time. If you want to continue getting input, you're going to need to put that inside your loop:</p> <pre><code>action = None while action != '4': action =...
5
2016-08-12T16:19:24Z
[ "python" ]
Error using python and sqlite3
38,922,391
<p>I have a directory (/home/usuario/Desktop/Example) with one database (MyBBDD.db) and the file (script.py) that run the command "UPDATE". If in the terminal I'm in the directory "Example", script.py work fine but if Im not in the directory "Example" and I execute script.py like this: "<code>python /home/usuario/Desk...
1
2016-08-12T16:13:46Z
38,922,476
<p>When you create a connection object with <code>sqlite3</code> in script.py, use the absolute file path, i.e. </p> <pre><code>con = sqlite3.connect('/home/usuario/Desktop/Example/MyBBDD.db') </code></pre>
3
2016-08-12T16:18:19Z
[ "python", "sqlite3" ]
Import lxml module cause PyImport_ImportModule failed
38,922,394
<p>I wrote python test code which uses the module <code>lxml</code>.</p> <p>I want to call <code>foo</code> in c++. </p> <p>It will fail in step <code>PyImport_ImportModule</code> if I add the <code>from lxml import html</code> but works well when I remove it</p> <p>Test.py</p> <pre><code>import os import sys impor...
0
2016-08-12T16:13:54Z
38,926,401
<p>Your code will crash at</p> <pre><code>PyObject* pModule = PyImport_ImportModule("Test"); PyObject* pDict = PyModule_GetDict(pModule); //will crash </code></pre> <p>if <code>pModule == NULL</code>. You should check the return values, for example</p> <pre><code>if (pModule == NULL || PyErr_Occurred()) { PyErr_...
0
2016-08-12T21:00:55Z
[ "python", "html", "c++", "import", "lxml" ]
Import lxml module cause PyImport_ImportModule failed
38,922,394
<p>I wrote python test code which uses the module <code>lxml</code>.</p> <p>I want to call <code>foo</code> in c++. </p> <p>It will fail in step <code>PyImport_ImportModule</code> if I add the <code>from lxml import html</code> but works well when I remove it</p> <p>Test.py</p> <pre><code>import os import sys impor...
0
2016-08-12T16:13:54Z
38,928,226
<p>I resolved it , it's the lxml installer's fault.</p> <p>I download version 3.6.0 from <a href="https://pypi.python.org/pypi/lxml/3.6.0" rel="nofollow">https://pypi.python.org/pypi/lxml/3.6.0</a> (lxml-3.6.0.win32-py2.7.exe) ,because it had no version 3.6.1 installer. and it caused the question i mentioned.</p> <p>...
0
2016-08-13T01:03:12Z
[ "python", "html", "c++", "import", "lxml" ]
Python: Writing multiple json object to a file; Later to be open and load via json.load
38,922,442
<p>I have constructed a json object from a data stream where each user will have a json object. </p> <pre><code>{ "entities": { "description": { "urls": [] } }, "utc_offset": -10800, "id" "name": "Tom", "hit_count": 7931, "private": false, "active_last_month"...
1
2016-08-12T16:16:16Z
38,922,908
<p>I think you should add the new JSON data to a list containing the previous data:</p> <pre><code>newData = {"entities": { "description": { "urls": [] } }, "utc_offset": -10500, "id": 3, "name": "Mary", "hit_count": 554, "private": False, "active_last_month": False, "location": "", "contacted": False,...
-1
2016-08-12T16:46:07Z
[ "python", "json" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is ...
0
2016-08-12T16:24:52Z
38,922,633
<p>How about a list comprehension?</p> <pre><code>str = 'era' list = ['we', 'st'] packed = [(str,str2) for str2 in list] </code></pre>
7
2016-08-12T16:27:24Z
[ "python", "string", "zip" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is ...
0
2016-08-12T16:24:52Z
38,922,671
<pre><code>str = 'era' list = ['we', 'st'] res = [(str,list[0]), (str, list[1])] </code></pre>
-1
2016-08-12T16:30:11Z
[ "python", "string", "zip" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is ...
0
2016-08-12T16:24:52Z
38,922,746
<p>Use <code>itertools.product</code>:</p> <pre><code>import itertools ss = "era" lst = ["we", "st"] print list(itertools.product([ss], lst)) </code></pre> <p>Avoid using keyword as variables, such as <strong>list</strong>.</p>
2
2016-08-12T16:36:05Z
[ "python", "string", "zip" ]
Making pairs of a string and an element in a list
38,922,589
<p>I have a single string that I would like to make pair with each element in a list. </p> <pre><code>str = "era" list = ["we", "st"] </code></pre> <p>With the code:</p> <pre><code>zip(str, list) </code></pre> <p>I obtain</p> <pre><code> [('e', 'we'), ('r', 'st')] </code></pre> <p>What I would like to achieve is ...
0
2016-08-12T16:24:52Z
38,922,883
<p>Thought I'd offer an alternative to @<em>jphollowed</em>'s simple and concise answer.</p> <pre><code>s = "era" l = ["we", "st"] print([tuple(i.split(',')) for i in map(lambda x: x+','+s, l)]) </code></pre>
1
2016-08-12T16:44:52Z
[ "python", "string", "zip" ]
click-and-run docker image (or VM) with web interface?
38,922,616
<p>I am in a position to deliver an application to a user, however it requires quite a few programs and components installed, which represents some overhead and explanation that I'd prefer to avoid. One method that I thought of that would be quite nice would be to simply supply a VM or Docker image. In this idea, the...
0
2016-08-12T16:26:44Z
38,922,789
<p>In order for a Docker container to run you need a Docker-engine. If your customer wants to run the container on her host, then she needs docker installed.</p> <p>Quick example: One of you component is Nginx:</p> <pre><code>docker pull ngnix:latest docker run --name webInterface --host web -it ngnix:latest </code><...
1
2016-08-12T16:37:54Z
[ "python", "docker", "virtual-machine", "software-distribution" ]
click-and-run docker image (or VM) with web interface?
38,922,616
<p>I am in a position to deliver an application to a user, however it requires quite a few programs and components installed, which represents some overhead and explanation that I'd prefer to avoid. One method that I thought of that would be quite nice would be to simply supply a VM or Docker image. In this idea, the...
0
2016-08-12T16:26:44Z
38,923,154
<p>Yes, you can import and export Docker images as simple TAR files. To export an existing image into a tar file, use the following <code>docker save</code> command:</p> <pre><code>docker save your_image &gt; your_image.tar </code></pre> <p>The TAR file created this way is self-contained and you can distribute it any...
1
2016-08-12T17:04:31Z
[ "python", "docker", "virtual-machine", "software-distribution" ]
Select pandas columns by several strings
38,922,632
<p>I have tried to select several rows of dataframe by specific partial string. </p> <p>The dataframe below is the original example data: </p> <pre><code>CODE DATA AA2016 47518 BB2016 47518 CC2014 47518 AA2014 47518 EE2015 47518 BB2015 47518 FF2016 47518 ...
1
2016-08-12T16:27:23Z
38,922,863
<p>As @ayhan notes in the comment, you can use <code>df[df.CODE.str[0:2].isin(Select_list)]</code>.</p> <p>Alternatively, note that you can use regular expressions via <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>pd.Series.str.contains</code></a>:...
1
2016-08-12T16:43:15Z
[ "python", "python-2.7", "pandas", "dataframe" ]
How to add an item to a list in python and save it
38,922,664
<p>My program is set up so I can add items to the lists from terminal but whenever I do this for example <code>myFile.append('hello')</code> it keeps it there but when I exit terminal and do it again <code>'hello'</code> is deleted. Please help. Thank you!</p> <p>Code</p> <pre><code>elif userInput in command: pri...
-1
2016-08-12T16:29:22Z
38,922,698
<p>Try something like:</p> <pre><code>with open(myFile, 'a') as f: f.write('hello') </code></pre> <p>You can append to a list with<code>.append</code> but not a file. Instead, you can use the 'a' flag as above to append to the file <code>myFile</code> where <code>myFile</code> is a file path.</p> <h1>Update:</h1...
3
2016-08-12T16:32:48Z
[ "python" ]
Tasks that throw exceptions block IPython-Parallel queue
38,922,764
<p>I am using IPython-Parallel's <code>load_balanced_view</code> and map to perform some simulations. I use the asynchronous version of the view so it doesn't block.</p> <p>Whenever the function applied by <code>map</code>throws an exception, the <code>error</code> property of the asynchronous map is set correctly. If...
0
2016-08-12T16:36:51Z
38,991,657
<p>This was a bug in <code>ipyparallel</code> and is fixed in master. </p> <p>The related GitHub issue is <a href="https://github.com/ipython/ipyparallel/issues/184" rel="nofollow">here</a>.</p>
0
2016-08-17T08:28:28Z
[ "python", "ipython", "jupyter", "ipython-parallel" ]
In python how can I make data ready for garbage collection to free memory?
38,922,850
<p>I have function that uses numpy to return an array with 4 fields. I use that function in a loop extract data from multiple sources. However my processing only is on 1 out of 4 fields. How do I reasonably make sure that the 3/4 fields I do not need will not be in memory before the next loop iteration? Here is my curr...
0
2016-08-12T16:42:18Z
38,923,216
<p>I am not really sure but i guess memory in python can't be freed, mean the memory occupied by some array or any object cannot be added to free memory pool programmatically even if you delete the reference variable. it will be deleted by the <code>GC</code> when the time comes.Try <a href="http://stackoverflow.com/qu...
0
2016-08-12T17:08:51Z
[ "python", "numpy", "memory", "garbage-collection" ]
In python how can I make data ready for garbage collection to free memory?
38,922,850
<p>I have function that uses numpy to return an array with 4 fields. I use that function in a loop extract data from multiple sources. However my processing only is on 1 out of 4 fields. How do I reasonably make sure that the 3/4 fields I do not need will not be in memory before the next loop iteration? Here is my curr...
0
2016-08-12T16:42:18Z
38,926,018
<p>It looks like you have a structured array; at least that's consistent with how you are accessing fields.</p> <p>In my current ipython session I have a structured array with 3 fields, and 64 elements.</p> <pre><code>In [1383]: data1.shape Out[1383]: (64,) In [1384]: data1.dtype Out[1384]: dtype([('f0', 'u1'), ('f1'...
0
2016-08-12T20:30:10Z
[ "python", "numpy", "memory", "garbage-collection" ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</c...
0
2016-08-12T16:50:11Z
38,923,035
<p>Use pandas' NaN. Those cells will be empty in Excel (you will be able to use 'select empty cells' command for example. You cannot do that with empty strings). </p> <pre><code>import numpy as np df.replace(['None', 'nan'], np.nan, inplace=True) </code></pre> <p><a href="http://i.stack.imgur.com/y7yZA.png" rel="nofo...
1
2016-08-12T16:56:15Z
[ "python", "string", "pandas", "dataframe", null ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</c...
0
2016-08-12T16:50:11Z
38,923,089
<p>Use a list of strings to replace with blanks strings that won't affect actual <code>nan</code>'s...</p> <pre><code>df.replace(['nan', 'None'], '') </code></pre> <p>Which'll give you a new dataframe of:</p> <pre><code>ID col1 col2 col3 col4 1 Apple NaN 2 orange NaN 3 ...
0
2016-08-12T17:00:02Z
[ "python", "string", "pandas", "dataframe", null ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</c...
0
2016-08-12T16:50:11Z
38,923,174
<p>You can compare each column to the numpy object dtype (which is basically text columns), and then only do replacements for those columns.</p> <pre><code>for col in df: if df[col] == np.dtype('O'): # Object df.col1.replace(['None', 'NaN', np.nan], "", inplace=True) </code></pre>
1
2016-08-12T17:05:51Z
[ "python", "string", "pandas", "dataframe", null ]
How to Replace All the "nan" Strings with Empty String in My DataFrame?
38,922,952
<p>I have <code>"None"</code> and <code>"nan"</code> strings scattered in my dataframe. Is there a way to replace all of those with empty string <code>""</code> or <code>nan</code> so they do not show up when I export the dataframe as excel sheet?</p> <p>Simplified Example:</p> <p><strong>Note:</strong> <code>nan</c...
0
2016-08-12T16:50:11Z
38,924,953
<p>All those loop-de-loop solutions...</p> <pre><code>replacers = [None, np.nan, "None", "NaN", "nan"] # and everything else that needs replacing. df.loc[:, df.dtypes == 'object'].replace(replacers, '', inplace=True) </code></pre>
0
2016-08-12T19:10:00Z
[ "python", "string", "pandas", "dataframe", null ]
Django AttributeError: 'InterestsForm' object has no attribute '_errors'
38,922,969
<p>I am trying to use a Django form to allow a Django User to input their three favourite interests. The error occurs during the template rendering where it says <code>{{form.as_ul}}</code>.</p> <p>Here is the code:</p> <p><strong>reg_interests.html</strong></p> <pre><code>{% block content %} &lt;br&gt;&lt;br&gt; &...
1
2016-08-12T16:51:44Z
38,923,171
<p>This code can't possibly work at all, because you override the <code>__init__</code> method of the form so that a) you only accept a <code>request</code> argument - and not any of the other things a form is expecting, like <code>data</code> or <code>initial</code> - and b) you never call the superclass init method t...
1
2016-08-12T17:05:47Z
[ "python", "django", "django-1.10" ]
Django unit test query against production database
38,923,002
<p>I am trying to write some unit tests for an asynchronous method in my Django app. Essentially, when a user does a certain POST, this method is kicked off so the application doesn't hang. What I want to test is the ability to cancel this request as it is running (in this case via celery). The only problem with doi...
1
2016-08-12T16:53:58Z
38,934,925
<p>I'm not sure if testing against your prod is a better solution than running your celery workers in dev mode against your test database. How are you starting your celery workers ?? I imagine you're starting your celery workers external of the test using your prod/real settings, then you're running your tests using t...
0
2016-08-13T16:48:39Z
[ "python", "django", "unit-testing", "celery", "integration-testing" ]
Iterating a list of lists and modifying values backwards
38,923,061
<p>I have a list of lists, like so.</p> <pre><code>[[1, 2, 3], [4, 2, 7], [9, 5, 6]] </code></pre> <p>I want to subtract the first element of each sublist by the first element of the previous sublist, and afterwards, I also want to set the first element of the first sublist to zero. Yielding</p> <pre><code>[[0, 2, 3...
-1
2016-08-12T16:58:02Z
38,923,239
<p>If I got the question right, you want to only modify the first element of the sub lists, right? You could do something like this-</p> <pre><code>li = [[1, 2, 3], [4, 2, 7], [9, 5, 6]] for i in range(2, 0, -1): li[i][0] = li[i][0] - li[i-1][0] li[0][0] = 0 </code></pre> <p>Starting from the back, you subtract f...
2
2016-08-12T17:11:20Z
[ "python", "list", "iteration" ]
Iterating a list of lists and modifying values backwards
38,923,061
<p>I have a list of lists, like so.</p> <pre><code>[[1, 2, 3], [4, 2, 7], [9, 5, 6]] </code></pre> <p>I want to subtract the first element of each sublist by the first element of the previous sublist, and afterwards, I also want to set the first element of the first sublist to zero. Yielding</p> <pre><code>[[0, 2, 3...
-1
2016-08-12T16:58:02Z
38,923,240
<p>You can use the old zip-the-list-with-itself trick:</p> <pre><code>lists= [[1, 2, 3], [4, 2, 7], [9, 5, 6]] i= reversed(lists) # iterate backwards next(i) # drop the first (last) list j= reversed(lists) # create another reversed iterator, but don't drop the 1st list for list1, list2 in zip(i, j): # zip the two ite...
0
2016-08-12T17:11:24Z
[ "python", "list", "iteration" ]
Iterating a list of lists and modifying values backwards
38,923,061
<p>I have a list of lists, like so.</p> <pre><code>[[1, 2, 3], [4, 2, 7], [9, 5, 6]] </code></pre> <p>I want to subtract the first element of each sublist by the first element of the previous sublist, and afterwards, I also want to set the first element of the first sublist to zero. Yielding</p> <pre><code>[[0, 2, 3...
-1
2016-08-12T16:58:02Z
38,923,485
<pre><code>lst = [ [1, 2, 3], [4, 2, 7], [9, 5, 6] ] # print(lst) t = [ lst[0] ] for i in range( 1, len(lst) ): x = [ lst[i][0] - lst[i-1][0] ] x.extend( lst[i][1:] ) t.append( x ) t[0][0] = 0 print(t) </code></pre> <p>Result will be:</p> <p><code>[[0, 2, 3], [3, 2, 7], [5, 5, 6]]</code></p>
0
2016-08-12T17:27:13Z
[ "python", "list", "iteration" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value ...
10
2016-08-12T17:00:02Z
38,923,169
<p>It's only partially a matter of style. You need to do <em>something</em> to ensure your code doesn't raise an (uncaught) <code>NameError</code> following the loop, so your two choices are</p> <ol> <li><p>Ensure that the <code>NameError</code> cannot happen by making an unconditional assignment to <code>seventh_valu...
1
2016-08-12T17:05:42Z
[ "python" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value ...
10
2016-08-12T17:00:02Z
38,923,189
<p>This is a fine approach to set the value to <code>None</code> before the for-loop. Do not worry too much. Personally, I feel as long as code is readable by someone who has no idea at all -- it is fine.</p> <p>That being said, there's a slightly better (pythonic) way to avoid the problem altogether. <strong>Note</st...
2
2016-08-12T17:06:33Z
[ "python" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value ...
10
2016-08-12T17:00:02Z
38,923,472
<p>If you are sure that <code>seventh_value</code> should be set and you count on it in your program logic, you might even want your code to crash with <code>NameError</code> and write it without prior <code>seventh_value</code> definition.</p> <p>If you are sure that <code>seventh_value</code> might not be set when a...
1
2016-08-12T17:26:14Z
[ "python" ]
good style to introduce python variables within a loop
38,923,091
<p>I have a C++ background and I'm learning Python. I am writing code which needs to extract a particular value from a <code>for</code> loop:</p> <pre><code>seventh_value = None # ** my question is about this line for index in range(1, 10): value = f(index) # we have a special interest in the seventh value ...
10
2016-08-12T17:00:02Z
38,923,477
<p>You can do it exactly how you suggest, and if you try it, you will find it works exactly how you want.</p> <p>However, there is a better, (imho more pythonic) way, that totally avoids the need to pre-initialize the variable.</p> <pre><code>results = [] for index in range(1, 10): value = f(index) # (do othe...
0
2016-08-12T17:26:38Z
[ "python" ]
How can I combine (or make operations) between attributes of different classes (without specifying instances yet)?
38,923,102
<p>First of all, I am a total newbie. Thanks for your patience.</p> <p>I am designing a piece of software to calculate insulation materials and amounts on different houses. </p> <p>I have a <code>class House()</code>, which holds attributes like roof_area and wall_area.</p> <p>I have a <code>class Insulator()</code>...
0
2016-08-12T17:00:50Z
38,923,267
<p>If you want to use attributes without creating an instance you should use class attributes.</p> <pre><code>class House(object): roof_area = 10 # Or whatever you see fit. roof_surface = 20 class Insulator(object): thickness = 10 # Or whatever you see fit. surface = 20 </code></pre> <p>This way you ...
0
2016-08-12T17:13:07Z
[ "python", "class", "instances" ]
How can I combine (or make operations) between attributes of different classes (without specifying instances yet)?
38,923,102
<p>First of all, I am a total newbie. Thanks for your patience.</p> <p>I am designing a piece of software to calculate insulation materials and amounts on different houses. </p> <p>I have a <code>class House()</code>, which holds attributes like roof_area and wall_area.</p> <p>I have a <code>class Insulator()</code>...
0
2016-08-12T17:00:50Z
38,924,429
<p>It doesn't make any sense to try to compute the number of insulation packages you need to cover the roof of a house, without using any instances of your <code>House</code> or <code>Insulator</code> classes. It only makes sense if you have one instance of each.</p> <p>You can, however, write the code to do the calc...
1
2016-08-12T18:34:32Z
[ "python", "class", "instances" ]
Why are my ZenDesk macros being updated, but no change actually going through?
38,923,106
<p>I was trying to bulk edit the signature of my personal macros on ZenDesk, and the only way to do that is via the API. So I wrote this quick Python script to try to do it:</p> <pre><code>import sys import time import logging import requests import re start_time = time.time() # Set up logging logger = logging.getLo...
2
2016-08-12T17:01:16Z
38,929,858
<p>Looks like you're double-encoding the JSON data in your PUT request:</p> <pre><code>response = requests.put(url, json="{'macro': {'actions': %r}}" % updated_data, headers={"Content-Type": "application/json"}, auth=(user + "/token", pwd)) </code></pre> <p>The json parameter expects an object, which it then dutifull...
3
2016-08-13T06:22:07Z
[ "python", "python-2.7", "zendesk-api" ]