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
wxPython unintentional window resizing when hiding/showing panels on Windows
37,928,208
<p>I have a wx 2.8 (Python 2.7) basic GUI that switches panels when the next button is pressed. When the GUI is opened, it is maximized. For some reason though, on Windows 7/10, the whole window resizes to the minimum size but on Ubuntu 14.04, it doesn't. Can someone please tell me what I'm doing wrong here? I don't wa...
0
2016-06-20T17:12:25Z
37,931,618
<p>Try replacing the <code>self.whatever.TopSizer.Fit(self)</code> lines with just <code>self.Layout()</code>. You don't want to change the size of anything, which <code>Fit</code> does, you just want the contents of the panels to be laid out according to the sizer's layout algorithm. </p>
1
2016-06-20T20:52:22Z
[ "python", "wxpython", "wxwidgets", "wx" ]
Python CSV - Dynamic number of rows based on a variable
37,928,228
<p>I'm trying to write a CSV file, which contains lists with lengths that vary dynamically depending on a user's data input. I'm OK with printing the lists but I also need to put a header row at the top, that should look something like:</p> <p>Generation:, 1, 2, 3, 4, 5, (etc - counting up the number of generations.)<...
0
2016-06-20T17:13:48Z
37,928,432
<pre><code>import csv numGens = 4 header = ['Generation:'] for n in range(numGens): header.append(str(n + 1)) with open('testthing.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(...
0
2016-06-20T17:28:00Z
[ "python", "csv", "variables", "header", "row" ]
Error when trying to start python.exe from C#
37,928,321
<p>I am trying to execute a python script from C#. I found a way to accomplish this in another post at the following link: <a href="http://stackoverflow.com/questions/11779143/run-a-python-script-from-c-sharp">run a python script from c#</a>. However, I am getting an error when the process arrives to the using <code>(P...
0
2016-06-20T17:20:41Z
37,928,514
<p>You're initializing your <code>cmd</code> variable incorrectly. The "@" should precede the quotation mark (i.e. @"C:/..."). Of course, using forward slashes instead of backslashes negates the need for the verbatim string anyway so you can omit the "@" altogether.</p> <pre><code>String cmd = "C:/Program Files (x86)/...
2
2016-06-20T17:32:50Z
[ "c#", "python", "visual-studio" ]
Defining an ID number once and using it every file path
37,928,477
<p>I have a bunch of file paths:</p> <pre><code>shapefile = "C:\\file\\path \\here\\this\\one\\is\\different\\2001_6W.shp" place1 = "C:\\file\\path\\here\\place1_2001.shp" place2 = "C:\\file\\path\\here\\place2_2001.shp" place3 = "C:\\file\\path\\here\\place3_2001.shp" </code></pre> <p>I would like it if I could defi...
2
2016-06-20T17:30:48Z
37,928,524
<pre><code>ID = "2001" place1 = "C:\\file\\path\\here\\place1_" + ID + ".shp" </code></pre> <p>Notice the quotes around the ID value "2001", that makes it a string, which allows you to add it to other strings. Otherwise you'd end up with a TypeError which will arise when you try to add integers to strings.</p>
0
2016-06-20T17:33:47Z
[ "python", "filenames", "filepath" ]
Defining an ID number once and using it every file path
37,928,477
<p>I have a bunch of file paths:</p> <pre><code>shapefile = "C:\\file\\path \\here\\this\\one\\is\\different\\2001_6W.shp" place1 = "C:\\file\\path\\here\\place1_2001.shp" place2 = "C:\\file\\path\\here\\place2_2001.shp" place3 = "C:\\file\\path\\here\\place3_2001.shp" </code></pre> <p>I would like it if I could defi...
2
2016-06-20T17:30:48Z
37,928,622
<p>You should use string formatting, like so:</p> <pre><code>ID = 2001 # Positionally replace {} place1 = "c:\\file\\path\\here\\place1_{}.shp".format(ID) # It also works with keywords! place2 = "c:\\file\\path\\here\\place2_{id}.shp".format(id=ID) </code></pre> <p>This lets it be type-ambiguous, in case you want to ...
3
2016-06-20T17:39:41Z
[ "python", "filenames", "filepath" ]
ImportError: No module named zlib; tox
37,928,497
<p>I am trying to run tox tests as python 2.6. I just installed 2.6 and am now getting past the "Interpreter error: no python 2.6" style error, but tox is now crashing at zlib. Zlib is on my machine however. My tox issue looks like:</p> <pre><code>$ tox -e py26 GLOB sdist-make: /home/cchilders/work_projects/webapi/set...
1
2016-06-20T17:31:50Z
37,930,669
<p>Solved by obscure ubuntu problem:</p> <p><a href="http://joequery.me/guides/python26-no-module-zlib/" rel="nofollow">http://joequery.me/guides/python26-no-module-zlib/</a></p>
1
2016-06-20T19:48:46Z
[ "python", "unit-testing", "python-2.6", "python-unittest", "tox" ]
How can I add a value to a row in pyspark?
37,928,535
<p>I have a dataframe that looks like this: </p> <pre><code>preds.take(1) [Row(_1=0, _2=Row(val1=False, val2=1, val3='high_school'))] </code></pre> <p>I want the whole thing to be one row, without the nested row in there. So, the first value would get a name and be a part of the one row object. If I wanted to name it...
1
2016-06-20T17:34:46Z
37,928,937
<p>Since <code>Row</code> is a <code>tuple</code> and <code>tuples</code> are immutable you can only create a new object. Using plain tuples:</p> <pre><code>from pyspark.sql import Row r = Row(_1=0, _2=Row(val1=False, val2=1, val3='high_school')) r[:1] + r[1] ## (0, False, 1, 'high_school') </code></pre> <p>or prese...
0
2016-06-20T17:59:05Z
[ "python", "apache-spark", "pyspark" ]
Python 3.5.1 mixed line code file UTF-8 and UTF-16
37,928,540
<p>I have successfully been parsing data files that I recieve with a simple python script I wrote. The files I get are like this:</p> <p>file.txt, ~50 columns of data, x 1000s of rows</p> <pre><code>abcd1,1234a,efgh1,5678a,ijkl1 ...etc abcd2,1234b,efgh2,5678b,ijkl2 ...etc ... </code></pre> <p>Unfortunatly, sometim...
0
2016-06-20T17:34:50Z
37,928,955
<p>You can tell <code>fileinput</code> how to open your files. As <a href="https://docs.python.org/3/library/fileinput.html" rel="nofollow">the documentation</a> says:</p> <blockquote> <p>You can control how files are opened by providing an opening hook via the openhook parameter to fileinput.input() or FileInput()....
1
2016-06-20T18:00:31Z
[ "python", "unicode", "encoding", "utf-8", "utf-16" ]
Python 3.5.1 mixed line code file UTF-8 and UTF-16
37,928,540
<p>I have successfully been parsing data files that I recieve with a simple python script I wrote. The files I get are like this:</p> <p>file.txt, ~50 columns of data, x 1000s of rows</p> <pre><code>abcd1,1234a,efgh1,5678a,ijkl1 ...etc abcd2,1234b,efgh2,5678b,ijkl2 ...etc ... </code></pre> <p>Unfortunatly, sometim...
0
2016-06-20T17:34:50Z
37,964,719
<p>If your file has mixed encoding, you need to read it as binary and then decode different parts as necessary, or just process the whole thing as binary instead. The <code>latin-1</code> solution in the question works by accident really.</p> <p>In your example that would be something like:</p> <pre><code>with open('...
0
2016-06-22T10:01:11Z
[ "python", "unicode", "encoding", "utf-8", "utf-16" ]
Take array of indices, find matching indices in another array and replace values
37,928,553
<p>I have two arrays, one array that contains all indices of two arrays that meet a certain condition I had made previous to this. The other array is an array of booleans. I want to take the array of indices and find the same place in the array of booleans and replace those values.</p> <p>So for example what I am look...
3
2016-06-20T17:35:43Z
37,928,682
<p>I hope this works (not sure what you need):</p> <pre><code>myIdxs = [0, 3, 5] myBools = [1, 1, 1, 1, 1, 0] myBools = [myBools[i] if i in myIdxs else 0 for i in xrange(len(myBools))] &gt;&gt;&gt; print myBools [1, 0, 0, 1, 0, 0] </code></pre>
3
2016-06-20T17:43:02Z
[ "python", "list", "boolean" ]
Take array of indices, find matching indices in another array and replace values
37,928,553
<p>I have two arrays, one array that contains all indices of two arrays that meet a certain condition I had made previous to this. The other array is an array of booleans. I want to take the array of indices and find the same place in the array of booleans and replace those values.</p> <p>So for example what I am look...
3
2016-06-20T17:35:43Z
37,928,749
<p>Try using list comprehension with if-else statement.</p> <pre><code>[myBools[i] if i in myIdxs else 0 for i in range(len(myBools))] </code></pre> <p><strong>Output</strong></p> <pre><code>[1, 0, 0, 1, 0, 0] </code></pre>
0
2016-06-20T17:48:41Z
[ "python", "list", "boolean" ]
Take array of indices, find matching indices in another array and replace values
37,928,553
<p>I have two arrays, one array that contains all indices of two arrays that meet a certain condition I had made previous to this. The other array is an array of booleans. I want to take the array of indices and find the same place in the array of booleans and replace those values.</p> <p>So for example what I am look...
3
2016-06-20T17:35:43Z
37,929,028
<p>Poorly worded question, but here are two answers, both are extremely simple and straightforward, and don't required complex list comprehension.</p> <p><strong>If you want to change the bit to the opposite value</strong></p> <pre><code> myIdxs = [0, 3, 5] myBools = [1, 0, 0, 1, 1, 1, 0, 1, 0, 1] for i i...
1
2016-06-20T18:05:26Z
[ "python", "list", "boolean" ]
Cut within a pattern using Python regex
37,928,771
<p><strong>Objective:</strong> I am trying to perform a cut in Python RegEx where split doesn't quite do what I want. I need to cut within a pattern, but between characters.</p> <p><strong>What I am looking for:</strong></p> <p>I need to recognize the pattern below in a string, and split the string at the location of...
12
2016-06-20T17:50:25Z
37,928,861
<p>You can solve it with <code>re.split()</code> and positive <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">"look arounds"</a>:</p> <pre><code>&gt;&gt;&gt; re.split(r"(?&lt;=CDE)(\w+)(?=FG)", s) ['ABCDE', 'FGHIJKLMNOCDE', 'FGZYPE'] </code></pre> <hr> <p>Note that if one of the cut sequ...
5
2016-06-20T17:55:21Z
[ "python", "regex", "string", "split", "protein-database" ]
Cut within a pattern using Python regex
37,928,771
<p><strong>Objective:</strong> I am trying to perform a cut in Python RegEx where split doesn't quite do what I want. I need to cut within a pattern, but between characters.</p> <p><strong>What I am looking for:</strong></p> <p>I need to recognize the pattern below in a string, and split the string at the location of...
12
2016-06-20T17:50:25Z
37,929,012
<p>A non regex way would be to <a href="https://docs.python.org/2/library/stdtypes.html#str.replace">replace</a> the pattern with the piped value and then <a href="https://docs.python.org/2/library/stdtypes.html#str.split">split</a>. </p> <pre><code>&gt;&gt;&gt; pattern = 'CDE|FG' &gt;&gt;&gt; s = 'ABCDEFGHIJKLMNOCDEF...
7
2016-06-20T18:04:32Z
[ "python", "regex", "string", "split", "protein-database" ]
Cut within a pattern using Python regex
37,928,771
<p><strong>Objective:</strong> I am trying to perform a cut in Python RegEx where split doesn't quite do what I want. I need to cut within a pattern, but between characters.</p> <p><strong>What I am looking for:</strong></p> <p>I need to recognize the pattern below in a string, and split the string at the location of...
12
2016-06-20T17:50:25Z
37,942,614
<p>A safer non-regex solution could be this:</p> <pre><code>import re def split(string, pattern): """Split the given string in the place indicated by a pipe (|) in the pattern""" safe_splitter = "#@#@SPLIT_HERE@#@#" safe_pattern = pattern.replace("|", safe_splitter) string = string.replace(pattern.rep...
1
2016-06-21T10:59:39Z
[ "python", "regex", "string", "split", "protein-database" ]
Cut within a pattern using Python regex
37,928,771
<p><strong>Objective:</strong> I am trying to perform a cut in Python RegEx where split doesn't quite do what I want. I need to cut within a pattern, but between characters.</p> <p><strong>What I am looking for:</strong></p> <p>I need to recognize the pattern below in a string, and split the string at the location of...
12
2016-06-20T17:50:25Z
37,942,619
<p>To keep the splitting pattern when you split with <code>re.split</code>, or parts of it, enclose them in parentheses. </p> <pre><code>&gt;&gt;&gt; data 'ABCDEFGHIJKLMNOCDEFGZYPE' &gt;&gt;&gt; pieces = re.split(r"(CDE)(FG)", data) &gt;&gt;&gt; pieces ['AB', 'CDE', 'FG', 'HIJKLMNO', 'CDE', 'FG', 'ZYPE'] </code></pre>...
2
2016-06-21T10:59:57Z
[ "python", "regex", "string", "split", "protein-database" ]
Calculate date time difference python
37,928,815
<p>I am writing timediff function to calculate the time (seconds) difference between 2 giving date time</p> <pre><code>def timediff(time1, time2): timeformat = '%d%b%Y:%H:%M:%S' #time1="01MAR2016:07:11:53" #time2="01MAR2016:16:28:38" try: date_object1 = datetime.strptime(time1, timeformat) ...
1
2016-06-20T17:52:31Z
37,928,981
<p>You need to use <code>total_seconds()</code> and not <code>seconds</code>:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; f = '%d%b%Y:%H:%M:%S' &gt;&gt;&gt; t1 = '01MAR2016:07:11:53' &gt;&gt;&gt; t2 = '02MAR2016:07:11:53' &gt;&gt;&gt; d1 = datetime.datetime.strptime(t1, f) &gt;&gt;&gt; d2 = datetime.datet...
5
2016-06-20T18:02:19Z
[ "python", "date", "time", "difference" ]
Python ldap3 search creates an empty entry
37,928,821
<p>The first step of my program requires I search through the company's active directory and find a list of users by department. Here is my code so far:</p> <pre><code>from ldap3 import Server, Connection, SUBTREE, ALL server = Server('my.company.local', get_info=ALL) conn = Connection(server, auto_bind=True) conn.sea...
0
2016-06-20T17:52:59Z
37,928,975
<p>Shot in the dark, but try removing the parentheses around the query so <code>(givenName=Charles)</code> becomes <code>givenName=Charles</code>. Are you sure the domain components are correct?</p>
0
2016-06-20T18:01:56Z
[ "python", "search", "filter", "ldap", "entry" ]
Python ldap3 search creates an empty entry
37,928,821
<p>The first step of my program requires I search through the company's active directory and find a list of users by department. Here is my code so far:</p> <pre><code>from ldap3 import Server, Connection, SUBTREE, ALL server = Server('my.company.local', get_info=ALL) conn = Connection(server, auto_bind=True) conn.sea...
0
2016-06-20T17:52:59Z
37,931,243
<p>you are not providing a username, so your connection is anonymous. Try accessing with <code>username="myname", password="mypassword"</code> in the connection object. You can also try NTLM authentication with <code>authentication=NTLM</code>. (You must import NTLM from the ldap3 package). In this case username must b...
0
2016-06-20T20:25:25Z
[ "python", "search", "filter", "ldap", "entry" ]
Python ldap3 search creates an empty entry
37,928,821
<p>The first step of my program requires I search through the company's active directory and find a list of users by department. Here is my code so far:</p> <pre><code>from ldap3 import Server, Connection, SUBTREE, ALL server = Server('my.company.local', get_info=ALL) conn = Connection(server, auto_bind=True) conn.sea...
0
2016-06-20T17:52:59Z
37,947,155
<p>So both cannatag and ig0774 were correct. Providing user credentials is necessary to use the search function. Otherwise the search function returns an empty entries list. Thank you!</p>
1
2016-06-21T14:26:35Z
[ "python", "search", "filter", "ldap", "entry" ]
C# Escape on command line argument
37,928,896
<p>I am trying to pass a string argument to a python script I am calling from C#. However, the argument is not being recognized but the script still runs. I believe I am not using the correct approach in using escape sequences. Here is my code:</p> <pre><code>String argss = "C:/My_Python_lib/happyBirthday.py 'joe'"; <...
-1
2016-06-20T17:57:19Z
37,928,997
<p>As people have commented, you do not need the quotation marks around joe.</p>
0
2016-06-20T18:03:35Z
[ "c#", "python", "command-line" ]
C# Escape on command line argument
37,928,896
<p>I am trying to pass a string argument to a python script I am calling from C#. However, the argument is not being recognized but the script still runs. I believe I am not using the correct approach in using escape sequences. Here is my code:</p> <pre><code>String argss = "C:/My_Python_lib/happyBirthday.py 'joe'"; <...
-1
2016-06-20T17:57:19Z
37,929,270
<pre><code>var p = new Process { StartInfo = new ProcessStartInfo { FileName = @"C:\My_Python_lib\happyBirthday.py", Arguments = "joe", } }; p.Start(); </code></pre>
1
2016-06-20T18:22:11Z
[ "c#", "python", "command-line" ]
Calculating cosine similarity of columns of a python matrix
37,929,011
<p>I have a numpy matrix say A as below</p> <pre><code>array([[1, 2, 3], [1, 2, 2]]) </code></pre> <p>I want to find the cosine similarity matrix of this a matrix where cosine similarity is between the columns.</p> <p>Now cosine similarity of two vectors is just a dot product of two normalized by the L2 norm ...
0
2016-06-20T18:04:31Z
37,929,303
<p>Try this:</p> <pre><code>a = np.array([[1, 2, 3], [1, 2, 2]]) n = np.linalg.norm(a, axis=0).reshape(1, a.shape[1]) a.T.dot(a) / n.T.dot(n) array([[ 1. , 1. , 0.98058068], [ 1. , 1. , 0.98058068], [ 0.98058068, 0.98058068, 1. ]]) </code></pre> <p>This assignme...
1
2016-06-20T18:24:35Z
[ "python", "numpy", "matrix" ]
RuntimeError: Can not put single artist in more than one figure when using matplotlib 1.5
37,929,016
<p>Here is my code:</p> <pre><code>import matplotlib.pyplot as plt plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6]) plt.figure(2) ...
0
2016-06-20T18:04:42Z
37,930,125
<p>You shouldn't pass figure as a kwarg, instead use text method of a Figure (or Axes) instance. Example:</p> <pre><code>import matplotlib.pyplot as plt fig1, fig2 = plt.figure(1), plt.figure(2) sp1, sp2 = fig1.add_subplot(211), fig2.add_subplot(211) sp1.plot([1, 2, 3]) sp2.plot([0, 1, 3]) fig1.text(.5, .3, 'whole fi...
0
2016-06-20T19:13:23Z
[ "python", "matplotlib" ]
RuntimeError: Can not put single artist in more than one figure when using matplotlib 1.5
37,929,016
<p>Here is my code:</p> <pre><code>import matplotlib.pyplot as plt plt.figure(1) # the first figure plt.subplot(211) # the first subplot in the first figure plt.plot([1, 2, 3]) plt.subplot(212) # the second subplot in the first figure plt.plot([4, 5, 6]) plt.figure(2) ...
0
2016-06-20T18:04:42Z
37,931,273
<p>I'm completely stuck on this. My understanding is that <code>matplotlib.figure</code> is for embedding a graph within the GUI and then being able to update the info whilst keeping the frame constant?. This will (for me on python 2.7, I think it's <code>tkinter</code> in Python 3+) run without error and produce the s...
0
2016-06-20T20:28:02Z
[ "python", "matplotlib" ]
Python - Pandas Dataframe - data not matching source
37,929,068
<p>I'm trying to use monthly stock data from yahoo to analyze patterns. For some reason, the monthly returns the program is spitting out in a dataframe for a particular stock (ATVI) do not match the returns from the actual yahoo site. I compared monthly returns for the 2015 period and included columns for average incre...
-1
2016-06-20T18:08:51Z
37,929,636
<p>To get the average daily up/down price moves, you could:</p> <pre><code>from pandas_datareader.data import DataReader data = DataReader('ATVI', "yahoo", datetime(2015, 1, 1), datetime(2015, 12, 31))[['Open', 'Close']] open = data.Close.resample('M').first() # get the open of the first day, assign date of last day ...
0
2016-06-20T18:44:22Z
[ "python", "pandas", "logic", "yahoo-finance" ]
How to merge / overwrite columns in Pandas
37,929,109
<p>I've currently got two CSV files. One of them (f1) has ~1000 unique IDs in a column, and the other (f2) is a subset with ~50 unique IDs in a column of the same name.</p> <p>I'd like to merge these based on ID, but when f1 and f2 have columns with the same name, I'd like to choose the information in the f2 column. W...
3
2016-06-20T18:11:10Z
37,929,358
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">combine_first()</a></p> <pre><code>f2.set_index('KeyID').combine_first(f1.set_index('KeyID')) </code></pre>
2
2016-06-20T18:27:40Z
[ "python", "pandas" ]
How to merge / overwrite columns in Pandas
37,929,109
<p>I've currently got two CSV files. One of them (f1) has ~1000 unique IDs in a column, and the other (f2) is a subset with ~50 unique IDs in a column of the same name.</p> <p>I'd like to merge these based on ID, but when f1 and f2 have columns with the same name, I'd like to choose the information in the f2 column. W...
3
2016-06-20T18:11:10Z
37,930,004
<p>Just append f1 to f2 and drop all duplicates:</p> <pre><code>import pandas as pd df1 = pd.DataFrame(data=[['A', 442], ['B', 998], ['C', 45], ['F', 777]] , columns=['KeyID', 'Info']) df2 = pd.DataFrame(data=[['A', 12], ...
0
2016-06-20T19:06:08Z
[ "python", "pandas" ]
TFLearn Alexnet customized to a certain number of classes
37,929,194
<p>I'm using the <a href="https://github.com/tflearn/tflearn/blob/91e617c3f4ad94db5ea52fe09b7338035c517d28/examples/images/alexnet.py" rel="nofollow">Alexnet</a> example given in TFLearn to train on my own dataset of images, which is the <a href="http://grozi.calit2.net/grozi.html" rel="nofollow">GroZi-120 database</a>...
0
2016-06-20T18:16:56Z
37,929,380
<p>In the line: </p> <pre><code>model.fit(X, Y, n_epoch=1000, validation_set=0.1, shuffle=True, show_metric=True, batch_size=64, snapshot_step=200, snapshot_epoch=False, run_id='alexnet_oxflowers17') </code></pre> <p>You seem to still have the previous <code>Y</code> of shape <code>[batch_size, 17]</code>...
0
2016-06-20T18:29:07Z
[ "python", "tensorflow" ]
Django: get top tags?
37,929,205
<p>I'm using Django and the django-taggit app. For now, I pass the tags as they are:</p> <pre><code>def tags_page(request): """A page that displays all the tags.""" tags = Tag.objects.all() response = render(request, 'tags_page.html', {'tags': tags}) return response </code></pre> <p>In order to render...
1
2016-06-20T18:17:29Z
37,929,361
<p>Assuming that the tags are stored in a list:</p> <pre><code>sorted(lst, key=lst.count, reverse=True) </code></pre> <p><code>collections.Counter</code> also works and has the advantage of being <code>O(n)</code></p> <pre><code>counts = collections.Counter(lst) new_list = sorted(lst, key=lambda x: -counts[x]) </cod...
1
2016-06-20T18:28:04Z
[ "python", "django", "sorting", "tags" ]
Django: get top tags?
37,929,205
<p>I'm using Django and the django-taggit app. For now, I pass the tags as they are:</p> <pre><code>def tags_page(request): """A page that displays all the tags.""" tags = Tag.objects.all() response = render(request, 'tags_page.html', {'tags': tags}) return response </code></pre> <p>In order to render...
1
2016-06-20T18:17:29Z
37,929,417
<p>Actually, if, for example, the tags are applied to a model called Joke, you can simply do this:</p> <pre><code>tags = Joke.tags.most_common() </code></pre> <p>And it works just fine.</p>
1
2016-06-20T18:30:50Z
[ "python", "django", "sorting", "tags" ]
Python 3 REGEX assistance
37,929,294
<p>I am currently trying to scan a file for a specific pattern and capture pieces of the matched pattern to use in a replacement string. </p> <p>My current Python 3 script is using this pattern and captures the data in simple cases.</p> <pre><code> def readFile(filename): pattern = re.compile(b"(&lt;%Inser...
1
2016-06-20T18:24:09Z
37,958,374
<p>Give you an idear to solve the first problem. You can take two steps:</p> <ol> <li><p>get the whole expression with pattern:</p> <p><code>re.compile(b"(&lt;%InsertIf expression=\"\$\{\(\((.*?)\)\)\}\".*?\/InsertIf%&gt;)", re.DOTALL)</code></p></li> <li><p>When you get the context, you can use another pattern to fi...
0
2016-06-22T04:07:41Z
[ "python", "regex", "python-3.x" ]
Identation error in python 2.7
37,929,298
<p>self.Close(True) shows identation error in python 2.7. Is there any alternative to this. This is a basic wxpython code from thenewboston tutorials and is working fine there ?</p> <pre><code> import wx class bucky(wx.Frame): def __init__(self,parent,id): wx.Frame.__init__(self,parent,id,'Frame', sie=(300,200))...
-7
2016-06-20T18:24:15Z
37,929,348
<p>There, fixed it for you:</p> <pre><code>import wx class bucky(wx.Frame): def __init__(self, parent, id): wx.Frame.__init__(self, parent, id, 'Frame', sie=(300, 200)) panel = wx.Panel(self) button = wx.Button(panel, label="exit", pos=(130, 10), size=(60, 60)) self.Bind(wx.EVT_BUT...
-1
2016-06-20T18:27:03Z
[ "python" ]
Parallelize python for-loop
37,929,315
<p>I would like to parallelize the following python loop using a Mac Pro with 2 Quad-Core processors. </p> <pre><code>result_list = [] for a in a_range: for b in b_range: for c in c_range: result = call_fortran_program(a, b, c) result_list.append(result) </code></pre> <p>In my sear...
0
2016-06-20T18:25:13Z
37,929,437
<pre><code>from itertools import product from multiprocessing import Pool with Pool(processes=4) as pool: # assuming Python 3 pool.starmap(print, product(range(2), range(3), range(4))) </code></pre>
2
2016-06-20T18:32:13Z
[ "python", "parallel-processing" ]
Parallelize python for-loop
37,929,315
<p>I would like to parallelize the following python loop using a Mac Pro with 2 Quad-Core processors. </p> <pre><code>result_list = [] for a in a_range: for b in b_range: for c in c_range: result = call_fortran_program(a, b, c) result_list.append(result) </code></pre> <p>In my sear...
0
2016-06-20T18:25:13Z
37,929,452
<p>Try <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" rel="nofollow">ProcessPoolExecutor</a></p> <p>This can circumvent GIL lock by creating multiple processes.</p> <p>An example from the website:</p> <pre><code>import concurrent.futures import math PRIMES...
0
2016-06-20T18:32:47Z
[ "python", "parallel-processing" ]
Python Negative Indexing
37,929,334
<p>I know that negative indexing in Python selects elements starting from the back of the list, but is there some way of specifying elements in a python list that I <em>don't want</em>?</p> <pre><code>&gt; x = [1,2,3,4,5] &gt; print(x[(-2,-3)]) &gt; [1,2,5] </code></pre>
0
2016-06-20T18:26:22Z
37,929,460
<p>There isn't a good way to do that. Usually, I'll use a set with a comprehension:</p> <pre><code>[item for i, item in enumerate(lst) if i not in {2, 3}] </code></pre> <p>Using a <code>set</code> in this context is pretty important (especially as the number of indices that you want to omit grows) because it has O(1...
6
2016-06-20T18:33:01Z
[ "python" ]
How to pickle a defaultdict which uses a lambda function?
37,929,435
<p>How do I create pickle file of function (<code>defaultDict</code>)? The error I get is can't <code>pickle function objects</code></p> <pre><code>from collections import defaultdict dtree = lambda: defaultdict(tree) try: import cPickle as pickle except: import pickle #Create defaultdict object: hapPkl = dtree(...
0
2016-06-20T18:32:01Z
37,929,615
<p>The <code>cPickle</code> error message is a bit misleading; the <code>pickle</code> version is better. It's not that you can't pickle functions; it's that they need to be available by their <code>__name__</code>. A lambda has <code>__name__</code> set to <code>'&lt;lambda&gt;'</code>, so it's not picklable. Define i...
3
2016-06-20T18:43:01Z
[ "python", "lambda", "pickle", "defaultdict" ]
How to pickle a defaultdict which uses a lambda function?
37,929,435
<p>How do I create pickle file of function (<code>defaultDict</code>)? The error I get is can't <code>pickle function objects</code></p> <pre><code>from collections import defaultdict dtree = lambda: defaultdict(tree) try: import cPickle as pickle except: import pickle #Create defaultdict object: hapPkl = dtree(...
0
2016-06-20T18:32:01Z
37,929,720
<p>A simple workaround would be to implement your tree data-structure differently, without <code>defaultdict</code>:</p> <pre><code>class DTree(dict): def __missing__(self, key): value = self[key] = type(self)() return value try: import cPickle as pickle except: import pickle #Create dtree obj...
1
2016-06-20T18:49:07Z
[ "python", "lambda", "pickle", "defaultdict" ]
Regex returning inconsistent results on the same string
37,929,439
<p>I have a regex expression that is supposed to match the beginnings of certain paragraphs in some files I have. It works when I run it on a smaller version of the file, but when I run it on the whole file it picks up an excluded \r on the 4th match, and I'm not sure why. </p> <p>Heres the method:</p> <pre><code> ...
1
2016-06-20T18:32:14Z
37,929,953
<p>You could try some basic diagnostic's, </p> <p>try something like this to start. </p> <p><code>(?m-s)^(.{1,5}\(.*?\))</code> </p> <p>Leave out <code>[^_]*?</code> because it says don't match anything unless it has to. </p> <p>Here is the above without using modifiers. </p> <p><code>(?:^|\r?\n)([^\r\n]{1,...
1
2016-06-20T19:02:34Z
[ "python", "regex" ]
Spyder IDE: Need to press 'run script' twice to successfully execute Python script
37,929,465
<p>I'm currently working on an image processing script in Python (Spyder IDE, Python 3.5, Anaconda 4.0.0). When I first open the IDE, I only have to press 'run script' once for the script to execute. But after that, I have to press 'run script' twice, sometimes even three times, for it to execute. Searching around the ...
0
2016-06-20T18:33:18Z
37,930,229
<p>I think your issue is related to <a href="https://github.com/spyder-ide/spyder/issues/1831" rel="nofollow">this</a> its a bug in <code>spyder</code>.It provides a partial solution so far is to use a different Matplotlib backend. You can change it in:</p> <pre><code>Preferences &gt; Console &gt; External modules &gt...
1
2016-06-20T19:20:50Z
[ "python", "matplotlib", "spyder" ]
Ctypes, IndexError: list index out of range
37,929,508
<p>The range is 20 so I'm not sure where this error is coming from. Added print list length</p> <p>Error is in the second line. How I call the code:</p> <pre><code>plist = StreamingParameterList() print(len(plist)) plist = [plist[x] for x in [2,4,12,13,14]] </code></pre> <p>Print length shows 159</p> <p>StreamingPa...
0
2016-06-20T18:35:56Z
37,929,934
<p>Your range is not 20, that's the only way your index can be out of bounds. Either it is empty or it is less than 15.</p> <p>You can verify this by adding this immediately before the second line:</p> <pre><code>print len(plist) </code></pre> <p>This will verify that the length is not greater than 15</p>
2
2016-06-20T19:01:29Z
[ "python", "ctypes", "python-3.5" ]
construct HTML with AJAX interrupt via Flask
37,929,548
<p>So I am using an existing code "Vertical time-line" from <a href="https://codyhouse.co/demo/vertical-timeline/" rel="nofollow">here</a>, and now I am trying to make it robust. each news feed on timeline has a small code snipt of;</p> <pre><code> &lt;div class="cd-timeline-block"&gt; &lt;div class="cd-time...
1
2016-06-20T18:37:54Z
37,929,685
<p>You need to insert the new content as html, not text.</p> <pre><code> $.post('btn_clicked', function(data, status){ $("#new_feeds").html(data); }) </code></pre>
0
2016-06-20T18:47:17Z
[ "jquery", "python", "html", "ajax" ]
why comparison did not return an int
37,929,580
<p>I am making simple Old Maid game. Here is my class for player's hand:</p> <pre><code>class OldMaidHand(Hand): def removeMatches(self): count=0; originalCards=self.cards[:]; for card in originalCards: match=Card(3-card.suit,card.rank); if match in self.cards: ...
0
2016-06-20T18:40:08Z
37,930,485
<p>From the <a href="https://docs.python.org/2/reference/datamodel.html#object.__cmp__" rel="nofollow">documentation for <code>__cmp__</code></a>:</p> <blockquote> <p>Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self &lt; other, zero if self == ot...
1
2016-06-20T19:37:23Z
[ "python", "python-2.7", "typeerror" ]
cx_freeze issue python3 setup file
37,929,596
<p>How do I add <code>{'include_files':includefiles}</code> to the options field down below? All I get is an error in python.</p> <pre><code>from cx_Freeze import setup, Executable as cxExecutable import platform import sys # -*- coding: utf-8 -*- base = None if sys.platform == 'win32': base = 'Win32GUI' build...
0
2016-06-20T18:41:43Z
37,929,717
<pre><code>build_exe_options = { "include_msvcr": True, "includes": [ 'Icon.ico' , 'PlayTube.ipa' , 'libmobiledevice/' ], } </code></pre>
0
2016-06-20T18:49:04Z
[ "python", "cx-freeze" ]
Scraping sports data using beautiful soup and pandas
37,929,613
<p>I'm trying to scrape the score from the first quarter of the game on this <a href="http://espn.go.com/nba/scoreboard" rel="nofollow">webpage for the home team</a> and my code doesn't return anything. Here's what I have so far. Any feedback would be appreciated.</p> <pre><code>from bs4 import BeautifulSoup import ...
1
2016-06-20T18:42:47Z
37,930,388
<p>The content is dynamically loaded, if we do a bit of parsing we can pull the data from the source:</p> <pre><code>import re import json from pprint import pprint as pp r = requests.get("http://espn.go.com/nba/scoreboard").content scr = BeautifulSoup(r).find("script",text=re.compile("window.espn.scoreboardData")).t...
1
2016-06-20T19:30:20Z
[ "python", "pandas", "web-scraping", "beautifulsoup" ]
Is there a faster way to find matching features in two arrays (Python)?
37,929,772
<p>I'm trying to go through each feature in one file (1 per line) and find all matching features based on one column of that line in a second file. I have this solution, which does what I want on small files, but it's very slow on big files (my files have >20,000,000 lines). <a href="https://gist.github.com/ethanagbake...
1
2016-06-20T18:52:12Z
37,930,045
<p>To start with you are looping over ALL of <code>conservationFile</code> every time you read a single line from <code>peakFile</code> so stick a <code>break</code> after <code>n+=1</code> in the if statement and that should help somewhat. Assuming that there is only one match that is.</p> <p>Another option is to try...
0
2016-06-20T19:08:55Z
[ "python", "optimization", "comparison", "bioinformatics" ]
Is there a faster way to find matching features in two arrays (Python)?
37,929,772
<p>I'm trying to go through each feature in one file (1 per line) and find all matching features based on one column of that line in a second file. I have this solution, which does what I want on small files, but it's very slow on big files (my files have >20,000,000 lines). <a href="https://gist.github.com/ethanagbake...
1
2016-06-20T18:52:12Z
37,934,263
<p>Bedtools was made for this, specifically the <code>intersect</code> function:</p> <p><a href="http://bedtools.readthedocs.io/en/latest/content/tools/intersect.html" rel="nofollow">http://bedtools.readthedocs.io/en/latest/content/tools/intersect.html</a></p>
0
2016-06-21T01:36:24Z
[ "python", "optimization", "comparison", "bioinformatics" ]
Is there a faster way to find matching features in two arrays (Python)?
37,929,772
<p>I'm trying to go through each feature in one file (1 per line) and find all matching features based on one column of that line in a second file. I have this solution, which does what I want on small files, but it's very slow on big files (my files have >20,000,000 lines). <a href="https://gist.github.com/ethanagbake...
1
2016-06-20T18:52:12Z
37,934,472
<p>The best solution for my purposes seems to be rewriting the above code for pandas. Here's what's working well for me on some very large files:</p> <pre><code>from __future__ import division import pandas as pd FEATUREFILE = 'S2_STARRseq_rep1_vsControl_peaks.bed' CONSERVATIONFILEDIR = './conservation/' peakDF = pd...
1
2016-06-21T02:06:08Z
[ "python", "optimization", "comparison", "bioinformatics" ]
Django 1.9.4 + Djangae + rest_framework (warning deprecate)
37,929,878
<p>I'm using Django 1.9.4 + Djangae + rest_framework for my project.</p> <p>Everthing is working well but I got a warning when I launch my server by "python manage.py runserver"</p> <p>Stacktrace :</p> <blockquote> <p>lib/django/core/management/base.py:265: RemovedInDjango110Warning: > OptionParser usage for Djang...
0
2016-06-20T18:58:16Z
39,633,303
<p>You can safely ignore the warning.</p> <p>As it points out, OptionParser was removed in Django 1.10. Djangae just updated itself to remove its usage (see <a href="https://github.com/potatolondon/djangae/issues/749" rel="nofollow">https://github.com/potatolondon/djangae/issues/749</a>). The Djangae fix hasn't yet be...
0
2016-09-22T07:52:37Z
[ "python", "django", "google-app-engine" ]
Why would NumPy reshape() create a new array and why might order not be preserved?
37,929,911
<p>There are a few questions on SO about checking whether the <code>numpy.reshape</code> call has returned a copy or not<a href="http://stackoverflow.com/questions/11524664/how-can-i-tell-if-numpy-creates-a-view-or-a-copy"> [1</a>, <a href="http://stackoverflow.com/questions/11286864/is-there-a-way-to-check-if-numpy-ar...
0
2016-06-20T19:00:21Z
37,930,048
<blockquote> <p>What I'm wondering is in what circumstances will NumPy return a copy?</p> </blockquote> <pre><code>In [13]: x = numpy.array([[1, 2, 3], ....: [4, 5, 6]]) In [14]: x[:, :2].reshape([4]).base is x Out[14]: False </code></pre> <p>If the strides don't work for the new shape, NumPy h...
2
2016-06-20T19:09:09Z
[ "python", "arrays", "numpy", "reshape" ]
How can I compute the maximum in a vectorized lambda with NumPy?
37,929,923
<p>I want to plot the maximum over two functions like this:</p> <pre class="lang-py prettyprint-override"><code>%matplotlib inline import numpy as np import matplotlib.pyplot as plt x = np.linspace(-10, 100) plt.plot(x, (lambda x: max(x**2, -.5 * x + 3))(x)) plt.show() </code></pre> <p>However, it complains about <co...
2
2016-06-20T19:00:51Z
37,930,067
<p>Try with this line instead:</p> <pre><code>np.array([x**2, 3-x/2]).max(0) </code></pre> <p>All together:</p> <pre><code>%matplotlib inline import numpy as np import matplotlib.pyplot as plt x = np.linspace(-10, 100) plt.plot(x, np.array([x**2, 3-x/2]).max(0)) plt.show() </code></pre> <p><a href="http://i.stack.i...
0
2016-06-20T19:10:14Z
[ "python", "numpy" ]
How can I compute the maximum in a vectorized lambda with NumPy?
37,929,923
<p>I want to plot the maximum over two functions like this:</p> <pre class="lang-py prettyprint-override"><code>%matplotlib inline import numpy as np import matplotlib.pyplot as plt x = np.linspace(-10, 100) plt.plot(x, (lambda x: max(x**2, -.5 * x + 3))(x)) plt.show() </code></pre> <p>However, it complains about <co...
2
2016-06-20T19:00:51Z
37,930,075
<p>The issue is that the <code>lambda</code> function isn't operating on each element of the numpy array individually. It is operating on the <em>entire</em> array and <code>max</code> does not know how to compare two arrays. <code>np.max</code> also doesn't work because the second input should be the axis along which ...
2
2016-06-20T19:10:58Z
[ "python", "numpy" ]
How can I compute the maximum in a vectorized lambda with NumPy?
37,929,923
<p>I want to plot the maximum over two functions like this:</p> <pre class="lang-py prettyprint-override"><code>%matplotlib inline import numpy as np import matplotlib.pyplot as plt x = np.linspace(-10, 100) plt.plot(x, (lambda x: max(x**2, -.5 * x + 3))(x)) plt.show() </code></pre> <p>However, it complains about <co...
2
2016-06-20T19:00:51Z
37,930,095
<p>I don't understand perfectly what you want with the last x-term in this line:</p> <pre><code>plt.plot(x, (lambda x: max(x**2, -.5 * x + 3))(x)) </code></pre> <p>Anyway, you should be able to do something like this:</p> <pre><code>y_func = np.vectorize(lambda x: max(x**2, -.5 * x + 3)) plt.plot(x, y_func(y)) </cod...
0
2016-06-20T19:11:48Z
[ "python", "numpy" ]
when i do yield from inside __next__. why does it return generator object?
37,929,956
<p>I am using yield to return the next value in the <strong>next</strong> function in my class. But its does not return the next value, it returns the generator object. I am trying to better understand iterators and yield. I might be doing it in the wrong way. Please have a look.</p> <pre><code>class MyString: def...
3
2016-06-20T19:02:40Z
37,929,989
<p><code>next</code> pretty much just calls <code>__next__()</code> in this case. Calling <code>__next__</code> on your object will start the generator and return it (no magic is done at this point).</p> <hr> <p>In this case, you <em>might</em> be able to get away with not defining <code>__next__</code> at all:</p> ...
3
2016-06-20T19:04:56Z
[ "python", "generator", "next" ]
Python parse js to list
37,930,078
<p>we have a problem to parse js to list. This similiar with json parse, but in my problem only need to put data from list of <code>"markers"</code>.</p> <p>Example, we have data from <a href="http://localhost:4000/static/libary/jogja.js" rel="nofollow">http://localhost:4000/static/libary/jogja.js</a></p> <pre><code>...
-5
2016-06-20T19:11:02Z
37,930,193
<p>What you have is <em>almost</em> json. It should be good enough to split on the first <code>=</code> and then parse with the standard library json module:</p> <pre><code>json_data = data.split('=', 1)[1] myList = json.loads(json_data)['markers'] </code></pre> <p>Here's a demo from my terminal:</p> <pre><code>&gt...
0
2016-06-20T19:18:35Z
[ "python", "list", "parsing", "python-requests" ]
Python parse js to list
37,930,078
<p>we have a problem to parse js to list. This similiar with json parse, but in my problem only need to put data from list of <code>"markers"</code>.</p> <p>Example, we have data from <a href="http://localhost:4000/static/libary/jogja.js" rel="nofollow">http://localhost:4000/static/libary/jogja.js</a></p> <pre><code>...
-5
2016-06-20T19:11:02Z
37,930,214
<p>Ok so I'm going to assume this is JSON that you're parsing. If you put more information in the comments, I might be able to help more</p> <pre><code>import json resp = {your JSON String} json_dict = json.loads(resp) print(json_dict[markers]) </code></pre> <p>This seems like a pretty straightforward use of the ...
0
2016-06-20T19:19:49Z
[ "python", "list", "parsing", "python-requests" ]
Python parse js to list
37,930,078
<p>we have a problem to parse js to list. This similiar with json parse, but in my problem only need to put data from list of <code>"markers"</code>.</p> <p>Example, we have data from <a href="http://localhost:4000/static/libary/jogja.js" rel="nofollow">http://localhost:4000/static/libary/jogja.js</a></p> <pre><code>...
-5
2016-06-20T19:11:02Z
37,930,236
<p>This has been asked too many times, your variable jogjaAddress is a dictionary, so you should treat it like so. Consider reading pythons documentation on Data structures: <a href="https://docs.python.org/3.4/tutorial/datastructures.html" rel="nofollow">https://docs.python.org/3.4/tutorial/datastructures.html</a></p...
0
2016-06-20T19:21:26Z
[ "python", "list", "parsing", "python-requests" ]
Extract Link URL After Specified Element with Python and Beautifulsoup4
37,930,164
<p>I'm trying to extract a link from a page with python and the beautifulsoup library, but I'm stuck. The link is on the following page, on the sidebar area, directly underneath the h4 subtitle "Original Source:</p> <p><a href="http://www.eurekalert.org/pub_releases/2016-06/uonc-euc062016.php" rel="nofollow">http://ww...
1
2016-06-20T19:16:13Z
37,930,201
<p>You're looking for the link which is the <code>href</code> html attribute. source_url is a <code>bs4.element.Tag</code> which has the <code>get</code> method like:</p> <pre><code>source_url.get('href') </code></pre>
1
2016-06-20T19:19:08Z
[ "python", "web-scraping", "beautifulsoup" ]
Extract Link URL After Specified Element with Python and Beautifulsoup4
37,930,164
<p>I'm trying to extract a link from a page with python and the beautifulsoup library, but I'm stuck. The link is on the following page, on the sidebar area, directly underneath the h4 subtitle "Original Source:</p> <p><a href="http://www.eurekalert.org/pub_releases/2016-06/uonc-euc062016.php" rel="nofollow">http://ww...
1
2016-06-20T19:16:13Z
37,930,209
<p>You almost got it!!</p> <hr> <p><strong>SOLUTION 1:</strong></p> <p>You just have to run the <code>.text</code> method on the <code>soup</code> you've assigned to <code>source_url</code>.</p> <p>So instead of:</p> <pre><code>print(source_url) </code></pre> <p>You should use:</p> <pre><code>print(source_url.te...
0
2016-06-20T19:19:30Z
[ "python", "web-scraping", "beautifulsoup" ]
In the Django admin page, when creating a new instance of a model, is there a way to disallow certain foreign key instances from appearing as choices?
37,930,311
<p>Let's say I have three models: Restaurant, MenuCategory(breakfast, lunch, etc.), and FoodItem. FoodItem has two foreign key fields, one to Restaurant, and the other to MenuCategory. MenuCategory has one foreign key field, to Restaurant.</p> <p>When I try to create a new FoodItem via the Django admin page, I am aske...
2
2016-06-20T19:26:03Z
37,930,997
<p>Sounds like you just need to restrict the queryset used in dropdown field. </p> <p><a href="https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_queryset</a><...
0
2016-06-20T20:08:46Z
[ "python", "django" ]
How to import dict initialized in init constructor from one python file to another?
37,930,314
<p>I am trying to figure out how to import my dictionary in a python file to another dictionary. When I try:</p> <p>filename1.py</p> <pre><code>from filename import myDict </code></pre> <p>I get "ImportError: cannot import name myDict" and I imagine this is because my dictionary is initialized as follows:</p> <p>f...
-1
2016-06-20T19:26:12Z
37,930,484
<p>Something like this?</p> <p>filename.py</p> <pre><code>class X: def __init__(self): self.myDict = {} </code></pre> <p>filename1.py</p> <pre><code>from filename import X print X().myDict </code></pre>
0
2016-06-20T19:37:23Z
[ "python", "dictionary" ]
How to import dict initialized in init constructor from one python file to another?
37,930,314
<p>I am trying to figure out how to import my dictionary in a python file to another dictionary. When I try:</p> <p>filename1.py</p> <pre><code>from filename import myDict </code></pre> <p>I get "ImportError: cannot import name myDict" and I imagine this is because my dictionary is initialized as follows:</p> <p>f...
-1
2016-06-20T19:26:12Z
37,930,491
<p>If your dictionary isn't actually part of a class, take it out of <code>__init__</code> and just declare it:</p> <pre><code>myDict = {} </code></pre> <p>Then, you can just import it as you had:</p> <pre><code>from filename import myDict # Now use myDict as if it was declared in this file print myDict </code></pre...
0
2016-06-20T19:37:50Z
[ "python", "dictionary" ]
breaking a loop when enter is pressed
37,930,408
<p>I'm trying to break the loop once Enter is pressed, while writing data to a file. This is what I have so far. I also don't want to limit the number of time the loop is run either... (example output is below)</p> <pre><code>def main(): myfile = open('friends.txt','w') friend = input('Enter first name of frie...
0
2016-06-20T19:31:52Z
37,930,501
<p>You had a couple of errors in your code, such as using <code>range()</code> and indentation and using <code>input</code> for a string, when <code>raw_input</code> may have been a better choice.</p> <p>To do what you want, you should put the <code>write</code> at the beginning of your loop, and after asking for the ...
0
2016-06-20T19:38:31Z
[ "python", "loops" ]
breaking a loop when enter is pressed
37,930,408
<p>I'm trying to break the loop once Enter is pressed, while writing data to a file. This is what I have so far. I also don't want to limit the number of time the loop is run either... (example output is below)</p> <pre><code>def main(): myfile = open('friends.txt','w') friend = input('Enter first name of frie...
0
2016-06-20T19:31:52Z
37,930,542
<pre><code>def main(): myfile = open('friends.txt','w') while True: friend = input('Enter first name of friend or Enter to quit: ') if not friend: myfile.close() break else: age = input('Enter age (integer) of this friend: ') myfile.write(...
1
2016-06-20T19:41:21Z
[ "python", "loops" ]
Select all occurrences of top K values along each column in a NumPy array
37,930,431
<p>Lets say I have a NumPy array as follows: My original array is 50K X8.5K size. This is sample</p> <pre><code>array([[ 1. , 2. , 3. ], [ 1. , 0.5, 2. ], [ 2. , 3. , 1. ]]) </code></pre> <p>Now what I want is that for each column, only keep top K values (lets take K as 2 here) and re-code others to zero....
1
2016-06-20T19:33:40Z
37,931,169
<p>This should get you there:</p> <pre><code>def rwhere(a, b, p, k): if p &gt;= len(b) or p &gt;= k: return 0 else: return np.where(a == b[p], b[p], rwhere(a, b, p + 1, k)) def codek(a, k): b = a.copy() b.sort(0) b = b[::-1] return rwhere(a, b, 0, k) codek(a, 2) array([[ 1., ...
0
2016-06-20T20:20:34Z
[ "python", "numpy" ]
Select all occurrences of top K values along each column in a NumPy array
37,930,431
<p>Lets say I have a NumPy array as follows: My original array is 50K X8.5K size. This is sample</p> <pre><code>array([[ 1. , 2. , 3. ], [ 1. , 0.5, 2. ], [ 2. , 3. , 1. ]]) </code></pre> <p>Now what I want is that for each column, only keep top K values (lets take K as 2 here) and re-code others to zero....
1
2016-06-20T19:33:40Z
37,931,936
<p>Ok. I just figured out what was the problem in my code. The where clause should be in return condition of lambda function. The below works fine. </p> <pre><code>array([[ 1. , 2. , 3. ], [ 1. , 0.5, 2. ], [ 2. , 3. , 1. ]]) e=copy.deepcopy(a) for y in range(e.shape[1]): e[:,y]=map(lambda x:...
0
2016-06-20T21:15:01Z
[ "python", "numpy" ]
Select all occurrences of top K values along each column in a NumPy array
37,930,431
<p>Lets say I have a NumPy array as follows: My original array is 50K X8.5K size. This is sample</p> <pre><code>array([[ 1. , 2. , 3. ], [ 1. , 0.5, 2. ], [ 2. , 3. , 1. ]]) </code></pre> <p>Now what I want is that for each column, only keep top K values (lets take K as 2 here) and re-code others to zero....
1
2016-06-20T19:33:40Z
37,933,092
<p>With focus on performance for such large arrays, here's a vectorized approach to solve it -</p> <pre><code>K = 2 # Select top K values along each column # Sort A, store the argsort for later usage sidx = np.argsort(A,axis=0) sA = A[sidx,np.arange(A.shape[1])] # Perform differentiation along rows and look for non-...
1
2016-06-20T22:56:05Z
[ "python", "numpy" ]
having an issua comparing comparing Strings @ python
37,930,440
<p>Probably there is an easier way to do this, but i read there is no Switch/case in Python. I wanted to ask the user, to introduce a name of a color, and after calling the function that should take care of that, it should return the color code in RGB. My if statements should also accept when the first letter or the wh...
0
2016-06-20T19:33:59Z
37,930,835
<p>The way you return the color could be simplified a lot by doing this. It also fixes your bug.</p> <pre><code>White =(255, 0, 0) Black = (0, 0, 0) Red = (255, 0, 0) Green = (0, 255, 0) Blue = (0, 0, 255) Yellow = (255, 255, 0) Cyan = (0, 255, 255) Purple = (255, 0, 255) colours = { 'white' : White, 'black...
1
2016-06-20T19:58:59Z
[ "python", "if-statement", "printing", "func" ]
having an issua comparing comparing Strings @ python
37,930,440
<p>Probably there is an easier way to do this, but i read there is no Switch/case in Python. I wanted to ask the user, to introduce a name of a color, and after calling the function that should take care of that, it should return the color code in RGB. My if statements should also accept when the first letter or the wh...
0
2016-06-20T19:33:59Z
37,930,885
<p>first i'd rewrite the get_color function to something more like this</p> <pre><code>def get_color(): print('Please introduce one of the following colors') print(' \n White \n Black \n Red \n Green \n Blue \n Yellow \n Cyan \n Purple') color = input().lower() print (color) if color == 'black': re...
0
2016-06-20T20:02:18Z
[ "python", "if-statement", "printing", "func" ]
Dot product for arbitrary shaped NumPy arrays
37,930,465
<p>Given two <code>numpy.ndarray</code> objects, <code>A</code> and <code>B</code>, of arbitrary shapes, I'd like to compute an <code>numpy.ndarray</code> <code>C</code> with the property that <code>C[i] == np.dot(A[i], B[i])</code> for all <code>i</code>. How can I do this?</p> <p>Example 1: <code>A.shape==(2,3,4)</c...
3
2016-06-20T19:36:07Z
37,930,581
<p>Assuming you want ordinary matrix multiplication for <code>dot</code> (not, say, matrix-vector or the weird crap <code>dot</code> does for higher dimensions), then sufficiently recent NumPy versions (1.10+) let you do</p> <pre><code>C = numpy.matmul(A, B) </code></pre> <p>and sufficiently recent Python versions (3...
0
2016-06-20T19:44:10Z
[ "python", "numpy", "matrix-multiplication" ]
Dot product for arbitrary shaped NumPy arrays
37,930,465
<p>Given two <code>numpy.ndarray</code> objects, <code>A</code> and <code>B</code>, of arbitrary shapes, I'd like to compute an <code>numpy.ndarray</code> <code>C</code> with the property that <code>C[i] == np.dot(A[i], B[i])</code> for all <code>i</code>. How can I do this?</p> <p>Example 1: <code>A.shape==(2,3,4)</c...
3
2016-06-20T19:36:07Z
37,930,701
<p>Here's a generic solution to cover all kinds of cases / arbitrary shapes using some <code>reshaping</code> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a>. <code>einsum</code> helps here as we need alignment along the first axis and reduct...
4
2016-06-20T19:51:00Z
[ "python", "numpy", "matrix-multiplication" ]
How to test Login error validation python selenium
37,930,499
<p>I need to test Login page validation. If the user doesn't enter username, then the formErrorContent need to show beside the username.</p> <p>This is what I did</p> <pre><code> def test_UserNameValidate(self): self.driver.getElement("id", "user").click() self.driver.getElement("id", "password").click() ...
1
2016-06-20T19:38:27Z
37,930,623
<p>If you don't use <code>try except</code> your script will fail in case of no error message disappear (<code>try except</code> 'ignore' NoSuchElementException). You should also write assertion to check if message is present, because if you use <code>try except</code> the test will always pass.</p>
0
2016-06-20T19:46:18Z
[ "python", "selenium" ]
How to put dowloaded JSON data into variables in python
37,930,500
<pre><code>import requests import json import csv # These our are demo API keys, you can use them! #location = "" api_key = 'simplyrets' api_secret = 'simplyrets' #api_url = 'https://api.simplyrets.com/properties?q=%s&amp;limit=1' % (location) api_url = 'https://api.simplyrets.com/properties' response = requests.get(...
0
2016-06-20T19:38:29Z
37,930,582
<p>From <a href="https://docs.python.org/2/library/json.html" rel="nofollow">https://docs.python.org/2/library/json.html</a> :</p> <blockquote> <p><code>json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])</code></p> <p>Deserialize s (a str o...
0
2016-06-20T19:44:13Z
[ "python", "json", "dictionary" ]
How to put dowloaded JSON data into variables in python
37,930,500
<pre><code>import requests import json import csv # These our are demo API keys, you can use them! #location = "" api_key = 'simplyrets' api_secret = 'simplyrets' #api_url = 'https://api.simplyrets.com/properties?q=%s&amp;limit=1' % (location) api_url = 'https://api.simplyrets.com/properties' response = requests.get(...
0
2016-06-20T19:38:29Z
37,930,592
<p>The problem is that <code>json.loads()</code> doesn't necessarily return a dictionary. If the outside container of the JSON is a list, then <code>json.loads()</code> will return a list, where the elements could be lists or dictionaries. Try iterating through the list returned by <code>json.loads()</code>. It's possi...
0
2016-06-20T19:44:55Z
[ "python", "json", "dictionary" ]
How to put dowloaded JSON data into variables in python
37,930,500
<pre><code>import requests import json import csv # These our are demo API keys, you can use them! #location = "" api_key = 'simplyrets' api_secret = 'simplyrets' #api_url = 'https://api.simplyrets.com/properties?q=%s&amp;limit=1' % (location) api_url = 'https://api.simplyrets.com/properties' response = requests.get(...
0
2016-06-20T19:38:29Z
37,930,646
<p>There are 2 different types of JSON elements: nodes and arrays.</p> <p>A node looks like:</p> <pre><code>node = { foo = 7 bar = "Hello World!" } </code></pre> <p>A array looks like this:</p> <pre><code>array = [ "one", "two", 3, 4, "5ive" ] </code></pre> <p>Your JSON element is probably a array. You ca...
0
2016-06-20T19:47:39Z
[ "python", "json", "dictionary" ]
How to put dowloaded JSON data into variables in python
37,930,500
<pre><code>import requests import json import csv # These our are demo API keys, you can use them! #location = "" api_key = 'simplyrets' api_secret = 'simplyrets' #api_url = 'https://api.simplyrets.com/properties?q=%s&amp;limit=1' % (location) api_url = 'https://api.simplyrets.com/properties' response = requests.get(...
0
2016-06-20T19:38:29Z
37,930,709
<p>There are some minor changes you should do:</p> <ol> <li>Your API response is returning a list, so you have to iterate over it.</li> <li><p>The <code>requests</code> library already supports converting to JSON so you don't have to worry about it.</p> <pre><code>import requests # These our are demo API keys, you ...
0
2016-06-20T19:51:23Z
[ "python", "json", "dictionary" ]
How to put dowloaded JSON data into variables in python
37,930,500
<pre><code>import requests import json import csv # These our are demo API keys, you can use them! #location = "" api_key = 'simplyrets' api_secret = 'simplyrets' #api_url = 'https://api.simplyrets.com/properties?q=%s&amp;limit=1' % (location) api_url = 'https://api.simplyrets.com/properties' response = requests.get(...
0
2016-06-20T19:38:29Z
37,930,748
<p>There are hundreds of properties returned, all of which are in a list.</p> <p>You'll need to specify which property you want, so for the first one:</p> <pre><code>p = houseData[0]['property'] </code></pre>
1
2016-06-20T19:53:35Z
[ "python", "json", "dictionary" ]
Python (Django) error - Page not found (404)
37,930,553
<p>When I open my website, I see this, I created project (mysite) and application (polls)</p> <pre><code>Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: ^polls/ ^admin/ The current URL, , d...
0
2016-06-20T19:42:04Z
37,930,675
<p>You need to define a route in your mysite/urls.py file. Currently, </p> <pre><code>def index(request) </code></pre> <p>works when you hit <a href="http://127.0.0.1:8000/polls" rel="nofollow">http://127.0.0.1:8000/polls</a>. You should add </p> <pre><code>url(r'^$', your_view.index, name='index') </code></pre> <...
0
2016-06-20T19:49:06Z
[ "python", "django" ]
Using tarfile library with special characters
37,930,566
<p>I want to create tarfile with Turkish characters(like "ö") but I get an error. I'm using python 2.7 on Windows 8.1.</p> <p>Here is my code:</p> <pre><code># -*- coding: utf-8 -*- import tarfile import os import sys foldername = "klasör" foldername = foldername.decode(sys.getfilesystemencoding()) tar = tarfile...
0
2016-06-20T19:43:00Z
37,930,618
<p>Use "u" before the name like so.</p> <pre><code>foldername = u"klasör" </code></pre> <p>You do not need to encode/decode it, instead leave it as unicode and open like you did.</p>
2
2016-06-20T19:45:59Z
[ "python", "python-2.7", "unicode", "tarfile" ]
Python 3 - if statement not matching exact string
37,930,588
<p>I'm following the "Learn Python The Hard Way" book. In the partial example below the input string is compared against some values.</p> <p>When I execute the code, if you enter any input that contains the word + any other character, it is still evaluated to True, </p> <blockquote> <p>e.g. > fleeee, headsss, headh...
0
2016-06-20T19:44:31Z
37,930,639
<p>Use <code>==</code> instead of <code>in</code>.</p> <p>By using <code>in</code> you search if it's inside.<br> Using <code>==</code> checks for the exact string.</p>
4
2016-06-20T19:47:16Z
[ "python", "python-3.x" ]
Using Selenium, PhantomJS and Tor in python
37,930,681
<p>I'm trying to use phantomJS with selenium and Tor. I have the following: </p> <pre><code>from selenium import webdriver service_args = [ '--proxy=127.0.0.1:9050', ' --proxy-type=socks5', ] driver = webdriver.PhantomJS(service_args = service_args) </code></pre> <p>Every time I try to connect, I ...
0
2016-06-20T19:49:39Z
39,221,883
<p>Try adding your exact phantomjs path?</p> <pre><code>driver = webdriver.PhantomJS(executable_path=&lt;your_phantomjs_path&gt;, service_args = service_args) </code></pre>
0
2016-08-30T07:57:20Z
[ "python", "selenium", "phantomjs", "tor" ]
How can I make a barplot and a lineplot in the same seaborn plot with different Y axes nicely?
37,930,693
<p>I have two different sets of data with a common index, and I want to represent the first one as a barplot and the second one as a lineplot in the same graph. My current approach is similar to the following.</p> <pre><code>ax = pt.a.plot(alpha = .75, kind = 'bar') ax2 = ax.twinx() ax2.plot(ax.get_xticks(), pt.b.valu...
4
2016-06-20T19:50:25Z
37,932,559
<p>You have to remove grid lines of the second axis. Add to the code <code>ax2.grid(False)</code>. However y-ticks of the second axis will be not align to y-ticks of the first y-axis, like here:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sns import numpy as np import pandas as pd fig = plt.figu...
1
2016-06-20T22:04:23Z
[ "python", "pandas", "matplotlib", "visualization", "seaborn" ]
How to write argparse in python using abstract base class
37,930,737
<p>I am new in python, and trying to use Parser for command line options, arguments and subcommand.</p> <p>My command should look like as:</p> <p>if store in s3 or swift then:</p> <pre><code>$snapshotter S3 [-h] [-v] --aws-access-key-id AWS_ACCESS_KEY_ID --aws-secret-access-key AWS_SECRET_AC...
-2
2016-06-20T19:53:00Z
37,931,129
<p>It sounds like you want 2 levels of subcommands, one that distinguishes between <code>S3</code> and <code>Swift</code> and another between <code>list</code>, <code>backup</code> etc.</p> <p>This structure does that:</p> <pre><code>import argparse parser = argparse.ArgumentParser() sp1 = parser.add_subparsers(dest...
0
2016-06-20T20:17:49Z
[ "python", "python-2.7", "argparse", "abc" ]
Not able to delete string item with colon in python list
37,930,757
<p>So I'm having the following problem while coding in python: I have a few string items in a list like so:</p> <pre><code>['X','Y','Z','A', 'B:C', 'D'] </code></pre> <p>I want to delete everything past <code>'Z'</code>. I use the following code to attempt this:</p> <pre><code>for item in lines: if ((item == "A")...
0
2016-06-20T19:54:29Z
37,930,825
<p>You may use the <code>.index()</code> method to find the index of a specific element inside a list.</p> <p>Then after finding the <code>z_index</code>, you may create another list by slicing the first one.</p> <p>Here's an example:</p> <pre><code>l1 = ['X','Y','Z','A', 'B:C', 'D'] #finding index of element 'Z' z...
1
2016-06-20T19:58:28Z
[ "python" ]
Not able to delete string item with colon in python list
37,930,757
<p>So I'm having the following problem while coding in python: I have a few string items in a list like so:</p> <pre><code>['X','Y','Z','A', 'B:C', 'D'] </code></pre> <p>I want to delete everything past <code>'Z'</code>. I use the following code to attempt this:</p> <pre><code>for item in lines: if ((item == "A")...
0
2016-06-20T19:54:29Z
37,930,837
<p>Modifying a list while iterating over it is usually a bad thing. Some of the elements get skipped when you remove the current element. You <em>may</em> be able to fix it by iterating over <code>reversed(lines)</code>, but it is better to create a new list that doesn't have the elements that you want to drop:</p> ...
4
2016-06-20T19:59:04Z
[ "python" ]
Not able to delete string item with colon in python list
37,930,757
<p>So I'm having the following problem while coding in python: I have a few string items in a list like so:</p> <pre><code>['X','Y','Z','A', 'B:C', 'D'] </code></pre> <p>I want to delete everything past <code>'Z'</code>. I use the following code to attempt this:</p> <pre><code>for item in lines: if ((item == "A")...
0
2016-06-20T19:54:29Z
37,930,866
<p>Generally, it is not a good idea to delete elements from a list you are iterating. In your case, you may consider creating a new list with the result you want:</p> <pre><code>l = ['X','Y','Z','A', 'B:C', 'D'] clean_l = [i for i in l if i not in ('A', 'B:C', 'D')] </code></pre> <p>Which is a good option if you know...
0
2016-06-20T20:00:42Z
[ "python" ]
Not able to delete string item with colon in python list
37,930,757
<p>So I'm having the following problem while coding in python: I have a few string items in a list like so:</p> <pre><code>['X','Y','Z','A', 'B:C', 'D'] </code></pre> <p>I want to delete everything past <code>'Z'</code>. I use the following code to attempt this:</p> <pre><code>for item in lines: if ((item == "A")...
0
2016-06-20T19:54:29Z
37,930,989
<p>Firstly you would want to find the position of 'Z' by using the index() method. </p> <pre><code>x = ['X','Y','Z','A', 'B:C', 'D'] position = x.index('Z') </code></pre> <p>Then to delete everything after z i would do this:</p> <pre><code>del x[postion+1:] </code></pre> <p>You have to add one to the position other...
0
2016-06-20T20:08:21Z
[ "python" ]
How add plots to subplots using matplotlib
37,930,768
<p>I want to add plots to subplots using </p> <pre><code>fig, axarr = plt.subplots(2, 2) plt.sca(axarr[0, 0]) result = desire_salary.pivot_table('city', 'cult', aggfunc='count') axarr[0, 0] = result.plot(kind='bar', alpha=0.75, rot=0, label="Presence / Absence of cultural centre") axarr[0, 0].set_xlabel("Cultu...
0
2016-06-20T19:55:17Z
37,931,134
<p>When you use pandas (I assume), the surest way to ensure which axes is used is to pass the reference to the axes to the plotting function using the <code>ax=</code> parameter</p> <pre><code>fig, axarr = plt.subplots(2, 2) result = desire_salary.pivot_table('city', 'cult', aggfunc='count') result.plot(kind='bar', al...
1
2016-06-20T20:18:03Z
[ "python", "matplotlib" ]
Implementing Python methods in batch by casting
37,930,777
<p>I have a Python class <code>Foo</code> and a more memory-conscious version <code>LightFoo</code>. The information contained in their attributes is ultimately the same but is encoded differently. </p> <p>A handful of <code>Foo</code>'s methods will be completely re-written for <code>LightFoo</code>, but for most of ...
0
2016-06-20T19:55:55Z
37,930,916
<p>If fooize() is doing some custom processing to convert the object to a Foo, you can do this by just defining <code>__getattr__</code>, which is called when you access an attribute that can't be found. You can call <code>fooize()</code> there.</p> <pre><code>def __getattr__(self, name): return getattr(self.fooiz...
1
2016-06-20T20:04:16Z
[ "python" ]
How do I duplicate CSV rows row_number times?
37,930,799
<p>I am trying to use Python to generate a CSV file "distances" where I want to duplicate the rows of another file, "result" like this:</p> <p>result.csv:</p> <pre><code>|ID | |---| | 1 | | 2 | | 3 | ... </code></pre> <p>distances.csv</p> <pre><code>|ID1 |ID2 | |----|----| | 1 | 1 | | 1 | 2 | | 1 | 3 | | 2 |...
0
2016-06-20T19:57:18Z
37,931,047
<p>Since the <a href="https://docs.python.org/2/library/csv.html#csv.reader" rel="nofollow"><code>csv.reader</code></a> is an iterator over the file, you can only go through it once. Try reading the rows into a list:</p> <pre><code>with open("result.csv", "b") as f, open("distances.csv", "wb") as ff: reader = csv....
1
2016-06-20T20:12:24Z
[ "python", "loops", "csv" ]
How do I duplicate CSV rows row_number times?
37,930,799
<p>I am trying to use Python to generate a CSV file "distances" where I want to duplicate the rows of another file, "result" like this:</p> <p>result.csv:</p> <pre><code>|ID | |---| | 1 | | 2 | | 3 | ... </code></pre> <p>distances.csv</p> <pre><code>|ID1 |ID2 | |----|----| | 1 | 1 | | 1 | 2 | | 1 | 3 | | 2 |...
0
2016-06-20T19:57:18Z
37,931,053
<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> to make the repetitions on column <code>ID</code> in <code>distance.csv</code>:</p> <pre><code>from itertools import product import csv with open('result.csv', 'r') as fin, op...
2
2016-06-20T20:12:50Z
[ "python", "loops", "csv" ]
drop all files in gridfs mongodb with pymongo
37,930,826
<p>i would like to drop all the files in gridfs but i didn't manage to do it :</p> <pre><code>from pymongo import MongoClient from bson.objectid import ObjectId #add the file to GridFS, per the pymongo documentation: http://api.mongodb.org/python/current/examples/gridfs.html db_file = MongoClient('192.168.0.16', 270...
0
2016-06-20T19:58:34Z
38,369,790
<p>Try this:</p> <blockquote> <p>my_collection = db['collection_name']<br> my_collection.drop()</p> </blockquote> <p>or drop database :</p> <blockquote> <p>client = MongoClient('192.168.0.16', 27017)<br> client.drop_database("database_name")</p> </blockquote>
1
2016-07-14T08:57:50Z
[ "python", "mongodb" ]
Using p4python with grep command
37,930,963
<p>Does anyone knows how to use <code>grep()</code> command in P4Python?<br/> I am developing an script that runs with Perforce and makes it easy for me to <b>search for specific texts inside multiple files</b>.</p> <p>I already tried to create a tool in Perforce > Tools > Manage Custom Tools using P4 commands like <c...
1
2016-06-20T20:07:03Z
37,939,247
<p>Don't expect <code>p4.run()</code> to print to <code>STDOUT</code>. It's an API call - capture its return value (structured data) and process it.</p> <p>I believe that by convention of the API, you <em>should</em> be able to use <code>p4.run("grep", ARGS)</code> as well as <code>p4.run_grep(ARGS)</code>. It's proba...
0
2016-06-21T08:29:16Z
[ "python", "perforce", "p4python" ]
Postgresql insert data error when using python
37,931,006
<p>I am trying to insert data to the table that was created earlier using python script. Here is the code I am trying to execute. I want to insert data into table with date as well.</p> <pre><code>date_today = dt.date.today() conn = psycopg2.connect(host = serverip, port = port, database = database, user = uid, pa...
-1
2016-06-20T20:09:29Z
37,931,069
<p>This line:</p> <pre><code>cursor.execute("INSERT INTO My_TABLE (Date, Class, Total_students, failed_students, Percent_passed_students) VALUES (date_today, 'Class Name', int1, int2, int3)") </code></pre> <p>Is the incorrect way to dynamically insert values into a database.</p> <hr> <p>Here's a functional and corr...
3
2016-06-20T20:14:14Z
[ "python", "postgresql", "jenkins" ]
Reading a Multigraph in NetworkX from gml file
37,931,040
<p>I am attempting to read a gml file into a multigraph object; however, I am receiving the following error:</p> <pre><code>NetworkXError: edge #1 (0--3) is duplicated </code></pre> <p>In the gml file the the edge is duplicated:</p> <pre><code> edge [ source 0 target 3 LinkLabel "Green" ] edge [ ...
1
2016-06-20T20:12:08Z
37,931,495
<p>Your gml file probably lacks of <code>multigraph 1</code> below <code>graph [</code>. Here is a MWE.</p> <pre><code>import networkx as nx G = nx.read_gml('test.gml') print(type(G)) # &lt;class 'networkx.classes.multigraph.MultiGraph'&gt; print(G.edges(data=True)) # [(0, 3, {u'LinkLabel': u'Green'}),...
1
2016-06-20T20:44:09Z
[ "python", "networkx" ]
Python generating repmat using each column individually
37,931,104
<p>I have an array of shape 3x3 which looks something like:</p> <pre><code>import numpy as np A = np.array(([1,2,3],[11,12,5],[4,9,1])) &gt;&gt;&gt; A array([[ 1, 2, 3], [11, 12, 5], [ 4, 9, 1]]) </code></pre> <p>I want to repmat one column at a time for 3 times so that I can achieve the following:...
0
2016-06-20T20:16:43Z
37,931,204
<p>This is the job of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.repeat.html" rel="nofollow"><code>numpy.repeat</code></a>. Quoting an example from the docs:</p> <pre><code>&gt;&gt;&gt; x = np.array([[1,2],[3,4]]) &gt;&gt;&gt; np.repeat(x, 3, axis=1) array([[1, 1, 1, 2, 2, 2], [3, 3, 3, ...
2
2016-06-20T20:22:54Z
[ "python", "numpy" ]
Installing pocketsphinx - pulseaudio development package
37,931,125
<p>In the <a href="http://cmusphinx.sourceforge.net/wiki/tutorialpocketsphinx" rel="nofollow">instructions for setting up pocketsphinx</a>, one of the dependencies is <code>pulseaudio development package</code>. What exactly is this? Where should I download it?</p>
-2
2016-06-20T20:17:40Z
38,059,575
<p>PulseAudio is a sound server library. The "development package" means that you'll need to install the development headers. For example on Ubuntu, instead of just installing the "pulseaudio" package, you instead need something like:</p> <pre><code>$ sudo apt-get install libpulse-dev </code></pre> <p>If you are deve...
2
2016-06-27T17:10:44Z
[ "python", "osx", "cmusphinx", "pocketsphinx" ]
Python IDLE is glitching when I try to load images with pygame
37,931,165
<p>I don't know how to explain this so I have included a video showing you what's happening.</p> <p><a href="https://www.youtube.com/watch?v=XCNl24mpko0&amp;feature=youtu.be" rel="nofollow">https://www.youtube.com/watch?v=XCNl24mpko0&amp;feature=youtu.be</a></p>
0
2016-06-20T20:20:17Z
37,932,803
<p>Notice how it says it's trying to load "imagesed shield.png" This is because the baskslash is escaping "r". Putting an "r" at the front will fix it by converting the string to a raw string, as will replacing the backslash with a forward slash, or escaping the backslash itself.</p> <pre><code>red_shield = pyg.image....
1
2016-06-20T22:25:28Z
[ "python", "pygame" ]
Scope of Python variables in this case - Difference between Enclosing and Local Variable
37,931,197
<p>I am confused about the scope of python variables. How is this working</p> <p>Consider the following example</p> <pre><code>i = 12 if i==12 : str = "is equal" else: str = "NOT" print str //Prints is equal - recognized the string str </code></pre> <p>The variable <code>str</code> is only in the scope of i...
0
2016-06-20T20:22:30Z
37,931,240
<blockquote> <p>The variable <code>str</code> is only in the scope of if statement and its scope is lost at the else statement.</p> </blockquote> <p>Nope. Python is function scoped, not block scoped. Entering an <code>if</code> block doesn't create a new scope, so the <code>str</code> variable is still in scope for ...
4
2016-06-20T20:25:13Z
[ "python" ]
Scope of Python variables in this case - Difference between Enclosing and Local Variable
37,931,197
<p>I am confused about the scope of python variables. How is this working</p> <p>Consider the following example</p> <pre><code>i = 12 if i==12 : str = "is equal" else: str = "NOT" print str //Prints is equal - recognized the string str </code></pre> <p>The variable <code>str</code> is only in the scope of i...
0
2016-06-20T20:22:30Z
37,931,247
<p>Python doesn't have general block scope for, only function scope (with some additional weirdness for cases like <code>class</code> declarations). Any name assigned within a function will remain valid for the life of the function.</p> <p>Enclosing scope applies when nesting function declarations, e.g.:</p> <pre><co...
1
2016-06-20T20:25:48Z
[ "python" ]