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 identify a string as being a byte literal?
39,778,978
<p>In Python 3, if I have a string such that:</p> <pre><code>print(some_str) </code></pre> <p>yields something like this:</p> <pre><code>b'This is the content of my string.\r\n' </code></pre> <p>I know it's a byte literal. </p> <p>Is there a function that can be used to determine if that string is in byte literal ...
7
2016-09-29T19:59:29Z
39,779,592
<p>Just to complement the other answer, the built-in <a href="https://docs.python.org/3/library/functions.html#type" rel="nofollow"><code>type</code></a> also gives you this information. You can use it with <code>is</code> and the corresponding type to check accordingly.</p> <p>For example, in Python 3:</p> <pre><cod...
4
2016-09-29T20:39:52Z
[ "python", "string", "python-3.x" ]
Pandas scatter_matrix analog function to pairs(lower.panel, upper.panel)
39,778,987
<p>I need to create a scatter matrix in Python. I tried using scatter_matrix for this but I would like to leave only the scatter plots above the diagonal line.</p> <p>I`m in the really beginning (did not got far) and I have troubles when columns have names (not the default numbers).</p> <p>Here is my code:</p> <pre>...
1
2016-09-29T20:00:22Z
39,779,214
<p>You have an issue when selecting a column from a data frame. You can use <code>iloc</code> to select columns based on integer location. Change your last line to:</p> <pre><code>ax.scatter(data.iloc[:,j], data.iloc[:,i], s=10) </code></pre> <p>Gives:</p> <p><a href="http://i.stack.imgur.com/gxNuV.png" rel="nofollo...
1
2016-09-29T20:14:23Z
[ "python", "pandas", "scatter-plot", "subplot" ]
sklean fit_predict not accepting a 2 dimensional numpy array
39,779,113
<p>I am trying to perform some clustering analysis using three different clustering algorithms. I am loading in data from stdin as follows</p> <pre><code>import sklearn.cluster as cluster X = [] for line in sys.stdin: x1, x2 = line.strip().split() X.append([float(x1), float(x2)]) X = numpy.array(X) </code></p...
2
2016-09-29T20:08:36Z
39,779,313
<pre><code> class sklearn.cluster.KMeans(n_clusters=8, init='k-means++', n_init=10, max_iter=300, tol=0.0001, precompute_distances='auto', verbose=0, random_state=None, copy_x=True, n_jobs=1, algorithm='auto')[source] </code></pre> <p>They way you'd call the KMeans class is,</p> <pre><code>KMeans(n_clusters=5) </code...
2
2016-09-29T20:21:47Z
[ "python", "numpy", "scikit-learn" ]
Python : split text to list of lines
39,779,316
<p>am new to Python , But i have text File like :</p> <pre><code>12345 | 6789 | abcd | efgh </code></pre> <p>i want my output be Like :</p> <pre><code>12345 6789 abcd efgh </code></pre> <p>=====================</p> <p>i really don't know the script but i made a lot of scripts by those function split() , strip()...
2
2016-09-29T20:22:01Z
39,779,485
<p>Some problems with the code you posted:</p> <ul> <li><code>f.read</code> doesn't read the whole line. It should be <code>f.readline()</code>. </li> <li>What is the function <code>splitlines</code>?</li> </ul> <p>Your question is pretty unclear in differnt aspects. Maybe this snippet could be of some help:</p> <pr...
0
2016-09-29T20:32:24Z
[ "python", "text", "split", "lines" ]
Python : split text to list of lines
39,779,316
<p>am new to Python , But i have text File like :</p> <pre><code>12345 | 6789 | abcd | efgh </code></pre> <p>i want my output be Like :</p> <pre><code>12345 6789 abcd efgh </code></pre> <p>=====================</p> <p>i really don't know the script but i made a lot of scripts by those function split() , strip()...
2
2016-09-29T20:22:01Z
39,779,512
<p>I strongly suggest using csv module for this kind of task, as it seems like a csv-type file, using '|' as delimiter:</p> <pre><code>import csv with open('contacts_index1.txt','r') as f: reader=csv.reader(f,delimiter='|') for row in reader: #do things with each line print "\n".join(row) </cod...
0
2016-09-29T20:34:05Z
[ "python", "text", "split", "lines" ]
Python : split text to list of lines
39,779,316
<p>am new to Python , But i have text File like :</p> <pre><code>12345 | 6789 | abcd | efgh </code></pre> <p>i want my output be Like :</p> <pre><code>12345 6789 abcd efgh </code></pre> <p>=====================</p> <p>i really don't know the script but i made a lot of scripts by those function split() , strip()...
2
2016-09-29T20:22:01Z
39,783,096
<p>From all of your comments, it looks like the issue has to do with the actual text in the file, and not the ability to parse it. It looks like everyone's solution in here is on the right track, you just need to force the encoding.</p> <p>The error you are describing is described <a href="http://stackoverflow.com/qu...
0
2016-09-30T03:16:06Z
[ "python", "text", "split", "lines" ]
Python : split text to list of lines
39,779,316
<p>am new to Python , But i have text File like :</p> <pre><code>12345 | 6789 | abcd | efgh </code></pre> <p>i want my output be Like :</p> <pre><code>12345 6789 abcd efgh </code></pre> <p>=====================</p> <p>i really don't know the script but i made a lot of scripts by those function split() , strip()...
2
2016-09-29T20:22:01Z
39,783,129
<p>You will have to use decode. The following code will work:</p> <pre><code>def dataFunction(filename): with open(filename, encoding="utf8") as f: return f.read() </code></pre> <p>Call this function with filename as parameter:</p> <pre><code>Contents = dataFunction(filename) elements = Contents.split("|...
1
2016-09-30T03:19:11Z
[ "python", "text", "split", "lines" ]
Python : split text to list of lines
39,779,316
<p>am new to Python , But i have text File like :</p> <pre><code>12345 | 6789 | abcd | efgh </code></pre> <p>i want my output be Like :</p> <pre><code>12345 6789 abcd efgh </code></pre> <p>=====================</p> <p>i really don't know the script but i made a lot of scripts by those function split() , strip()...
2
2016-09-29T20:22:01Z
39,783,414
<p>Please do this line by line. There is no need to read the entire file at once.</p> <p>Something like:</p> <pre><code>with open(file_name) as f_in: for line in f_in: for word in line.split('|'): print word.strip() </code></pre> <hr> <p>If it is a unicode issue, most of the time it is autom...
0
2016-09-30T03:53:23Z
[ "python", "text", "split", "lines" ]
how to export data to unix system location using python
39,779,412
<p>I am trying to write the file to my company's project folder which is unix system and the location is /department/projects/data/. So I used the following code</p> <p>df.to_csv("/department/projects/data/Test.txt", sep='\t', header = 0)</p> <p>The error message shows it cannot find the locations. how to specify the...
0
2016-09-29T20:27:59Z
39,780,239
<pre><code>df.to_csv("C:\Users\abc\Desktop\Test.txt", sep='\t', header = 0) </code></pre> <p>Either you really mean that the backslashes are doubled as in</p> <pre><code>df.to_csv("C:\\Users\\abc.... </code></pre> <p>or your strings are just wrong. I believe that Python will support Unix style paths on both Windows ...
0
2016-09-29T21:22:53Z
[ "python", "unix" ]
how to export data to unix system location using python
39,779,412
<p>I am trying to write the file to my company's project folder which is unix system and the location is /department/projects/data/. So I used the following code</p> <p>df.to_csv("/department/projects/data/Test.txt", sep='\t', header = 0)</p> <p>The error message shows it cannot find the locations. how to specify the...
0
2016-09-29T20:27:59Z
39,813,792
<p>I have find the solution. It might because I am using Spyder from anaconda. As long as I use "\" instead of "\", python can recognize the location.</p>
0
2016-10-02T04:13:43Z
[ "python", "unix" ]
What is a pythonic way to select data from one of two locations?
39,779,435
<p>I am making a backwards incompatible change to an api endpoint in a different app that I call from a client app (where this code lives). I need to for a time support it handling both the previous case (where the data lived at the "ledger" level") and the new case (where the data lived at the "profile" ledger).</p> ...
1
2016-09-29T20:29:24Z
39,779,689
<p>Instead of</p> <pre><code>owner_data = owner_data_from_ledger if owner_data_from_ledger else owner_data_from_profile </code></pre> <p>you can write this which is equivalent:</p> <pre><code>owner_data = owner_data_from_ledger or owner_data_from_profile </code></pre> <p>Alternatively shorten the whole thing:</p> ...
0
2016-09-29T20:45:37Z
[ "python", "styles", "readability" ]
Transform dna alignment into numpy array using biopython
39,779,488
<p>I have several DNA sequences that have been aligned and I would like to keep only the bases that are variable at a specific position. </p> <p>This maybe could be done if we first transform the alignment into an array. I tried using the code in the Biopython tutorial but it gives an error.</p> <pre><code>import nu...
3
2016-09-29T20:32:35Z
39,779,933
<p><code>AlignIO</code> doesn't seem to be the tool you want for this job. You have a file presumably with many sequences, not with many multiple sequence alignments, so you probably want to use <code>SeqIO</code>, not <code>AlignIO</code> (<a href="http://biopython.org/wiki/AlignIO" rel="nofollow">source</a>). This i...
1
2016-09-29T20:59:17Z
[ "python", "numpy", "biopython" ]
Transform dna alignment into numpy array using biopython
39,779,488
<p>I have several DNA sequences that have been aligned and I would like to keep only the bases that are variable at a specific position. </p> <p>This maybe could be done if we first transform the alignment into an array. I tried using the code in the Biopython tutorial but it gives an error.</p> <pre><code>import nu...
3
2016-09-29T20:32:35Z
39,784,698
<p>I'm answering to your problem instead of fixing your code. If you want to keep only certain positions, you want to use <code>AlignIO</code>:</p> <p>FASTA sample <code>al.fas</code>:</p> <pre><code>&gt;seq1 CATCGATCAGCATCGACATGCGGCA-ACG &gt;seq2 CATCGATCAG---CGACATGCGGCATACG &gt;seq3 CATC-ATCAGCATCGACATGCGGCATACG &...
1
2016-09-30T06:01:42Z
[ "python", "numpy", "biopython" ]
Programmatic distinction between ternary then function call versus function call dependent on condition
39,779,501
<p>Recently I have been conflicted regarding the following question. It may just be a stylistic choice, but I was wondering if there is a programmatic difference between the following... (in python, but applicable for most languages)</p> <p>Case #1:</p> <pre><code>arg = A if condition else B result = func(arg) </code...
0
2016-09-29T20:33:17Z
39,779,808
<p>My opinion is in Case #1 you'd better be sure that you're checking for some kind of binary condition, e.g. an integer is either odd or even. In thoses cases I'd prefer Case #1 for the sake of simplicity.</p> <p>If the expression in the condition is not binary, such as checking the remainder of an integer module n, ...
0
2016-09-29T20:52:05Z
[ "python", "function", "ternary-operator" ]
How to get lineno of "end-of-statement" in Python ast
39,779,538
<p>I am trying to work on a script that manipulates another script in Python, the script to be modified has structure like:</p> <pre><code>class SomethingRecord(Record): description = 'This records something' author = 'john smith' </code></pre> <p>I use <code>ast</code> to locate the <code>description</code> ...
35
2016-09-29T20:35:58Z
39,811,752
<p><a href="https://docs.python.org/3.5/library/ast.html" rel="nofollow">ast</a> only stores the beginning line number for each node.</p> <p>If your scripts always have another assignment (to <code>author</code>, from your example) after the <code>description</code> assignment, then you could do something like this .....
-3
2016-10-01T21:45:42Z
[ "python", "abstract-syntax-tree" ]
How to get lineno of "end-of-statement" in Python ast
39,779,538
<p>I am trying to work on a script that manipulates another script in Python, the script to be modified has structure like:</p> <pre><code>class SomethingRecord(Record): description = 'This records something' author = 'john smith' </code></pre> <p>I use <code>ast</code> to locate the <code>description</code> ...
35
2016-09-29T20:35:58Z
39,879,026
<p>Indeed, the information you need is not stored in the <code>ast</code>. I don't know the details of what you need, but it looks like you could use the <code>tokenize</code> module from the standard library. The idea is that every logical Python statement is ended by a <code>NEWLINE</code> token (also it could be a s...
2
2016-10-05T16:12:40Z
[ "python", "abstract-syntax-tree" ]
How to get lineno of "end-of-statement" in Python ast
39,779,538
<p>I am trying to work on a script that manipulates another script in Python, the script to be modified has structure like:</p> <pre><code>class SomethingRecord(Record): description = 'This records something' author = 'john smith' </code></pre> <p>I use <code>ast</code> to locate the <code>description</code> ...
35
2016-09-29T20:35:58Z
39,879,196
<p>As a workaround you can change:</p> <pre><code> description = 'line 1' \ 'line 2' \ 'line 3' </code></pre> <p>to:</p> <pre><code> description = 'new value'; tmp = 'line 1' \ 'line 2' \ 'line 3' </code></pre> <p>etc. </p> <p>It is a simple change but ...
6
2016-10-05T16:22:55Z
[ "python", "abstract-syntax-tree" ]
How to get lineno of "end-of-statement" in Python ast
39,779,538
<p>I am trying to work on a script that manipulates another script in Python, the script to be modified has structure like:</p> <pre><code>class SomethingRecord(Record): description = 'This records something' author = 'john smith' </code></pre> <p>I use <code>ast</code> to locate the <code>description</code> ...
35
2016-09-29T20:35:58Z
39,897,622
<p>My solution takes a different path: When I had to change code in another file I opened the file, found the line and got all the next lines which had a deeper indent than the first and return the line number for the first line which isn't deeper. I return None, None if I couldn't find the text I was looking for. Thi...
1
2016-10-06T13:40:01Z
[ "python", "abstract-syntax-tree" ]
How to get lineno of "end-of-statement" in Python ast
39,779,538
<p>I am trying to work on a script that manipulates another script in Python, the script to be modified has structure like:</p> <pre><code>class SomethingRecord(Record): description = 'This records something' author = 'john smith' </code></pre> <p>I use <code>ast</code> to locate the <code>description</code> ...
35
2016-09-29T20:35:58Z
39,945,762
<p>I looked at the other answers; it appears people are doing backflips to get around the problems of computing line numbers, when your real problem is one of modifying the code. That suggests the baseline machinery is not helping you the way you really need.</p> <p>If you use a <a href="https://en.wikipedia.org/wik...
7
2016-10-09T16:17:34Z
[ "python", "abstract-syntax-tree" ]
Reverse model admin custom URLs
39,779,545
<p>Inside my <code>admin.py</code> file I have:</p> <pre><code>def get_urls(self): urls = super(TextAdmin, self).get_urls() my_urls = patterns('', url( r'customfunc1', customfunc2, name='customfunc23', ), ) return my_urls + urls </code></pre> <p>Whic...
1
2016-09-29T20:36:19Z
39,779,708
<p>You have <code>name='customfunc23'</code>, and it is in the <code>admin</code> app, so you should use:</p> <pre><code>reverse('admin:customfunc23') </code></pre>
0
2016-09-29T20:46:30Z
[ "python", "django", "python-2.7", "django-admin" ]
Cannot make boolean global in Python
39,779,551
<p>I am very new to programming and am creating a function that takes a letter or letters and checks to see if it is within a word. I need to control the number of guesses so I would like to set a boolean to test whether it was correct. To be clear, I have looked through many other answers on this type of question but ...
1
2016-09-29T20:36:50Z
39,779,691
<p>Some issues in the code:</p> <ul> <li><code>randomWord</code> seems to be undefined.</li> <li><code>guessedLetters</code> seems to be undefined as well.</li> <li>There are 2 returns in the function</li> </ul> <p>If your code did run then maybe it never gets into the inner loop. Add some <code>print</code> statemen...
0
2016-09-29T20:45:47Z
[ "python", "global-variables", "local" ]
Retrieve a list of files located at a URL with filenames matching a known pattern
39,779,570
<p>There is a URL where a colleague has set up a large number of files for me to download, </p> <pre><code>url = "http://www.some.url.edu/some/dirname/" </code></pre> <p>Inside this directory, there are a large number of files with different filename patterns that are known to me in advance, e.g., "subvol1_file1.tar....
1
2016-09-29T20:38:27Z
39,779,827
<p>Not sure this is applicable in your case, but you can apply a regular expression pattern on the <code>href</code> attribute values:</p> <pre><code>import re pattern = re.compile(r"subvol1_file\d+\.tar\.gz") links = [a["href"] for a in soup.find_all("a", href=pattern)] </code></pre>
0
2016-09-29T20:53:18Z
[ "python", "beautifulsoup", "urllib2" ]
Calculating the entropy of an attribute in the ID3 algorithm when a split is perfectly classified
39,779,587
<p>I have been reading about the ID3 algorithm recently and it says that the best attribute to be selected for splitting should result in the maximum information gain which can be computed with the help of the entropy. </p> <p>I have written a simple python program to compute the entropy. It is shown below:</p> <pre>...
3
2016-09-29T20:39:31Z
39,786,695
<p><strong>Entropy is a measure of impurity.</strong> So if a node is pure it means entropy is zero. </p> <p>Have a look at <a href="https://github.com/HashCode55/ML_from_scratch/blob/master/decision_tree.py" rel="nofollow">this</a> - </p> <pre><code>def information_gain(data, column, cut_point): """ For calc...
1
2016-09-30T08:11:26Z
[ "python", "machine-learning", "decision-tree" ]
Calculating the entropy of an attribute in the ID3 algorithm when a split is perfectly classified
39,779,587
<p>I have been reading about the ID3 algorithm recently and it says that the best attribute to be selected for splitting should result in the maximum information gain which can be computed with the help of the entropy. </p> <p>I have written a simple python program to compute the entropy. It is shown below:</p> <pre>...
3
2016-09-29T20:39:31Z
39,803,320
<p>The entropy of a split measures the uncertainty associated with the class labels in that split. In a binary classification problem (classes = {0,1}), the probability of class 1 (in your text, x) can range from 0 to 1. The entropy is maximum (with a value of 1) when x=0.5. Here both classes are equally probable. The ...
0
2016-10-01T05:23:53Z
[ "python", "machine-learning", "decision-tree" ]
Django - Changing order_by on click
39,779,617
<p>Using Django and I would like to change the order of the display of the objects on click without refreshing the page.</p> <p>my model</p> <pre><code>class IndexView(generic.ListView): template_name = 'movies/index.html' page_template = 'movies/all_movies.html' context_object_name = 'all_movies' mod...
1
2016-09-29T20:41:29Z
39,780,037
<p>Your question seems to illustrate a misunderstanding of how front-end and back-end languages work: a click event occurs on the front-end, <em>after</em> the data has been sent from the server. The <code>order_by</code> function is run and completed <em>before</em> the request is completed. </p> <p>To load new data ...
1
2016-09-29T21:07:11Z
[ "python", "django" ]
Setting up a LearningRateScheduler in Keras
39,779,710
<p>I'm setting up a Learning Rate Scheduler in Keras, using history loss as an updater to self.model.optimizer.lr, but the value on self.model.optimizer.lr does not get inserted in the SGD optimizer and the optimizer is using the dafault learning rate. The code is:</p> <pre><code>from keras.models import Sequential fr...
2
2016-09-29T20:46:41Z
39,781,985
<p>The learning rate is a variable on the computing device, e.g. a GPU if you are using GPU computation. That means that you have to use <code>K.set_value</code>, with <code>K</code> being <code>keras.backend</code>. For example:</p> <pre><code>import keras.backend as K K.set_value(opt.lr, 0.01) </code></pre> <p>or i...
0
2016-09-30T00:36:26Z
[ "python", "optimization", "keras" ]
Setting up a LearningRateScheduler in Keras
39,779,710
<p>I'm setting up a Learning Rate Scheduler in Keras, using history loss as an updater to self.model.optimizer.lr, but the value on self.model.optimizer.lr does not get inserted in the SGD optimizer and the optimizer is using the dafault learning rate. The code is:</p> <pre><code>from keras.models import Sequential fr...
2
2016-09-29T20:46:41Z
39,807,000
<p>Thanks, I found an alternative solution, as I'm not using GPU:</p> <pre><code>from keras.models import Sequential from keras.layers import Dense, Dropout, Activation from keras.optimizers import SGD from keras.callbacks import LearningRateScheduler sd=[] class LossHistory(keras.callbacks.Callback): def on_trai...
1
2016-10-01T13:09:46Z
[ "python", "optimization", "keras" ]
Python DataFrame error for having a header with parenthesis
39,779,726
<p>I am very new to python and programming in general. I have a CSV file that has the first column as string headers.</p> <p>ie</p> <pre><code>time, speed(m/s), distance(m) 2,6,20 3,2,10 etc.. </code></pre> <p>What I am trying to do is a program that will spit out a bunch of graphs based on my selection. for exampl...
1
2016-09-29T20:47:40Z
39,780,184
<p>You should consider that accessing your columns via the <code>.</code> (dot) operator a privileged convenience. It can break under many circumstances and sometimes silently so. If you want to access the column do so with <code>[]</code> or <code>loc[]</code> or <code>iloc[]</code>.</p> <p>Parenthesis are one of t...
1
2016-09-29T21:18:35Z
[ "python", "pandas", "matplotlib", "dataframe" ]
After installing anaconda - command not found: jupyter
39,779,744
<p>I have installed anaconda on my MAC laptop, and tried to run jupyter notebook to install it, but I get error jupyter command not found.</p>
2
2016-09-29T20:48:22Z
39,779,791
<p>You need to activate your conda environment and then do</p> <pre><code>$ pip install jupyter $ jupyter notebook # to actually run the notebook server </code></pre>
3
2016-09-29T20:51:19Z
[ "python", "anaconda", "jupyter-notebook" ]
Python list comprehension vs. nested loop, conciseness/efficiency
39,779,757
<p>The following 2 methods do the same thing. Which one is more efficient in terms of time/space complexity?</p> <pre><code>** Method A** for student in group.students: for grade in student.grades: some_operation(grade) ** Method B** for grade in [grade for student in group.students for grade in student.g...
0
2016-09-29T20:49:20Z
39,779,801
<p>These have the same time complexity, <code>O(nm)</code>, since it's a loop over another loop. So, the <code>n</code> is <code>group.students</code>, and <code>m</code> is <code>students.grades</code>. Functionally, these should be the same time complexity too since it's iterating over both lists either way.</p>
0
2016-09-29T20:51:45Z
[ "python", "code-complexity" ]
Python list comprehension vs. nested loop, conciseness/efficiency
39,779,757
<p>The following 2 methods do the same thing. Which one is more efficient in terms of time/space complexity?</p> <pre><code>** Method A** for student in group.students: for grade in student.grades: some_operation(grade) ** Method B** for grade in [grade for student in group.students for grade in student.g...
0
2016-09-29T20:49:20Z
39,779,816
<p>Method B looks weird and redundant. You could shorten it to:</p> <pre><code>[some_operation(grade) for student in group.students for grade in student.grades] </code></pre> <p>But method A is better either way because it doesn't create a list. Making a list simply to throw it away is confusing to the reader and was...
1
2016-09-29T20:52:26Z
[ "python", "code-complexity" ]
Why can't add a row to pandas dataframe?
39,779,832
<p>I have a 370864*493 dataset, I want to add a new row at the tail of the data set. I have tried Dataframe.loc[370864]=.... and Dataframe.append(). Both methods didn't work as my expectation.But the same code can work on a smaller data set, just 20 thousand rows. I hope to know the reason. The size of dataset is 1.6G....
0
2016-09-29T20:53:29Z
39,780,542
<p>Try changing the last line that you gave us from </p> <pre><code>df_genomicMatrix.loc[370864]=list_M </code></pre> <p>to</p> <pre><code>df_genomicMatrix.loc[len(df_genomicMatrix)]=list_M </code></pre> <p><code>len(df_genomicMatrix)</code> returns the length of the dataframe. Using this instead of a static number...
0
2016-09-29T21:46:26Z
[ "python", "pandas" ]
pip says it is a package, by python says it is not
39,779,961
<p>I am using Windows and have a directory like this:</p> <pre><code>troopcalc/ setup.py troopcalc/ __init__.py troopcalc.py troopcfg.py tests/ __init__.py test_troopcalc.py test_troopcfg.py </code></pre> <p>I used pip to install the package....
0
2016-09-29T21:01:22Z
39,797,884
<blockquote> <p>If I run <code>python .\troopcalc.py</code> I get the following:</p> </blockquote> <p>Well, yes. Python thinks that <code>troopcalc</code> is <code>troopcalc.py</code>, since that's in the directories in <code>sys.path</code>.</p> <pre><code>python -m troopcalc.troopcalc </code></pre>
1
2016-09-30T18:29:17Z
[ "python" ]
Django Aggregate ManyToMany fields
39,780,067
<p>Say I have Django models like so:</p> <pre><code>class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): authors = models.ManyToManyField(Author) </code></pre> <p>What's the best way to get the the number of books each author created (preferably ordered) within a quer...
0
2016-09-29T21:08:55Z
39,780,133
<p>in your model book add...</p> <pre><code>... author = models.ForeignKey(Author) ... </code></pre> <p>and to get then you use a QuerySet like</p> <pre><code>... Author.objects.get(id=some_id).book_set.all() # this line, return all book of these author, if you want get the number just add at end '.count()' ... </co...
-2
2016-09-29T21:14:50Z
[ "python", "django", "many-to-many" ]
Python 2.7 connection to Oracle: loosing (Polish) characters
39,780,090
<p>I connect from Python 2.7 to Oracle data base. When I use:</p> <pre><code>cursor.execute("SELECT column1 FROM table").fetchall()] </code></pre> <p>I have got almost proper values for column1 because all Polish characters ("ęóąśłżćń") are converted to ascii one ("eoaslzcn"). Using another tool like SQLDevel...
0
2016-09-29T21:10:45Z
39,783,932
<p>Try setting the environment variable <code>NLS_LANG</code> to your database language string, something like</p> <pre><code>os.environ['NLS_LANG'] = 'POLISH_POLAND.EE8MSWIN1250' </code></pre>
0
2016-09-30T04:55:04Z
[ "python", "oracle", "python-2.7", "character-encoding", "polish" ]
Python 2.7 connection to Oracle: loosing (Polish) characters
39,780,090
<p>I connect from Python 2.7 to Oracle data base. When I use:</p> <pre><code>cursor.execute("SELECT column1 FROM table").fetchall()] </code></pre> <p>I have got almost proper values for column1 because all Polish characters ("ęóąśłżćń") are converted to ascii one ("eoaslzcn"). Using another tool like SQLDevel...
0
2016-09-29T21:10:45Z
39,872,368
<p>@Mark Harrison - thank you very much ! It works! There is an exact instruction what I did:</p> <p>I checked in Oracle what is the language:</p> <pre><code>SELECT USERENV ('language') FROM DUAL </code></pre> <p>The response was:</p> <pre><code>POLISH_POLAND.UTF8 </code></pre> <p>Then I changed NLS_LA value in Py...
0
2016-10-05T11:09:40Z
[ "python", "oracle", "python-2.7", "character-encoding", "polish" ]
stackplot legend issue when there is a secondary subplot for Matplotlib in python
39,780,101
<p>Here is my code and below it is the error produced. </p> <p>My legend appears, but only one of the lines is in it.<br> The stacked subplot labels do not appear. </p> <pre><code>import xlrd import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime file_location = "/Users/adampatel/Desktop/...
0
2016-09-29T21:11:57Z
39,939,998
<p>So I thought about it and googled a few solutions. Here are the lines of code that I used. </p> <pre><code>import xlrd import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.patches as mpatches import datetime file_location = "/Users/adampatel/Desktop/psw02.xls" workbook = xlrd.open_...
0
2016-10-09T04:21:00Z
[ "python", "matplotlib", "subplot" ]
Python code to accept pre-defined grammar
39,780,166
<p>I'm trying to make a code to recognize a chain of characters following the grammar rules:</p> <ul> <li>S-> abK</li> <li>K-> x|xK|H</li> <li>H-> c|d</li> </ul> <p>So that words like <em>abx</em>, <em>abxxx</em>, <em>abc</em>, <em>abxd</em>, <em>abxc</em>, etc... are all accepted and words like <em>ab</em>, <em>abb<...
0
2016-09-29T21:17:14Z
39,780,372
<p>Your implementation is unnecessarily verbose and repetitive: there is no need to pass around the index, for instance, when you can just pass to the next function the relevant part of the word. Here is a quick implementation I threw together that should resolve it:</p> <pre><code>def S(chars): word = ''.join(chars...
1
2016-09-29T21:32:49Z
[ "python", "grammar" ]
Python Multiprocessing - execution time increased, what am I doing wrong?
39,780,179
<p>I'm doing a simple multiprocessing test and something seems off. Im running this on i5-6200U 2.3 Ghz with Turbo Boost.</p> <pre><code>from multiprocessing import Process, Queue import time def multiply(a,b,que): #add a argument to function for assigning a queue que.put(a*b) #we're putting return value into que...
-1
2016-09-29T21:18:12Z
39,782,468
<p>Here's a brief example of (silly) code that gets a nice speedup. As already covered in comments, it doesn't create an absurd number of processes, and the work done per remote function invocation is high compared to interprocess communication overheads.</p> <pre><code>import multiprocessing as mp import time def f...
0
2016-09-30T01:46:27Z
[ "python", "multiprocessing", "python-multiprocessing" ]
python plotting with twiny() doesn't position ticks and destroys aspect-ratio
39,780,201
<p>I have created a function to plot many similar plots of contours. I am showing the minimal form of what I am doing. In this minimal example I would like to put only ticks at (0,0) A, (3,0) B, (3,3) C, (0,3) D, where A,B,C,D the labels of the ticks. I can get it to work up to putting A and B. When I introduce <code>t...
1
2016-09-29T21:20:07Z
39,780,937
<p>The aspect ratio is just fine, you see a perfect circle, don't you?</p> <p>Concerning the labels and their position you need to tell matplotlib that you want equal x limits. Put <code>bx.set_xlim(ax.get_xlim())</code> at the end of your function.</p>
0
2016-09-29T22:23:25Z
[ "python", "matplotlib", "aspect-ratio" ]
CSV Filtering for numpy
39,780,244
<p>I've got this rather large CSV file, and I only care about the rows that contain the word "Slave"...Some rows that contain Slave are not exactly the same as others, but they all contain the word "Slave".</p> <p>I want to throw away all the other rows and then work on the data that's left over in the other column.</...
1
2016-09-29T21:23:31Z
39,780,388
<p>As a csv, each line contains 2 columns, one before and one after the comma. <code>x[1][1]</code> is the second column from the second list, since python uses 0-based indices. And <code>x[:][1]</code> is equivalent to <code>x[1]</code>, so no surprise there.</p> <p>I suggest filtering and keeping the very first colu...
1
2016-09-29T21:33:57Z
[ "python", "list", "csv", "numpy", "filtering" ]
Django FileField not including uploaded file in form output request
39,780,247
<p>I am having trouble getting access to a simple uploaded file which I need to parse without saving it. Since the file does not need to be saved I have not made a model for it. All other threads on this state the html form encoding type, name tag are the primary reasons why request.FILES is not appearing-- I have addr...
0
2016-09-29T21:23:35Z
39,781,528
<p>Most likely, problem is just that you are trying to access file using wrong name. Field on form has name <code>docfile</code>. Same name it will have in <code>request.FILES</code> array. </p> <p>Possibly, you simply misunderstood an error message saying that there is no <code>file</code> in <code>FILES</code>. </p...
0
2016-09-29T23:28:02Z
[ "python", "html", "django", "filefield" ]
Django FileField not including uploaded file in form output request
39,780,247
<p>I am having trouble getting access to a simple uploaded file which I need to parse without saving it. Since the file does not need to be saved I have not made a model for it. All other threads on this state the html form encoding type, name tag are the primary reasons why request.FILES is not appearing-- I have addr...
0
2016-09-29T21:23:35Z
39,801,190
<p>So apparently the only thing missing was looking for request.FILES['docfile']</p> <p>not request.FILES['file'] . It works! Hope this is helpful to someone </p>
0
2016-09-30T22:55:39Z
[ "python", "html", "django", "filefield" ]
Rock, Paper, Scissors doesn't let user win
39,780,248
<pre><code>#RoShamBo import random count=0 while count&lt;2 and count&gt; -2: compnum=random.randint(0,2) usernum=int(input("Scissor(0), Rock(1), Paper(2)")) if compnum==0: if usernum==0: print("Draw") elif usernum==1: print("Win") count=count+1 el...
1
2016-09-29T21:23:36Z
39,780,332
<p>You can try it with <code>if count==2:</code></p>
2
2016-09-29T21:29:22Z
[ "python", "while-loop" ]
Numpy Savetxt Overwriting, Cannot Figure Out Where to Place Loop
39,780,364
<p>I am creating a program that calculates correlations between my customer's data. I want to print the correlation values to a CSV so I can further analyze the data.</p> <p>I have successfully gotten my program to loop through all the customers (12 months of data each) while calculating their individual correlations ...
0
2016-09-29T21:32:10Z
39,781,761
<p>This portion of the code is just sloppy:</p> <pre><code> result_correlation = [(demo_one_corr_balance),...] result_correlation_combined = emptylist.append([result_correlation]) cust_delete_list = [0,(x_customer),1] overalldata = numpy.delete(overalldata, (cust_delete_list), a...
1
2016-09-30T00:00:15Z
[ "python", "csv", "numpy", "for-loop", "overwrite" ]
Numpy Savetxt Overwriting, Cannot Figure Out Where to Place Loop
39,780,364
<p>I am creating a program that calculates correlations between my customer's data. I want to print the correlation values to a CSV so I can further analyze the data.</p> <p>I have successfully gotten my program to loop through all the customers (12 months of data each) while calculating their individual correlations ...
0
2016-09-29T21:32:10Z
39,782,057
<p>I took the advice of the above poster and corrected my code. I am now able to write to a file. However, I am having trouble with the number of iterations complete, I will post that in a different question as it is unrelated. Here is the solution that I used.</p> <pre><code>for x_customer in range(0,len(overalldata)...
0
2016-09-30T00:46:36Z
[ "python", "csv", "numpy", "for-loop", "overwrite" ]
Group by Column in Dataframe and create seperate csv for each group
39,780,399
<p>I have a huge csv file of 1 GB which contains records of each day .Example like below </p> <pre><code>Date orderquantity 2015-06-19 23 2015-06-19 30 2015-06-20 33 2015-06-20 40 </code></pre> <p>So record is present of each and everyday ,is there a efficient way in Python Pandas data frame where I ...
1
2016-09-29T21:35:23Z
39,780,621
<p>Try this:</p> <pre><code>for name, group in df.groupby('Date'): group.to_csv('{}.csv'.format(name), index=False) </code></pre>
1
2016-09-29T21:53:29Z
[ "python", "csv", "pandas", "dataframe" ]
python3: Read json file from url
39,780,403
<p>In python3, I want to load <a href="https://www.govtrack.us/data/congress/113/votes/2013/s11/data.json" rel="nofollow">this_file</a>, which is a json format.</p> <p>Basically, I want to do something like [pseudocode]:</p> <pre><code>&gt;&gt;&gt; read_from_url = urllib.some_method_open(this_file) &gt;&gt;&gt; my_di...
1
2016-09-29T21:35:31Z
39,780,472
<p>So you want to be able to reference specific values with inputting keys? If i think i know what you want to do, this should help you get started. You will need the libraries urlllib2, json, and bs4. just pip install them its easy.</p> <pre><code>import urllib2 import json from bs4 import BeautifulSoup url = urllib...
1
2016-09-29T21:40:57Z
[ "python", "json", "url" ]
python3: Read json file from url
39,780,403
<p>In python3, I want to load <a href="https://www.govtrack.us/data/congress/113/votes/2013/s11/data.json" rel="nofollow">this_file</a>, which is a json format.</p> <p>Basically, I want to do something like [pseudocode]:</p> <pre><code>&gt;&gt;&gt; read_from_url = urllib.some_method_open(this_file) &gt;&gt;&gt; my_di...
1
2016-09-29T21:35:31Z
39,780,510
<p>You were close:</p> <pre><code>import requests import json response = json.loads(requests.get("your_url").text) </code></pre>
3
2016-09-29T21:43:42Z
[ "python", "json", "url" ]
python3: Read json file from url
39,780,403
<p>In python3, I want to load <a href="https://www.govtrack.us/data/congress/113/votes/2013/s11/data.json" rel="nofollow">this_file</a>, which is a json format.</p> <p>Basically, I want to do something like [pseudocode]:</p> <pre><code>&gt;&gt;&gt; read_from_url = urllib.some_method_open(this_file) &gt;&gt;&gt; my_di...
1
2016-09-29T21:35:31Z
39,780,515
<p>Just use json and requests modules:</p> <pre><code>import requests, json content = requests.get("http://example.com") json = json.loads(content.content) </code></pre>
3
2016-09-29T21:43:54Z
[ "python", "json", "url" ]
scikit-learn - how to force selection of at least a single label in LinearSVC
39,780,473
<p>I'm doing a <a href="http://scikit-learn.org/stable/modules/multiclass.html" rel="nofollow">multi-label classification</a>. I've trained on a dataset and am getting back suggested labels. However, not all have at least a single label. I'm running into this exact issue that was <a href="http://scikit-learn-general...
0
2016-09-29T21:40:58Z
39,792,433
<p>Thanks to "lejlot", this was extremely close to what I wanted. I didn't want to override the cases where I had one or more predictions though. This is what I came up with that seems to be working:</p> <pre><code>lb = preprocessing.MultiLabelBinarizer() Y = lb.fit_transform(y_train_text) classifier = Pipeline([ ...
0
2016-09-30T13:14:17Z
[ "python", "machine-learning", "scipy", "scikit-learn" ]
Python - Split crontab entry to 6 fields
39,780,573
<p>I would like to know how to split a crontab line into 6 variables like the following. Maybe with split() or other string functions.</p> <pre><code>Input: 0 5 * * * Command1 arg1 arg2;Command2 arg1 arg2;... Output: Var1 = 0 Var2 = 5 Var3 = * Var4 = * Vat5 = Command1 arg1 arg 2;Command 2 arg1 arg2... </code></pre>...
0
2016-09-29T21:49:28Z
39,780,603
<p><a href="https://docs.python.org/3.6/library/stdtypes.html#str.split" rel="nofollow"><code>str.split()</code></a> has an optional 2nd argument to limit the number of returned values:</p> <pre><code>In [11]: s='0 5 * * * Command1 arg1 arg2;Command2 arg1 arg2;...' In [12]: s.split(None, 5) Out[12]: ['0', '5', '*', '...
1
2016-09-29T21:51:40Z
[ "python", "split", "crontab" ]
UDP- Trouble reading bytes from socket in python?
39,780,683
<p>I'm trying to send 14bit sensor data from a microcontroller to a PC using UDP Protocol. When I send the data and receive it on the <code>package sender</code> application I am getting data in hex as expected.</p> <p><a href="http://i.stack.imgur.com/xyUBI.jpg" rel="nofollow">Energia Code: </a></p> <p><a href="http...
0
2016-09-29T21:59:40Z
39,782,080
<p>You can use the <code>struct</code> module to unpack it like this:</p> <pre><code>import struct data = ['\x03W'] val = struct.unpack('&gt;H', data[0]) # now an integer </code></pre>
0
2016-09-30T00:50:16Z
[ "python", "arduino", "network-programming", "udp", "serversocket" ]
Python index out of range when missing user user input
39,780,700
<p>I know this is a simple fix--but I can't for the life of me figure out how to fix this IndexError. </p> <pre><code>def show_status(): print("\nThis is the " + rooms[current_room]["name"]) rooms = { 1 : { "name" : "Highway" , "west" : 2 , "east" : 2 , "north...
1
2016-09-29T22:01:37Z
39,780,749
<p><code>move[0]</code> checks for the first member of the list, and will throw an <code>IndexError</code> if <code>move</code> is an empty, as when the user simply presses enter. You can check that <code>move</code> is true first: if it isn't, the <code>and</code> operator will circumvent the next check.</p> <p>It se...
1
2016-09-29T22:05:45Z
[ "python", "indexoutofrangeexception" ]
Hiding rows in QTableWidget if 1 of the column does not have any values
39,780,704
<p>I had wanted some opinions about a portion of code that I have written. My UI consists of a QTableWidget in which it has 2 columns, where one of the 2 columns are populated with QComboBox.</p> <p>For the first column, it will fill in the cells with the list of character rigs (full path) it finds in the scene, while...
0
2016-09-29T22:01:49Z
39,781,300
<p>You can hide rows using <a href="http://doc.qt.io/qt-4.8/qtableview.html#setRowHidden" rel="nofollow">setRowHidden</a>. As for the rest of the code, I don't see much wrong with what you currently have, but FWIW I would write it something like this (completely untested, of course):</p> <pre><code>def populate_table_...
1
2016-09-29T23:00:23Z
[ "python", "combobox", "pyqt", "maya" ]
how to generate a responsive PDF with Django?
39,780,715
<p>how to generate a responsive PDF with Django?.</p> <p>I want to generate a PDF with Django but i need that is responsive, that is to say, the text of the PDF has that adapted to don't allow space empty.</p> <p>for example to a agreement this change in the text, then, i need to adapt the to space of paper leaf.</p>...
1
2016-09-29T22:02:24Z
39,792,862
<p>PDF is not built to be responsive, it is built to display the same no matter where it is viewed.</p> <p>As @alxs pointed out in a comment, there are a few features that PDF viewing applications have added to simulate PDFs being responsive. Acrobat's <em>Reflow</em> feature is the best example of this that I am awar...
1
2016-09-30T13:36:09Z
[ "python", "html", "django", "pdf-generation", "weasyprint" ]
How to remove spacing inside a gridLayout (QT)?
39,780,766
<p>I want to create a child container layout which will contains 2 widgets. Those 2 widgets should be placed right next to each other but my current setup still has some spacing in between.</p> <p>I have already set the spacing to 0 <code>setSpacing(0)</code>. And <code>setContentsMargins(0,0,0,0)</code> doesn't helpe...
-1
2016-09-29T22:07:32Z
39,781,072
<p>The QT documentation says: <strong>By default, QLayout uses the values provided by the style. On most platforms, the margin is 11 pixels in all directions.</strong></p> <p>Ref:<a href="http://doc.qt.io/qt-4.8/qlayout.html#setContentsMargins" rel="nofollow">http://doc.qt.io/qt-4.8/qlayout.html#setContentsMargins</a>...
0
2016-09-29T22:38:24Z
[ "python", "c++", "qt", "pyqt", "qgridlayout" ]
How to build a sparkSession in Spark 2.0 using pyspark?
39,780,792
<p>I just got access to spark 2.0; I have been using spark 1.6.1 up until this point. Can someone please help me set up a sparkSession using pyspark (python)? I know that the scala examples available online are similar (<a href="https://databricks-prod-cloudfront.cloud.databricks.com/public/4027ec902e239c93eaaa8714f173...
1
2016-09-29T22:09:33Z
39,781,384
<p>As you can see in the scala example, Spark Session is part of sql module. Similar in python. hence, see <a href="http://spark.apache.org/docs/latest/api/python/pyspark.sql.html" rel="nofollow">pyspark sql module documentation</a></p> <blockquote> <p>class pyspark.sql.SparkSession(sparkContext, jsparkSession=None)...
0
2016-09-29T23:11:01Z
[ "python", "sql", "apache-spark", "pyspark" ]
Why is python adding "ï £" to my filenames when decrypting AES?
39,780,940
<p>I'm not running into any error just the output for my program is doing something strange. I've also noticed this thread here: <a href="http://stackoverflow.com/questions/30070309/encrypt-file-with-aes-256-and-decrypt-file-to-its-original-format">Encrypt file with AES-256 and Decrypt file to its original format</a>. ...
0
2016-09-29T22:23:56Z
39,781,113
<p>Let's read the <a href="https://docs.python.org/2/library/stdtypes.html#bltin-file-objects" rel="nofollow">documentation</a> (emphasis mine):</p> <blockquote> <pre><code>file.readline([size]) </code></pre> <p>Read one entire line from the file. <strong><em>A trailing newline character is kept in the string (bu...
2
2016-09-29T22:41:30Z
[ "python", "linux", "encryption", "cryptography", "filenames" ]
Getting Error with Django Phone Number Form Field
39,780,945
<p>I'm building a Django form that includes a phone number field. I've been referring to these two SO questions to understand how to do it: <a href="http://stackoverflow.com/questions/19130942/whats-the-best-way-to-store-phone-number-in-django-models">1</a>, <a href="http://stackoverflow.com/questions/6478875/regular-...
0
2016-09-29T22:24:11Z
39,781,139
<p>I just discovered the error. It's in this line:</p> <pre><code>error_messages = {'required', 'Phone number required'}, </code></pre> <p>I needed to replace the "," with a ":":</p> <pre><code>error_messages = {'required': 'Phone number required'}, </code></pre>
0
2016-09-29T22:43:31Z
[ "python", "django", "django-forms" ]
Using while loops and variables
39,780,993
<p>I'm trying to write a collatz program from the 'Automate the Boring Stuff with Python book', but have ran into some problems. I'm using python 3.5.2. Here's the project outline:</p> <blockquote> <p>Write a function named collatz() that has one parameter named number. If number is even, then collatz() should print...
0
2016-09-29T22:29:57Z
39,781,021
<p>Your code:</p> <pre><code>while(True): if collatz(num) == 1: break </code></pre> <p>didn't work because everytime <code>collatz</code> gets called it gets called with the same value of num and as a result returns the same number again and again. That number is not 1, so you have an infinite loop.</p> ...
2
2016-09-29T22:33:10Z
[ "python", "variables", "while-loop" ]
traversing folders, several subfolders for the files in python
39,781,110
<p>I've a folder structure similar to what's outlined below.</p> <pre><code>Path | | +----SubDir1 | | | +---SubDir1A | | | | | |----- FileA.0001.ext | | |----- ... | | |----- ... | | |----- FileA.1001.ext | | |----- FileB.0001.ext | ...
1
2016-09-29T22:41:09Z
39,829,545
<p>Your issue is actually those two lines, remove them and you sould be fine:</p> <pre><code>if len(subdirList) &gt; 0: del subdirList[0] </code></pre> <p><strong>Explanation</strong> : </p> <p>What they do is <strong>they make the first subdirectory inside each directory disappear before <code>os.walk</code> ha...
0
2016-10-03T10:32:12Z
[ "python", "glob", "folders", "subdirectories", "os.walk" ]
Python: Looping through a list of dictionaries and extracting values to a new dictionary
39,781,154
<p>I need to loop on a list of dictionaries and check if a value exist. If it exists then I take another value from this same dictionary and store it on a new dictionary inside another list. What I have is this</p> <pre><code>class_copy=[] for root, dirs, files in os.walk(files_path+"/TD"): for file in files: ...
-2
2016-09-29T22:44:46Z
39,781,192
<p>You are not actually creating a <em>new</em> dictionary, you are updating an existing one:</p> <pre><code>cc['class']=d['fic'] </code></pre> <p>simply updates the value associated with the key <code>'class'</code>. Change your code to this:</p> <pre><code>cc = {'class': d['fic']} </code></pre> <p>which will crea...
3
2016-09-29T22:49:34Z
[ "python", "loops", "dictionary" ]
Python: Looping through a list of dictionaries and extracting values to a new dictionary
39,781,154
<p>I need to loop on a list of dictionaries and check if a value exist. If it exists then I take another value from this same dictionary and store it on a new dictionary inside another list. What I have is this</p> <pre><code>class_copy=[] for root, dirs, files in os.walk(files_path+"/TD"): for file in files: ...
-2
2016-09-29T22:44:46Z
39,781,197
<pre><code>class_copy.append({'class': d['fic']'}) </code></pre>
0
2016-09-29T22:49:59Z
[ "python", "loops", "dictionary" ]
multiple for loop to select special rows from a dataframe in python
39,781,176
<p>I have a large data frame in python and I want to select specific rows based on multiple for loops. Some columns contain lists in them. My final goal is to generate some optimization constraints and pass them through another software:</p> <pre><code> T S W Arrived Departed [1,2] [4,...
1
2016-09-29T22:46:44Z
39,783,264
<p>Currently, you are constantly adjusting your dataframe with each nested loop where <code>A</code> is re-written over each time and does not yield a growing result but only of the very, very last iteration.</p> <p>But consider creating a cross join of all ranges and then checking the equality logic:</p> <pre><code>...
0
2016-09-30T03:35:51Z
[ "python", "for-loop", "dataframe" ]
install YCM error: python site module not loaded
39,781,219
<p>So I really wanted to try YCM, which has been said to be a great plugin for Vim. I have been spending several hours on installation and cannot succeed due to the error of <code>E887: Sorry, this command is disabled, the Python's site module could not be loaded.</code> </p> <p>I installed MacVim, Vim, and Python usi...
1
2016-09-29T22:51:56Z
39,781,841
<p>This issue usually happens when recompiling python after vim, try to just reinstall vim &amp; macvim, the issue might get resolved.</p> <pre><code>$ brew reinstall vim macvim </code></pre> <p>hope this helps</p>
0
2016-09-30T00:15:14Z
[ "python", "vim", "homebrew", "macvim", "youcompleteme" ]
install YCM error: python site module not loaded
39,781,219
<p>So I really wanted to try YCM, which has been said to be a great plugin for Vim. I have been spending several hours on installation and cannot succeed due to the error of <code>E887: Sorry, this command is disabled, the Python's site module could not be loaded.</code> </p> <p>I installed MacVim, Vim, and Python usi...
1
2016-09-29T22:51:56Z
39,796,681
<p>So I had this same problem on Sierra, home-brew seems to be placing the latest python here:</p> <pre><code>/usr/local/Cellar/python/2.7.12_1/Frameworks </code></pre> <p>But <code>brew install vim</code> ends up trying to link to python from the wrong directory. Looking at <code>vim --version | grep python</code> I...
2
2016-09-30T17:11:30Z
[ "python", "vim", "homebrew", "macvim", "youcompleteme" ]
install YCM error: python site module not loaded
39,781,219
<p>So I really wanted to try YCM, which has been said to be a great plugin for Vim. I have been spending several hours on installation and cannot succeed due to the error of <code>E887: Sorry, this command is disabled, the Python's site module could not be loaded.</code> </p> <p>I installed MacVim, Vim, and Python usi...
1
2016-09-29T22:51:56Z
39,799,937
<p>While @Matthew Hutchinson's answer help me got vim and python connected, I found the answer in this <a href="https://github.com/Valloric/YouCompleteMe/issues/620" rel="nofollow">issue of YCM</a> stop Python from crashing by the command <code>export DYLD_FORCE_FLAT_NAMESPACE=1</code>, thanks to <a href="https://githu...
0
2016-09-30T20:53:45Z
[ "python", "vim", "homebrew", "macvim", "youcompleteme" ]
Why is my python unittest script calling my script when I am importing it?
39,781,233
<p>I am trying to test a python script and when I import the script into my testing suite, it calls the script. In my example below I import list3rdparty and once I run the test it immediate calls list3rdparty. I do not want this to happen. I would like the test to only call the functions within every test case.</p> l...
1
2016-09-29T22:53:20Z
39,781,284
<p>You probably have code at the module level which will be executed on import. For example, if you had a file with the following, it will print the string the first time it's imported.</p> <pre><code>import something from whatever import another print 'ding' </code></pre> <p>To avoid this, put the code inside a blo...
2
2016-09-29T22:59:09Z
[ "python", "unit-testing", "python-unittest" ]
File does not complete write until script completes
39,781,257
<p>I'm getting stuck on something i think should be simple enough. I'm creating a file containing a json string to import into a postgres database. However the file does not import even though an internal test by the python script says it is present. </p> <p>However if i execute the postgres import after the script h...
0
2016-09-29T22:56:28Z
39,781,314
<p>You are not closing the file.</p> <p>This does nothing, becuase it is missing parenthesis:</p> <pre><code>dataFile.close </code></pre> <p>But event if it did close, it would do it in first iteration through xx.</p> <p>Do it this way:</p> <pre><code>with open('Data.txt','w') as dataFile: for x in xx: ...
4
2016-09-29T23:01:43Z
[ "python", "json", "io" ]
Find the location that occurs most in every cluster in DBSCAN
39,781,262
<p>Playing around with this DBSCAN example: <a href="http://geoffboeing.com/2014/08/clustering-to-reduce-spatial-data-set-size/" rel="nofollow">http://geoffboeing.com/2014/08/clustering-to-reduce-spatial-data-set-size/</a></p> <p>The author uses center-most point for each cluster. However, I would like to use the co-o...
0
2016-09-29T22:57:05Z
39,785,224
<p>That blog post is not particularly good.</p> <p>By setting min_samples=1 he is not really using DBSCAN (because this disables <em>density</em>). Instead, he obtained a <em>single-linkage hierarchical clustering</em> result (with the dendrogram 'cut' at height epsilon).</p> <p>Because DBSCAN allows arbitrary shaped...
1
2016-09-30T06:41:49Z
[ "python", "pandas", "scikit-learn", "cluster-analysis", "dbscan" ]
Reference imported class from within imported class
39,781,301
<p>For a chess board, imagine there's a <code>Board</code> class, with a <code>squares</code> attribute, which is an array of <code>Square</code> instances. The file structure is that there is <code>main.py</code>, <code>board.py</code>, <code>square.py</code>, and an empty <code>__init__.py</code> (I have to say I don...
-1
2016-09-29T23:00:23Z
39,781,336
<p>In main.py you import both classes, however, Board has no way to see Square, and vice versa. Add "import Square" to your Board class, and remove it from main.py.</p>
0
2016-09-29T23:04:43Z
[ "python", "class", "namespaces", "python-import" ]
UndefinedError: 'None' has no attribute 'key'
39,781,327
<p>How would I access <code>{{c.key().id()}}</code> in my python file? It correctly prints out the correct id in my html. When I try to get the id from the request I get an error <code>UndefinedError: 'None' has no attribute 'key'</code> but if I set the <code>id</code> to something such as <code>id=5222955109842944</...
0
2016-09-29T23:03:16Z
39,781,341
<p><code>self.request.get('id')</code> is a string. You need to turn it into an <code>int</code>:</p> <p><code>int(self.request.get('id'))</code></p>
1
2016-09-29T23:05:29Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
Django. Access the foreign key fields in the template from a form object
39,781,330
<p>I use Django 1.8.14. I have two models:</p> <pre><code>class Event(models.Model): title = models.CharField(max_length=255,) date = models.DateTimeField() ... def __unicode__(self): return self.title class Card(models.Model): user = models.ForeignKey(MyUser, related_name="user") ...
0
2016-09-29T23:03:40Z
39,795,625
<p>I've found a solution.</p> <pre><code>class CardForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CardForm, self).__init__(*args, **kwargs) self.fields['event'].label_from_instance = lambda obj: "%s %s" % (obj.title, obj.date) </code></pre>
0
2016-09-30T16:00:26Z
[ "python", "django", "django-forms" ]
Communication to Different Networks
39,781,344
<p>I would like to make a game with python and PyGame where two players play via wi-fi on different networks networks. I currently have this code (which I got from a video). </p> <pre><code># SERVER import socket def Main(): host = '127.0.0.1' port = 5000 s = socket.socket(socket.AF_INET, socket.SOCK_DG...
0
2016-09-29T23:05:45Z
39,781,459
<p>change to <code>host= '0.0.0.0'</code> (for the server)</p> <p>this makes it publish to any available interface ... if you have a router you (probably) will also need to use the port-forward settings of your router to direct traffic to the correct computer</p> <p>as an aside ... what is this nonsense? <code>server...
0
2016-09-29T23:19:32Z
[ "python", "networking", "udp" ]
python function parameters that include symbols
39,781,444
<p>I wrote a python script as below</p> <pre><code>def single_value(account,key): file = open('%s.txt'%account) file.write('Hello') file.close() file2 = open('%s.txt'%key) file2.write('hoiiii') file2.close() single_value(accountname, 2345kwjhf53825==) </code></pre> <p...
0
2016-09-29T23:16:47Z
39,781,502
<p>The invalid syntax error is because strings must be in quotes. Thus, replace:</p> <pre><code>single_value(accountname, 2345kwjhf53825==) </code></pre> <p>With:</p> <pre><code>single_value('accountname', '2345kwjhf53825==') </code></pre> <p>The next error is that the files are opened read-only and you want to wr...
2
2016-09-29T23:24:25Z
[ "python", "python-3.x" ]
Trying to average a list, but I don't know what is meant by the error: unsupported operand type(s) for +: 'int' and 'tuple'
39,781,621
<pre><code>First_Name = input("What is your first name: ") Last_Name = input("what is your Last Name: ") print ("Hello, let's see what your grades are like", First_Name, Last_Name, ",you degenerate!") grade_one = int(input("Enter your first grade: ")) grade_two = int(input("Enter your second grade: ")) grade_three...
1
2016-09-29T23:40:31Z
39,781,660
<h1>Explanation</h1> <p>That is because you are creating a tuple at this line: </p> <pre><code>grades = grade_one,grade_two,grade_three,grade_four,grade_five </code></pre> <p>If you set a <code>print(grades)</code> right after that line, you will see your output is, for example: </p> <pre><code>(56, 56, 56, 56, 56)...
1
2016-09-29T23:45:00Z
[ "python", "list", "compiler-errors" ]
NumPy Array to List Conversion
39,781,628
<p>In OpenCV 3 the function <code>goodFeaturesToTrack</code> returns an array of the following form</p> <pre><code>[[[1, 2]] [[3, 4]] [[5, 6]] [[7, 8]]] </code></pre> <p>After converting that array into a Python list I get </p> <pre><code>[[[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]]] </code></pre> <p>Although this is...
0
2016-09-29T23:41:31Z
39,781,884
<p>Because you have a 3d array with one element in second axis:</p> <pre><code>In [26]: A = [[[1, 2]], [[3, 4]], [[5, 6]], [[7, 8]]] In [27]: A[0] Out[27]: [[1, 2]] </code></pre> <p>And when you want to access the second item by <code>A[0][1]</code> it raises an IndexError:</p> <pre><code>In [28]: A[0][1] ---------...
1
2016-09-30T00:21:42Z
[ "python", "python-3.x", "opencv" ]
TypeError: 'int' object does not support item assignment, In threads
39,781,629
<p>I have 2 modules:</p> <p>First Keyboard.py</p> <pre><code>import USB,evdev,threading,sys global codigo codigo = [1] class Teclado: def __init__(self,port): self.puerto = USB.usb(port) def iniciar_teclado(self): p = threading.Thread(target=self.puerto.obtener_evento,args=(codigo)) p...
0
2016-09-29T23:41:35Z
39,781,850
<p>try</p> <pre><code>p = threading.Thread(target=self.puerto.obtener_evento,args=(codigo,)) </code></pre>
0
2016-09-30T00:16:21Z
[ "python", "pass-by-reference", "python-multithreading", "input-devices" ]
FlaskWTFDeprecationWarning with Flask_Security
39,781,635
<p>I am received a warning every time I use Flask Security.</p> <pre><code>FlaskWTFDeprecationWarning: "flask_wtf.Form" has been renamed to "FlaskForm" and will be removed in 1.0. </code></pre> <p>Is this an issue with Flask Security or something I could address myself? I am using Flask-Security==1.7.5</p> <pre><co...
1
2016-09-29T23:42:04Z
39,782,045
<p>It looks like 1.7.5 is the latest release of Flask-Security. And the latest version of Flask-WTF is 0.13 (make sure you have that installed by checking a <code>pip freeze</code>).</p> <p>Since you don't use Flask-WTF directly, the issue isn't your code. The issue is coming from Flask-Security's code itself, <a hr...
3
2016-09-30T00:45:13Z
[ "python", "flask-security" ]
Django - get_or_create() with auto_now=True
39,781,666
<p>I’m using Django and I'm having a problem with a Python script that uses Django models The script that I'm using takes data from an api and loads it into my database.</p> <p>my model:</p> <pre><code>class Movie(models.Model): title = models.CharField(max_length=511) tmdb_id = models.IntegerField(null=Tru...
1
2016-09-29T23:45:27Z
39,785,754
<blockquote> <p>but the purpose I put the edit field is to know when exactly a movie got edited, ie: some other field got changed.</p> </blockquote> <p>That probably means you are using the wrong function. You should be using <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#update-or-create" r...
1
2016-09-30T07:13:30Z
[ "python", "django" ]
Factory class with abstractmethod
39,781,670
<p>I've created a factory class called <code>FitFunction</code> that adds a whole bunch of stuff beyond what I've shown. The label method <code>pretty_string</code> is supposed to just return the string as written. When I run this file, it prints a string that is as useful as the <code>repr</code>. Does someone know ho...
1
2016-09-29T23:45:53Z
39,781,711
<p>Use:</p> <pre><code>print("Gaussian.pretty_string: %s" % Gaussian.pretty_string()) </code></pre> <p>Or else you are printing the <code>repr</code> of the <em>method</em>, not the <em>result of calling the method</em>, which is the string you are looking for.</p>
0
2016-09-29T23:53:57Z
[ "python", "abstract-factory", "abc" ]
Factory class with abstractmethod
39,781,670
<p>I've created a factory class called <code>FitFunction</code> that adds a whole bunch of stuff beyond what I've shown. The label method <code>pretty_string</code> is supposed to just return the string as written. When I run this file, it prints a string that is as useful as the <code>repr</code>. Does someone know ho...
1
2016-09-29T23:45:53Z
39,782,921
<p>I am unsure if this will fix your problem since I cannot check it myself right now but you should probably be using <code>@abc.abstractstaticmethod</code> (and get rid of the <code>self</code> argument obviously) to decorate the base class method. If that doesn't fix it I'll delete this answer later. If it does fix ...
0
2016-09-30T02:52:44Z
[ "python", "abstract-factory", "abc" ]
SSHed into my Vagrant virtual machine to run a python script...but the python script doesn't work unless I'm in the VM itself
39,781,746
<p>I have a Vagrant virtual machine that I use for running automated tests. When I vagrant up and open up the console in my virtual machine, I'm able to start my tests with a simple command on the command line. After SSHing into that virtual machine and running the same exact script from the same exact directory, I'm g...
1
2016-09-29T23:58:26Z
39,796,430
<p>You aren't using the same Python executable in the two environments. For some reason, your vagrant console is using a <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtual environment</a>.</p> <p>When you SSH into your VM, run this command before executing your test script:</p> <pre><code>source /...
2
2016-09-30T16:53:32Z
[ "python", "selenium", "ssh", "vagrant", "robot" ]
how to convert data into list in python
39,781,774
<p>I have sample dataset A. It looks like:</p> <pre><code>1:CH,AG,ME,GS;AP,CH;HE,AC;AC,AG 2:CA;HE,AT;AT,AC;AT,OG 3:NE,AG,AC;CS,OD </code></pre> <p>The expected result should be:</p> <pre><code>['CH','AG','ME','GS','AP','CH','HE','AC','AC','AG','CA','HE','AT','AT','AC','AT','OG','NE','AG','AC','CS','OD'] </code></pre...
-1
2016-09-30T00:02:43Z
39,781,792
<p>One option would be to locate all 2 consecutive upper-case letter cases with a regular expression:</p> <pre><code>In [1]: import re In [2]: data = """ ...: 1:CH,AG,ME,GS;AP,CH;HE,AC;AC,AG ...: 2:CA;HE,AT;AT,AC;AT,OG ...: 3:NE,AG,AC;CS,OD""" In [3]: re.findall(r"[A-Z]{2}", data, re.MULTILINE) Out[3]: ['C...
4
2016-09-30T00:05:24Z
[ "python", "list" ]
excel file merge with sheets in python
39,781,784
<p>I am trying to append many excel files with sheet1 and sheet2. I have written the following code</p> <pre><code>import os import pandas as pd files = os.listdir("C:/Python27/files") files df = pd.DataFrame() for f in files: data = pd.read_excel(f, 'Sheet1', 'Sheet2') df = df.append(data) </code></pre> <p>...
0
2016-09-30T00:04:27Z
39,782,199
<p>Python <code>os.listdir</code> will return a list containing the <strong>relative names</strong> of files inside the given directory. If you are running your script from a folder other than <code>"C:/Python27/files"</code> (or whatever folder your xls files are located), then you need to give it the full path to the...
0
2016-09-30T01:09:53Z
[ "python", "excel" ]
How can I tell if Gensim Word2Vec is using the C compiler?
39,781,812
<p>I am trying to use Gensim's Word2Vec implementation. Gensim warns that if you don't have a C compiler, the training will be 70% slower. Is there away to verify that Gensim is correctly using the C Compiler I have installed?</p> <p>I am using Anaconda Python 3.5 on Windows 10.</p>
1
2016-09-30T00:09:37Z
39,940,007
<p>Apparently gensim offers a variable to detect this:</p> <pre><code>assert gensim.models.doc2vec.FAST_VERSION &gt; -1 </code></pre> <p>I found this line in this tutorial: <a href="https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/doc2vec-IMDB.ipynb" rel="nofollow">https://github.com/RaRe-Techn...
1
2016-10-09T04:24:25Z
[ "python", "compilation", "installation", "gensim", "word2vec" ]
How can I tell if Gensim Word2Vec is using the C compiler?
39,781,812
<p>I am trying to use Gensim's Word2Vec implementation. Gensim warns that if you don't have a C compiler, the training will be 70% slower. Is there away to verify that Gensim is correctly using the C Compiler I have installed?</p> <p>I am using Anaconda Python 3.5 on Windows 10.</p>
1
2016-09-30T00:09:37Z
39,940,533
<p>Gensim provides both wheels and an installer for Windows.</p> <pre><code>pip install gensim </code></pre> <p>should get you gensim with Cython optimization without the work of getting Cython up and running (not that it's not great to have Cython, but sometimes it's nice to just have stuff run).</p>
1
2016-10-09T06:02:17Z
[ "python", "compilation", "installation", "gensim", "word2vec" ]
How can i simplify this condition in python?
39,781,887
<p>Do you know a simpler way to achieve the same result as this? I have this code:</p> <pre><code>color1 = input("Color 1: ") color2 = input("Color 2: ") if ((color1=="blue" and color2=="yellow") or (color1=="yellow" and color2=="blue")): print("{0} + {1} = Green".format(color1, color2)) </code></pre> <p...
9
2016-09-30T00:22:10Z
39,781,928
<p>Don't miss the <em>bigger picture</em>. Here is a better way to approach the problem in general.</p> <p>What if you would define the "mixes" dictionary where you would have mixes of colors as keys and the resulting colors as values.</p> <p>One idea for implementation is to use immutable by nature <a href="https://...
7
2016-09-30T00:27:48Z
[ "python", "python-3.x", "if-statement", "condition", "simplify" ]
How can i simplify this condition in python?
39,781,887
<p>Do you know a simpler way to achieve the same result as this? I have this code:</p> <pre><code>color1 = input("Color 1: ") color2 = input("Color 2: ") if ((color1=="blue" and color2=="yellow") or (color1=="yellow" and color2=="blue")): print("{0} + {1} = Green".format(color1, color2)) </code></pre> <p...
9
2016-09-30T00:22:10Z
39,781,933
<p>You can use <code>set</code>s for comparison.</p> <blockquote> <p>Two sets are equal if and only if every element of each set is contained in the other</p> </blockquote> <pre><code>In [35]: color1 = "blue" In [36]: color2 = "yellow" In [37]: {color1, color2} == {"blue", "yellow"} Out[37]: True In [38]: {color...
19
2016-09-30T00:28:37Z
[ "python", "python-3.x", "if-statement", "condition", "simplify" ]
Split words on boundary
39,781,936
<p>I have some tweets which I wish to split into words. Most of it works fine except when people combine words like: <code>trumpisamoron</code> or <code>makeamericagreatagain</code>. But then there are also things like <code>password</code> which shouldn't be split up into <code>pass</code> and <code>word</code>.</p> ...
1
2016-09-30T00:29:07Z
39,800,133
<p>Ref : My Answer on another Question - <a href="http://stackoverflow.com/questions/38621703/need-to-split-tags-to-text/38624458#38624458">Need to split #tags to text</a>.</p> <p>Changes in this answer I made are - (1) Different corpus to get <code>WORDS</code> and (2) Added <code>def memo(f)</code> to speed up proce...
1
2016-09-30T21:08:36Z
[ "python", "nlp", "nltk" ]
Python Django, access to function value through urls?
39,781,967
<p>how can I get the value of "otro" function ?, this code works but it only show me the value of get function, how can get the value of otro? I do not understand how to do it un the urls.</p> <pre><code>views: from django.views.generic import ListView, View from . models import Autor from django.shortcuts import re...
0
2016-09-30T00:33:34Z
39,782,026
<p>Django has <a href="https://docs.djangoproject.com/en/1.10/topics/class-based-views/intro/" rel="nofollow">class based generic views</a>, a system that allows you to use basic functionally without writing repetitive code. If you would like to return a <code>HttpResponse</code> with custom output, like "otro" or a JS...
0
2016-09-30T00:42:33Z
[ "python", "django" ]
Python 2.7 on Mac OSX. Corrupt module of framework
39,782,024
<p>I'm learning python and made a program on Mac OSX El Capitan and the code was working fine but randomly it started givving me errors without me changing anything in the code. I keep getting this Message:</p> <pre> Traceback (most recent call last): File "time.py", line 2, in &lt;module> from lxml import html ...
0
2016-09-30T00:42:14Z
39,785,814
<p>Thanks for the help. I changed the name of the file to t.py like ShreevatsaR said. Also put the file on Desktop, and I have everything installed through pip. For some odd reason I installed requests and tabulate manually by downloading them and running setup.py and vuala!! It worked!</p> <p>user3543300, maybe the p...
0
2016-09-30T07:17:18Z
[ "python", "osx" ]
Move to next column after specific number of lines in python
39,782,060
<p>If I have a data set that runs:<br> 1<br> 2<br> 3<br> 4<br> 5<br> 6<br> from a python output, and i want:<br> 1 4<br> 2 5<br> 3 6<br> basically after a specific number of lines, I would like to move the output into the next column, can this be done in Python? </p> <p>This is what I currently have: </p> <p><co...
0
2016-09-30T00:46:54Z
39,782,805
<pre><code>lines = ['1','2','3','4','5','6'] print(lines[:round(len(lines)/2)]) for i in range(round(len(lines)/2)): print(lines[i] + lines[i + 3], sep=' ') ## 1 4 ## 2 5 ## 3 6 </code></pre> <p>Anyways you are going to keep your file data in list. So I see that you are able to do it by your own. It is the f...
0
2016-09-30T02:35:52Z
[ "python", "file", "row", "multiple-columns", "lines" ]
Python Iterating Through Large Data Set and Deleting Assessed Data
39,782,084
<p>I am working with a data set with 10,000 customers data from months 1-12. I am generating correlations for different values over the 12 month period for each customer.</p> <p>Currently my output correlation file has more rows than my original file. I realize this is an iteration error from when I am trying to delet...
-1
2016-09-30T00:50:57Z
39,791,710
<p>This may not completely solve your problem, but I think it's relevant.</p> <p>When you run <code>.append</code> on a list object (empty or otherwise), the value returned by that method is <code>None</code>. So, with the line <code>result_correlation_combined = emptylist.append([result_correlation])</code>, regardle...
0
2016-09-30T12:37:19Z
[ "python", "list", "csv", "for-loop", "iteration" ]
Computing aggregate by creating nested dictionary on the fly
39,782,108
<p>I'm new to python and I could really use your help and guidance at the moment. I am trying to read a csv file with three cols and do some computation based on the first and second column i.e.</p> <pre><code>A spent 100 A spent 2040 A earned 60 B earned 48 B earned 180 A spent 40 . . . </cod...
4
2016-09-30T00:55:38Z
39,782,312
<pre><code>if record in entries[truck]: entries[truck][record].append(amount) else: entries[truck][record] = [amount] </code></pre> <p>I believe this is what you would want? Now we are directly accessing the truck's records, instead of trying to check a local dictionary called <code>records</code>. Just like y...
0
2016-09-30T01:23:40Z
[ "python", "pandas", "dictionary", "group-by", "aggregate" ]
Computing aggregate by creating nested dictionary on the fly
39,782,108
<p>I'm new to python and I could really use your help and guidance at the moment. I am trying to read a csv file with three cols and do some computation based on the first and second column i.e.</p> <pre><code>A spent 100 A spent 2040 A earned 60 B earned 48 B earned 180 A spent 40 . . . </cod...
4
2016-09-30T00:55:38Z
39,794,082
<p>For the kind of calculation you are doing here, I highly recommend <a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a>.</p> <p>Assuming <code>in.csv</code> looks like this:</p> <pre><code>truck,type,amount A,spent,100 A,earned,60 B,earned,48 B,earned,180 A,spent,40 </code></pre> <p>You can do the totall...
2
2016-09-30T14:38:57Z
[ "python", "pandas", "dictionary", "group-by", "aggregate" ]
List previous prime numbers of n
39,782,111
<p>I am trying to create a program in python that takes a number and determines whether or not that number is prime, and if it is prime I need it to list all of the prime numbers before it. What is wrong with my code?</p> <pre><code>import math def factor(n): num=[] for x in range(2,(n+1)): i=2 ...
-1
2016-09-30T00:56:21Z
39,782,296
<p>Your method only returns whether the 'n' is prime or not. For this purpose, you don't need a nested loop. Just like this</p> <pre><code>def factor(n): num=[] for x in range(2,(n+1)): if n % x == 0: break if x &gt; abs(n-1): num.append(n) print(n,"is prime",num) el...
0
2016-09-30T01:22:12Z
[ "python", "prime-factoring" ]
Python: Check if a numpy array contains an object with specific attribute
39,782,113
<p>I want to check if there is any object with a specific attribute in my numpy array:</p> <pre><code>class Test: def __init__(self, name): self.name = name l = numpy.empty( (2,2), dtype=object) l[0][0] = Test("A") l[0][1] = Test("B") l[1][0] = Test("C") l[1][1] = Test("D") </code></pre> <p>I know that following...
1
2016-09-30T00:56:32Z
39,782,268
<p>One simple way would be creating your array object by inheriting from Numpy's ndarray object. Then use a custom function for checking the existence of your object based on the name attribute:</p> <pre><code>In [71]: class Myarray(np.ndarray): ....: def __new__(cls, inputarr): ....: obj...
1
2016-09-30T01:17:30Z
[ "python", "python-2.7", "numpy" ]
Python: Check if a numpy array contains an object with specific attribute
39,782,113
<p>I want to check if there is any object with a specific attribute in my numpy array:</p> <pre><code>class Test: def __init__(self, name): self.name = name l = numpy.empty( (2,2), dtype=object) l[0][0] = Test("A") l[0][1] = Test("B") l[1][0] = Test("C") l[1][1] = Test("D") </code></pre> <p>I know that following...
1
2016-09-30T00:56:32Z
39,782,433
<p>I'm clearly not proficient in numpy but couldn't you just do something like:</p> <pre><code>numpy.any([ x.name=='A' for x in l[:,0] ]) </code></pre> <p>edit: (Google tells me that) it's possible to iterate over arrays with <code>nditer</code>; is this what you want?</p> <pre><code>numpy.any([ x.name=='A' for x in...
0
2016-09-30T01:40:44Z
[ "python", "python-2.7", "numpy" ]