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 sort by likes or views Flask?
39,001,584
<p>I have a problem sorting <strong>Authors</strong> by <code>Author.likes</code> or <code>Author.views</code> .</p> <p>Lets me first show you my codes snippets :</p> <p><strong>views.py</strong></p> <pre><code>from sqlalchemy import func @app.route('/authors/') def authors(): page = request.args.get('page', 1, ...
-1
2016-08-17T16:13:00Z
39,001,673
<p>Remove <code>func.count</code> and just order by <code>Author.likes</code>, it's already a count. <code>func.count</code> is for counting groups of things. Currently, you're grouping everything into one group and so you only get one item back. </p>
1
2016-08-17T16:17:38Z
[ "python", "sqlalchemy" ]
Django ImageField file max upload limit
39,001,618
<p>I have my avatar in my UserProfile model in models.py file:-</p> <pre><code>class UserProfile(models.Model): profileuser = models.OneToOneField(User) handle = models.CharField(max_length=128, blank=True) avatar = models.ImageField(upload_to='profile_images', blank=True) </code></pre> <p>In my forms....
0
2016-08-17T16:14:46Z
39,001,934
<p>This should work:</p> <pre><code>class UserProfileForm(forms.ModelForm): class Meta: model= UserProfile exclude= ('profileuser',) def clean(self, *args, **kwargs): super(UserProfileForm, self).clean(*args, **kwargs) try: avatar = self.cleaned_data['avatar'] except Exception as e...
0
2016-08-17T16:32:26Z
[ "python", "django" ]
UnicodeDecodeError on python3
39,001,641
<p>Im currently trying to use some simple regex on a very big .txt file (couple of million lines of text). The most simple code that causes the problem:</p> <pre><code>file = open("exampleFileName", "r") for line in file: pass </code></pre> <p>The error message:</p> <pre><code>Traceback (most recent ...
2
2016-08-17T16:15:57Z
39,001,821
<p>It looks like it is invalid UTF-8 and you should try to read with <code>latin-1</code> encoding. Try</p> <pre><code>file = open('exampleFileName', 'r', encoding='latin-1') </code></pre>
0
2016-08-17T16:25:33Z
[ "python", "regex", "utf-8", "decoding" ]
UnicodeDecodeError on python3
39,001,641
<p>Im currently trying to use some simple regex on a very big .txt file (couple of million lines of text). The most simple code that causes the problem:</p> <pre><code>file = open("exampleFileName", "r") for line in file: pass </code></pre> <p>The error message:</p> <pre><code>Traceback (most recent ...
2
2016-08-17T16:15:57Z
39,002,048
<p>It is not possible to identify the encoding on the fly. So, either user a method which I wrote as a comment or use similar constructions (as proposed by another answer), but this is a wild shot:</p> <pre class="lang-py prettyprint-override"><code>try: file = open("exampleFileName", "r") except UnicodeDecodeErro...
0
2016-08-17T16:40:09Z
[ "python", "regex", "utf-8", "decoding" ]
Calculating surface normal in Python using Newell's Method
39,001,642
<p>I'm trying to implement Newell's Method to calculate the surface normal vector in Python, based on the following pseudocode from <a href="https://www.opengl.org/wiki/Calculating_a_Surface_Normal" rel="nofollow">here</a>.</p> <pre><code>Begin Function CalculateSurfaceNormal (Input Polygon) Returns Vector Set Ver...
2
2016-08-17T16:15:57Z
39,001,875
<p>If you want an alternate approach to Newell's Method you can use the Cross-Product of 2 non-parallel vectors. That should work for just about any planar shape you'd provide it. I know the theory says it is for convex polygons, but examples we've looked at on Wolfram Alpha return an appropriate surface normal for e...
1
2016-08-17T16:28:49Z
[ "python", "3d", "geometry" ]
Calculating surface normal in Python using Newell's Method
39,001,642
<p>I'm trying to implement Newell's Method to calculate the surface normal vector in Python, based on the following pseudocode from <a href="https://www.opengl.org/wiki/Calculating_a_Surface_Normal" rel="nofollow">here</a>.</p> <pre><code>Begin Function CalculateSurfaceNormal (Input Polygon) Returns Vector Set Ver...
2
2016-08-17T16:15:57Z
39,021,428
<p>Ok, the problem was actually a stupid one.</p> <p>The lines like:</p> <pre><code>n[0] += (v_curr.y - v_next.y) * (v_curr.z - v_next.z) </code></pre> <p>should be:</p> <pre><code>n[0] += (v_curr.y - v_next.y) * (v_curr.z + v_next.z) </code></pre> <p>The values in the second set of brackets should be added, not ...
0
2016-08-18T14:55:56Z
[ "python", "3d", "geometry" ]
cython error by python import
39,001,828
<p>I’m making an C++ class to manage the communication with a device (SPI). The idea is to use this C++ class on an Arduino and a Raspberry Pi. This way I need to make this class only once. </p> <p>I will use the class on the Arduino (this is no problem). I also want to use it on my Raspberry Pi together with python...
0
2016-08-17T16:26:07Z
39,002,696
<p><code>bcm2835_init</code> is presumably in "bcm2835.cpp" so you need to add that to <code>sources</code> in "setup.py"</p> <pre><code>sources=["dev.pyx","Device.cpp","bcm2835.cpp"] </code></pre> <p>Alternatively, if you have a bcm2835 library already compiled you might want to link to it by adding to "setup.py"</p...
0
2016-08-17T17:16:13Z
[ "python", "c++", "cython" ]
Convert Tecplot ascii to Python numpy
39,001,856
<p>I want to convert a <em>Tecplot</em> file into an array but I don't know how to do it. Here is an extract of the file:</p> <pre><code>TITLE = "Test" VARIABLES = "x" "y" ZONE I=18, F=BLOCK 0.1294538E-01 0.1299554E-01 0.1303974E-01 0.1311453E-01 0.1313446E-01 0.1319080E-01 0.1322709E-01 0.1323904E-01 0.133175...
0
2016-08-17T16:28:00Z
39,004,033
<p>Solved it with the last option:</p> <pre><code>arrays = [] with open(file, 'r') as a: for line in a.readlines(): A = re.match(r'TITLE = (.*$)', line, re.M | re.I) B = re.match(r'VARIABLES = (.*$)', line, re.M | re.I) C = re.match(r'ZONE (.*$)', line, re.M | re.I) if A or B or C: ...
0
2016-08-17T18:39:10Z
[ "python", "numpy", "io", "converter" ]
Selenium webdriver functions are not showing in autosuggestion list pycharm
39,002,097
<p>I have installed Python pip selenium pycharm. all works but I see that the autosuggestion box doesn't show the web driver functions. is there a reason for this?</p> <p>Selenium is installed for project interpreter in pycharm</p> <p><a href="http://i.stack.imgur.com/LHkMQ.png" rel="nofollow">This is how autosuggest...
1
2016-08-17T16:42:37Z
39,044,220
<p>When installing Selenium many folder are installed in the pythonxxx folder. Keep the folder Lib > site-package > Selenium and delete the other Selenium folder in python.</p>
0
2016-08-19T16:54:26Z
[ "python", "python-3.x", "selenium", "selenium-webdriver", "pycharm" ]
Binning time series with pandas
39,002,122
<p>I'm having a time series in form of a <code>DataFrame</code> that I can <code>groupby</code> to a series </p> <pre><code>pan.groupby(pan.Time).mean() </code></pre> <p>which has just two columns <code>Time</code> and <code>Value</code>: </p> <pre><code>Time Value 2015-04-24 06:38:49 0.023844 2015-04...
1
2016-08-17T16:44:00Z
39,003,074
<p>IIUC, you could use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.Grouper.html" rel="nofollow"><code>TimeGrouper</code></a> along with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> on the index lev...
1
2016-08-17T17:39:23Z
[ "python", "pandas" ]
Matplotlib - Legend of a specific contour at different instants
39,002,125
<p>I m trying to plot a figure with a specific contour line (level = 320) at different times that is why a loop is used. I would like plot a legend with labels to specify the time during the loop as here :</p> <p><a href="http://i.stack.imgur.com/cfSMK.png" rel="nofollow"><img src="http://i.stack.imgur.com/cfSMK.png"...
0
2016-08-17T16:44:08Z
39,064,664
<p>I used: <a href="http://matplotlib.org/examples/pylab_examples/contour_demo.html" rel="nofollow">http://matplotlib.org/examples/pylab_examples/contour_demo.html</a></p> <pre><code>cmap = plt.cm.hot lines = [] labels = [] i = 0 instant = 0 for instant in range(0,Sigma_stockMAX.shape[2]): name = 'test' VM_M...
1
2016-08-21T13:21:52Z
[ "python", "numpy", "matplotlib", "contour" ]
rasterio transform and affine
39,002,173
<p>Im trying to do some basic image filtering. Ive included a snippet verbatim from the rasterio cookbook (I removed .astype() from the median filter output). The issue is that my input and output rasters should have the same extent but dont. The transform and affine are different for the input and output. Is this the ...
2
2016-08-17T16:46:18Z
39,021,707
<p>The rasterio docs include a <a href="https://mapbox.github.io/rasterio/topics/migrating-to-v1.html#affine-affine-vs-gdal-style-geotransforms" rel="nofollow">history affine/transform usage</a> that you may find useful. I used to have a couple lines like the following to handle this:</p> <pre><code>out_profile = src....
0
2016-08-18T15:08:50Z
[ "python", "rasterio" ]
Scrapy: TypeError: start_requests() takes exactly 2 arguments (1 given)
39,002,285
<p>I'm starting work on a new scrapy project. So far I have:</p> <pre><code>class ContactSpider(Spider): name = "contact" allowed_domains = ["http://www.domain.com/"] start_urls = [ "http://web.domain.com/DECORATION" ] def start_requests(self,response): l = response.selector.xpa...
0
2016-08-17T16:51:55Z
39,005,071
<p><code>start_requests</code> is a method from <code>scrapy.spider</code> it takes no arguments other than <code>self</code>. It is used to create starting <code>Requests</code> so it should <strong>yield</strong> some <code>Request</code> objects(or return a list of <code>Requests</code>).</p> <pre><code>def start_r...
3
2016-08-17T19:45:50Z
[ "python", "scrapy" ]
Pandas GroupBy apply all
39,002,340
<p>I've got an involved situation. Let's say I have the following example dataframe of loans:</p> <pre><code>test_df = pd.DataFrame({'name': ['Jack','Jill','John','Jack','Jill'], 'date': ['2016-08-08','2016-08-08','2016-08-07','2016-08-08','2016-08-08'], 'amount': [1000.0,1500.0,2...
4
2016-08-17T16:55:13Z
39,002,970
<p>You can do it by iterating through the groups, testing the condition using <code>any</code>, then setting back to the original dataframe using <code>loc</code>:</p> <pre><code>test_df = pd.DataFrame({'name': ['Jack','Jill','John','Jack','Jill'], 'date': ['2016-08-08','2016-08-08','2016-08-07','20...
2
2016-08-17T17:32:38Z
[ "python", "pandas", "dataframe" ]
TensorFlow Choose GPU to use from multiple GPUs
39,002,352
<p>I'm new to TensorFlow and have installed CUDA-7.5 and cudnn-v4 as per the instructions on the TensorFlow website. After adjusting the TensorFlow configuration file and trying to run the following example from the website:</p> <pre><code>python -m tensorflow.models.image.mnist.convolutional </code></pre> <p>I'm pre...
0
2016-08-17T16:56:04Z
39,002,657
<p>You can set the <code>CUDA_VISIBLE_DEVICES</code> environment variable to expose only the ones that you want, quoting this example on <a href="http://www.acceleware.com/blog/cudavisibledevices-masking-gpus" rel="nofollow">masking gpus</a>:</p> <pre><code>CUDA_VISIBLE_DEVICES=1 Only device 1 will be seen CUDA_VISIB...
3
2016-08-17T17:14:12Z
[ "python", "cuda", "tensorflow", "gpu" ]
How to see if a string contains all substrings from a list? [Python]
39,002,391
<p>Here's the scenario:</p> <p>I have a long list of time-stamped file names with characters before and after the time-stamp.</p> <p>Something like this: <code>prefix_20160817_suffix</code></p> <p>What I want is a list (which will ultimately be a subset of the original list) that contains file names with specific pr...
0
2016-08-17T16:58:32Z
39,002,476
<p>I'd compile the list into a <a href="https://docs.python.org/2/library/fnmatch.html" rel="nofollow"><code>fnmatch</code> pattern</a>:</p> <pre><code>import fnmatch pattern = '*'.join(contains) filetered_filenames = fnmatch.filter(master_list, pattern) </code></pre> <p>This basically concatenates all strings in <c...
4
2016-08-17T17:03:46Z
[ "python", "python-3.x" ]
How to see if a string contains all substrings from a list? [Python]
39,002,391
<p>Here's the scenario:</p> <p>I have a long list of time-stamped file names with characters before and after the time-stamp.</p> <p>Something like this: <code>prefix_20160817_suffix</code></p> <p>What I want is a list (which will ultimately be a subset of the original list) that contains file names with specific pr...
0
2016-08-17T16:58:32Z
39,002,523
<p>You're looking for something like that (using <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201608171708486260643">list comprehension</a> and <a class='doc-link' href="http://stackoverflow.com/documentation/python/209/list/8125/any-and-all#t=2016...
1
2016-08-17T17:06:24Z
[ "python", "python-3.x" ]
How to see if a string contains all substrings from a list? [Python]
39,002,391
<p>Here's the scenario:</p> <p>I have a long list of time-stamped file names with characters before and after the time-stamp.</p> <p>Something like this: <code>prefix_20160817_suffix</code></p> <p>What I want is a list (which will ultimately be a subset of the original list) that contains file names with specific pr...
0
2016-08-17T16:58:32Z
39,002,543
<p>Given:</p> <pre><code>&gt;&gt;&gt; cond1=['prefix1', '2016', 'suffix'] &gt;&gt;&gt; cond2=['201608', 'suffix'] &gt;&gt;&gt; fn="prefix_20160817_suffix" </code></pre> <p>You can test the existence of each substring in the list of conditions with <code>in</code> and (in the interim example) a list comprehension:</p>...
0
2016-08-17T17:07:23Z
[ "python", "python-3.x" ]
How to see if a string contains all substrings from a list? [Python]
39,002,391
<p>Here's the scenario:</p> <p>I have a long list of time-stamped file names with characters before and after the time-stamp.</p> <p>Something like this: <code>prefix_20160817_suffix</code></p> <p>What I want is a list (which will ultimately be a subset of the original list) that contains file names with specific pr...
0
2016-08-17T16:58:32Z
39,002,577
<p>This should work for you.</p> <pre><code>filtered_list = [] for file_name in master_list: for element in contains_array: if element not in file_name: break filtered_list.append(file_name) </code></pre>
0
2016-08-17T17:09:46Z
[ "python", "python-3.x" ]
How to see if a string contains all substrings from a list? [Python]
39,002,391
<p>Here's the scenario:</p> <p>I have a long list of time-stamped file names with characters before and after the time-stamp.</p> <p>Something like this: <code>prefix_20160817_suffix</code></p> <p>What I want is a list (which will ultimately be a subset of the original list) that contains file names with specific pr...
0
2016-08-17T16:58:32Z
39,002,636
<p>Your pseudocode was not far from a usable implementation as you see:</p> <pre><code>masterList=["prefix_20160817_suffix"] containsArray=['prefix1', '2016', 'suffix'] filteredListOfFilenames=[] for fileName in masterList: if all((element in fileName) for element in containsArray): filteredListOfFilename...
0
2016-08-17T17:13:06Z
[ "python", "python-3.x" ]
how to extract date/time parameters from a list of strings?
39,002,454
<p>i have a pandas dataframe having a column as </p> <pre><code> from pandas import DataFrame df = pf.DataFrame({ 'column_name' : [u'Monday,30 December,2013', u'Delivered', u'19:23', u'1']}) </code></pre> <p>now i want to extract every thing from it and store in three columns as</p> <pre><code>date sta...
0
2016-08-17T17:02:26Z
39,002,718
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><strong><code>apply()</code></strong></a> a function to a column, see the whole example:</p> <pre><code>from pandas import DataFrame df = DataFrame({'date': ['Monday,30 December,2013'], 'delivery': ['D...
0
2016-08-17T17:17:41Z
[ "python", "date", "pandas" ]
Installing OpenCV Python Bindings on Mac with VirtualEnv: Can't find interpreter
39,002,549
<p>I've been following <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-python-2-7-on-osx/" rel="nofollow">this</a> guide on installing OpenCV on MacOS. I'm stuck on step 8, where you cmake everything.</p> <p>From the <code>~/opencv/build</code> directory, I run</p> <pre><code>$ cmake -D ...
0
2016-08-17T17:07:43Z
39,024,863
<p>Well, eventually I went with the following approach: Don't bother getting cmake to use the virtualenv interpreter. You can just compile opencv and the copy the cv2.so file into your virtualenv. In my case this involved proceeding with the <a href="http://www.pyimagesearch.com/2015/06/15/install-opencv-3-0-and-pyth...
0
2016-08-18T18:10:08Z
[ "python", "opencv", "numpy", "cmake" ]
Using python for loop to average data
39,002,558
<p>I have a data set that contains 20 years of monthly averages in a numpy array with dimensions (1x240). I'm trying to write a function to spit out the yearly averages. I've managed to do it (I believe), using a for loop, but when I stick the exact same code into a function, it only gives me the first of what should b...
0
2016-08-17T17:08:21Z
39,002,700
<p>here's what you need...</p> <pre><code>def yearlymean_gm(gm_data): data= np.load(gm_data) average = np.zeroes(20) for i in range (0,20): average[i]= data[i*12:i*12+12].sum()/12 print average return average #don't return until the loop has completed </code></pre>
1
2016-08-17T17:16:33Z
[ "python", "arrays", "numpy", "for-loop" ]
Using python for loop to average data
39,002,558
<p>I have a data set that contains 20 years of monthly averages in a numpy array with dimensions (1x240). I'm trying to write a function to spit out the yearly averages. I've managed to do it (I believe), using a for loop, but when I stick the exact same code into a function, it only gives me the first of what should b...
0
2016-08-17T17:08:21Z
39,003,162
<p>Why not avoid the "for" loop altogether?</p> <pre><code>def yearlymean_gm(gm_data): data = np.load(gm_data) data = data.reshape((12, 20)) print data.mean(axis=1) return data.mean(axis=1) </code></pre>
4
2016-08-17T17:44:58Z
[ "python", "arrays", "numpy", "for-loop" ]
Creating bigrams from a string using regex
39,002,563
<p>I have a string like:</p> <pre><code>"[u'LOCATION_SLOT~-prep_in+*extend*to~prepc_according_to+expectancy~-nsubj+is~parataxis+NUMBER~nsubj+NUMBER_SLOT', u'LOCATION_SLOT~-prep_in+*extend*to~prepc_according_to+expectancy~-nsubj+is~parataxis+NUMBER~nsubj+NUMBER_SLOT']" </code></pre> <p>Which is taken from an Excel fil...
0
2016-08-17T17:08:36Z
39,002,851
<p>I have solved this. The regex needs to go through twice to replace first the brackets, then get the first string, then remove quotes:</p> <pre><code> text = "[u'LOCATION_SLOT~-prep_in+*extend*to~prepc_according_to+expectancy~-nsubj+is~parataxis+NUMBER~nsubj+NUMBER_SLOT', u'LOCATION_SLOT~-prep_in+*extend*to~prepc_...
0
2016-08-17T17:25:21Z
[ "python", "regex", "string", "list", "n-gram" ]
Creating bigrams from a string using regex
39,002,563
<p>I have a string like:</p> <pre><code>"[u'LOCATION_SLOT~-prep_in+*extend*to~prepc_according_to+expectancy~-nsubj+is~parataxis+NUMBER~nsubj+NUMBER_SLOT', u'LOCATION_SLOT~-prep_in+*extend*to~prepc_according_to+expectancy~-nsubj+is~parataxis+NUMBER~nsubj+NUMBER_SLOT']" </code></pre> <p>Which is taken from an Excel fil...
0
2016-08-17T17:08:36Z
39,003,797
<p>Your string looks like a Python list of unicode strings, right?</p> <p>You can evaluate it to get list of unicode string. A good way to do that is to use <code>ast.literal_eval</code> function from the <a href="https://docs.python.org/2/library/ast.html#ast-helpers" rel="nofollow"><strong>ast</strong></a> module.</...
1
2016-08-17T18:23:20Z
[ "python", "regex", "string", "list", "n-gram" ]
Django - QuerySet - Get count for all determined child objects inside all parent objects
39,002,617
<p>I've got this model:</p> <pre><code>class Order(models.Model): #bunch of fields# class Laptop(models.Model): #bunch of fields# class Camera(models.Model): #bunch of fields# class MusicPlayer(models.Model): #bunch of fields# </code></pre> <p>The last three have a foreign key associated to the Ord...
0
2016-08-17T17:12:12Z
39,002,832
<p>Add related_name to your models:</p> <pre><code>class Laptop(models.Model): order = models.ForeignKey(Order, related_name='laptops') class Camera(models.Model): order = models.ForeignKey(Order, related_name='cameras') class MusicPlayer(models.Model): order = models.ForeignKey(Order, related_name='musi...
1
2016-08-17T17:23:44Z
[ "python", "django", "django-queryset" ]
Python program to map a series of chemical reactions with unique nodes only appearing once
39,002,631
<p>I have written a program in python to compose a map of a chemistry an example of which is the below text in the format: reactants > products.</p> <pre><code>H2 &gt; H2 H2 &gt; H2 H2 &gt; H2* H2 &gt; H2* H2 &gt; H + H H2 &gt; H2^ H2 &gt; H* + H H2 &gt; H + H H2^ &gt; H2^ H2^ &gt; H^ + H H2^ &gt; H + H H3^ &gt; H3^ H...
1
2016-08-17T17:12:59Z
39,006,157
<p>One of the problems you seem to be having is that you're not stripping the whitespace from around the reactants/products you parse out of the "qstrings" of reactions. This means that e.g. <code>' H2'</code> and <code>'H2 '</code> are treated as different species and so get distinct nodes in your graph.</p> <p>You p...
1
2016-08-17T20:57:48Z
[ "python", "networkx" ]
Getting 'dict_keys' object does not support indexing despite casting to list
39,002,665
<p>I am using Python 3 and despite of casting to list, I cannot seem to run my program.</p> <p>This is the function calling:</p> <pre><code>path = euleriancycle(edges) </code></pre> <p>And this is where I have used the keys method:</p> <pre><code>def euleriancycle(e): currentnode = list[e.keys()[0]] path = ...
0
2016-08-17T17:14:27Z
39,002,721
<p>The <code>dict_keys</code> objects, like sets, can not be indexed.</p> <p>Instead of this:</p> <pre><code>list[e.keys()[0]] </code></pre> <p>The next closest thing would be this:</p> <pre><code>list(e)[0] </code></pre> <p>Python makes no guarantee on what key from the dict will be returned, so you might want to...
4
2016-08-17T17:17:45Z
[ "python", "python-3.x", "dictionary", "jupyter-notebook" ]
Getting 'dict_keys' object does not support indexing despite casting to list
39,002,665
<p>I am using Python 3 and despite of casting to list, I cannot seem to run my program.</p> <p>This is the function calling:</p> <pre><code>path = euleriancycle(edges) </code></pre> <p>And this is where I have used the keys method:</p> <pre><code>def euleriancycle(e): currentnode = list[e.keys()[0]] path = ...
0
2016-08-17T17:14:27Z
39,002,770
<p>You are trying to index the <code>dict_keys</code> object, <em>then</em> convert that element to a list (syntax error of <code>list[...]</code> vs <code>list(...)</code> aside). You need to convert the entire object to a list first, <em>then</em> index it.</p> <pre><code>currentnode = list[e.keys()[0]] # Wrong cu...
2
2016-08-17T17:20:16Z
[ "python", "python-3.x", "dictionary", "jupyter-notebook" ]
Error in python function pymongo
39,002,751
<p>This is a function that returns an error at the line with <code>post['date']</code>.</p> <p>This is the error:</p> <pre><code>in get_posts post['date'] = post['date'].strftime("%A, %B %d %Y at %I:%M%p") KeyError: 'date' </code></pre> <p>What does it mean?</p> <p>This is the function:</p> <pre><code>def get_...
1
2016-08-17T17:19:11Z
39,003,146
<p><code>KeyError: 'date'</code> means that <code>post</code> doesn't have the attribute <code>date</code>.</p>
0
2016-08-17T17:44:12Z
[ "python", "mongodb", "mongodb-query", "pymongo", "keyerror" ]
Sending message with Router-Dealer Proxy using c# and python
39,002,823
<p>I am able to have c# (client) and python (server) talk to each other by using a simple request-reply. However, I want my web application built on c# asp.net to be stable and need more clients and servers, so I tried connecting c# and python using the Router-Dealer Proxy with python.</p> <p>I tried running the proxy...
0
2016-08-17T17:23:13Z
39,005,000
<p>I'm assuming your servers use bind, so the proxy should <code>connect</code> to them rather than also using <code>bind</code>.</p> <p>Note: in zeromq the order of application startup doesn't matter so you can tell your proxy to <code>connect</code> to a server that doesn't yet exist, when the server is started the ...
0
2016-08-17T19:41:47Z
[ "c#", "python", "proxy", "zeromq", "netmq" ]
Python curses not accept curses.KEY_UP as input
39,002,864
<p>I need your help in understanding the mistake in my new menu based python program.</p> <p>I have created a menu based python using the curses library. The program works fine with main menu options by accepting all the keys including special keys as input when getting user input via <code>getch()</code> but with a s...
0
2016-08-17T17:26:03Z
39,059,220
<p>When you did </p> <pre><code>self.s = curses.newwin(height+2, 20, 6, 14) </code></pre> <p>you omitted setting properties for the new window, e.g,</p> <pre><code>self.s.keypad(1) </code></pre>
2
2016-08-20T22:25:22Z
[ "python", "menuitem", "curses" ]
Too many open files in Windows when writing multiple HDF5 files
39,002,942
<p>My question is <strong>how to close HDF5 files indefinitely after writing them</strong>?</p> <p>I am trying to save data to HDF5 files - there are around 200 folders and each folder contains some data for each day for this year.</p> <p>When I retrieve and save data using pandas HDFStore with following code in iPyt...
1
2016-08-17T17:31:07Z
39,005,921
<p>You can check / list all open files belonging to Python process in Windows using <code>psutil</code> module.</p> <p>Demo:</p> <pre><code>In [52]: [proc.open_files() for proc in psutil.process_iter() if proc.pid == os.getpid()] Out[52]: [[popenfile(path='C:\\Windows\\System32\\en-US\\KernelBase.dll.mui', fd=-1), ...
1
2016-08-17T20:41:26Z
[ "python", "pandas", "hdf5", "hdfstore" ]
How to swap the rows of two tables in python (astropy.table)?
39,003,083
<p>I am trying to swap the rows of two python tables, e.g</p> <pre><code> In [15]: print t2 x y z ---- ---- ---- 20.0 30.0 40.0 50.0 60.0 70.0 80.0 90.0 99.0 In [16]: print t1 a b c --- --- --- 1.0 2.0 3.0 3.0 4.0 5.0 6.0 7.0 8.0 </code></pre> <p>I...
-1
2016-08-17T17:40:02Z
39,003,408
<p>Looks like your code has changed <code>t1[1]</code>and then the new value has overwritten <code>t2[1]</code>. You need to make an explicit copy of t1, change the copy and then alter t2 based on the original t1. If you have to do this with multiple steps, it might just be safer to make a copy of each and then overwri...
0
2016-08-17T18:00:01Z
[ "python", "swap", "astropy" ]
Better way of filtering in Django and seeing if the object exists
39,003,093
<p>A lot of times I find myself filtering for an object and returning <code>None</code> if it can't be found. However, the method I do this seems really inefficient (in terms of lines of code)</p> <p>When I filter for an object I normally do something like this:</p> <pre><code>person = Person.objects.filter(id=id) if...
-2
2016-08-17T17:40:41Z
39,003,465
<p>Your <code>if/else</code> is unusual in that you assign <code>person</code> twice. I can't understand why. You have two options I think.</p> <p>First, you could reduce <code>if/else</code> to just <code>if</code> like this:</p> <pre><code>person = Person.objects.filter(name=name) if not person: person = None <...
1
2016-08-17T18:03:27Z
[ "python", "django" ]
Better way of filtering in Django and seeing if the object exists
39,003,093
<p>A lot of times I find myself filtering for an object and returning <code>None</code> if it can't be found. However, the method I do this seems really inefficient (in terms of lines of code)</p> <p>When I filter for an object I normally do something like this:</p> <pre><code>person = Person.objects.filter(id=id) if...
-2
2016-08-17T17:40:41Z
39,003,528
<p>Filter return list (or empty list), so if you know you get list, and want to replace empty list with None:</p> <pre><code>persons = Person.objects.filter(name=name) if not any(person): person = None # single person person = persons[0] # but there could be more than one </code></pre> <p>If you want single Perso...
1
2016-08-17T18:07:21Z
[ "python", "django" ]
Better way of filtering in Django and seeing if the object exists
39,003,093
<p>A lot of times I find myself filtering for an object and returning <code>None</code> if it can't be found. However, the method I do this seems really inefficient (in terms of lines of code)</p> <p>When I filter for an object I normally do something like this:</p> <pre><code>person = Person.objects.filter(id=id) if...
-2
2016-08-17T17:40:41Z
39,003,754
<p>Just use <code>.get()</code> if you want to get one person or return None.</p> <pre><code>try: person = Person.objects.get(name=name) except (Person.DoesNotExist, Person.MultipleObjectsReturned) as e: person = None </code></pre>
1
2016-08-17T18:20:15Z
[ "python", "django" ]
Better way of filtering in Django and seeing if the object exists
39,003,093
<p>A lot of times I find myself filtering for an object and returning <code>None</code> if it can't be found. However, the method I do this seems really inefficient (in terms of lines of code)</p> <p>When I filter for an object I normally do something like this:</p> <pre><code>person = Person.objects.filter(id=id) if...
-2
2016-08-17T17:40:41Z
39,004,279
<p>You can use <code>exists()</code></p> <p>From the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.exists" rel="nofollow" title="docs">docs</a>:</p> <blockquote> <p>If you only want to determine if at least one result exists (and don’t need the actual object...
1
2016-08-17T18:54:08Z
[ "python", "django" ]
Better way of filtering in Django and seeing if the object exists
39,003,093
<p>A lot of times I find myself filtering for an object and returning <code>None</code> if it can't be found. However, the method I do this seems really inefficient (in terms of lines of code)</p> <p>When I filter for an object I normally do something like this:</p> <pre><code>person = Person.objects.filter(id=id) if...
-2
2016-08-17T17:40:41Z
39,047,988
<p>You cannot do like this. </p> <pre><code>person = Person.objects.get(name=name) </code></pre> <p>will raise an exception.</p> <p>What you can do is:</p> <pre><code>try: person = Person.objects.get(name=name) except Person.MultipleObjectsReturned: person = Person.objects.first() except Person.DoesNotExist: ...
1
2016-08-19T21:34:59Z
[ "python", "django" ]
Python: Access camera WITHOUT OpenCV
39,003,106
<p>Comrades,</p> <p>I'd like to capture images from the laptop camera in Python. Currently all signs point to OpenCV. Problem is OpenCV is a nightmare to install, and it's a nightmare that reoccurs every time you reinstall your code on a new system. </p> <p>Is there a more lightweight way to capture camera data in...
0
2016-08-17T17:41:23Z
39,003,827
<p>I've done this before using <a href="http://www.pygame.org/download.shtml" rel="nofollow">pygame</a>. But I can't seem to find the script that I used... It seems there is a tutorial <a href="http://www.pygame.org/docs/tut/camera/CameraIntro.html" rel="nofollow">here</a> which uses the native camera module and is not...
1
2016-08-17T18:24:41Z
[ "python", "osx", "camera" ]
A more efficient solution for solving this matrix puzzle?
39,003,147
<p>Find the 3x3 matrix, M, whose rows, columns and diagonals add up to 15. Condition: you must use every number from 1-9.</p> <p>I'm not very clever, so I just tried this brute force method:</p> <pre><code>def solve_999(): for a in range(1, 10): for b in range(1, 10): for c in range(1, 10): ...
1
2016-08-17T17:44:15Z
39,003,495
<p>The biggest speedup you will get will be from generating your squares so that they are already unique. The easiest way to do this is <code>itertools.permutations</code>. This will reduce you to checking 9! == 362880 boards rather than 387420489 boards (about 1/1000th the work) and you don't have to check to make sur...
1
2016-08-17T18:05:06Z
[ "python", "matrix", "puzzle" ]
A more efficient solution for solving this matrix puzzle?
39,003,147
<p>Find the 3x3 matrix, M, whose rows, columns and diagonals add up to 15. Condition: you must use every number from 1-9.</p> <p>I'm not very clever, so I just tried this brute force method:</p> <pre><code>def solve_999(): for a in range(1, 10): for b in range(1, 10): for c in range(1, 10): ...
1
2016-08-17T17:44:15Z
39,003,505
<p>You can use the itertools.permutations library to iterate over all possibilities checking for your required sums.</p> <p>While your code works for fixed size of input array (in this case 3x3 = 9), I have generalized it to check for any given sum over any range that is provided through the use of some python assist...
0
2016-08-17T18:05:46Z
[ "python", "matrix", "puzzle" ]
A more efficient solution for solving this matrix puzzle?
39,003,147
<p>Find the 3x3 matrix, M, whose rows, columns and diagonals add up to 15. Condition: you must use every number from 1-9.</p> <p>I'm not very clever, so I just tried this brute force method:</p> <pre><code>def solve_999(): for a in range(1, 10): for b in range(1, 10): for c in range(1, 10): ...
1
2016-08-17T17:44:15Z
39,003,794
<p>Bit shorter than the others:</p> <pre><code>&gt;&gt;&gt; from itertools import permutations &gt;&gt;&gt; for a, b, c, d, e, f, g, h, i in permutations(range(1, 10)): if 15 == a+b+c == d+e+f == a+d+g == b+e+h == a+e+i == c+e+g: print(a, b, c) print(d, e, f) print(g, h, i) ...
1
2016-08-17T18:23:12Z
[ "python", "matrix", "puzzle" ]
A more efficient solution for solving this matrix puzzle?
39,003,147
<p>Find the 3x3 matrix, M, whose rows, columns and diagonals add up to 15. Condition: you must use every number from 1-9.</p> <p>I'm not very clever, so I just tried this brute force method:</p> <pre><code>def solve_999(): for a in range(1, 10): for b in range(1, 10): for c in range(1, 10): ...
1
2016-08-17T17:44:15Z
39,004,079
<p>Its easy. Just think how many ways are there to build 15 out of a sum of three numbers.</p> <pre><code>1+5+9, 1+6+8, 2+4+9, 2+5+8, 2+6+7, 3+4+8, 3+5+7, 4+5+6 </code></pre> <p>Each sum appears in your square because there are only 8 ways. 5 must be in the center because it appears 4 times. 2,4,6,8 must be in the c...
3
2016-08-17T18:41:45Z
[ "python", "matrix", "puzzle" ]
Excel to PostgreSQL using Python
39,003,159
<p>I'm new to Python and I'm trying to export excel directly into postgreSQL without CSV files.</p> <p>I don't know if it's possible.</p> <p>I keep running into the error <code>'column "daily_date" is of type date but expression is of type numeric'</code>.</p> <pre><code>import psycopg2 import xlrd book = xlrd.open...
-1
2016-08-17T17:44:42Z
39,005,370
<p>Excel stores datetimes as numbers. You can use <code>xlrd.xldate.xldate_as_datetime</code> to convert:</p> <pre><code> Daily_Date = xlrd.xldate.xldate_as_datetime(sheet.cell(r,0).value,book.datemode) </code></pre>
0
2016-08-17T20:05:49Z
[ "python", "excel", "postgresql" ]
Pygame reset an Image after scaling it
39,003,192
<p>I tried to enlarge an image by moving the mouse over the image and make it to the original size when moving away from it. For example:</p> <pre><code>if ImageRect.collidepoint(mouseX,mouseY): Image = pygame.transform.scale(Image, (100,100)) else: Image = pygame.transform.scale(Image, (64,64)) #actual size...
0
2016-08-17T17:46:18Z
39,003,476
<blockquote> <p>Some of the transforms are considered destructive. These means every time they are performed they lose pixel data. Common examples of this are resizing and rotating. For this reason, it is better to retransform the original surface than to keep transforming an image multiple times. (For exampl...
0
2016-08-17T18:04:13Z
[ "python", "image", "pygame", "mouse" ]
how to check django_tables2 object empty/null?
39,003,216
<p>The problem I'm trying to solve:<br> Display a search bar only when the table <code>my_table</code> is not empty, else, hide it.</p> <p>Here's my views.py:</p> <pre><code>def my_table(request): model1 = Model1.objects.all().filter(Q(some_query)) table = MyTable(model1) RequestConfig(request).configure(...
2
2016-08-17T17:47:39Z
39,007,177
<p>In you views.py you can use:</p> <pre><code>if table.data.data.__len__ &gt; 0: </code></pre> <p>and in your template you can use:</p> <pre><code>{% if table.data|length &gt; 0 %} do whatever you want here... {% endif %} </code></pre>
1
2016-08-17T22:24:06Z
[ "python", "django" ]
Python parsing multi column file
39,003,251
<p>I have a file where i need to parse and construct in to a single row from multi row using python</p> <pre><code>NAME ID TITLE DEP USER1 0023 S1 SALES USER2 0022 A2 ACCOUNT </code></pre> <p>As you can see here the file header are NAME, ID, TITLE, DEP</p> <p>I want to print output like below so i can read ...
-1
2016-08-17T17:49:48Z
39,003,358
<p>Having all the words in a file called <code>file.txt</code> here is the code:</p> <pre><code> # read all the words with open('file.txt') as f: words = f.read().split() # convert to groups of 4-s groups4 = [words[i:i+4] for i in range(0, len(words), 4)] # convert to lines with commas using join() lines = [', '...
0
2016-08-17T17:56:55Z
[ "python", "parsing", "multiline" ]
Python parsing multi column file
39,003,251
<p>I have a file where i need to parse and construct in to a single row from multi row using python</p> <pre><code>NAME ID TITLE DEP USER1 0023 S1 SALES USER2 0022 A2 ACCOUNT </code></pre> <p>As you can see here the file header are NAME, ID, TITLE, DEP</p> <p>I want to print output like below so i can read ...
-1
2016-08-17T17:49:48Z
39,003,761
<pre><code>infile = open('test_file_parse.csv','r') def custom_func(x): return next(x).strip().split() while infile: try: print ','.join(reduce(lambda x, y: x + y, (custom_func(infile) for z in range(4)))) except TypeError: break infile.close() </code></pre>
0
2016-08-17T18:20:52Z
[ "python", "parsing", "multiline" ]
Python parsing multi column file
39,003,251
<p>I have a file where i need to parse and construct in to a single row from multi row using python</p> <pre><code>NAME ID TITLE DEP USER1 0023 S1 SALES USER2 0022 A2 ACCOUNT </code></pre> <p>As you can see here the file header are NAME, ID, TITLE, DEP</p> <p>I want to print output like below so i can read ...
-1
2016-08-17T17:49:48Z
39,004,006
<p>If you know everything will be pairs of two lines and you know you can ignore empty lines, you could do something like:</p> <pre><code>infile = open('test_file_parse.csv', 'r') # A generator that yields the non-empty lines, without newlines. lines = (l.strip() for l in infile if l.strip()) # An iterator to iterat...
0
2016-08-17T18:36:59Z
[ "python", "parsing", "multiline" ]
How can I detect whether I'm running in a Celery worker?
39,003,282
<p>Is there a way to determine, programatically, that the current module being imported/run is done so in the context of a celery worker?</p> <p>We've settled on setting an environment variable before running the Celery worker, and checking this environment variable in the code, but I wonder if there's a better way?</...
0
2016-08-17T17:52:06Z
39,019,837
<p>Adding a environment variable is a good way to check if the module is being run by celery worker. In the task submitter process we may set the environment variable, to mark that it is not running in the context of a celery worker.</p> <p>But the better way may be to use some celery signals which may help to know if...
0
2016-08-18T13:44:00Z
[ "python", "celery" ]
How can I detect whether I'm running in a Celery worker?
39,003,282
<p>Is there a way to determine, programatically, that the current module being imported/run is done so in the context of a celery worker?</p> <p>We've settled on setting an environment variable before running the Celery worker, and checking this environment variable in the code, but I wonder if there's a better way?</...
0
2016-08-17T17:52:06Z
39,023,702
<p>Depending on what your use-case scenario is exactly, you may be able to detect it by checking whether the request id is set:</p> <pre><code>@app.task(bind=True) def foo(self): print self.request.id </code></pre> <p>If you invoke the above as <code>foo.delay()</code> then the task will be sent to a worker and <...
0
2016-08-18T16:57:21Z
[ "python", "celery" ]
How can I detect whether I'm running in a Celery worker?
39,003,282
<p>Is there a way to determine, programatically, that the current module being imported/run is done so in the context of a celery worker?</p> <p>We've settled on setting an environment variable before running the Celery worker, and checking this environment variable in the code, but I wonder if there's a better way?</...
0
2016-08-17T17:52:06Z
39,093,390
<p>It is a good practice to start workers with names, so that it becomes easier to manage(stop/kill/restart) them. You can use <code>-n</code> to name a worker.</p> <pre><code>celery worker -l info -A test -n foo </code></pre> <p>Now, in your script you can use <code>app.control.inspect</code> to see if that worker i...
0
2016-08-23T05:58:25Z
[ "python", "celery" ]
wxpython dialog return values with option to destroy
39,003,360
<p>I have a wxpython dialog (wrapped in a function call which returns user selection) that Im using to prompt user for "ok", "cancel" type questions.</p> <p>I have another thread that is running that allows the user to click a button and perform an emergency stop (also wxpython). when the emergency stop button is clic...
1
2016-08-17T17:56:59Z
39,003,717
<p>since i dont really understand what you are asking for, I will instead address "I wish wxpython just had a closeAll() :)"</p> <pre><code>def wx_closeAll(): for win in wx.GetTopLevelWindows(): win.Destroy() def closeAllButPrimary(): for win in wx.GetTopLevelWindows(): if win != wx.GetTopLeve...
2
2016-08-17T18:17:49Z
[ "python", "multithreading", "return", "wxpython" ]
wxpython dialog return values with option to destroy
39,003,360
<p>I have a wxpython dialog (wrapped in a function call which returns user selection) that Im using to prompt user for "ok", "cancel" type questions.</p> <p>I have another thread that is running that allows the user to click a button and perform an emergency stop (also wxpython). when the emergency stop button is clic...
1
2016-08-17T17:56:59Z
39,003,808
<p>Doing GUI from threads is not a good idea, and nearly always gives unexpected results.</p> <p>In order to show the message box from a thread, you need to make the thread ask the main thread to show the message box. </p> <p>You do this using the function <a href="https://wiki.wxpython.org/CallAfter" rel="nofollow">...
2
2016-08-17T18:23:43Z
[ "python", "multithreading", "return", "wxpython" ]
Brute force with python selenium?
39,003,378
<p>I am trying to brute force with <code>python selenium</code> But it seems to be too time taking unlike brute force with python requests,although both are different.I was wondering is there any way that brute force can be done more faster?</p>
-1
2016-08-17T17:58:02Z
39,003,568
<p>I once wrote a Python script that used Splinter to drive Firefox via Selenium for a video that demonstrated brute-forcing a Wordpress login in the same fashion (for educating site owners about how easy it was to brute-force the Wordpress login by default). I used this method precisely because it was slower (and it w...
1
2016-08-17T18:08:56Z
[ "python", "selenium", "python-requests", "python-3.4" ]
Programmatically getting list of child processes of a given PID
39,003,433
<p>I'd like to get a list of all the immediate children of a given PID. I'm OK with using <code>/proc</code> but <code>/proc/&lt;PID&gt;/task/&lt;PID&gt;/children</code> is NOT precise and may return inaccurate results (<a href="https://lwn.net/Articles/475688/" rel="nofollow">see section 3.7 here</a>). I'd like a more...
1
2016-08-17T18:01:34Z
39,003,721
<p>Why not use psutils?</p> <p>Here is an example where I kill all the children.</p> <pre><code>def infanticide(pid): try: parent = psutil.Process(pid) except psutil.NoSuchProcess: return children = parent.children(recursive=True) for p in children: os.kill(p.pid, signal.SIGKILL) <...
0
2016-08-17T18:18:01Z
[ "python", "node.js", "linux", "ubuntu", "process" ]
Transform 3D polygon to 2D, perform clipping, and transform back to 3D
39,003,450
<p>My problem is that I have two walls, represented as 2D planes in 3D space, (<code>wallA</code> and <code>wallB</code>). These walls are overlapping. I need to convert that into three wall sections, one for the <code>wallA.intersect(wallB)</code>, one for <code>wallA.diff(wallB)</code>, and one for <code>wallB.diff(w...
0
2016-08-17T18:02:48Z
39,008,641
<p>Rather than rotating, you can simply project. The key is to map the 3d space onto a 2d plane in a way that you can then reverse. (Any distortion resulting from the projection will be undone when you map back.) To do this, you should first find the plane that contains both of your walls. Here is some example code:</p...
2
2016-08-18T01:33:28Z
[ "python", "3d", "geometry", "transforms3d" ]
How to fix appengine ImportError: No module named protobuf?
39,003,464
<p>I have the following folders structure:</p> <pre><code>myappdir - libs - somelib script1.py script2.py - google - protobuf __init__.py message.py ... __init__.py ... app.yaml appengine_config.py ... </code></pre> <p>And the following...
1
2016-08-17T18:03:24Z
39,003,903
<p>Change the lines in your <strong>appengine_config.py</strong> file, from:</p> <pre><code>import sys sys.path.append('libs') </code></pre> <p>to:</p> <pre><code>import sys import os.path sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs')) </code></pre>
0
2016-08-17T18:29:55Z
[ "python", "google-app-engine", "protocol-buffers", "python-import" ]
How to easy switch db in Django 1.9.x across multiple servers
39,003,588
<p>I have one application in Django 1.9.x, and I want to use multidb.</p> <p>Have any configuration on the settings that I can enter multiple databases, and when it is on a specific server it uses the correct database. For example:</p> <p>When I'm programming localhost use default, When I put in test serve, automatic...
0
2016-08-17T18:10:14Z
39,004,529
<p>It sounds like you want to have environment specific databases, not necessarily a single app that connects to many databases. You can easily accomplish this with a custom settings module for each of these environments. </p> <p>You might have a structure like the following : </p> <pre><code>myproject/ - settin...
1
2016-08-17T19:12:47Z
[ "python", "mysql", "django", "database", "postgresql" ]
How to easy switch db in Django 1.9.x across multiple servers
39,003,588
<p>I have one application in Django 1.9.x, and I want to use multidb.</p> <p>Have any configuration on the settings that I can enter multiple databases, and when it is on a specific server it uses the correct database. For example:</p> <p>When I'm programming localhost use default, When I put in test serve, automatic...
0
2016-08-17T18:10:14Z
39,005,365
<p>In your settings file:</p> <pre><code>try: from [app_name].local_settings import * except ImportError: pass </code></pre> <p>Changes you make in this local_settings file will be overridden. So now you can have a different local_settings file for your localhost, development or production. You can specify a ...
4
2016-08-17T20:05:38Z
[ "python", "mysql", "django", "database", "postgresql" ]
Beginner's Factorial Code
39,003,652
<p>I'm starting to learn Python and I have a small bit of code that takes the factorial of a user input. I'm trying to understand the logic behind what's going on so I can better understand the process. Why is it when I change the location of one of my variables the output changes? (I'm using python 2)</p> <pre><code...
-2
2016-08-17T18:14:04Z
39,003,695
<p>If it is in the loop, that means that each loop iteration, product will be reset to 1. So you end up with the same result as if you ran just the final iteration of the loop. In other words the products don't accumulate.</p>
0
2016-08-17T18:16:58Z
[ "python" ]
Beginner's Factorial Code
39,003,652
<p>I'm starting to learn Python and I have a small bit of code that takes the factorial of a user input. I'm trying to understand the logic behind what's going on so I can better understand the process. Why is it when I change the location of one of my variables the output changes? (I'm using python 2)</p> <pre><code...
-2
2016-08-17T18:14:04Z
39,003,702
<p>That's because every time the for loop runs, you're setting:</p> <p>product = 1</p>
0
2016-08-17T18:17:25Z
[ "python" ]
Beginner's Factorial Code
39,003,652
<p>I'm starting to learn Python and I have a small bit of code that takes the factorial of a user input. I'm trying to understand the logic behind what's going on so I can better understand the process. Why is it when I change the location of one of my variables the output changes? (I'm using python 2)</p> <pre><code...
-2
2016-08-17T18:14:04Z
39,003,724
<p>product is reset to 1 in every iteration of the loop.</p>
0
2016-08-17T18:18:06Z
[ "python" ]
Beginner's Factorial Code
39,003,652
<p>I'm starting to learn Python and I have a small bit of code that takes the factorial of a user input. I'm trying to understand the logic behind what's going on so I can better understand the process. Why is it when I change the location of one of my variables the output changes? (I'm using python 2)</p> <pre><code...
-2
2016-08-17T18:14:04Z
39,003,743
<p>By putting</p> <pre><code>product = 1 </code></pre> <p>inside the loop, you are re-initializing the total value each iteration of the loop.</p> <p>If the user were to enter 3, It would show <code>1, 2, 3</code> because every iteration you are just creating a variable product with the value of 1, and multiplying ...
1
2016-08-17T18:19:07Z
[ "python" ]
Beginner's Factorial Code
39,003,652
<p>I'm starting to learn Python and I have a small bit of code that takes the factorial of a user input. I'm trying to understand the logic behind what's going on so I can better understand the process. Why is it when I change the location of one of my variables the output changes? (I'm using python 2)</p> <pre><code...
-2
2016-08-17T18:14:04Z
39,003,769
<p>The loop works like this:</p> <pre><code>user_input = input("enter a positive number") for i in range(user_input): product = 1 #Set product to 1 product = product * (i + 1) #Increase product print(product) #Print the product </code></pre> <p>Every loop the value of <cod...
1
2016-08-17T18:21:45Z
[ "python" ]
Beginner's Factorial Code
39,003,652
<p>I'm starting to learn Python and I have a small bit of code that takes the factorial of a user input. I'm trying to understand the logic behind what's going on so I can better understand the process. Why is it when I change the location of one of my variables the output changes? (I'm using python 2)</p> <pre><code...
-2
2016-08-17T18:14:04Z
39,003,782
<p>this isnt going to answer your question ... but I find factorial is easiest to think about recursively </p> <pre><code>def factorial(n): #base case if n is 0 or 1 : 0! == 1! = 1 if n in (1,0): return 1 #recursive case : otherwise n! == n*(n-1)! return n*factorial(n-1) </code></pre>
1
2016-08-17T18:22:35Z
[ "python" ]
Beginner's Factorial Code
39,003,652
<p>I'm starting to learn Python and I have a small bit of code that takes the factorial of a user input. I'm trying to understand the logic behind what's going on so I can better understand the process. Why is it when I change the location of one of my variables the output changes? (I'm using python 2)</p> <pre><code...
-2
2016-08-17T18:14:04Z
39,003,787
<p>I think this is what you want to do. </p> <pre><code>user_input = int(input("enter a positive number")) product = 1 for i in range(user_input): product = product * (i + 1) print(product) </code></pre> <p>But when you put <strong>product = 1</strong> into loop, every time loop start with product =1 wh...
0
2016-08-17T18:22:42Z
[ "python" ]
AWS - OS Error permission denied Lambda Script
39,003,668
<p>I'm trying to execute a Lambda Script in Python with an imported library, however I'm getting permission errors. I am also getting some alerts about the database, but database queries are called after the subprocess so I don't think they are related. Could someone explain why do I get error?</p> <p>Alert informatio...
0
2016-08-17T18:15:12Z
39,023,870
<p>I'm fairly certain that this is a restriction imposed by the lambda execution environment, but it can be worked around by executing the script through the shell.<br> Try providing shell=True to your subprocess call:</p> <pre><code>xml_output = subprocess.check_output(["./mediainfo", "--full", "--output=XML", signed...
1
2016-08-18T17:07:58Z
[ "python", "amazon-web-services", "aws-lambda" ]
cp: cannot stat ‘/mnt/ask78b30/TEST_FILE’: Remote I/O error
39,003,801
<p>I am copying a file to nfs mounted dir. When I run the following command manually, the file is successfully copied</p> <p>sudo cp TEST_FILE /mnt/ask78b30</p> <p>However, when I use the same command in a python script, I get the following error,</p> <p>running cmd = sudo cp TEST_FILE /mnt/ask78b30</p> <p>cp: ca...
1
2016-08-17T18:23:32Z
39,003,862
<p>I would recommend to use pythons shutil to copy files instead of calling cp</p> <pre><code>from shutil import copyfile copyfile(src, dst) </code></pre>
0
2016-08-17T18:27:10Z
[ "python", "linux", "shell", "mount", "cp" ]
How to find a word inside a list and search backwards from that word?
39,003,837
<p>How can I search for a specific word inside a list? Once I have searched for that specific word, how can I search backwards from there? In my example, I need to search for the city, and then search backwards to find the street type (ex: Rd, St, Ave, etc.)</p> <p>I first allow a user to input an address, like <em>12...
1
2016-08-17T18:25:14Z
39,004,104
<pre><code>for items in address: if searchWord in items: for each in reversed(address[0:address.index(searchWord)]): if each == 'St': print each </code></pre> <p>Once you find the city, reverse traverse the list using reversed</p>
0
2016-08-17T18:43:31Z
[ "python", "list" ]
How to find a word inside a list and search backwards from that word?
39,003,837
<p>How can I search for a specific word inside a list? Once I have searched for that specific word, how can I search backwards from there? In my example, I need to search for the city, and then search backwards to find the street type (ex: Rd, St, Ave, etc.)</p> <p>I first allow a user to input an address, like <em>12...
1
2016-08-17T18:25:14Z
39,004,149
<p>You can use <code>list.index</code> method to search the index of an item in a list.</p> <p>There is no <code>list.rindex</code> method to search backward. You need to use:</p> <pre><code>rev_idx = len(my_list) - my_list[::-1].index(item) - 1 </code></pre> <p>I don't really understand what’s your aim, be I can ...
0
2016-08-17T18:46:17Z
[ "python", "list" ]
passing arguments when scheduling a function with asyncio/aiocron
39,003,853
<p>I am using the <code>aiocron</code> library to schedule function calls for certain times of day. This is a minimal example of what I want to do. In this example, I want to send a "good morning" message every day at 8:00</p> <pre><code>class GoodMorningSayer: @asyncio.coroutine def send_message(text)...
1
2016-08-17T18:26:12Z
39,005,726
<p>I solved this myself for now by using a closure:</p> <pre><code>class GoodMorningSayer: def __init__(self): @aiocron.crontab("0 8 * * *") @asyncio.coroutine def on_morning() yield from self.send_message("good morning!") @asyncio.coroutine def send_message(text...
0
2016-08-17T20:29:15Z
[ "python", "python-3.x", "python-asyncio" ]
Django encoding problems with CSV
39,003,878
<p>File export works well, but I have a problem with encoding data. Where I made ​​mistakes?</p> <p>My code is </p> <pre><code>for user in users: result = user[0].encode('utf-8') for x in filter(lambda q: q is not None, user): result += ', ' if type(x) in (str, unicode): resul...
-4
2016-08-17T18:28:36Z
39,005,251
<p>The .encode method gets applied to a Unicode string to make a byte-string; if your CSV data is NOT in utf-8, and instead encoded let's say in latin-1, then you need a "transcoding". Something like this:</p> <pre><code>line.decode('latin-1').encode('utf-8') </code></pre> <p>if you know your CSV encoding, then repla...
0
2016-08-17T19:58:28Z
[ "python", "django", "csv", "encoding", "decoding" ]
Django registration | change behaviour
39,003,883
<p>After succesfully registering, the user is redirected to the template 'registration_done.html'.</p> <p>Is there any way of changing this behaviour to redirecting the user to the registration page and displaying a message?</p> <p>I tried these code below also tried different ways to change it but have different typ...
1
2016-08-17T18:28:48Z
39,013,555
<p>You are trying to pass the kwarg <code>success_url</code> to your function <code>register</code></p> <p>Your function <code>register(request)</code> only accepts one argument: 'request'.</p> <p>So you can accept a second argument, say success_url, like so</p> <pre><code>def register(request, success_url): ......
1
2016-08-18T08:40:11Z
[ "python", "django", "python-3.x", "django-views", "django-1.9" ]
Can't find TF_MIN_GPU_MULTIPROCESSOR_COUNT
39,003,909
<p>I get a message that says my GPU Device is ignored because its multiprocessor count is lower than the minimum set. However, it gives me the environment variable <em>TF_MIN_GPU_MULTIPROCESSOR_COUNT</em> but it doesn't seem to exist because I keep getting command not found. When I look at the environment variables usi...
0
2016-08-17T18:30:17Z
39,004,702
<p>Do something like this before running your main script <code>export TF_MIN_GPU_MULTIPROCESSOR_COUNT=4</code> </p> <p>Note though that the default is set for a reason -- if you enable slower GPU by changing that variable, your program may run slower than it would without any GPU available, because TensorFlow will tr...
0
2016-08-17T19:23:29Z
[ "python", "tensorflow", "gpu" ]
Joining elements in list in python
39,003,982
<p>I have the data below, I want to find the unique values in 'a' and sum the data for the corresponding indices from 'b', 'c'. Any ideas on the best way to do this? I'm not sure where to start.</p> <pre><code>a = ['x', 'y', 'z', 'z', 'x', 'w'] b = [ 1, 4, 5, 7, 9, 5] c = [ 3, 6, 7, 8, 9, 7] </code...
2
2016-08-17T18:35:05Z
39,004,173
<p>Use <code>collections.defaultdict</code>:</p> <pre><code>from collections import defaultdict a = ['x', 'y', 'z', 'z', 'x', 'w'] b = [ 1, 4, 5, 7, 9, 5] c = [ 3, 6, 7, 8, 9, 7] b_unique = collections.defaultdict(int) c_unique = collections.defaultdict(int) for k, bv, cv in zip(a,b,c): b_uni...
2
2016-08-17T18:48:08Z
[ "python", "list" ]
Joining elements in list in python
39,003,982
<p>I have the data below, I want to find the unique values in 'a' and sum the data for the corresponding indices from 'b', 'c'. Any ideas on the best way to do this? I'm not sure where to start.</p> <pre><code>a = ['x', 'y', 'z', 'z', 'x', 'w'] b = [ 1, 4, 5, 7, 9, 5] c = [ 3, 6, 7, 8, 9, 7] </code...
2
2016-08-17T18:35:05Z
39,004,178
<p>Could do something like this using <a href="https://docs.python.org/3/library/collections.html#ordereddict-objects" rel="nofollow">OrderedDict</a>, since you need to maintain the same order:</p> <pre><code>from collections import OrderedDict a = ['x', 'y', 'z', 'z', 'x', 'w'] b = [ 1, 4, 5, 7, 9, 5] c = ...
4
2016-08-17T18:48:27Z
[ "python", "list" ]
Joining elements in list in python
39,003,982
<p>I have the data below, I want to find the unique values in 'a' and sum the data for the corresponding indices from 'b', 'c'. Any ideas on the best way to do this? I'm not sure where to start.</p> <pre><code>a = ['x', 'y', 'z', 'z', 'x', 'w'] b = [ 1, 4, 5, 7, 9, 5] c = [ 3, 6, 7, 8, 9, 7] </code...
2
2016-08-17T18:35:05Z
39,004,282
<p>Using Pandas:</p> <pre><code>import pandas as pd # To keep original order of values. a_ordered = [val for idx, val in enumerate(a) if val not in a[:idx]] # &gt;&gt;&gt; a_ordered # OUT: ['x', 'y', 'z', 'w'] df = pd.DataFrame({'a': a, 'b': b, 'c': c}).groupby('a').sum().T[a_ordered] a = df.columns.tolist() b, c = ...
2
2016-08-17T18:54:33Z
[ "python", "list" ]
Joining elements in list in python
39,003,982
<p>I have the data below, I want to find the unique values in 'a' and sum the data for the corresponding indices from 'b', 'c'. Any ideas on the best way to do this? I'm not sure where to start.</p> <pre><code>a = ['x', 'y', 'z', 'z', 'x', 'w'] b = [ 1, 4, 5, 7, 9, 5] c = [ 3, 6, 7, 8, 9, 7] </code...
2
2016-08-17T18:35:05Z
39,004,516
<p>Just felt like playing a little code-golf:</p> <pre><code>&gt;&gt;&gt; from collections import OrderedDict &gt;&gt;&gt; od = OrderedDict() &gt;&gt;&gt; for t in zip(a,zip(b,c)): ... od[t[0]] = [i + x for i,x in zip(od.get(t[0],[0,0]), t[1])] ... &gt;&gt;&gt; od OrderedDict([('x', [10, 12]), ('y', [4, 6]), ('z', ...
0
2016-08-17T19:11:55Z
[ "python", "list" ]
Joining elements in list in python
39,003,982
<p>I have the data below, I want to find the unique values in 'a' and sum the data for the corresponding indices from 'b', 'c'. Any ideas on the best way to do this? I'm not sure where to start.</p> <pre><code>a = ['x', 'y', 'z', 'z', 'x', 'w'] b = [ 1, 4, 5, 7, 9, 5] c = [ 3, 6, 7, 8, 9, 7] </code...
2
2016-08-17T18:35:05Z
39,004,728
<p>here is an elementary approach</p> <pre><code>d1 = defaultdict(int) d2 = defaultdict(int) for x,y,z in zip(a,b,c): d1[x] += y d2[x] += z an=list() bn=list() cn=list() for k in sorted(d1.keys(), key=lambda x:a.index(x)): an.append(k) bn.append(d1[k]) cn.append(d2[k]) [an,bn,cn] [['x', 'y', '...
0
2016-08-17T19:24:42Z
[ "python", "list" ]
Data entry in sqlite database
39,004,080
<p>l m a fresh user and l m not good at coding yet. l created a database with 3 columns: <code>(date, station, pcp )</code>. l have <code>41_years_data</code> set and by using a <code>for</code> loop, l would like to insert these data set in database. I could not do it correctly. When l run the code, it gives </p> <pr...
1
2016-08-17T18:41:48Z
39,004,137
<p>Your <code>INSERT</code> statement </p> <pre><code>c.execute("INSERT INTO pcp VALUES(kdm,station,klm)") </code></pre> <p>contains the names of your variables that hold the data values.</p> <p>You need to construct the <code>INSERT</code> statement by concatenating the values inside those variables. Like so. (Mayb...
0
2016-08-17T18:45:39Z
[ "python", "sqlite3" ]
Data entry in sqlite database
39,004,080
<p>l m a fresh user and l m not good at coding yet. l created a database with 3 columns: <code>(date, station, pcp )</code>. l have <code>41_years_data</code> set and by using a <code>for</code> loop, l would like to insert these data set in database. I could not do it correctly. When l run the code, it gives </p> <pr...
1
2016-08-17T18:41:48Z
39,024,054
<p>l solved the problem and it inserted values of date, station and pcp into pcp columns but l had to use range(1000(just for trial number)) for it.is there any suggestion to make my code better?</p> <pre><code>import sqlite3 from sqlite3 import * from datetime import date, datetime, timedelta conn=sqlite3.connect("...
0
2016-08-18T17:20:11Z
[ "python", "sqlite3" ]
In python multi-producer & multi-consumer threading, may queue.join() be unreliable?
39,004,095
<p>A python multi-producer &amp; multi-consumer threading pseudocode:</p> <pre><code>def threadProducer(): while upstreams_not_done: data = do_some_work() queue_of_data.put(data) def threadConsumer(): while True: data = queue_of_data.get() do_other_work() queue_of_data....
1
2016-08-17T18:43:01Z
39,004,610
<p>The usual way is to put a sentinel value (like <code>None</code>) on the queue, one for each consumer thread, when producers are done. Then consumers are written to exit the thread when it pulls <code>None</code> from the queue.</p> <p>So, e.g., in the main program:</p> <pre><code>for t in list_of_producers: ...
1
2016-08-17T19:18:13Z
[ "python", "multithreading", "queue" ]
Python-Using character exclusion and quantifiers in a lookbehind to ignore characters if they exist
39,004,117
<p>Want to be able to grab a string with regex that is able to grab values regardless of whether or not something exists in a lookbehind. E.g. the two strings below</p> <pre><code> string_1 = "this('isastring', 'secondstring')" string_2 = "this(\\'issomeotherstring\\', \\'ADiffSecondString\\') </code></pre> <p...
0
2016-08-17T18:44:35Z
39,004,297
<p>If by "grab", you mean find all strings, you can do as follow:</p> <pre><code>string_1 = "this('isastring', 'secondstring')" string_2 = "this(\\'issomeotherstring\\', \\'ADiffSecondString\\')" import re findall_str = re.compile(r"\\?'(.*?)\\?'").findall print(findall_str(string_1)) print(findall_str(string_2)) <...
0
2016-08-17T18:55:31Z
[ "python", "regex" ]
Most efficient way to turn dictionary into symmetric/distance matrix (Python | Pandas)
39,004,152
<p>I'm doing pairwise distance for something w/ a weird distance metric. I have a dictionary like <code>{(key_A, key_B):distance_value}</code> and I want to make a symmetric <code>pd.DataFrame</code> like a distance matrix. </p> <p>What is the most efficient way to do this? I found one way but it doesn't seem like t...
2
2016-08-17T18:46:29Z
39,004,744
<p>You can use <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.squareform.html#scipy.spatial.distance.squareform"><code>scipy.spatial.distance.squareform</code></a>, which converts a vector of distance computations, i.e. <code>[d(A,B), d(A,C), ..., d(C,D)]</code>, into the dis...
7
2016-08-17T19:25:55Z
[ "python", "pandas", "numpy", "matrix", "distance" ]
Most efficient way to turn dictionary into symmetric/distance matrix (Python | Pandas)
39,004,152
<p>I'm doing pairwise distance for something w/ a weird distance metric. I have a dictionary like <code>{(key_A, key_B):distance_value}</code> and I want to make a symmetric <code>pd.DataFrame</code> like a distance matrix. </p> <p>What is the most efficient way to do this? I found one way but it doesn't seem like t...
2
2016-08-17T18:46:29Z
39,005,028
<p>Given a dictionary of keys (of single characters) and distances, here's a NumPy based approach -</p> <pre><code>def dict2frame(D_pair_value): # Extract keys and values k = np.array(D_pair_value.keys()) v = np.array(D_pair_value.values()) # Get row, col indices from keys idx = (np.fromstring(k.t...
1
2016-08-17T19:43:38Z
[ "python", "pandas", "numpy", "matrix", "distance" ]
Command failed: ./distribute.sh -l
39,004,228
<p>I am trying to follow the instructions on <a href="https://kivy.org/docs/guide/packaging-android-vm.html" rel="nofollow">https://kivy.org/docs/guide/packaging-android-vm.html</a> to create kivy android applications. I installed Kivy Buildozer VM and was following instructions on the Readme file. Created the buildoze...
0
2016-08-17T18:51:17Z
39,004,764
<p>As you can see here <a href="https://github.com/kivy/python-for-android/blob/master/distribute.sh" rel="nofollow">python-for-android</a> the distribute.sh file is not supposed to be used anymore. <a href="http://buildozer.readthedocs.io/en/latest/quickstart.html" rel="nofollow">Here</a> you have a guide how to use <...
0
2016-08-17T19:27:12Z
[ "android", "python", "kivy" ]
Command failed: ./distribute.sh -l
39,004,228
<p>I am trying to follow the instructions on <a href="https://kivy.org/docs/guide/packaging-android-vm.html" rel="nofollow">https://kivy.org/docs/guide/packaging-android-vm.html</a> to create kivy android applications. I installed Kivy Buildozer VM and was following instructions on the Readme file. Created the buildoze...
0
2016-08-17T18:51:17Z
39,436,346
<p>If you get this error in the Kivy Android Build Image you should update buildozer like this:</p> <p>1.type</p> <pre><code>sudo pip install -U buildozer </code></pre> <p>2. delete the .buildozer folder in your app folder</p> <p>The sudo password for this image is kivy123</p> <ol start="3"> <li><p>type </p> <pre...
0
2016-09-11T12:58:48Z
[ "android", "python", "kivy" ]
List of dictionaries to csv file without square brackets
39,004,283
<pre><code>with open('processedData/file.tsv', 'wb') as f: dict_writer = csv.DictWriter(f, keys, delimiter = '\t') dict_writer.writeheader() dict_writer.writerows(hgnc_list) </code></pre> <p>By executing the above code, I'm successfully writing my list of dictionaries to a file. </p> <p><code>The catch is...
0
2016-08-17T18:54:36Z
39,004,366
<p>The <code>csv</code> module (and CSV files in general) don't handle things like list entries in any special way. If you want to put a list into a CSV entry, you need to explicitly convert your values to strings, store the string values, and then parse them back into lists yourself when you read the data.</p> <p>Fo...
1
2016-08-17T19:00:32Z
[ "python", "list", "csv", "dictionary" ]
Tensorflow loss not changing and also computed gradients and applied batch norm but still loss is not changing?
39,004,303
<p>My Tensorflow loss is not changing. This is my code.</p> <pre><code>from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np import math import os import nltk import random import tflearn batch_size = 100 start = 0 end =...
1
2016-08-17T18:56:00Z
39,006,053
<p>You can get all variables in the current graph by using <code>tf.all_variables()</code>. This will give a list of all variables as variable objects, and you can find what you are looking for by using <code>variable.name()</code> to identify a variable. You should also go and name all of the variables you are interes...
0
2016-08-17T20:50:54Z
[ "python", "numpy", "machine-learning", "neural-network", "tensorflow" ]
Chaining filters for a Series
39,004,336
<p>It's convenient to <a href="http://stackoverflow.com/a/28159296/336527">chain filters on a DataFrame using query</a>:</p> <pre><code># quoting from the SO answer above df = pd.DataFrame( np.random.randn(30,3), columns = ['a','b','c']) df_filtered = df.query('a&gt;0').query('0&lt;b&lt;2') </code></pre> <p>What if I...
2
2016-08-17T18:58:10Z
39,004,359
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_frame.html" rel="nofollow">to_frame()</a> method:</p> <pre><code>In [10]: df.groupby('a').b.sum().to_frame('v').query('v &gt; 3').query('v % 3 == 1') Out[10]: v a 1 7 </code></pre> <p>if you need result as series:</p> ...
3
2016-08-17T18:59:59Z
[ "python", "python-3.x", "pandas", "dataframe" ]
Mock entire python class
39,004,540
<p>I'm trying to make a simple test in python, but I'm not able to figure it out how to accomplish the mocking process.</p> <p>This is the class and def code:</p> <pre><code>class FileRemoveOp(...) @apply_defaults def __init__( self, source_conn_keys, source_conn_id='conn_d...
3
2016-08-17T19:13:33Z
39,004,889
<p>First it is very important to understand that you always need to Mock where it the thing you are trying to mock out is used as stated in the <code>unittest.mock</code> documentation.</p> <blockquote> <p>The basic principle is that you patch where an object is looked up, which is not necessarily the same place a...
4
2016-08-17T19:34:26Z
[ "python", "unit-testing", "magicmock" ]
How to display percentage label in histogram plot in Python
39,004,606
<p>I managed to create a plot that shows the number of records per class label for each age in my Pandas dataframe. But I would also like to see a percentage label for the "non functional" class in each age group.</p> <p>The Python code for the graph is</p> <pre><code>train['age_wpt'] = train.date_recorded.str.split(...
0
2016-08-17T19:18:02Z
39,004,677
<blockquote> <p>normed : boolean, optional If <code>True</code>, the first element of the return tuple will be the counts normalized to form a probability density, i.e., <code>n/(len(x)`dbin)</code>, i.e., the integral of the histogram will sum to 1. If <em>stacked</em> is also <em>True</em>, ...
0
2016-08-17T19:22:04Z
[ "python", "matplotlib" ]
Google Cloud Storage API write files with special characters vs regular python files
39,004,673
<p>I am using Google App Engine to write a new file to a Google Cloud Storage bucket for eventual serving in the browser. Normally on my local computer this writes a nice text file which I can open and see the test character as expected:</p> <pre><code>with open('new_file.txt', 'w') as f: f.write(u'é'.encode('utf...
1
2016-08-17T19:21:36Z
39,005,315
<p>The default charset for HTTP 1.1 is ISO-8859-1.</p> <p>If you want the browser to interpret your text as UTF-8, you should set the content-type header to include the charset, like this:</p> <pre><code>with gcs.open('/mybucket/newfile.txt', 'w', content_type='text/html; charset=utf-8') as f: </code></pre>
1
2016-08-17T20:02:20Z
[ "python", "google-app-engine", "character-encoding", "google-cloud-storage", "google-cloud-platform" ]
pd.read_sql unicode types causing problems
39,004,686
<p>I'm formatting some data I'm pulling from a database using sqlalchemy, pyodbc, and pandas read_sql, which I get back as a dataframe <code>df</code>.</p> <p>I want to apply a formatting of the data in each 'cell' of the dataframe, row by row and excluding the first two columns using this: </p> <pre><code>df.iloc[6...
0
2016-08-17T19:22:33Z
39,007,144
<p>You're trying to do string formatting for a <code>float</code>, but you're actually passing it a string.</p> <p>To illustrate the source of your error, consider the following:</p> <pre><code>'{:,.2f}%'.format(u'1') </code></pre> <p>which raises the same error:</p> <pre><code>-------------------------------------...
1
2016-08-17T22:21:10Z
[ "python", "python-2.7", "pandas" ]
Custom sorting in Python
39,004,687
<p>I'm new to Python, thus the question,</p> <p>I have the following list of list items,</p> <pre><code>[[0, 1], [2,3], [1,2], [4, 5], [3, 5]] </code></pre> <p>I want to sort this list in increasing order comparing the second item of each list first and then the first item</p> <p>This is my code,</p> <pre><code>de...
1
2016-08-17T19:22:34Z
39,004,792
<p>You should use Python's built-in <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> method, it already has support for lambda comparisons.</p> <pre><code>l = [[0, 1], [2,3], [1,2], [4, 5], [3, 5]] l = sorted(l, cmp=sorting) </code></pre> <p>Your comparison fu...
1
2016-08-17T19:28:34Z
[ "python", "lambda" ]
Custom sorting in Python
39,004,687
<p>I'm new to Python, thus the question,</p> <p>I have the following list of list items,</p> <pre><code>[[0, 1], [2,3], [1,2], [4, 5], [3, 5]] </code></pre> <p>I want to sort this list in increasing order comparing the second item of each list first and then the first item</p> <p>This is my code,</p> <pre><code>de...
1
2016-08-17T19:22:34Z
39,004,861
<p>You can reverse the order when the sort looks at them. Just don't alter the original list items.</p> <p>sorted(l, key=lambda x: (x[1], x[0]))</p>
2
2016-08-17T19:32:17Z
[ "python", "lambda" ]
simple matrix type rotation (without numpy or pandas)
39,004,701
<p>This must be something that is really simple, but I could not fix it.</p> <p>I want to do a matrix type transpose with native python list of list (i.e., without using <code>numpy</code> or <code>pandas</code>). Code is show following. I am having a hard time trying to figure out where it is wrong.</p> <pre><code>r...
0
2016-08-17T19:23:24Z
39,004,809
<p>Well, doing a transpose with vanilla lists in Python is pretty easy: use <code>zip</code> and the splat operator:</p> <pre><code>&gt;&gt;&gt; raw_matrix_list = [[1, 0, 1, 0, 1, 0], ... [1, 0, 0, 0, 1, 0], ... [0, 0, 0, 0, 0, 1], ... [1, 0, 0, 0, 1, 1]] &gt;&g...
2
2016-08-17T19:29:23Z
[ "python" ]