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 update/refresh qTreewidget?
39,279,792
<p>I have this little UI that lists text and python script files for a given path, but when I try to UPDATE or REPLACE the list with new items, I think the data is placed there, but they appear blank. I assume it has something to do with not telling the UI that data has been updated and that the UI has to be redrawn?</...
0
2016-09-01T19:48:58Z
39,289,995
<p>Honestly, I don't quite get your code. But if you want to add new items to a <code>QTreeWidget</code>, here's how you do it:</p> <pre><code>item = QTreeWidgetItem() item.setText(0, "John") # first name item.setText(1, "Doe") # last name item.setText(2, "35") # age self.treeWidget.addTopLevelItem(item) </code></pre...
0
2016-09-02T10:17:15Z
[ "python", "python-2.7", "qt", "pyqt", "pyqt4" ]
How to define and instantiate a derived class at once in python?
39,279,810
<p>I have a base class that I want to derive and instantiate together. I can do that in java like: </p> <pre><code>BaseClass derivedClassInstance = new BaseClass() { @override void someBaseClassMethod() { // my statements} }; </code></pre> <p>In python I can derive and and instantiate a base class like: </p...
0
2016-09-01T19:50:03Z
39,280,023
<p>I think you are looking for metaclass programming. </p> <pre><code>class Base(object): def test(self): print 'hit' a =type( 'Derived',(Base,),{})() a.test() hit </code></pre>
0
2016-09-01T20:04:09Z
[ "python", "inheritance" ]
How to define and instantiate a derived class at once in python?
39,279,810
<p>I have a base class that I want to derive and instantiate together. I can do that in java like: </p> <pre><code>BaseClass derivedClassInstance = new BaseClass() { @override void someBaseClassMethod() { // my statements} }; </code></pre> <p>In python I can derive and and instantiate a base class like: </p...
0
2016-09-01T19:50:03Z
39,280,047
<p>In general you won't see this kind of code, because is difficult to read and understand. I really suggest you find some alternative and avoid what comes next. Having said that, you can create a class and an instance in one single line, like this:</p> <pre><code>&gt;&gt;&gt; class BaseClass(object): ... def f1(s...
2
2016-09-01T20:05:30Z
[ "python", "inheritance" ]
Use None instead of np.nan for null values in pandas DataFrame
39,279,824
<p>I have a pandas DataFrame with mixed data types. I would like to replace all null values with None (instead of default np.nan). For some reason, this appears to be nearly impossible. </p> <p>In reality my DataFrame is read in from a csv, but here is a simple DataFrame with mixed data types to illustrate my probl...
2
2016-09-01T19:51:12Z
39,279,898
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow">Use <code>pd.DataFrame.where</code></a><br> Uses <code>df</code> value when condition is met, otherwise uses <code>None</code></p> <pre><code>df.where(df.notnull(), None) </code></pre> <p><a href="http://i.st...
2
2016-09-01T19:55:24Z
[ "python", "pandas", "dataframe" ]
How to draw a graphical count table in pandas
39,279,858
<p>I have a dataframe df with two columns <code>customer1</code> and <code>customer2</code> which are string valued. I would like to make a square graphical representation of the count number for each pair from those two columns. </p> <p>I can do</p> <pre><code>df[['customer1', 'customer2']].value_counts() </cod...
2
2016-09-01T19:53:24Z
39,280,203
<p><strong>UPDATE:</strong> </p> <blockquote> <p>Is it possible to sort the rows/columns so the highest count rows are at the top ? In this case the order would be b,a,c</p> </blockquote> <p>IIUC you can do it this way (where ):</p> <pre><code>In [80]: x = df.pivot_table(index='customer1',columns='customer2',ag...
2
2016-09-01T20:15:14Z
[ "python", "pandas" ]
How to draw a graphical count table in pandas
39,279,858
<p>I have a dataframe df with two columns <code>customer1</code> and <code>customer2</code> which are string valued. I would like to make a square graphical representation of the count number for each pair from those two columns. </p> <p>I can do</p> <pre><code>df[['customer1', 'customer2']].value_counts() </cod...
2
2016-09-01T19:53:24Z
39,280,256
<p>As @MaxU mentioned, <code>seaborn.heatmap</code> should work. It appears that you can use the Pandas DataFrame as the input.</p> <p><code>seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annot_kws=None, linewidths=0, linecolor='white', cbar=True, cbar_kws=None...
0
2016-09-01T20:20:07Z
[ "python", "pandas" ]
create a pandas frame of shape (x**0.5,x**0.5) from a array of size x python
39,279,881
<p>I have an array of size 64, such has:</p> <pre><code>In[164]: x_y.values / x_ysquare.stack().values Out[164]: array([ 1. , 0.01623716, -0.03305102, 0.03264311, -0.0175754 , 0.04017079, 0.15731795, -0.01797369, 0.01623716, 1. , 0.08387368, -0.09562322, 0.02700502, 0.0614588 , 0...
1
2016-09-01T19:54:39Z
39,280,044
<p>Maybe you can do:</p> <pre><code>arr_reshaped = arr.reshape(8,8) df = pd.DataFrame(arr_reshaped) </code></pre>
2
2016-09-01T20:05:15Z
[ "python", "pandas" ]
python find FAILED numbers in log file
39,279,884
<p>I would like Python code to search for FAILED number from a file.txt .like here 5 , i need to search the FAILED number, whether 0 or any number. then i can send an email the number of failures. I have tried the grep but it does not works. </p> <pre><code>searchfile = open("file.txt", "r") for line in searchfil...
0
2016-09-01T19:54:44Z
39,280,553
<p>You can find the position of the FAILED column and look at the values at that position in the rows of interest: </p> <pre><code>result = {} col = 'FAILED' col_index = None row_names = {'Dirs', 'Files'} for l in open('file.txt').readlines(): if col_index is None: if col in l: col_index = l.f...
0
2016-09-01T20:42:18Z
[ "python", "windows", "robocopy" ]
how to access an element of the get_context_data in django
39,279,885
<p>I'm trying to access to the elements of the get_context_data like:</p> <pre><code>context = super(DetallePlanillasContratado,self).get_context_data(**kwargs) </code></pre> <p>and then access in this way:</p> <pre><code>context['new_context'] = context.element_of_the_context </code></pre> <p>do we have something ...
1
2016-09-01T19:54:47Z
39,280,024
<p><code>context['new_context'] = context['elements_of_the_context']</code></p>
1
2016-09-01T20:04:16Z
[ "python", "django" ]
How to import custom module the same way as pip-installed modules?
39,279,943
<p>I feel really dumb asking this question, but it's a quirk of python I've put up with for awhile now that I finally want to fix.</p> <p>On CentOS 7, given that I have "roflmao.py" and "__init__.py" in the directory:</p> <pre><code> /usr/lib/python2.7/site-packages/roflmao </code></pre> <p>Why is it that when I'm u...
3
2016-09-01T19:58:41Z
39,279,965
<p>Put <code>from roflmao import *</code> into <code>__init__.py</code>.</p> <p>If you do this, then you don't really need to use <code>roflmao.py</code>. Because it would then be pointless to do <code>from roflmao import roflmao</code>. So it's best to just put the code from <code>roflmao.py</code> into <code>__ini...
3
2016-09-01T20:00:22Z
[ "python", "import", "module" ]
Recursion and breaking out of (or ignoring) a cycle
39,279,958
<p>I have the following:</p> <pre><code>def rfunction(x, y): new_x = assignment1 new_y = assignment2 print "x depends on new_x of form y" rfunction(new_x, new_y) </code></pre> <p>My true code is a lot more complex, relies on multiple jsons, etc. but this is the gist of the issue. Running this will yie...
2
2016-09-01T19:59:57Z
39,281,204
<p>If the only cycles you might encounter are self-references (e.g. <code>new_x, new_y</code> is <code>x, y</code>), then you could fix this with a simple <code>if</code> check:</p> <pre><code>def rfunction(x, y): new_x = assignment1 new_y = assignment2 print "x depends on new_x of form y" if new_x != ...
2
2016-09-01T21:33:31Z
[ "python", "recursion", "infinite-loop" ]
What is the simplest way to run a constant loop in a tkinter frame?
39,280,004
<p>I want to run a method in the background of my tkinter frame that will constantly check if certain files exist in a specific folder. As long as the files dont exist, there will be a red <code>tk.label</code> that says "Incomplete", and as soon as it detects these specific files, the <code>tk.label</code> will turn g...
1
2016-09-01T20:02:36Z
39,280,143
<p>Define a function that does whatever you want, and have that function schedule itself to be run again in the future. It will run until the program quits.</p> <p>This example assumes a global variable named <code>root</code> that refers to the root window, but any widget reference will work.</p> <pre><code>def do_s...
1
2016-09-01T20:11:07Z
[ "python", "python-2.7", "tkinter", "tk" ]
strange python destructor behaviour
39,280,050
<p>While playing with OO Python I came across following curiosity. Consider following simple class:</p> <pre><code>&gt;&gt;&gt; class Monty(): def __init__(self): print 'start m' def __del__(self): print 'deleted m' </code></pre> <p>Instantiating object goes as expected:</p> <pre><code>&gt;&g...
1
2016-09-01T20:05:43Z
39,280,120
<p>The Python interpreter creates an <em>additional reference</em>. Every time an expression doesn't return <code>None</code>, the result is echoed <strong>and</strong> stored in the <code>_</code> built-in name.</p> <p>When you then echo a different result, <code>_</code> is rebound to the new result, and the old obj...
3
2016-09-01T20:09:53Z
[ "python", "oop", "garbage-collection" ]
how to check each letter in a string and do some action, in Python
39,280,060
<p>So I was messing around in python, and developed a problem. I start out with a string like the following:</p> <pre><code>a = "1523467aa252aaa98a892a8198aa818a18238aa82938a" </code></pre> <p>For every number, you have to add it to a <code>sum</code> variable.Also, with every encounter of a letter, the index iterato...
-1
2016-09-01T20:06:22Z
39,280,150
<p>This part is not doing what you think:</p> <pre><code>for i in a: if isinstance(a[i], int): </code></pre> <p>Since <code>i</code> is an iterator, there is no need to use <code>a[i]</code>, it will confuse Python.</p> <p>Also, since <code>a</code> is a string, no element of it will be an <code>int</code>, they...
1
2016-09-01T20:11:54Z
[ "python", "string" ]
how to check each letter in a string and do some action, in Python
39,280,060
<p>So I was messing around in python, and developed a problem. I start out with a string like the following:</p> <pre><code>a = "1523467aa252aaa98a892a8198aa818a18238aa82938a" </code></pre> <p>For every number, you have to add it to a <code>sum</code> variable.Also, with every encounter of a letter, the index iterato...
-1
2016-09-01T20:06:22Z
39,280,194
<p>You have a few problems with your code. You don't seem to understand how <code>for... in</code> loops work, but @Will already addressed that problem in his answer. Furthermore, you have a misunderstanding of how <code>isinstance()</code> works. As the numbers are characters of a string, when you iterate over that st...
0
2016-09-01T20:14:26Z
[ "python", "string" ]
closing python comand subprocesses
39,280,171
<p>I want to continue with commands after closing subprocess. I have following code but <code>fsutil</code> is not executed. how can I do it?</p> <pre><code>import os from subprocess import Popen, PIPE, STDOUT os.system('mkdir c:\\temp\\vhd') p = Popen( ["diskpart"], stdin=PIPE, stdout=PIPE ) p.stdin.write("create vd...
4
2016-09-01T20:12:50Z
39,280,436
<p>At the least, I think you need to change your code to look like this:</p> <pre><code>import os from subprocess import Popen, PIPE os.system('mkdir c:\\temp\\vhd') p = Popen(["diskpart"], stdin=PIPE, stdout=PIPE, stderr=PIPE) p.stdin.write("create vdisk file=c:\\temp\\vhd\\test.vhd maximum=2000 type=expandable\n") ...
1
2016-09-01T20:33:49Z
[ "python", "subprocess", "stdout" ]
UTF-16 codepoint counting in python
39,280,183
<p>I'm getting some data from an API (telegram-bot) I'm using. I'm using the <a href="https://github.com/python-telegram-bot/python-telegram-bot" rel="nofollow">python-telegram-bot</a> library which interacts with the <a href="https://core.telegram.org/bots/api" rel="nofollow">Telegram Bot api</a>. The data is returned...
4
2016-09-01T20:13:49Z
39,280,419
<p>Python has already correctly decoded the UTF-8 encoded JSON data to Python (Unicode) strings, so there is no need to handle UTF-8 here.</p> <p>You'd have to encode to UTF-16, take the length of the encoded data, and divide by two. I'd encode to either <code>utf-16-le</code> or <code>utf-16-be</code> to prevent a BO...
3
2016-09-01T20:32:18Z
[ "python", "python-3.x", "encoding", "utf-8", "utf-16" ]
Handling DisambiguationError?
39,280,195
<p>I'm using the <code>wikipedia</code> library and I want to handle the <code>DisambiguationError</code> as an exception. My first try was</p> <pre><code>try: wikipedia.page('equipment') # could be any ambiguous term except DisambiguationError: pass </code></pre> <p>During execution line 3 isn't reached. ...
0
2016-09-01T20:14:28Z
39,280,294
<p>Here's a working example:</p> <pre><code>import wikipedia try: wikipedia.page('equipment') except wikipedia.exceptions.DisambiguationError as e: print("Error: {0}".format(e)) </code></pre> <p>Regarding to your more general question <code>how can I find the error type for a library-specific class like this...
1
2016-09-01T20:22:38Z
[ "python", "error-handling", "try-except", "pywikipedia" ]
Pandas - how to remove spaces in each column in a dataframe?
39,280,278
<p>I'm trying to remove spaces, apostrophes, and double quote in each column data using this for loop</p> <p><code>for c in data.columns: data[c] = data[c].str.strip().replace(',', '').replace('\'', '').replace('\"', '').strip()</code></p> <p>but I keep getting this error:</p> <p><code>AttributeError: 'Series' o...
-1
2016-09-01T20:21:42Z
39,280,341
<p>data[c] does not return a value, it returns a series (a whole column of data). </p> <p>You can apply the strip operation to an entire column df.apply. You can apply the strip function this way.</p>
0
2016-09-01T20:26:28Z
[ "python", "pandas" ]
Pandas - how to remove spaces in each column in a dataframe?
39,280,278
<p>I'm trying to remove spaces, apostrophes, and double quote in each column data using this for loop</p> <p><code>for c in data.columns: data[c] = data[c].str.strip().replace(',', '').replace('\'', '').replace('\"', '').strip()</code></p> <p>but I keep getting this error:</p> <p><code>AttributeError: 'Series' o...
-1
2016-09-01T20:21:42Z
39,280,710
<p><strong>UPDATE:</strong> using your sample DF:</p> <pre><code>In [80]: df Out[80]: id city country 0 1 Ontario Canada 1 2 Calgary ' Canada' 2 3 'Vancouver Canada In [81]: df.replace(r'[,\"\']','', regex=True).replace(r'\s*([^\s]+)\s*', r'\1', regex=True) Out[81]: id cit...
1
2016-09-01T20:55:20Z
[ "python", "pandas" ]
Python Entry point 'console_scripts' not found
39,280,326
<p>I'm unable to import entry point console scripts in my python package. Looking for help debugging my current issue, as I have read every relevant post on the issue.</p> <p>Here is what my directory structure looks like:</p> <pre><code>├── ContentAnalysis │   ├── __init__.py │   ├── comman...
1
2016-09-01T20:25:22Z
39,281,387
<p>Investigation of the relevant site-packages folder clued me that my <code>python setup.py install</code> command was not putting all the relevant files where they needed to be. </p> <p>I'm still not 100% of the underlying cause of the issue, but I was only able to get my site-packages folder to truly update by pass...
0
2016-09-01T21:48:39Z
[ "python", "debian", "anaconda", "setuptools", "setup.py" ]
How to construct a puppet resource from Python
39,280,335
<p>I would like to construct a puppet resource from within Python. If I had a hash of keys and values, or variables with values, how could this be done?</p> <p>This is a simple example of a puppet resource.</p> <pre><code>file { '/etc/passwd': owner =&gt; root, group =&gt; root, mode =&gt; 644 } </code></pre> ...
0
2016-09-01T20:26:04Z
39,323,645
<p>From your comment it seems you just want to be able to output your python objects into puppet manifest format. Since there is not a python package that does this I propose writing your own classes to handle the resource types you need, then overriding the <strong>str</strong> function so that it outputs the manifes...
0
2016-09-05T03:46:35Z
[ "python", "puppet" ]
Python os.environ throws key error?
39,280,435
<p>I'm accessing an environment variable in a script with <code>os.environ.get</code> and it's throwing a <code>KeyError</code>. It doesn't throw the error from the Python prompt. This is running on OS X 10.11.6, and is Python 2.7.10.</p> <p>What is going on?</p> <pre><code>$ python score.py Traceback (most recent ca...
8
2016-09-01T20:33:48Z
39,280,619
<p>I'd recommend you start debugging os.py, for instance, on windows it's being used this implementation:</p> <pre><code>def get(self, key, failobj=None): print self.data.__class__ print key return self.data.get(key.upper(), failobj) </code></pre> <p>And if I test it with this:</p> <pre><code>import os ...
-3
2016-09-01T20:47:44Z
[ "python", "python-2.7" ]
Python os.environ throws key error?
39,280,435
<p>I'm accessing an environment variable in a script with <code>os.environ.get</code> and it's throwing a <code>KeyError</code>. It doesn't throw the error from the Python prompt. This is running on OS X 10.11.6, and is Python 2.7.10.</p> <p>What is going on?</p> <pre><code>$ python score.py Traceback (most recent ca...
8
2016-09-01T20:33:48Z
39,280,914
<p>Try running:</p> <pre><code>find . -name \*.pyc -delete </code></pre> <p>To delete your <code>.pyc</code> files. </p> <p>Researching your problem I came across <a href="http://stackoverflow.com/q/26861856/3642398">this question</a>, where a user was experiencing the same thing: <code>.get()</code> seemingly raisi...
4
2016-09-01T21:11:34Z
[ "python", "python-2.7" ]
Select rows where a particular column has is two characters long
39,280,448
<p>I know how to select rows by value in a particular column. For example:</p> <pre><code>df.loc[df['column_name'] == some_value] </code></pre> <p>How do I modify that so the column value is exactly two capital letters. E.g. AB or FZ.</p>
0
2016-09-01T20:34:32Z
39,280,479
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.match.html" rel="nofollow">.str.match()</a> method:</p> <pre><code>In [55]: df Out[55]: col 0 xy 1 ABC 2 ZS 3 AAAAA 4 XC In [56]: df.col.str.match(r'^[A-Z]{2}$') Out[56]: 0 False 1 False 2 Tr...
4
2016-09-01T20:36:59Z
[ "python", "pandas", "dataframe" ]
Can't import 'datasets' with scikit-learn
39,280,466
<p>I just installed Python (tried both 3.5.2 and 2.7.12 with the exact same result). I've tried Googling it and looking through issues but can't find anything on it.</p> <p>The code I'm trying to run is simply the beginning of the basic tutorial:</p> <pre><code>from sklearn import datasets iris = datasets.load_iris()...
1
2016-09-01T20:35:50Z
39,280,646
<p>The error is caused from the file that you have named <code>/Users/fredrik/code/scikit-learn/sklearn.py</code></p> <p>The <code>sklearn</code> library is being overridden by your local file, so you just need to rename the <code>sklearn.py</code> file in your project to something else and it should work.</p>
2
2016-09-01T20:50:24Z
[ "python", "numpy", "scipy", "scikit-learn" ]
altering a word encoder and decoder to give recognize spaces and punctuation
39,280,585
<p>The 2nd function encodes a word phase and the 3rd one decodes that same word function but it doesn't skip over the spaces and punctuation. </p> <pre><code>def buildCipher(key): alpha="abcdefghijklmnopqrstuvwxyz" rest = "" for letter in alpha: if not(letter in key): rest = rest + letter ...
1
2016-09-01T20:44:44Z
39,280,740
<p>At the moment the space character isn't in either alpha or your keyletters - if you don't want space encrypted then add it in the same position in both.</p> <p>NOTE your code currently ignores the fact that space is in the string to encode but not in the keyletters. It would be a good idea to be explicit about this...
0
2016-09-01T20:57:04Z
[ "python" ]
altering a word encoder and decoder to give recognize spaces and punctuation
39,280,585
<p>The 2nd function encodes a word phase and the 3rd one decodes that same word function but it doesn't skip over the spaces and punctuation. </p> <pre><code>def buildCipher(key): alpha="abcdefghijklmnopqrstuvwxyz" rest = "" for letter in alpha: if not(letter in key): rest = rest + letter ...
1
2016-09-01T20:44:44Z
39,280,751
<p>What happens if <code>letter</code> isn't alphabetic? Exactly, it doesn't get added since it can't find it's index in <code>alpha</code>. You need to have an <code>if/else</code> statement:</p> <pre><code>def encode(string,keyletters): alpha="abcdefghijklmnopqrstuvwxyz" secret = "" for letter in string: i...
0
2016-09-01T20:57:40Z
[ "python" ]
How to share conda environments across platforms
39,280,638
<p>The conda docs at <a href="http://conda.pydata.org/docs/using/envs.html" rel="nofollow">http://conda.pydata.org/docs/using/envs.html</a> explain how to share environments with other people.</p> <p>However, the docs tell us this is not cross platform:</p> <pre><code>NOTE: These explicit spec files are not usually c...
2
2016-09-01T20:49:23Z
39,299,669
<h2>Answer</h2> <p>This answer is given with the assumption that you would like to make sure that the same versions of the packages that you generally care about are on different platforms and that you don't care about the exact same versions of all packages in the entire dependency tree. If you are trying to install...
2
2016-09-02T19:41:37Z
[ "python", "cross-platform", "conda" ]
Connect and handle multiple raw sockets at once in Python 2.x
39,280,687
<p>I am new to Python, and trying to learn it "on the job". And I am required to do this.</p> <p>I am required to communicate with 3 servers with a raw socket connection. I can easily do that in a sequential manner. But I was wondering if there is a way I can communicate with these 3 servers at once? All 3 servers hav...
1
2016-09-01T20:53:54Z
39,280,725
<p>If you only have one listening thread, you can use select to wait on multiple sockets and get woken when any of them return data:</p> <p><a href="https://docs.python.org/2/library/select.html" rel="nofollow">https://docs.python.org/2/library/select.html</a></p>
1
2016-09-01T20:56:09Z
[ "python", "multithreading", "sockets", "multiprocessing", "raw-sockets" ]
Connect and handle multiple raw sockets at once in Python 2.x
39,280,687
<p>I am new to Python, and trying to learn it "on the job". And I am required to do this.</p> <p>I am required to communicate with 3 servers with a raw socket connection. I can easily do that in a sequential manner. But I was wondering if there is a way I can communicate with these 3 servers at once? All 3 servers hav...
1
2016-09-01T20:53:54Z
39,281,157
<p>It's hard to prescribe a wealth of knowledge without knowing more information about your server protocol, what you are listening for and what you intend to do with it, et-c, but I can imagine, given no other additional information, a scenario where the communication is handled by a multiprocessing.Pool(3) where each...
0
2016-09-01T21:30:36Z
[ "python", "multithreading", "sockets", "multiprocessing", "raw-sockets" ]
Connect and handle multiple raw sockets at once in Python 2.x
39,280,687
<p>I am new to Python, and trying to learn it "on the job". And I am required to do this.</p> <p>I am required to communicate with 3 servers with a raw socket connection. I can easily do that in a sequential manner. But I was wondering if there is a way I can communicate with these 3 servers at once? All 3 servers hav...
1
2016-09-01T20:53:54Z
39,281,226
<p>Have a look at the <a href="https://docs.python.org/3/library/asyncio.html" rel="nofollow">asyncio</a> module.</p> <p>It requires Python 3, but allows to write single-threaded applications with multiple execution contexts - kind of cooperative multihreading, where the context is switched only when the user says so....
0
2016-09-01T21:34:51Z
[ "python", "multithreading", "sockets", "multiprocessing", "raw-sockets" ]
Connect and handle multiple raw sockets at once in Python 2.x
39,280,687
<p>I am new to Python, and trying to learn it "on the job". And I am required to do this.</p> <p>I am required to communicate with 3 servers with a raw socket connection. I can easily do that in a sequential manner. But I was wondering if there is a way I can communicate with these 3 servers at once? All 3 servers hav...
1
2016-09-01T20:53:54Z
39,282,157
<p><a href="http://stackoverflow.com/questions/2957116/make-2-functions-run-at-the-same-time/2957131#2957131">This answer</a> using <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">threading</a> actually worked out for me. </p>
0
2016-09-01T23:13:06Z
[ "python", "multithreading", "sockets", "multiprocessing", "raw-sockets" ]
String Formatting Confusion
39,280,741
<p>O'Reilly's Learn Python Powerful Object Oriented Programming by Mark Lutz teaches different ways to format strings.</p> <p>This following code has me confused. I am interpreting 'ham' as filling the format place marker at index zero, and yet it still pops up at index one of the outputted string. Please help me unde...
0
2016-09-01T20:57:05Z
39,280,793
<p>The only thing you have to understand is that <code>{0}</code> refers to the first (zeroeth) <strong>unnamed</strong> argument sent to <code>format()</code>. We can see this to be the case by removing all unnamed references and trying to use a linear fill-in:</p> <pre><code>&gt;&gt;&gt; "{motto}".format("boom") Tra...
2
2016-09-01T20:59:59Z
[ "python", "string-formatting" ]
visualization of convolutional layer in keras model
39,280,813
<p>I created a model in Keras (I am a newbie) and somehow managed to train it nicely. It takes 300x300 images and try to classify them in two groups.</p> <pre><code># size of image in pixel img_rows, img_cols = 300, 300 # number of classes (here digits 1 to 10) nb_classes = 2 # number of convolutional filters to use n...
1
2016-09-01T21:01:24Z
39,385,599
<p>Keras makes it quite easy to get layers' weights and outputs. Have a look at <a href="https://keras.io/layers/about-keras-layers/" rel="nofollow">https://keras.io/layers/about-keras-layers/</a> or <a href="https://keras.io/getting-started/functional-api-guide/#the-concept-of-layer-node" rel="nofollow">https://keras....
0
2016-09-08T08:01:19Z
[ "python", "visualization", "keras" ]
visualization of convolutional layer in keras model
39,280,813
<p>I created a model in Keras (I am a newbie) and somehow managed to train it nicely. It takes 300x300 images and try to classify them in two groups.</p> <pre><code># size of image in pixel img_rows, img_cols = 300, 300 # number of classes (here digits 1 to 10) nb_classes = 2 # number of convolutional filters to use n...
1
2016-09-01T21:01:24Z
39,988,934
<p>In your Network, there are only 16 filters in the first convolution layer and then 16 in the next, so you have 32 Convolution filters. But you are running the for loop for 200. Try to change it to 16 or 32. I am running this code with TF backend and it is working for my small CNN. Also,change the image stitching co...
0
2016-10-12T00:56:59Z
[ "python", "visualization", "keras" ]
ImportError: No module named 'matplotlib'
39,280,899
<p>Brand new to Python (typically program in MSDN C#) and I'm trying to make use of the matplotlib to generate some graphics from .csv files</p> <p>I've downloaded &amp; installed Python as well as Anaconda onto my Windows 10 machine, the versions are Python 3.5.2 and Anaconda 4.1.1</p> <p>I open up the Python "notep...
0
2016-09-01T21:09:42Z
39,282,133
<p>You essentially have 2 versions of python on your system - the standard one you downloaded and the one that ships with Anaconda. When you are running code in the IDLE you are using the standard version (in <code>C:\Users\a.watts.ISAM-NA\AppData\Local\Programs\Python\Python35-32\python.exe</code>) where <code>matplot...
3
2016-09-01T23:09:16Z
[ "python", "matplotlib" ]
A way to pass c++ object to another object's method in cython
39,280,945
<p>I have two classes (let's assume the most simple ones, implementation is not important). My <code>defs.pxd</code> file (with cython defs) looks like this:</p> <pre><code>cdef extern from "A.hpp": cdef cppclass A: A() except + cdef extern from "B.hpp": cdef cppclass B: B() except + int func (A) </co...
1
2016-09-01T21:13:48Z
39,285,420
<pre><code>def func(self, A a): return # ... as before </code></pre> <p>You need to tell Cython that <code>a</code> is of type <code>A</code> (the type is checked when you call it). That way it knows about <code>a._this</code> and doesn't treat it as a Python attribute lookup. You can only access <code>cdef</code>...
1
2016-09-02T06:10:55Z
[ "python", "c++", "cython" ]
pandas equivalent of SELECT * FROM table WHERE column1=column2
39,280,953
<p>What is the pandas equivalent of 'SELECT * FROM table WHERE column1=column2'?</p> <p>You have a dataframe, two columns with values. You want all rows where the numbers in both columns are the same. What's the code for that?</p> <pre><code>dataframe: column1 column2 a b b a c c d d a ...
-1
2016-09-01T21:14:27Z
39,281,169
<p>In this case, you will use something from Pandas called Masking</p> <p>Basically, DataFrame[condition, on a column or the entire dataframe itself] returns a DataFrame where the condition is True.</p> <pre><code>import pandas as pd import numpy as np data = {'a':np.random.randint(0, 10, 100), 'b':np.random....
1
2016-09-01T21:31:23Z
[ "python", "pandas" ]
How to update Django Rest User attribute?
39,281,017
<p>I have this model:</p> <pre><code>class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') stuff = models.TextField(default='') User.profile = property(UserProfile) </code></pre> <p>With this serializer:</p> <pre><code>class UserProfileSerializer(UserSerializer): s...
1
2016-09-01T21:19:02Z
39,284,246
<p>if your update method is executing and you are getting instance.profile in the method. The Issue happens at </p> <pre><code>instance.profile.stuff = validated_data.get('stuff', instance.profile.stuff) instance.save() </code></pre> <p>you need to update the profile instance. </p> <pre><code>instance.profile.stuff ...
0
2016-09-02T04:18:44Z
[ "python", "django", "rest", "django-rest-framework" ]
pygobject add item to container within signal callback
39,281,102
<p>I'm working on a simple GUI application using PyGObject and GTK+ 3. In this case, I'm wanting to have a button which brings up a dialog box that when you click OK will add an item to a list. I have that part working but the final part that doesn't work is adding the item to the list. It appears that an item does ...
1
2016-09-01T21:25:09Z
39,281,322
<p>The widget added to the window needs to have its .show() method called before it'll appear.</p>
0
2016-09-01T21:42:49Z
[ "python", "gtk3", "gobject" ]
Solving matrix equation A B = C. with B(n* 1) and C(n *1)
39,281,149
<p>I am trying to solve a matrix equation such as <code>A.B = C</code>. The A is the unknown matrix and i must find it. I have <code>B(n*1)</code> and <code>C(n*1)</code>, so <code>A</code> must be <code>n*n</code>. </p> <p>I used the <code>BT* A.T =C.T</code> method (<code>numpy.linalg.solve(B.T, C.T)</code>). But i...
0
2016-09-01T21:30:06Z
39,281,212
<p>Here's a little example for you:</p> <pre><code>import numpy as np a = np.array([[1, 2], [3, 4]]) b = np.array([5, 6]) x = np.linalg.solve(a, b) print "A={0}".format(a) print "B={0}".format(b) print "x={0}".format(x) </code></pre> <p>For more information, please read the <a href="http://docs.scipy.org/doc/numpy/...
0
2016-09-01T21:34:05Z
[ "python", "matrix", "equation-solving" ]
Solving matrix equation A B = C. with B(n* 1) and C(n *1)
39,281,149
<p>I am trying to solve a matrix equation such as <code>A.B = C</code>. The A is the unknown matrix and i must find it. I have <code>B(n*1)</code> and <code>C(n*1)</code>, so <code>A</code> must be <code>n*n</code>. </p> <p>I used the <code>BT* A.T =C.T</code> method (<code>numpy.linalg.solve(B.T, C.T)</code>). But i...
0
2016-09-01T21:30:06Z
39,290,812
<p>If you're solving for the matrix, there is an infinite number of solutions (assuming that <code>B</code> is nonzero). Here's one of the possible solutions: </p> <p>Choose an nonzero element of <code>B</code>, <code>Bi</code>. Now construct a matrix <code>A</code> such that the <code>i</code>th column is <code>C / B...
1
2016-09-02T11:01:30Z
[ "python", "matrix", "equation-solving" ]
@method_decorator(csrf_exempt) NameError: name 'method_decorator' is not defined
39,281,162
<p>I was following the following guide (<a href="https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok" rel="nofollow">https://abhaykashyap.com/blog/post/tutorial-how-build-facebook-messenger-bot-using-django-ngrok</a>) on how to create a chatbot, until the part where I updated...
1
2016-09-01T21:30:53Z
39,281,283
<p>The tutorial you're reading leaves out a number of crucial imports, such as the one that provides <code>method_decorator</code>:</p> <pre><code>from django.utils.decorators import method_decorator </code></pre> <p>It may help to follow the "View code on github" link, which takes you to a <a href="https://github.co...
1
2016-09-01T21:39:36Z
[ "python", "django", "server", "bots", "method-declaration" ]
Flask: NameError: 'app' is not defined?
39,281,199
<p>My Flask application has been running fine for the last 24 hours, however I just took it offline to work on it and i'm trying to start it up again and i'm getting this error:</p> <pre><code>Traceback (most recent call last): File "runserver.py", line 1, in &lt;module&gt; from app import app File "/home/MY N...
0
2016-09-01T21:33:09Z
39,281,275
<p>In <code>app.py</code> you should remove the <code>from Views import *</code>. Instead in your <code>Views.py</code> you need to have <code>from app import app</code></p> <p>That will bring app into the views namespace and I believe that should work for you.</p>
1
2016-09-01T21:39:14Z
[ "python", "flask" ]
Python encode string to html
39,281,329
<p>How would one take a string and encode special characters to html?</p> <p>for example, if I have "test@test" how would I encode it so it becomes "test%40test"</p> <p>Is there an easy way of doing this instead of using replace to manually list every one I want to replace?</p>
0
2016-09-01T21:43:46Z
39,281,354
<p>Try <code>urlencode</code>function. Documentation here.</p> <p><a href="https://docs.python.org/2/library/urllib.html#urllib.urlencode" rel="nofollow">https://docs.python.org/2/library/urllib.html#urllib.urlencode</a></p>
1
2016-09-01T21:45:41Z
[ "python", "html", "string", "encode" ]
Facebook "Not Delivering Not Approved" Ad Sets via Python SDK
39,281,371
<p>Having a little trouble here with filtering ad sets via the Facebook Ads Python SDK.</p> <p>I'm making the following call (the variable account is an instance of <a href="https://github.com/facebook/facebook-python-ads-sdk/blob/f02c6d5a5a3b211751f4eb3975cd3659cf001f17/facebookads/adobjects/adset.py" rel="nofollow"...
0
2016-09-01T21:47:42Z
39,353,835
<p>Ad Sets aren't approved or disapproved, Ads are.</p> <p>I'm not 100% sure what you're seeing in the Power Editor UI, but I suspect it's showing 'Not Delivering, Not Approved' via detecting that all of the Ads in that Ad Set are DISAPPROVED</p> <p>In your case, you should filter on the Ads' status by fetching at th...
0
2016-09-06T16:32:10Z
[ "python", "facebook-graph-api", "facebook-ads-api" ]
Concatenating strings from two different for loops at each turn
39,281,402
<p>I have two different <code>for</code> loops that run the same number of times and produce a string at each iteration. (I am scraping an html file) I want the string from first loop to merge/concatenate/append with the string from the second loop FOR EACH ITERATION ( this is the tricky part )Here is the code i have:<...
0
2016-09-01T21:50:27Z
39,281,525
<p>There are a lots of ways to do what you're asking for, here's a very simple one:</p> <pre><code>tableList = [ ["a", "b"], ["1", "2"], ["father", "mother"] ] tdList = [ ["c", "d", "e"], ["3", "4", "5"], ["son", "daughter", "twin"] ] len_list = max(len(tableList), len(tdList)) for i in rang...
0
2016-09-01T22:00:34Z
[ "python", "string", "python-2.7", "loops", "concatenation" ]
Concatenating strings from two different for loops at each turn
39,281,402
<p>I have two different <code>for</code> loops that run the same number of times and produce a string at each iteration. (I am scraping an html file) I want the string from first loop to merge/concatenate/append with the string from the second loop FOR EACH ITERATION ( this is the tricky part )Here is the code i have:<...
0
2016-09-01T21:50:27Z
39,281,539
<p>Use <code>zip</code>, and also use <code>join</code> instead of concatenating commas:</p> <pre><code>for table,td in zip(tableList,tdList): a = ', '.join(table.find_all("span", {"class":"results_body_text"})) b = ', '.join(td.find_all("span", {"class":"results_body_text"})) print(a, b, sep=', ') </code>...
0
2016-09-01T22:01:54Z
[ "python", "string", "python-2.7", "loops", "concatenation" ]
Converting Integer programming to binary in python
39,281,434
<p><a href="http://i.stack.imgur.com/TpuQy.png" rel="nofollow"><img src="http://i.stack.imgur.com/TpuQy.png" alt="Excel Image"></a></p> <p>See the image above to understand my explanation of the problem.</p> <pre><code>from scipy.optimize import linprog a = [-800,-1200,-800] b = [[200,100,400],[200,200,400],[200,30...
0
2016-09-01T21:53:00Z
39,282,781
<p>First of all: <strong>your question was very very badly phrased</strong> (and your usage of linprog is not common; <code>Variable A</code> is typically the 2d-one).</p> <p>Usually i'm hesitant to work on these kind of questions (=very incomplete), but i think i got the problem now.</p> <h2>What's the big problem w...
1
2016-09-02T00:43:17Z
[ "python", "binary", "integer", "linear-programming" ]
SWIG with Eigen3::Vector3d and std::vector<Vector3d>
39,281,461
<p>The corresponding gist is <a href="https://gist.github.com/nschloe/5e213272671db5dd745508093f37a4a1" rel="nofollow">here</a>.</p> <hr> <p>I'd like to use SWIG to call a bunch of C++ function from Python, specifically functions that accept vectors. So far, I've implemented it all with <code>std_vector.i</code> and ...
0
2016-09-01T21:55:08Z
39,451,545
<p>There are a few examples of wrapping Eigen types with NumPy floating around on the web, where the <a href="https://github.com/Biomechanical-ToolKit/BTKCore/blob/master/Utilities/SWIG/eigen.i" rel="nofollow">Biomechanical Toolkit</a> implementation is the most widely copied, and I would recommend using that one too. ...
1
2016-09-12T13:31:23Z
[ "python", "c++", "swig", "eigen", "eigen3" ]
Unable to bundle app with libusb1 in PyInstaller
39,281,554
<p>I'm running Python 2.7.12 with a simple python file and importing a couple of modules (PyQt5 and usb1). No additional assets or files. </p> <p>When I try to bundle the app, with a default spec file, the app works fine on my host machine. But trying to run it on another machine (with Python 2.7.10) fails with this e...
0
2016-09-01T22:02:48Z
39,283,667
<p>OK, finally solved it! I manually copied the libusb-1.0.0.dylib from /usr/local/Cellar/libusb/1.0.20/lib/ and pasted/overwrote the one in the distributed folder. Then created a symlink in the folder as libusb-1.0.dylib and that seemed to do it. Hope this helps someone!</p>
0
2016-09-02T02:58:49Z
[ "python", "pyinstaller", "libusb-1.0" ]
efficient function to find harmonic mean across different pandas dataframes
39,281,575
<p>I have several dataframes with identical shape/types, but slightly different numeric values. I can easily produce a new dataframe with the mean of all input dataframes via:</p> <pre><code>df = pd.concat([input_dataframes]) df = df.groupby(df.index).mean() </code></pre> <p>I want to do the same with harmonic mean ...
2
2016-09-01T22:04:36Z
39,281,843
<p>Create a pandas Panel, and apply the harmonic mean function over the 'item' axis.</p> <p>Example with your dataframes <code>df1</code> and <code>df2</code>:</p> <pre><code>import pandas as pd from scipy import stats d = {'1':df1,'2':df2} pan = pd.Panel(d) pan.apply(axis='items',func=stats.hmean) </code></pre> <p...
3
2016-09-01T22:32:56Z
[ "python", "pandas", "scipy" ]
Check if a number is a perfect power of another number
39,281,632
<p>For example, 243 is a perfect power of 3 because 243=3^5.</p> <p>I've previously been using <code>(math.log(a) / math.log(b)).is_integer()</code>, which I thought worked fine, but then I tried it with the example above and it actually returns 4.999999999999999 due to floating point arithmetic. So it's only reliable...
2
2016-09-01T22:10:23Z
39,281,679
<p>Try:</p> <pre><code>b ** int(round(math.log(a, b))) == a </code></pre> <p>That is, only use <code>log()</code> (note there is a 2-argument form!) to get a guess at an integer power, then verify whether "that works".</p> <p>Note that <code>math.log()</code> returns a sensible result even for integer arguments much...
3
2016-09-01T22:14:45Z
[ "python", "math" ]
Check if a number is a perfect power of another number
39,281,632
<p>For example, 243 is a perfect power of 3 because 243=3^5.</p> <p>I've previously been using <code>(math.log(a) / math.log(b)).is_integer()</code>, which I thought worked fine, but then I tried it with the example above and it actually returns 4.999999999999999 due to floating point arithmetic. So it's only reliable...
2
2016-09-01T22:10:23Z
39,281,767
<p>maybe something like:</p> <pre><code>def is_perfect_power(a, b): while a % b == 0: a = a / b if a == 1: return True return False print is_perfect_power(8,2) </code></pre>
1
2016-09-01T22:24:08Z
[ "python", "math" ]
Check if a number is a perfect power of another number
39,281,632
<p>For example, 243 is a perfect power of 3 because 243=3^5.</p> <p>I've previously been using <code>(math.log(a) / math.log(b)).is_integer()</code>, which I thought worked fine, but then I tried it with the example above and it actually returns 4.999999999999999 due to floating point arithmetic. So it's only reliable...
2
2016-09-01T22:10:23Z
39,281,928
<p>If both the base and exponent are wildcards here and you are starting with only the "big number" result, then you're going to face a speed-memory trade-off. Since you seem to have implied that nested loops would be "inefficient", I assume that CPU cycle efficiency is important to you. In this case, may I suggest pre...
0
2016-09-01T22:43:13Z
[ "python", "math" ]
Check if a number is a perfect power of another number
39,281,632
<p>For example, 243 is a perfect power of 3 because 243=3^5.</p> <p>I've previously been using <code>(math.log(a) / math.log(b)).is_integer()</code>, which I thought worked fine, but then I tried it with the example above and it actually returns 4.999999999999999 due to floating point arithmetic. So it's only reliable...
2
2016-09-01T22:10:23Z
39,282,125
<p>If you will be working with large numbers, you may want to look at <a href="https://pypi.python.org/pypi/gmpy2" rel="nofollow">gmpy2</a>. <code>gmpy2</code> provides access to the GMP multiple-precision library. One of the functions provided is <code>is_power()</code>. It will return True if the argument is a perfec...
1
2016-09-01T23:08:15Z
[ "python", "math" ]
Check if a number is a perfect power of another number
39,281,632
<p>For example, 243 is a perfect power of 3 because 243=3^5.</p> <p>I've previously been using <code>(math.log(a) / math.log(b)).is_integer()</code>, which I thought worked fine, but then I tried it with the example above and it actually returns 4.999999999999999 due to floating point arithmetic. So it's only reliable...
2
2016-09-01T22:10:23Z
39,286,024
<p>If you want a speed up over repeated division for large numbers, you can make a list of all the exponents of the base where the exponent is a power of 2, and test those only.</p> <p>For example, take 3<sup>9</sup>. 9 is 101 in binary, which is 2<sup>3</sup> + 2<sup>1</sup> = 8 + 1.</p> <p>So 3<sup>9</sup> = 3<sup>...
0
2016-09-02T06:51:46Z
[ "python", "math" ]
ROS2: ImportError: No module named genmsg
39,281,644
<p>I starting with <em>ROS2</em> which is currently in the alpha phase. While building the package <code>ros1_bridge</code> I got this error:</p> <pre><code>Traceback (most recent call last): File "bin/ros1_bridge_generate_factories", line 11, in &lt;module&gt; from ros1_bridge import generate_cpp File "/home/...
2
2016-09-01T22:11:31Z
39,282,311
<p>This happens while dependencies installed for <em>ROS</em> and <em>ROS2</em> on the same machine. Especially the package <code>python-genmsg</code> and <code>ros-kinetic-genmsg</code>. <code>genmsg</code> can now found at these places:</p> <ol> <li>/opt/ros/kinetic/lib/python2.7/dist-packages</li> <li>/usr/lib/pyth...
2
2016-09-01T23:33:31Z
[ "python", "ros" ]
Contrary of .join() pyspark
39,281,687
<p><code>join</code> returns an RDD containing all pairs of elements with matching keys.</p> <p><a href="https://spark.apache.org/docs/1.6.2/api/python/pyspark.html#pyspark.RDD.join" rel="nofollow">https://spark.apache.org/docs/1.6.2/api/python/pyspark.html#pyspark.RDD.join</a></p> <p>Example:</p> <pre><code> trueDu...
2
2016-09-01T22:15:37Z
39,281,736
<p>Use <code>subtractByKey</code>:</p> <blockquote> <p>Return each (key, value) pair in C{self} that has no pair with matching key in C{other}.</p> </blockquote> <pre><code>rdd1.subtractByKey(rdd2) </code></pre>
5
2016-09-01T22:20:40Z
[ "python", "apache-spark", "pyspark" ]
Running DFS on large graph
39,281,720
<p>I am trying to find Strongly Connected Components in a large graph implementing Kosaraju's algorithm. It requires running a DFS on a graph in reverse, and then forward. If you're interested the list of edges for this graph are here: <a href="https://dl.dropboxusercontent.com/u/28024296/SCC.txt.tar.gz" rel="nofollow"...
4
2016-09-01T22:19:19Z
39,282,185
<p>Kosaraju's algorithm probably requires that checking whether an element has been seen is an O(1) operation. But your seen data structure has O(n) time membership testing. Converting <code>seen</code> from a list to a set makes the code execute in a few seconds on my system (after also removing the prints which took ...
1
2016-09-01T23:16:26Z
[ "python", "graph", "graph-algorithm" ]
Python string.replace is stripping off my quote characters
39,281,782
<p>What I'm doing is feeding my python script a CSV file which contains millions of records separated by commas. Any strings are "contained by double qoutes".</p> <p>I pass this .csv file through my python script</p> <pre><code>import csv import string import sys, getopt inFile = open(sys.argv[1], 'r') outFile = ope...
0
2016-09-01T22:25:29Z
39,281,886
<p>This is normal. When reading, <code>csv.reader</code> will strip off the quotes because it's assumed that the program consuming the data doesn't want or need them. <code>csv.writer</code> will then put them back on if necessary, depending on the setting of <a href="https://docs.python.org/3/library/csv.html#csv.Dial...
1
2016-09-01T22:38:17Z
[ "python", "string", "csv", "replace" ]
Openstack Python SDK - Glance does not return image MD5
39,281,790
<p>I'm trying to download an OpenStack image from glance using only the Openstack Python SDK, but I only get this error:</p> <pre><code>Traceback (most recent call last): File "/home/openstack/discovery/discovery.py", line 222, in &lt;module&gt; main(sys.argv[1:]) File "/home/openstack/discovery/discovery.py",...
0
2016-09-01T22:26:30Z
39,457,662
<p>Turns out this was indeed a bug SDK/Glance. More details about it can be found here: <a href="https://bugs.launchpad.net/python-openstacksdk/+bug/1619675" rel="nofollow">https://bugs.launchpad.net/python-openstacksdk/+bug/1619675</a></p> <p>And the fix implemented can be seen here: <a href="https://github.com/opens...
0
2016-09-12T19:42:51Z
[ "python", "openstack", "openstack-glance", "openstack-api" ]
How do I send a JavaScript confirm response over Django to a script to perform operations based on the response?
39,281,884
<p>I'm very very new to Django and I'm currently trying to build a simple To-Do application. I'm currently able to display my To-Do list on the webpage using HTML Tables, but to be able to delete it, I added a new row at the end of every entry called <code>"Delete"</code> with an a <code>href element, on click event</c...
1
2016-09-01T22:38:00Z
39,282,726
<p>I don't think that this would be a good way to solve the problem, </p> <p>try to do this:</p> <p>in your template.html:</p> <pre><code>&lt;form method="POST" action=""&gt; {% csrf_token %} &lt;input type="submit" name="delete_amount" onclick="delete_me(event)" /&gt; &lt;/form&gt; </code></pre> <p>in your...
0
2016-09-02T00:36:28Z
[ "javascript", "python", "django", "post", "get" ]
Changing text font and colour
39,281,903
<p>Whether it's a module or something I can define in my code, is there a way to change the output text like making it <em>italic</em> or <strong>BOLD</strong>? Also, are colours a thing?</p>
0
2016-09-01T22:39:49Z
39,282,055
<p>Taking the question @LukeK posted, you can use <a href="https://en.wikipedia.org/wiki/ANSI_escape_code?wprov=sfla1" rel="nofollow">ANSI escape sequences</a> anywhere in your strings:</p> <pre><code>print("Roses are \033[31mred\033[0m") # Will make red... red </code></pre> <p>You can combine them in that way (I hop...
0
2016-09-01T22:59:48Z
[ "python" ]
access/update global/shared defaultdict from different tornado.RequestHandler instances
39,281,912
<p>Is it safe to access/update a global <code>defaultdict</code> from different <code>RequestHandler</code> instances? E.g.</p> <pre><code>GlobalMap = defaultdict(list) class Event(tornado.web.RequestHandler): def get(self, unit): # This is where the access/modify might happen # The list.append() ...
0
2016-09-01T22:41:26Z
39,282,083
<p>Yes, that's fine to do. Tornado code typically runs in the main thread; any code that accesses a Python data structure like this.</p> <p>However, if you're deploying a Tornado application in production you'll want multiple Tornado processes, maybe running on multiple machines, so you'll want to put data in a shared...
1
2016-09-01T23:03:02Z
[ "python", "python-3.x", "tornado", "defaultdict" ]
access/update global/shared defaultdict from different tornado.RequestHandler instances
39,281,912
<p>Is it safe to access/update a global <code>defaultdict</code> from different <code>RequestHandler</code> instances? E.g.</p> <pre><code>GlobalMap = defaultdict(list) class Event(tornado.web.RequestHandler): def get(self, unit): # This is where the access/modify might happen # The list.append() ...
0
2016-09-01T22:41:26Z
39,297,942
<p>In an async/threaded/multiprocess app, accessing global variables are as safe as you make them. As in, it's never really a good idea to have shared states. But for the most part it's fairly safe to access values from a global <code>dict</code> especially in an a single threaded async app.</p> <p>On the other hand, ...
1
2016-09-02T17:32:31Z
[ "python", "python-3.x", "tornado", "defaultdict" ]
Remove columns where all items in column are identical (excluding header) and match a specified string
39,281,956
<p>My question is an extension of <a href="http://stackoverflow.com/questions/21164910/delete-column-in-pandas-based-on-condition">Delete Column in Pandas based on Condition</a>, but I have headers and the information isn't binary. Instead of removing a column containing all zeros, I'd like to be able to pass a variabl...
0
2016-09-01T22:47:25Z
39,282,009
<p>You can check the number of <code>non-red</code> item in the column, if it is not zero then select it using <code>loc</code>:</p> <pre><code>df.loc[:, (df != 'red').sum() != 0] # Name Header2 Header3 # 0 name1 red red # 1 name2 orange red # 2 name3 yellow red # 3 name4 gree...
1
2016-09-01T22:53:10Z
[ "python", "pandas" ]
Keeping code DRY when repeatedly referring to command-line options' configuration
39,282,047
<p>I just got a Raspberry Pi, and I'm building a Reddit API-based application for it, using the <a href="http://praw.readthedocs.io/en/stable/" rel="nofollow">PRAW</a> library. I'm executing my python files by using:</p> <pre class="lang-sh prettyprint-override"><code>sudo python3 main.py </code></pre> <p>However, I ...
0
2016-09-01T22:58:44Z
39,282,153
<p>Define your own custom "print" method, which checks if some variable (silent) is set, and then skips printing it if that value is set. So all your lines print('value') will turn into something like myprint('value'). I personally like using the function names verbose() and debug() and having two log levels. In you...
1
2016-09-01T23:12:21Z
[ "python", "methods", "arguments", "line", "code-duplication" ]
Confused about passing by reference in this Python function
39,282,051
<p>I have this simple Python 2.7 function:</p> <pre><code>def sort_rows(mat): mat = [sorted(i) for i in mat] </code></pre> <p>However, when I run: </p> <pre><code>M = [[4, 5, 2, 8], [3, 9, 6, 7]] sort_rows(M) print(M) </code></pre> <p>I get</p> <pre><code>[[4, 5, 2, 8], [3, 9, 6, 7]] </code></pre> <p>Why was...
-1
2016-09-01T22:59:26Z
39,282,105
<p>The reason is that the <code>sorted</code> function doesn't sort the list in place, if you want it be sorted in place, you can use <code>list.sort()</code> method:</p> <pre><code>def sort_rows(mat): [i.sort() for i in mat] M = [[4, 5, 2, 8], [3, 9, 6, 7]] sort_rows(M) print(M) # [[2, 4, 5, 8], [3, 6, 7, 9]] ...
0
2016-09-01T23:05:37Z
[ "python", "python-2.7" ]
Confused about passing by reference in this Python function
39,282,051
<p>I have this simple Python 2.7 function:</p> <pre><code>def sort_rows(mat): mat = [sorted(i) for i in mat] </code></pre> <p>However, when I run: </p> <pre><code>M = [[4, 5, 2, 8], [3, 9, 6, 7]] sort_rows(M) print(M) </code></pre> <p>I get</p> <pre><code>[[4, 5, 2, 8], [3, 9, 6, 7]] </code></pre> <p>Why was...
-1
2016-09-01T22:59:26Z
39,282,114
<p>When your <code>sort_rows</code> is called <code>mat</code> points to the same list that <code>M</code> points to. This statement, however, changes that:</p> <pre><code>mat = [sorted(i) for i in mat] </code></pre> <p>After the above is executed, <code>mat</code> now points to a different list. <code>M</code> is ...
2
2016-09-01T23:06:26Z
[ "python", "python-2.7" ]
Confused about passing by reference in this Python function
39,282,051
<p>I have this simple Python 2.7 function:</p> <pre><code>def sort_rows(mat): mat = [sorted(i) for i in mat] </code></pre> <p>However, when I run: </p> <pre><code>M = [[4, 5, 2, 8], [3, 9, 6, 7]] sort_rows(M) print(M) </code></pre> <p>I get</p> <pre><code>[[4, 5, 2, 8], [3, 9, 6, 7]] </code></pre> <p>Why was...
-1
2016-09-01T22:59:26Z
39,282,190
<p>You could use the return function to return the variable mat at the end of sort row.</p> <pre><code>return M </code></pre> <p>Then if you try- </p> <pre><code>print(sort_rows(M)) </code></pre> <p>you should get the result you want. Thanks.</p>
0
2016-09-01T23:17:05Z
[ "python", "python-2.7" ]
Confused about passing by reference in this Python function
39,282,051
<p>I have this simple Python 2.7 function:</p> <pre><code>def sort_rows(mat): mat = [sorted(i) for i in mat] </code></pre> <p>However, when I run: </p> <pre><code>M = [[4, 5, 2, 8], [3, 9, 6, 7]] sort_rows(M) print(M) </code></pre> <p>I get</p> <pre><code>[[4, 5, 2, 8], [3, 9, 6, 7]] </code></pre> <p>Why was...
-1
2016-09-01T22:59:26Z
39,282,242
<p>You could use the return function to return the variable mat at the end of sort row.</p> <p>return M</p> <p>Then if you try </p> <p>print(sort_rows(M))</p> <p>you should get the result you want.</p> <p>I mean return mat I apologize</p>
0
2016-09-01T23:22:35Z
[ "python", "python-2.7" ]
Nonlinear regression on tensorflow
39,282,060
<p>What activation and cost functions on <code>tensorflow</code> could be suitable below for <strong>tf.nn</strong> to <strong>learn</strong> a simple single variate nonlinear relationship <code>f(x) = x * x</code> that is a priori unknown? </p> <p>Certainly, this impractical model is used for the sole purpose of unde...
0
2016-09-01T23:00:02Z
39,293,770
<p>The COST that is often used is simply the squared difference:</p> <pre><code>def squared_error(y1,y2): return tf.square(y1-y2) </code></pre> <p>Plus an L1 or L2 penalty if you feel like it. </p> <p>However it seems to me that you need a hidden layer in your neural network if you want something remotely interes...
0
2016-09-02T13:34:45Z
[ "python", "machine-learning", "neural-network", "tensorflow", "non-linear-regression" ]
groupby apply Pandas not yielding desired output
39,282,070
<p>Below is a small sample of my dataframe : I am trying a groupby.apply which is not giving me the desired result.</p> <pre><code> In [204]: df1 Out[204]: Location_ID Terminal Time 0 10000001405702 *WhF 2016-07-01 13:56:00 1 10000001405702 @W1n 2016-07-01 09:14:39 2 ...
0
2016-09-01T23:01:21Z
39,282,139
<p>The result of your operation is a pandas Series. If you want it to be a column in a Dataframe you need to assign it to one.</p> <p>Make <code>df3</code> as a copy of <code>df1</code> and change your call to:</p> <pre><code>df3['Time'] = df1.groupby(['Location_ID','Terminal'])['Time'].apply(lambda x : x.diff()&lt;=...
0
2016-09-01T23:10:53Z
[ "python", "pandas" ]
Advance filtering with list of elements using django tastypie
39,282,094
<p>I am using <a href="https://pypi.python.org/pypi/django-multiselectfield" rel="nofollow">MultiSelectField</a> to select multiple choices within my django admin it creates an array for fields in the backend of all the choices I select. I then use <code>django tastypie's</code> List Field to make sure its a list of el...
0
2016-09-01T23:03:59Z
39,289,015
<p><code>filters['q']</code> is a <code>athletic,bohemian</code> string. <code>__in</code> lookup need a list or tuple.</p> <pre><code>query = filters['q'].split(',') </code></pre>
0
2016-09-02T09:29:37Z
[ "python", "django", "tastypie" ]
python regex to split list entry's name into list name and index
39,282,120
<p>How can I use regular expressions to parse <code>&lt;listname&gt;[#]</code> into <code>[listname, #]</code>?</p> <p>Here's what I've tried:</p> <pre><code>&gt; s = 'li[10]' &gt; re.split(s,r'[%d]') ['[%d]'] &gt; re.findall(s,r'[%d]') [] &gt; s.split(r'[%d]') ['li[0]'] </code></pre> <p>the desired output is <code>...
1
2016-09-01T23:07:06Z
39,282,149
<p>First, you should put your pattern as the first part of the <code>findall</code> command as <code>findall( pattern, string)</code>. You pattern is only matching a single digit ie: <code>0</code> through <code>9</code>. To match more than 1 digit you can use:</p> <pre><code> re.findall(r'\[(\d+)\]', s) </code></pr...
1
2016-09-01T23:12:11Z
[ "python", "regex" ]
python regex to split list entry's name into list name and index
39,282,120
<p>How can I use regular expressions to parse <code>&lt;listname&gt;[#]</code> into <code>[listname, #]</code>?</p> <p>Here's what I've tried:</p> <pre><code>&gt; s = 'li[10]' &gt; re.split(s,r'[%d]') ['[%d]'] &gt; re.findall(s,r'[%d]') [] &gt; s.split(r'[%d]') ['li[0]'] </code></pre> <p>the desired output is <code>...
1
2016-09-01T23:07:06Z
39,282,150
<p>How about <code>(.*)\[(.*)\]</code>?</p> <pre><code>re.findall("(.*)\[(.*)\]", s) # [('li', '10')] </code></pre>
1
2016-09-01T23:12:14Z
[ "python", "regex" ]
python regex to split list entry's name into list name and index
39,282,120
<p>How can I use regular expressions to parse <code>&lt;listname&gt;[#]</code> into <code>[listname, #]</code>?</p> <p>Here's what I've tried:</p> <pre><code>&gt; s = 'li[10]' &gt; re.split(s,r'[%d]') ['[%d]'] &gt; re.findall(s,r'[%d]') [] &gt; s.split(r'[%d]') ['li[0]'] </code></pre> <p>the desired output is <code>...
1
2016-09-01T23:07:06Z
39,282,452
<p>I can also suggest a more restrictive pattern to use with <code>re.findall</code>:</p> <pre><code>re.findall(r'(\w+)\[(\d+)]', s) </code></pre> <p>See the <a href="http://ideone.com/a53Sh9" rel="nofollow">Python demo</a></p> <p>Or a variation with <code>zip</code>:</p> <pre><code>import re s = 'li[10] li[11]' na...
1
2016-09-01T23:52:58Z
[ "python", "regex" ]
Optimizing Bayer16 -> RGB in Python
39,282,179
<p>I am reading a camera that gives me Bayer16 format (GRGB) and I wrote the following code in python to modify it from bayer16 to bayer8, and then use OpenCV to convert it to RGB:</p> <pre><code>def _convert_GRGB_to_RGB(self, bayer16_image): bayer8_image = bytearray() # Convert bayer16 to bayer 8 for i in range...
0
2016-09-01T23:16:08Z
39,285,626
<p>Your can use standard python operators in your numpyified code, You'll also get a speedup by not slicing data_bytes (assuming it's <code>bytes</code> and not itself a numpy array)</p> <pre><code>def _convert_GRGB_to_RGB(self, data_bytes): data_bytes = numpy.frombuffer(data_bytes, dtype=numpy.uint8) even = d...
0
2016-09-02T06:27:13Z
[ "python", "image", "numpy" ]
Optimizing Bayer16 -> RGB in Python
39,282,179
<p>I am reading a camera that gives me Bayer16 format (GRGB) and I wrote the following code in python to modify it from bayer16 to bayer8, and then use OpenCV to convert it to RGB:</p> <pre><code>def _convert_GRGB_to_RGB(self, bayer16_image): bayer8_image = bytearray() # Convert bayer16 to bayer 8 for i in range...
0
2016-09-01T23:16:08Z
39,288,483
<p>As a guess, your color problem is as follows - your <code>GRBG</code> data comes in like this:</p> <pre><code>G0 B1 G2 ... R0 G1 R2 </code></pre> <p>Where the numbers represent the uint16 index. OpenCV needs them to be numbered</p> <pre><code>G0 B0 G1 R1 ... R6 G6 R7 G7 </code></pre> <p>You can fix this with som...
0
2016-09-02T09:05:52Z
[ "python", "image", "numpy" ]
Threading of Periodic Update to Class Member
39,282,197
<p>What is a method for updating a class member in Python while it is still being used by other methods in the class?</p> <p>I want the rest of the class to continue processing using the old version of the member until it is fully updated and then switch all processing to the new version once the update is complete.</...
1
2016-09-01T23:17:29Z
39,282,364
<p>Create a lock to control access to your list:</p> <pre><code>import threading def __init__(self, ...): # We could use Lock, but RLock is somewhat more intuitive in a few ways that might # matter when your requirements change or when you need to debug things. self.numberLock = threading.RLock() ... ...
1
2016-09-01T23:41:38Z
[ "python", "multithreading" ]
Threading of Periodic Update to Class Member
39,282,197
<p>What is a method for updating a class member in Python while it is still being used by other methods in the class?</p> <p>I want the rest of the class to continue processing using the old version of the member until it is fully updated and then switch all processing to the new version once the update is complete.</...
1
2016-09-01T23:17:29Z
39,283,514
<p>You could create a new thread for every call to <code>updateNumbers</code> but the more common way to do this type of thing is to have 1 thread running an infinite loop in the background. You should write a method or function with that infinite loop, and that method/function will serve as the target for your backgro...
1
2016-09-02T02:35:41Z
[ "python", "multithreading" ]
Joining an aliased selectable in Sqlalchemy Core
39,282,201
<p>I am attempting to make a left join on two tables: invoices and vendors. The typical problem is that I have multiple entries in the right table (vendors) which leads to duplicate results:</p> <pre><code> Vendors Invoices vend_id name vend_id line_amt 001 Lowes 001 5...
0
2016-09-01T23:18:10Z
39,298,116
<p>First joining the invoices table to the aliased table will work. I needed to use <code>.select_from</code> in order to complete the join. This is the code that works:</p> <pre> conn = engine.connect() a = select([vendors.c.vend_id.label('vend_id'), func.min(vendors.c.name).label('name')]).group_by(vendo...
0
2016-09-02T17:45:20Z
[ "python", "join", "sqlalchemy", "core" ]
Simplest solution to use Python to drive an Applescript script
39,282,231
<p>Since Apple has already integrated a full UI automation tool like Applescript (ancient, yes...ugly, yes; but can't find anything better), I was wondering if I can run a Applescript script, inside Python unit test class.</p> <p>I did find an abandoned project that was integrating AS and Python, but I would like to u...
0
2016-09-01T23:21:09Z
39,302,610
<p><a href="https://pypi.python.org/pypi/py-applescript" rel="nofollow">py-applescript</a> provides an easy-to-use wrapper around PyObjC and <code>NSAppleScript</code> for calling AS handlers and converting Python arguments and results to and from their AS equivalents automatically. (Strictly speaking I no longer suppo...
0
2016-09-03T02:07:53Z
[ "python", "applescript" ]
dictionary comprehension derived from existing lists
39,282,241
<p>as a part of a bigger exercise, I am trying to construct a dictionary based on inputs from smaller lists, but am struggling with an embedded iteration. suppose i have the following illustrative example:</p> <pre><code>cities = ['newyork','london','tokyo','paris'] citypairs = [i for i in it.combinations(cities,2)] a...
0
2016-09-01T23:22:25Z
39,282,490
<p>My belief is that the solution is simpler than you're making it:</p> <pre><code>from itertools import combinations cities = ['newyork','london','tokyo','paris'] citypairs = combinations(cities, 2) airlines = ['delta', 'united'] info = {'{city1}/{city2} {airline}'.format(city1=city1, city2=city2, airline=airline):...
1
2016-09-01T23:57:19Z
[ "python", "list", "python-2.7", "dictionary" ]
dictionary comprehension derived from existing lists
39,282,241
<p>as a part of a bigger exercise, I am trying to construct a dictionary based on inputs from smaller lists, but am struggling with an embedded iteration. suppose i have the following illustrative example:</p> <pre><code>cities = ['newyork','london','tokyo','paris'] citypairs = [i for i in it.combinations(cities,2)] a...
0
2016-09-01T23:22:25Z
39,282,505
<pre class="lang-py prettyprint-override"><code>info = { '{city1}/{city2} {airline}'.format(**vars()) : { "city1": city1, "city2": city2 } for city1, city2 in citypairs for airline in airlines } </code></pre> <p>yields:</p> <pre><code>{'london/paris delta': {'city1': 'london', 'city2': 'paris'}, 'lo...
1
2016-09-01T23:59:06Z
[ "python", "list", "python-2.7", "dictionary" ]
Couldn't import Django error when I try to startapp
39,282,309
<p>I usually work on PC's but started to work on projects on my mac. I run Python 3 and when I started a new project I did the following:</p> <p>1) In main project folder, installed virtualenv and activated it.</p> <p>2) Install Django and Gunicorn</p> <p>3) Did startproject</p> <p>When I try to python3 manage.py s...
0
2016-09-01T23:33:07Z
39,943,854
<p>I had the same problem, make sure you activated virtualenv, since once you close cmd it is no longer activated:</p> <p><code>env\Scripts\activate</code> in cmd</p> <p>Now cmd should have (env) just like this: <code>(env) c:\users\user\PROJECT\..</code></p> <p>Now you can type: <code>python manage.py runserver</co...
0
2016-10-09T12:54:38Z
[ "python", "django", "python-3.x" ]
Formating Django TimeField in a Django view
39,282,352
<p>How do you format a TimeField in a Django view?</p> <p>Currently in my django html template I can easily do something like: <code>{{movie.start_time|time:"g:iA"|lower}}</code></p> <p>How can I do the equivalent of the above in a Django view?</p>
1
2016-09-01T23:39:49Z
39,282,424
<p>Use the Python <code>strftime()</code> function. <a href="https://docs.python.org/2/library/time.html#time.strftime" rel="nofollow">https://docs.python.org/2/library/time.html#time.strftime</a></p>
2
2016-09-01T23:49:36Z
[ "python", "django" ]
Formating Django TimeField in a Django view
39,282,352
<p>How do you format a TimeField in a Django view?</p> <p>Currently in my django html template I can easily do something like: <code>{{movie.start_time|time:"g:iA"|lower}}</code></p> <p>How can I do the equivalent of the above in a Django view?</p>
1
2016-09-01T23:39:49Z
39,299,659
<p>Below is an example of how to achieve this. It isn't ideal, but this is what I came up with.</p> <pre><code>import datetime now = datetime.datetime.now() time = now.time() t = time.strftime("%I:%M %p") t = t.lower() t = list(t) if t[0] == '0': t.pop(0) t = ''.join(t) print t </code></pre>
0
2016-09-02T19:40:33Z
[ "python", "django" ]
Pandas Group to Divide by Max
39,282,355
<p>I'm trying to normalize a user count by dividing by the max users in each group. I'm able to get the results to calculate (commented out the print that works), but I'm having trouble getting the results to save back to the original table. The code below doesn't throw an error, but it also doesn't add any data to wee...
1
2016-09-01T23:40:16Z
39,282,362
<p>Use <code>groupby</code> and <code>transform</code></p> <pre><code>weeklyPerson.groupby('Person').users.transform(lambda x: x / x.max()) </code></pre> <p>Per @Jeff's suggestion</p> <pre><code>weeklyPerson.users / weeklyPerson.groupby('Person').users.transform(np.max) </code></pre> <p>This avoids using <code>lamb...
1
2016-09-01T23:41:24Z
[ "python", "pandas" ]
How to instal polyglot on mac?
39,282,400
<p>When following the <a href="http://polyglot.readthedocs.io/en/latest/Installation.html" rel="nofollow">instructions</a> I get the following error message:</p> <pre><code>Failed building wheel for PyICU </code></pre> <p>One of the dependencies is missing. However the module <code>PyICU</code> cannot be installed wi...
0
2016-09-01T23:46:32Z
39,282,401
<p>You can use <code>icu4c</code> instead of <code>PyICU</code>.</p> <p>Follow these steps: <a href="http://stackoverflow.com/a/33352241/1053612">http://stackoverflow.com/a/33352241/1053612</a> (May require installing python between steps 1 and 2, i.e. <code>brew install python</code>).</p>
0
2016-09-01T23:46:32Z
[ "python" ]
Confused about looping through list of people in Python
39,282,409
<p>I'm having issues with an exercise that is asking me to loop through my list of people and print everything that I know about each person while using a dictionary for each person. I'm trying to start out by just getting Python to accept and loop through my dictionaries, but whenever I try to run my code, I get an er...
0
2016-09-01T23:47:28Z
39,282,438
<p><code>people</code> is a list. You can only get one value at a time from a list. However, its <em>elements</em> are dictionaries. So, the following loop would work:</p> <pre><code>for element in people: for key, value in element: print( "\n" + key + ": " + value) </code></pre> <p>The outer loop goes th...
0
2016-09-01T23:51:32Z
[ "python" ]
Confused about looping through list of people in Python
39,282,409
<p>I'm having issues with an exercise that is asking me to loop through my list of people and print everything that I know about each person while using a dictionary for each person. I'm trying to start out by just getting Python to accept and loop through my dictionaries, but whenever I try to run my code, I get an er...
0
2016-09-01T23:47:28Z
39,282,444
<p>you are adding string in list. Please use the variable names. </p> <pre><code>people = [dictionaries_v, dictionaries_c, dictionaries_e] </code></pre> <p>Edit: Adding more code that fixes the problem of unpacking below.</p> <pre><code>for person in people: for key,value in person: print key, " : ", val...
0
2016-09-01T23:52:25Z
[ "python" ]
Confused about looping through list of people in Python
39,282,409
<p>I'm having issues with an exercise that is asking me to loop through my list of people and print everything that I know about each person while using a dictionary for each person. I'm trying to start out by just getting Python to accept and loop through my dictionaries, but whenever I try to run my code, I get an er...
0
2016-09-01T23:47:28Z
39,282,447
<p>Your first problem is that your list is holding three <em>strings</em>. Notice how you wrapped quotes around it. So when you iterate over your list, you will most definitely not be getting the dictionary you expect. </p> <p>Secondly, <code>people</code> is a <code>list</code>. So, when you iterate your list, your i...
3
2016-09-01T23:52:38Z
[ "python" ]
Equal Average Partition DP using Python 2 VS Python 3
39,282,416
<p>I was using memorization to try to solve the <a href="https://www.interviewbit.com/problems/equal-average-partition/" rel="nofollow">Equal Average Partition Problem</a>, somehow the solution that I came up with take a long time to solve the problem in <a href="https://repl.it/DJdT" rel="nofollow">Python 2.x</a> but ...
0
2016-09-01T23:48:08Z
39,319,913
<p>There is only one difference between python 2 and 3 that you are using. In line</p> <pre><code>if (idx, curSum, curSize) in dic.keys(): return dic[(idx, curSum, curSize)] </code></pre> <p>method <code>keys()</code> in python2 returns list of dict keys and in python3 returns iterator through keys (it was iterkeys()...
1
2016-09-04T18:00:45Z
[ "python", "dynamic-programming" ]
Equal Average Partition DP using Python 2 VS Python 3
39,282,416
<p>I was using memorization to try to solve the <a href="https://www.interviewbit.com/problems/equal-average-partition/" rel="nofollow">Equal Average Partition Problem</a>, somehow the solution that I came up with take a long time to solve the problem in <a href="https://repl.it/DJdT" rel="nofollow">Python 2.x</a> but ...
0
2016-09-01T23:48:08Z
39,320,016
<p><code>something in dic.keys()</code> will be O(n) in Python 2 (membership in list) and O(1) in in Python 3 (membership in set). This accounts for observed difference in performance.</p> <p>On <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects" rel="nofollow">dictionary view objects</a>...
0
2016-09-04T18:10:54Z
[ "python", "dynamic-programming" ]
Is there a way to get the argument of argparse in the order in which they were defined?
39,282,429
<p>I'd like to print all options of the program and they are grouped for readability. However when accessing the arguments via <code>vars(args)</code>, the order is random.</p>
0
2016-09-01T23:50:25Z
39,282,787
<p><code>argparse</code> parses the list of arguments in <code>sys.argv[1:]</code> (<code>sys.argv[0]</code> is used as the <code>prog</code> value in <code>usage</code>).</p> <p><code>args=parser.parser_args()</code> returns a <code>argparse.Namespace</code> object. <code>vars(args)</code> returns a dictionary based...
2
2016-09-02T00:44:08Z
[ "python", "argparse" ]
How do I format a string to use for a Method in Python?
39,282,464
<p>When trying to run the listPersons() command, every Person/Instance should call the sayHello() method. But as the names are str, it would raise an AttributeError (see below).</p> <p>How do I format the names so I can use the methods on them?</p> <pre><code>class person: def __init__ (self, name): self....
0
2016-09-01T23:54:10Z
39,282,666
<p>You're getting this error because names list is a list of strings, not the people objects you create. Since you are using globals(), each person is being assigned to a variable in the global scope. Rather than using globals(), I would suggest having a list of people. </p> <p>Another problem you will run into is tha...
2
2016-09-02T00:24:48Z
[ "python", "methods", "format" ]
How to use css styling in html with multiple directories?
39,282,466
<p>I'm trying to make a simple webapp using Google Appengine with Python, HTML, and CSS. I know that to put a .css styling from separate file into html one should use a link tag, however I can't seem to get it to work. Here is the general directory config:</p> <p>Main<br> ├── app.yaml<br> ├── files.py<br> ...
0
2016-09-01T23:54:16Z
39,282,504
<p>I'm not 100% sure from your file diagram, but I think you're not referencing the CSS file properly in the link tag.</p> <p>If the two files are in these spots:</p> <p>Main/Folder/Templates/form.html</p> <p>Main/Folder/Static/style.css</p> <p>Then in the HTML, your link tag will need to be</p> <pre><code>&lt;lin...
1
2016-09-01T23:58:57Z
[ "python", "html", "css", "google-app-engine" ]