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
Get all active campaigns from facebook ads api - how to set the filter
39,771,522
<p>I would like to get insights of all my active campaigns running on Facebook Ads. I manage to get all campaigns with FacebookAdsApi on my account but i am not able to use a filter so i only get campaigns with the "ACTIVE" status. </p> <p>Here is my code so far:</p> <pre><code>from facebookads.api import FacebookAds...
0
2016-09-29T13:21:44Z
39,855,389
<p>This is a common issue with insights queries. When working with lot of data (lot of campaigns, lot of days or both) you can easily run into described error.</p> <p><a href="https://developers.facebook.com/docs/marketing-api/insights/overview/v2.7" rel="nofollow">FB docs</a> say:</p> <blockquote> <p>There is no e...
1
2016-10-04T14:49:22Z
[ "python", "facebook-graph-api", "facebook-ads-api" ]
Visual C++ for python failed with exit status 2 when installing divisi2
39,771,592
<p>i am using Python 2.7 on Windows 8.1 46 bit.</p> <p>I want to install divisi2 <a href="https://pypi.python.org/pypi/Divisi2/2.2.5" rel="nofollow">https://pypi.python.org/pypi/Divisi2/2.2.5</a></p> <p>I have installed NumPy and SciPy which are the pre-requisites for divisi2 already. I have installed Visual C++ for ...
0
2016-09-29T13:24:36Z
39,786,213
<p>I finally solved this problem after getting this hint from a colleague i.e. to use</p> <p><a href="https://github.com/develersrl/gccwinbinaries" rel="nofollow">https://github.com/develersrl/gccwinbinaries</a>.</p> <p>This will install the requisites and then you can install divisi2.</p>
0
2016-09-30T07:42:07Z
[ "python", "pip" ]
Django template showing \u200e code
39,771,702
<p>Hey guys I am beyond frustrated/exhausted trying to fix this unicode code \u200e showing in my web page. I tried everything I can think of. Here is what my page looks like, its data scraped articles from news.google.com and shown on my page with the time submission (the time submission is where the \u200e pops up ev...
1
2016-09-29T13:29:18Z
39,772,393
<p>If you want, you can use <code>replace()</code> to strip the character from your string.</p> <pre><code>b = articles_times.text.replace('\u200E', '') </code></pre> <p>The reason that you see <code>\u200E</code> in the rendered html instead of <code>&amp;lrm;</code> is that you are including the tuple <code>{{ thef...
1
2016-09-29T13:58:06Z
[ "javascript", "python", "django" ]
How to set up different desktop launchers for anaconda spyder using conda environments?
39,771,849
<p>I have created a virtual machine for use in an upcoming data science lecture. I installed CentOS minimal into Virtualbox and included an XFCE desktop. I have also installed two analytic stack python versions (2.7, 3.5) using Anaconda mini and the conda environment manager. </p> <p>I set up another environment in ad...
0
2016-09-29T13:35:43Z
39,799,876
<p>After a bit of research, I figured out my issue. </p> <p>I needed to create a *.desktop file with the following contents:</p> <pre><code>[Desktop Entry] Version=1.0 Type=Application Name=Spyder py3 Comment= Exec=xfce4-terminal -e "bash -c 'cd /home/user1/anaconda/bin;source activate py3ds;spyder'" Icon= Path= Term...
0
2016-09-30T20:49:55Z
[ "python", "linux", "anaconda", "spyder", "conda" ]
Scraping: add data stored as a picture to CSV file in python 3.5
39,771,874
<p>For this project, I am scraping data from a database and attempting to export this data to a spreadsheet for further analysis. (Previously posted <a href="http://stackoverflow.com/questions/39762565/export-beautifulsoup-scraping-results-to-csv-scrape-include-image-values-in-c">here</a>--thanks for the help over ther...
2
2016-09-29T13:37:07Z
39,778,495
<p>This snippet will print the name of the elected person:</p> <pre><code>from bs4 import BeautifulSoup import requests req = requests.get("http://www.elections.ca/WPAPPS/WPR/EN/NC/Details?province=-1&amp;distyear=2013&amp;district=-1&amp;party=-1&amp;selectedid=8548") page_source = BeautifulSoup(req.text, "html.pars...
2
2016-09-29T19:28:01Z
[ "python", "csv", "web-scraping", "beautifulsoup", "python-3.5" ]
How to extract arrays from an arranged numpy array?
39,771,934
<p>This is a relative question of the post <a href="http://stackoverflow.com/questions/39673377/how-to-extract-rows-from-an-numpy-array-based-on-the-content/39674145?noredirect=1#comment66837793_39674145">How to extract rows from an numpy array based on the content?</a>, and I used the following code to split rows base...
1
2016-09-29T13:39:35Z
39,772,874
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains functionality to efficiently perform these type of operations:</p> <pre><code>import numpy_indexed as npi npi.group_by(a[:, :2]).split(a) </code></pre> <p>It has de...
0
2016-09-29T14:19:13Z
[ "python", "arrays", "numpy" ]
How to extract arrays from an arranged numpy array?
39,771,934
<p>This is a relative question of the post <a href="http://stackoverflow.com/questions/39673377/how-to-extract-rows-from-an-numpy-array-based-on-the-content/39674145?noredirect=1#comment66837793_39674145">How to extract rows from an numpy array based on the content?</a>, and I used the following code to split rows base...
1
2016-09-29T13:39:35Z
39,774,794
<p>If I apply that split line directly to your array I get your result, an empty array plus the original</p> <pre><code>In [136]: np.split(a,np.unique(a[:,1],return_index=True)[1][1:]) Out[136]: [array([], shape=(0, 3), dtype=int32), array([[2748309, 246211, 1], [2748309, 246211, 2], [...
0
2016-09-29T15:49:07Z
[ "python", "arrays", "numpy" ]
How to extract arrays from an arranged numpy array?
39,771,934
<p>This is a relative question of the post <a href="http://stackoverflow.com/questions/39673377/how-to-extract-rows-from-an-numpy-array-based-on-the-content/39674145?noredirect=1#comment66837793_39674145">How to extract rows from an numpy array based on the content?</a>, and I used the following code to split rows base...
1
2016-09-29T13:39:35Z
39,776,641
<p>Here's an approach considering pair of elements from each row as indexing tuples -</p> <pre><code># Convert to linear index equivalents lidx = np.ravel_multi_index(arr[:,:2].T,arr[:,:2].max(0)+1) # Get sorted indices of lidx. Using those get shifting indices. # Split along sorted input array along axis=0 using tho...
1
2016-09-29T17:34:32Z
[ "python", "arrays", "numpy" ]
File handling in Python for beginners
39,771,972
<p>Hello I am new to python and I am encountering this error :</p> <blockquote> <p>C:\Users\Dylan Galea\Desktop\Modelling and CS>python file_handling.py</p> <p>File "file_handling.py", line 4</p> <p>np.savetxt(\Users\Dylan Galea\Desktop\Modelling and </p> <p>CS\test.txt,twoDarray,delimeter='\t') ...
0
2016-09-29T13:41:05Z
39,772,071
<p>Please use the code-syntax of stackoverflow so we can read your code easier.</p> <p>It seems like you spelled <code>delimiter</code> wrong.</p>
0
2016-09-29T13:44:51Z
[ "python", "file", "numpy" ]
File handling in Python for beginners
39,771,972
<p>Hello I am new to python and I am encountering this error :</p> <blockquote> <p>C:\Users\Dylan Galea\Desktop\Modelling and CS>python file_handling.py</p> <p>File "file_handling.py", line 4</p> <p>np.savetxt(\Users\Dylan Galea\Desktop\Modelling and </p> <p>CS\test.txt,twoDarray,delimeter='\t') ...
0
2016-09-29T13:41:05Z
39,772,092
<p>Hi and welcome to StackOverflow. Please use the tools StackOverflow provides to properly structure your post (e.g. mark code etc.) and make sure the indentation and newlines of the Python code is correct since it's part of the syntax. </p> <p>Regarding the question it's probably an issue with your path which is not...
0
2016-09-29T13:45:42Z
[ "python", "file", "numpy" ]
File handling in Python for beginners
39,771,972
<p>Hello I am new to python and I am encountering this error :</p> <blockquote> <p>C:\Users\Dylan Galea\Desktop\Modelling and CS>python file_handling.py</p> <p>File "file_handling.py", line 4</p> <p>np.savetxt(\Users\Dylan Galea\Desktop\Modelling and </p> <p>CS\test.txt,twoDarray,delimeter='\t') ...
0
2016-09-29T13:41:05Z
39,772,121
<p>Your file name should be a string.</p> <pre><code>np.savetxt(r'\Users\Dylan Galea\Desktop\Modelling and CS\test.txt',twoDarray,delimeter='\t') </code></pre>
0
2016-09-29T13:46:36Z
[ "python", "file", "numpy" ]
Is it possible to include interpreter path (or set any default code) when I create new python file in Pycharm?
39,771,998
<p>I haven't been able to find anything and I am not sure if this is the place I should be asking... </p> <p>But I want to include the path to my interpreter in every new project I create. The reason being is that I develop locally and sync my files to a linux server. It is annoying having to manually type <code>#! ...
0
2016-09-29T13:42:07Z
39,772,172
<p>Click on the top-right tab with your project name, then go <code>Edit Configurations</code> and there you can change the interpreter.</p>
0
2016-09-29T13:49:11Z
[ "python", "linux", "pycharm" ]
Is it possible to include interpreter path (or set any default code) when I create new python file in Pycharm?
39,771,998
<p>I haven't been able to find anything and I am not sure if this is the place I should be asking... </p> <p>But I want to include the path to my interpreter in every new project I create. The reason being is that I develop locally and sync my files to a linux server. It is annoying having to manually type <code>#! ...
0
2016-09-29T13:42:07Z
39,772,630
<p>You should open <strong>File</strong> in the main menu and click <strong>Default Settings</strong>, collapse the <strong>Editor</strong> then click <strong>File and Code Templates</strong>, in the <strong>Files</strong> tab click on the <strong>+</strong> sign and create a new <strong>Template</strong>, give the new...
1
2016-09-29T14:07:47Z
[ "python", "linux", "pycharm" ]
tensorflow sequence_loss_by_example weight
39,772,033
<p>I want to make weight tensors for tf.nn.seq2seq.sequence_loss_by_example. I'm using RNN-LSTM with maximum 100 steps, and zero-padded each batch items by maximum steps (100).</p> <p>Shapes of my logits and labels are like this.</p> <pre><code>Tensor("dropout/mul_1:0", shape=(50000, 168), dtype=float32) # logits Ten...
0
2016-09-29T13:43:22Z
39,825,560
<p>Using <a href="http://stackoverflow.com/questions/34128104/tensorflow-creating-mask-of-varied-lengths">tensorflow creating mask of varied lengths</a> and <a href="https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/dynamic_rnn.py" rel="nofollow">https://github.com/aymericdamien...
0
2016-10-03T06:22:31Z
[ "python", "numpy", "tensorflow" ]
Join "colums" of list of lists into "rows" of list of lists
39,772,082
<p>Suppose I have several lists of length n:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] d = [-1, -2, -3] </code></pre> <p>I put those lists into a list:</p> <pre><code>x = [a, b, c] </code></pre> <p>Now I'd like to end up with the following list:</p> <pre><code>y = [[1, 4, 7, -1], [2, 5, 8, -2], [3, ...
1
2016-09-29T13:45:13Z
39,772,156
<p>There is a very simple and pythonic way to "reverse-zip" a list in this way. Simple use the <code>zip</code> function and the unpacking operator <code>*</code>:</p> <pre><code>&gt;&gt;&gt; y = zip(*x) &gt;&gt;&gt; list(y) [(1, 4, 7, -1), (2, 5, 8, -2), (3, 6, 9, -3)] </code></pre> <p>For more information about wha...
3
2016-09-29T13:48:28Z
[ "python" ]
Join "colums" of list of lists into "rows" of list of lists
39,772,082
<p>Suppose I have several lists of length n:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] d = [-1, -2, -3] </code></pre> <p>I put those lists into a list:</p> <pre><code>x = [a, b, c] </code></pre> <p>Now I'd like to end up with the following list:</p> <pre><code>y = [[1, 4, 7, -1], [2, 5, 8, -2], [3, ...
1
2016-09-29T13:45:13Z
39,772,187
<p>You can do it in one line of code:</p> <pre><code>[[z[i] for z in x] for i in range(len(x[0]))] </code></pre> <p>What it does is that to iterate over all indexes (<code>i</code>) and then iterate over all lists in <code>x</code> (<code>z</code>) and create a new list.</p>
3
2016-09-29T13:49:57Z
[ "python" ]
Join "colums" of list of lists into "rows" of list of lists
39,772,082
<p>Suppose I have several lists of length n:</p> <pre><code>a = [1, 2, 3] b = [4, 5, 6] c = [7, 8, 9] d = [-1, -2, -3] </code></pre> <p>I put those lists into a list:</p> <pre><code>x = [a, b, c] </code></pre> <p>Now I'd like to end up with the following list:</p> <pre><code>y = [[1, 4, 7, -1], [2, 5, 8, -2], [3, ...
1
2016-09-29T13:45:13Z
39,772,217
<p>You can try <code>zip</code></p> <pre><code>&gt;&gt;&gt; result = zip(a,b,c,d) # This gives ans as list of tuples [(1, 4, 7, -1), (2, 5, 8, -2), (3, 6, 9, -3)] &gt;&gt;&gt; result_list = [list(elem) for elem in result] #convert list of tuples to list of list &gt;&gt;&gt; result_list [[1, 4, 7, -1], [2, 5, 8, -2], [...
0
2016-09-29T13:51:14Z
[ "python" ]
Get Exceptions from popen in python
39,772,136
<p>I executed this code in python: (test.py)</p> <pre><code>from subprocess import Popen p = Popen("file.bat").wait() </code></pre> <p>Here is file.bat:</p> <pre><code>@echo off start c:\python27\python.exe C:\Test\p1.py %* start c:\python27\python.exe C:\Test\p2.py %* pause </code></pre> <p>Here is p1.py:</p> <pr...
0
2016-09-29T13:47:22Z
39,772,262
<p>Here's how I got it working: <code>test.py</code></p> <pre><code>from subprocess import Popen p = Popen(["./file.sh"]).wait() </code></pre> <p>Make sure to add the <code>[]</code> around file, as well as the <code>./</code>. You can also add arguments, like so: <code>["./file.sh", "someArg"]</code> Note that I am ...
0
2016-09-29T13:53:04Z
[ "python", "subprocess", "popen" ]
How to use SearchVector with multiple fields from a list of strings
39,772,355
<p>I don't have a lot of Python experience and can't figure out how to use a list of strings with the SearchVector functionality described <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/search/#searchvector" rel="nofollow">here</a>. I'm using Django 1.10 with PostgreSQL 9.6 and have verified that ...
0
2016-09-29T13:56:40Z
39,773,528
<p>Expand the list <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">using *</a> and SearchVector will happily search multiple fields. </p> <pre><code>results = targetClass.objects.annotate( search=SearchVector(*searchTargets[key]), ).filter(search=user_query...
0
2016-09-29T14:49:16Z
[ "python", "django", "postgresql" ]
How to extract certain data while filtering out the ones including colspan?
39,772,609
<p>For example:</p> <pre><code>&lt;tbody&gt; &lt;tr&gt;&lt;td colspan="2"&gt;&lt;p&gt;Unwanted Text 1&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;a href="http://www.example.com"&gt;Text 1&lt;/a&gt;&lt;/td&gt; &lt;td&gt;Nonesense 1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;a href="http://www.example2...
2
2016-09-29T14:06:52Z
39,772,694
<p>You can match the <code>a</code> elements directly:</p> <pre><code>for item in soup.select('tr &gt; td &gt; a'): print(item.get_text()) </code></pre> <p>Or, if you specifically want to skip rows with <code>td</code> elements having <code>colspan</code> attributes:</p> <pre><code>for item in soup.select('tr'):...
2
2016-09-29T14:10:46Z
[ "python", "web-scraping", "beautifulsoup" ]
can python classes share variable with parent classe
39,772,625
<p>I have a class named <code>SocialPlatform</code> :</p> <pre><code>class SocialPlatform: nb_post = 0 def __init__(self, data): self.data = data self._init_type() self.id_post = self._init_id_post() @classmethod def _init_id_post(cls): cls.nb_post += 1 return ...
1
2016-09-29T14:07:43Z
39,773,363
<p>You have to explicitly reference the base class in the increment expression:</p> <pre><code>def _init_id_post(cls): cls.nb_post += 1 return cls.nb_post </code></pre> <p>Should be:</p> <pre><code>def _init_id_post(cls): SocialPlatform.nb_post += 1 return SocialPlatform.nb_post </code></pre> <p>As ...
1
2016-09-29T14:41:14Z
[ "python", "inheritance" ]
can python classes share variable with parent classe
39,772,625
<p>I have a class named <code>SocialPlatform</code> :</p> <pre><code>class SocialPlatform: nb_post = 0 def __init__(self, data): self.data = data self._init_type() self.id_post = self._init_id_post() @classmethod def _init_id_post(cls): cls.nb_post += 1 return ...
1
2016-09-29T14:07:43Z
39,773,385
<p>When an attribute is not found, it will be looked up on a higher level. When assigning, the most local level is used though.</p> <p>For example:</p> <pre><code>class Foo: v = 1 a = Foo() b = Foo() print(a.v) # 1: v is not found in "a" instance, but found in "Foo" class Foo.v = 2 # modifies Foo class's "v" pr...
1
2016-09-29T14:42:35Z
[ "python", "inheritance" ]
can python classes share variable with parent classe
39,772,625
<p>I have a class named <code>SocialPlatform</code> :</p> <pre><code>class SocialPlatform: nb_post = 0 def __init__(self, data): self.data = data self._init_type() self.id_post = self._init_id_post() @classmethod def _init_id_post(cls): cls.nb_post += 1 return ...
1
2016-09-29T14:07:43Z
39,773,498
<pre><code> class A(): n = 0 def __init__(self): A.n += 1 class B(A): def __init__(self): super(B, self).__init__() class C(A): def __init__(self): super(C, self).__init__() a = A() print(a.n) #prints 1 b = B() print(a.n) #prints 2 c ...
1
2016-09-29T14:48:10Z
[ "python", "inheritance" ]
can python classes share variable with parent classe
39,772,625
<p>I have a class named <code>SocialPlatform</code> :</p> <pre><code>class SocialPlatform: nb_post = 0 def __init__(self, data): self.data = data self._init_type() self.id_post = self._init_id_post() @classmethod def _init_id_post(cls): cls.nb_post += 1 return ...
1
2016-09-29T14:07:43Z
39,773,608
<p>This works for me:</p> <pre><code>class SocialPlatform(object): nb_post = 0 def __init__(self): self.id_post = A.nb_post A.increment() @classmethod def increment(cls): cls.nb_post += 1 class Facebook(SocialPlatform): pass class Twitter(SocialPlatform): pass </code></pre> <p>And then:</p>...
0
2016-09-29T14:53:41Z
[ "python", "inheritance" ]
Flask return multiple variables?
39,772,670
<p>I am learning Flash with Python. My python skills are okay, but I have no experience with web apps. I have a form that takes some information and I want to display it back after it is submitted. I can do that part, however I can only return one variable from that form even tho there are 3 variables in the form. I ca...
1
2016-09-29T14:09:45Z
39,772,992
<p>Flask requires either a <code>str</code> or <code>Response</code> to be return, in you case you are attempting to return a <code>tuple</code>.</p> <p>You can either return your <code>tuple</code> as a formatted <code>str</code></p> <pre><code>return '{} {} {}'.format(firstname, lastname, cellphone) </code></pre> ...
1
2016-09-29T14:24:14Z
[ "python", "flask" ]
PyQt5: cannot write cookie to file using QFile
39,772,703
<p>I have a file named <em>cookies.txt</em>.</p> <pre><code>fd = QFile(":/cookies.txt") available_cookies = QtNetwork.QNetworkCookieJar().allCookies() for cookie in available_cookies: print(cookie.toRawForm(1)) QTextStream(cookie.toRawForm(1), fd.open(QIODevice.WriteOnly)) fd.close() </code></pre> <p>Here is my...
1
2016-09-29T14:11:29Z
39,773,468
<p>In <code>QTextStream(cookie.toRawForm(1), fd.open(QIODevice.WriteOnly))</code>, you pass 2 arguments, a <code>QByteArray</code>, and a <code>bool</code> (<code>QIODevice::open</code> returns a boolean), but <code>QTextStream</code> cannot take a <code>QByteArray</code> with a <code>bool</code>.</p>
1
2016-09-29T14:46:12Z
[ "python", "qt5", "pyqt5", "qfile", "qtextstream" ]
PyQt5: cannot write cookie to file using QFile
39,772,703
<p>I have a file named <em>cookies.txt</em>.</p> <pre><code>fd = QFile(":/cookies.txt") available_cookies = QtNetwork.QNetworkCookieJar().allCookies() for cookie in available_cookies: print(cookie.toRawForm(1)) QTextStream(cookie.toRawForm(1), fd.open(QIODevice.WriteOnly)) fd.close() </code></pre> <p>Here is my...
1
2016-09-29T14:11:29Z
39,775,150
<p>Are you really trying to write to a resource path? Resources are read-only, so that is not going to work.</p> <p>To write to a non-resource path:</p> <pre><code>fd = QFile('/tmp/cookies.txt') if fd.open(QIODevice.WriteOnly): available_cookies = QtNetwork.QNetworkCookieJar().allCookies() stream = QTextStrea...
0
2016-09-29T16:07:11Z
[ "python", "qt5", "pyqt5", "qfile", "qtextstream" ]
How to centralized ticks and labels in a heatmap matplotlib
39,772,708
<p>I am plotting a heatmap using matplotlib like the figure below:</p> <p><a href="http://i.stack.imgur.com/J8gmT.png" rel="nofollow"><img src="http://i.stack.imgur.com/J8gmT.png" alt="enter image description here"></a></p> <p>The code snip below is used to achive the plot:</p> <pre><code>C_range = 10. ** np.arange(...
0
2016-09-29T14:11:37Z
39,776,012
<p>For your specific code the simplest solution is to shift your tick positions by half a unit separation:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt C_range = 10. ** np.arange(-2, 8) gamma_range = 10. ** np.arange(-5, 4) confMat=np.random.rand(10, 9) heatmap = plt.pcolor(confMat) for y in r...
1
2016-09-29T16:56:32Z
[ "python", "matplotlib", "label", "heatmap" ]
How can be shown manyTomany field values into a single text box in django template
39,772,762
<p>I want to show manytomany field value into a single input textbox in django template. My output is ABC /n Abc /n BVC /n</p> <p>i want like ABC ,Abc,BVC</p> <p>my code sample is this</p> <pre><code> &lt;div class='col-sm-8'&gt; {% for car in cars %}&lt;br/&gt; &lt;input type='text' class='form-control' n...
0
2016-09-29T14:14:34Z
39,774,830
<p>You can do it:</p> <p>from python: (views.py)</p> <pre><code>... data_input = ', '.join([car for car in cars]) ... </code></pre> <p>and in your template:</p> <pre><code> &lt;div class='col-sm-8'&gt; &lt;input type='text' class='form-control' name='cars' placeholder='Select cars' value= "{{ data_input }}"&g...
0
2016-09-29T15:50:40Z
[ "python", "html", "django" ]
Generate pdf files with Weasyprint, save in zip file, send that zip file to client and present it for download
39,772,798
<p>Let me break down my requirement. Here's what I'm doing right now.</p> <p><strong>1. Generate PDF files from HTML</strong></p> <p>for this I'm using Weasyprint as following:</p> <pre><code>lstFileNames = [] for i, content in enumerate(lstHtmlContent): repName = 'report'+ str(uuid.uuid4()) + '.pdf' lstFile...
0
2016-09-29T14:16:14Z
39,773,939
<p>Once you have exited the <code>with</code> block the filehandle is closed. You should reopen the file (this time with open) and use <code>read()</code> to pass the contents to <code>HttpResponse</code> instead of passing the filehandle itself.</p> <pre><code>with zipfile.ZipFile(zipPath, 'w') as myzip for f in ...
0
2016-09-29T15:08:29Z
[ "javascript", "python", "django", "zipfile", "weasyprint" ]
Generate pdf files with Weasyprint, save in zip file, send that zip file to client and present it for download
39,772,798
<p>Let me break down my requirement. Here's what I'm doing right now.</p> <p><strong>1. Generate PDF files from HTML</strong></p> <p>for this I'm using Weasyprint as following:</p> <pre><code>lstFileNames = [] for i, content in enumerate(lstHtmlContent): repName = 'report'+ str(uuid.uuid4()) + '.pdf' lstFile...
0
2016-09-29T14:16:14Z
39,786,958
<p>A slightly different approach would be to move the zip file to a public directory and then send that location to the client (e.g. json formatted), i.e.:</p> <pre><code>publicPath = os.path.join('public/', os.path.basename(zipPath)) os.rename(zipPath, os.path.join('/var/www/', publicPath)) jsonResp = '{ "zip-locati...
1
2016-09-30T08:27:26Z
[ "javascript", "python", "django", "zipfile", "weasyprint" ]
Add prefix to specific columns of Dataframe
39,772,896
<p>I've a DataFrame like that :</p> <pre><code>col1 col2 col3 col4 col5 col6 col7 col8 0 5345 rrf rrf rrf rrf rrf rrf 1 2527 erfr erfr erfr erfr erfr erfr 2 2727 f f f f f f </code></pre> <p>I would like to rename all columns but not...
1
2016-09-29T14:20:07Z
39,772,981
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a> with a regex pattern to filter the cols of interest, then using <code>zip</code> construct a dict and pass this as the arg to <a href="http://pandas.pydata.org/pand...
2
2016-09-29T14:23:47Z
[ "python", "pandas" ]
Add prefix to specific columns of Dataframe
39,772,896
<p>I've a DataFrame like that :</p> <pre><code>col1 col2 col3 col4 col5 col6 col7 col8 0 5345 rrf rrf rrf rrf rrf rrf 1 2527 erfr erfr erfr erfr erfr erfr 2 2727 f f f f f f </code></pre> <p>I would like to rename all columns but not...
1
2016-09-29T14:20:07Z
39,773,021
<p>You can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rename.html" rel="nofollow">DataFrame.rename()</a> method</p> <pre><code>new_names = [(i,i+'_x') for i in df.iloc[:, 2:].columns.values] df.rename(columns = dict(new_names), inplace=True) </code></pre>
4
2016-09-29T14:25:27Z
[ "python", "pandas" ]
Add prefix to specific columns of Dataframe
39,772,896
<p>I've a DataFrame like that :</p> <pre><code>col1 col2 col3 col4 col5 col6 col7 col8 0 5345 rrf rrf rrf rrf rrf rrf 1 2527 erfr erfr erfr erfr erfr erfr 2 2727 f f f f f f </code></pre> <p>I would like to rename all columns but not...
1
2016-09-29T14:20:07Z
39,773,041
<p>Simpliest solution if <code>col1</code> and <code>col2</code> are first and second column names:</p> <pre><code>df.columns = df.columns[:2].union(df.columns[2:] + '_x') print (df) col1 col2 col3_x col4_x col5_x col6_x col7_x col8_x 0 0 5345 rrf rrf rrf rrf rrf rrf 1 1 2527 erfr ...
1
2016-09-29T14:26:30Z
[ "python", "pandas" ]
Longest path in a undirected and unweighted tree - in python
39,773,052
<p>I am solving a problem in which I need to calculate the diameter of the tree.I know how to calculate that using 2 bfs first to find the farthest node then do second bfs using the node we found from the first one.</p> <p>But I am having difficulty to implement a very simple step - making a adjacency list (dict in ...
0
2016-09-29T14:27:07Z
39,773,226
<p>You are using a <strong>0</strong> instead of <strong>o</strong> in makedic in first <em>elif</em> condition. Also made the correction for undirected graph.</p> <pre><code>def makedic(m): d = {} for i in range(m): o, p = map(int, raw_input().split()) if o not in d and p not in d: ...
-1
2016-09-29T14:34:55Z
[ "python", "algorithm" ]
Longest path in a undirected and unweighted tree - in python
39,773,052
<p>I am solving a problem in which I need to calculate the diameter of the tree.I know how to calculate that using 2 bfs first to find the farthest node then do second bfs using the node we found from the first one.</p> <p>But I am having difficulty to implement a very simple step - making a adjacency list (dict in ...
0
2016-09-29T14:27:07Z
39,773,240
<p>There are unnecessary checks in your code. For each <em>A - B</em> edge you just have to put <em>B</em> in <em>A</em>'s adjacency list and <em>A</em> in <em>B</em>'s adjacency list:</p> <pre><code>d = {} for i in range(m): u,v = map(int, raw_input().split()) if u in d: d[u].append(v) else: ...
-1
2016-09-29T14:35:33Z
[ "python", "algorithm" ]
Python unittesting request.get with mocking, not raising specific exception
39,773,061
<p>I have a simple function that sends a get request to an API, and I want to be able to write a Unit test to assert that the scriprt prints an error and then exits if the request returns an exception.</p> <pre><code>def fetch_members(self): try: r = requests.get(api_url, auth=('user', api_key)) except...
-1
2016-09-29T14:27:32Z
39,773,180
<p>Your function catches and handles the exception:</p> <pre><code>except requests.exceptions.HTTPError as error: </code></pre> <p>This means it'll <em>never</em> propagate further, so your <code>assertRaises()</code> fails. Just assert that <code>sys.exit()</code> has been called, that's enough.</p> <p>There is als...
1
2016-09-29T14:32:54Z
[ "python", "unit-testing" ]
HTML snapshots using the selenium webdriver?
39,773,186
<p>I am trying to capture all the visible content of a page as text. Let's say <a href="https://dukescript.com/best/practices/2015/11/23/dynamic-templates.html" rel="nofollow">that</a> one for example.</p> <p>If I store the page source then I won't be capturing the comments section because it's loaded using javascript...
0
2016-09-29T14:33:09Z
39,773,319
<p>This code will take a screenshot of the entire page:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() driver.get('https://dukescript.com/best/practices/2015/11/23/dynamic-templates.html') driver.save_screenshot('screenshot.png') driver.quit() </code></pre> <p>however, if you just want a ...
0
2016-09-29T14:38:51Z
[ "python", "selenium-webdriver", "web-crawler" ]
HTML snapshots using the selenium webdriver?
39,773,186
<p>I am trying to capture all the visible content of a page as text. Let's say <a href="https://dukescript.com/best/practices/2015/11/23/dynamic-templates.html" rel="nofollow">that</a> one for example.</p> <p>If I store the page source then I won't be capturing the comments section because it's loaded using javascript...
0
2016-09-29T14:33:09Z
39,773,670
<p>Regardless of whether or not the HTML of the page is generated using JavaScript, you will still be able to capture it using <code>driver.page_source</code>.</p> <p>I imagine the reason you haven't been able to capture the source of the comments section in your example is because it's contained in an iframe - In ord...
2
2016-09-29T14:56:15Z
[ "python", "selenium-webdriver", "web-crawler" ]
Neural network library for true-false based image recognition
39,773,193
<p>I'm in need of an artificial neural network library (preferably in python) for one (simple) task. I want to train it so that it can tell wether <strong><em>a thing</em></strong> is in an image. I would train it by feeding it lots of pictures and telling it wether it contains the thing I'm looking for or not:</p> <p...
1
2016-09-29T14:33:23Z
39,775,116
<p>There are several good Neural Network approaches in Python, including TensorFlow, Caffe, Lasagne, and <a href="https://scikit-neuralnetwork.readthedocs.io/en/latest/module_mlp.html#classifier" rel="nofollow">sknn</a> (Sci-kit Neural Network). sknn provides an easy, out of the box solution, although in my opinion it ...
2
2016-09-29T16:05:32Z
[ "python", "python-3.x", "boolean", "neural-network", "image-recognition" ]
Neural network library for true-false based image recognition
39,773,193
<p>I'm in need of an artificial neural network library (preferably in python) for one (simple) task. I want to train it so that it can tell wether <strong><em>a thing</em></strong> is in an image. I would train it by feeding it lots of pictures and telling it wether it contains the thing I'm looking for or not:</p> <p...
1
2016-09-29T14:33:23Z
39,777,049
<p>I am unaware of any library which can do this for you. I use a lot of <a href="http://caffe.berkeleyvision.org/" rel="nofollow">Caffe</a> and can give you a solution till you find a single library which can do it for you.</p> <p>I hope you know about <a href="http://www.image-net.org/" rel="nofollow">ImageNet</a> a...
-1
2016-09-29T17:59:30Z
[ "python", "python-3.x", "boolean", "neural-network", "image-recognition" ]
Using rpy2 for inline rmagic with jupyter notebook
39,773,209
<p>I am trying to use inline rmagic with jupyter notebook, but have had an extremely difficult time trying to get it to work. </p> <p>Whenever I try to load <code>%load_ext rpy2.ipython</code>, I get the following error:</p> <pre><code>ImportError: dlopen(/Users/MyName/anaconda/lib/python2.7/site packages/rpy2/rin...
0
2016-09-29T14:34:01Z
39,802,075
<p>This is looking like a conda issue to me (lzma present at build time, but missing at run time).</p> <blockquote> <p>Is there any way to get rpy2 to work with Jupyter notebook these days?</p> </blockquote> <p>Probably more than one way to achieve it, but the docker container mentioned on the front page (<a href="...
0
2016-10-01T01:16:11Z
[ "python", "anaconda", "jupyter-notebook", "rpy2" ]
Python Script in GIS Project
39,773,241
<p>I'm a student in a GIS Programming course. My professor did not inform me before registering that Python experience would be useful. I have no experience with Python and need help on this project. Any examples or clear explanations would be great. Here is the project:</p> <p>Make a copy of the FirDepartment.gdb...
-1
2016-09-29T14:35:36Z
40,080,198
<p>Firstly to install an ArcGIS desktop(trial license is required); The link to get trial license is as below: <a href="http://www.esri.com/software/arcgis/arcgis-for-desktop/free-trial" rel="nofollow">arcgis trial license</a></p> <p>Secondly, click help of ArcGIS desktop to go through the help document of arcPy. As t...
0
2016-10-17T06:57:25Z
[ "python", "gis", "arcgis" ]
pymssql get SQL command - last_executed
39,773,253
<p>I have a python script what isnert data to a MS SQL databse. Part of my code:</p> <pre><code>cursor.execute("INSERT INTO TABLE (COL1, COL2, COL3) VALUES (%s,%s,%s)", (a,b,c)) </code></pre> <p>The a, b and c are variables. I want to print executed SQL command. Is this possible?</p> <p>My goal is log/print every ex...
0
2016-09-29T14:36:03Z
39,773,304
<p>You can try</p> <pre><code>print ("INSERT INTO TABLE (COL1, COL2, COL3) VALUES (%s,%s,%s)", (a,b,c)) </code></pre>
1
2016-09-29T14:38:11Z
[ "python", "insert", "pymssql" ]
Google App Engine & Python
39,773,325
<p>I got a relatively tough one for you today.</p> <p>I'm currently taking a Web Development course online and as a first assignment, we're asked to install and use Google App Engine, which runs on Python 2.7 -- I have Python 3.5 installed on my computer. </p> <p>I tried completing the assignment even though I have t...
0
2016-09-29T14:39:04Z
39,774,073
<p><strong>1&amp;2</strong>: You need to change the application name in the <code>application: hello-udacity</code> line in your <code>app.yaml</code> to match <strong>your real</strong> app name that you obtain when you create your GAE project in the developer console (likely someone else already created an app with t...
1
2016-09-29T15:14:08Z
[ "python", "python-2.7", "python-3.x", "google-app-engine" ]
Merge SPSS variables if they don't exist in the original file, using Python
39,773,328
<p>I have an SPSS file that I am removing unwanted variables from, but want to bring in variables from elsewhere if they don't exist. So, I am looking for some Python code to go into my syntax to say - keep all the variables from a list and if any of these don't exist in the first file, then merge them in from the seco...
2
2016-09-29T14:39:11Z
39,774,890
<p>Here's an apporach to get you started:</p> <pre><code>DATA LIST FREE / ID A B C D E. BEGIN DATA 1 11 12 13 14 15 END DATA. DATASET NAME DS1. DATA LIST FREE / ID D E F G H. BEGIN DATA 1 24 25 26 27 28 END DATA. DATASET NAME DS2. BEGIN PROGRAM PYTHON. import spssaux, spss spss.Submit("dataset activate ds1.") ds1va...
2
2016-09-29T15:53:55Z
[ "python", "merge", "spss" ]
Merge SPSS variables if they don't exist in the original file, using Python
39,773,328
<p>I have an SPSS file that I am removing unwanted variables from, but want to bring in variables from elsewhere if they don't exist. So, I am looking for some Python code to go into my syntax to say - keep all the variables from a list and if any of these don't exist in the first file, then merge them in from the seco...
2
2016-09-29T14:39:11Z
39,777,762
<p>If you just <code>match files</code> regardless of what variables are missing, only the variables that exist in the <code>table</code> and do not exist in the <code>file</code> will be added to the <code>file</code>.<br> Note though you'll have trouble if you have text vars in both files with identical names but dif...
0
2016-09-29T18:42:32Z
[ "python", "merge", "spss" ]
Python multiprocessing - check status of each processes
39,773,377
<p>I wonder if it is possible to check how long of each processes take.<br> for example, there are four workers and the job should take no more than 10 seconds, but one of worker take more than 10 seconds.Is there way to raise a alert after 10 seconds and before process finish the job. <br> My initial thought is using ...
1
2016-09-29T14:41:52Z
39,773,925
<p>I have found this solution time ago (somewhere here in StackOverflow) and I am very happy with it.</p> <p>Basically, it uses <a href="https://docs.python.org/3/library/signal.html" rel="nofollow">signal</a> to raise an exception if a process takes more than expected.</p> <p>All you need to do is to add this class ...
2
2016-09-29T15:07:38Z
[ "python" ]
Python multiprocessing - check status of each processes
39,773,377
<p>I wonder if it is possible to check how long of each processes take.<br> for example, there are four workers and the job should take no more than 10 seconds, but one of worker take more than 10 seconds.Is there way to raise a alert after 10 seconds and before process finish the job. <br> My initial thought is using ...
1
2016-09-29T14:41:52Z
39,773,926
<p>You can check whether process is alive after you tried to join it. Don't forget to set timeout otherwise it'll wait until job is finished. </p> <p>Here is simple example for you </p> <pre><code>from multiprocessing import Process import time def task(): import time time.sleep(5) procs = [] for x in rang...
0
2016-09-29T15:07:40Z
[ "python" ]
python - Pandas - FillNa with another non null row having similar column
39,773,425
<p>I would like to fill missing value in one column with the value of another column.</p> <p>I read that looping through each row would be very bad practice and that it would be better to do everything in one go but I could not find out how to do it with the fillna method.</p> <p>Data Before</p> <pre><code>Day Cat1...
2
2016-09-29T14:44:19Z
39,773,579
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> and pass the df without <code>NaN</code> rows, setting the index to <code>Cat2</code> and then calling <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Ser...
1
2016-09-29T14:51:54Z
[ "python", "pandas", "numpy", "jupyter-notebook" ]
python pandas/numpy quick way of replacing all values according to a mapping scheme
39,773,480
<p>let's say I have a huge panda data frame/numpy array where each element is a list of ordered values:</p> <pre><code>sequences = np.array([12431253, 123412531, 12341234,12431253, 145345], [5463456, 1244562, 23452], [243524, 141234,12431253, 456367], [45...
4
2016-09-29T14:47:21Z
39,773,913
<p>Here's an approach that flattens into a <code>1D</code> array, uses <code>np.unique</code> to assign unique IDs to each element and then splits back into list of arrays -</p> <pre><code>lens = np.array(map(len,sequences)) seq_arr = np.concatenate(sequences) ids = np.unique(seq_arr,return_inverse=1)[1] out = np.spli...
3
2016-09-29T15:07:09Z
[ "python", "pandas", "numpy", "merge" ]
python pandas/numpy quick way of replacing all values according to a mapping scheme
39,773,480
<p>let's say I have a huge panda data frame/numpy array where each element is a list of ordered values:</p> <pre><code>sequences = np.array([12431253, 123412531, 12341234,12431253, 145345], [5463456, 1244562, 23452], [243524, 141234,12431253, 456367], [45...
4
2016-09-29T14:47:21Z
39,774,016
<p><strong><em>Option 1</em></strong><br> Using series definition</p> <pre><code>stop = sequences.sequence.apply(np.size).cumsum() start = end.shift().fillna(0).astype(int) params = pd.concat([start, stop], axis=1, keys=['start', 'stop']) params.apply(lambda x: list(np.arange(**x)), axis=1) 0 [0, 1, 2, 3] 1 ...
2
2016-09-29T15:11:26Z
[ "python", "pandas", "numpy", "merge" ]
Adding a text box to an excel chart using openpyxl
39,773,544
<p>I'm trying to add a text box to a chart I've generated with openpyxl, but can't find documentation or examples showing how to do so. Does openpyxl support it?</p>
0
2016-09-29T14:49:55Z
39,774,351
<p>I'm not sure what you mean by "text box". In theory you can add pretty much anything covered by the DrawingML specification to a chart but the practice may be slightly different.</p> <p>However, there is definitely no built-in API for this so you'd have to start by creating a sample file and working backwards from ...
0
2016-09-29T15:26:08Z
[ "python", "openpyxl" ]
SQLAlchemy: How do you delete multiple rows without querying
39,773,560
<p>I have a table that has millions of rows. I want to delete multiple rows via an in clause. However, using the code:</p> <pre><code>session.query(Users).filter(Users.id.in_(subquery....)).delete() </code></pre> <p>The above code will query the results, and then execute the delete. I don't want to do that. I want ...
4
2016-09-29T14:50:42Z
39,774,354
<p>Yep! You can call <code>delete()</code> on the table object with an associated whereclause. </p> <p>Something like this:</p> <p><code>stmt = Users.__table__.delete().where(Users.id.in_(subquery...))</code></p> <p>(and then don't forget to execute the statement: <code>engine.execute(stmt)</code>)</p> <p><a href="...
4
2016-09-29T15:26:14Z
[ "python", "orm", "sqlalchemy" ]
how to implement smart indent in python as done in Matlab
39,773,564
<p>Is there anyone who know some way to automate the correct indentation in coding in Python? For example, when I write codes as follows:</p> <pre><code>if condition1: print a else: print b </code></pre> <p>Then the codes should be formatted as follows:</p> <pre><code>if condition1: print a else: print b* </...
-3
2016-09-29T14:50:48Z
39,773,805
<p>I would recommend getting <a href="https://atom.io/" rel="nofollow">ATOM</a> it is a great text editor for python. By the way have you tried saving your source file as something.py before you gone ahead and started type in your code? it might be the reason.</p>
1
2016-09-29T15:02:01Z
[ "python", "indentation" ]
how to implement smart indent in python as done in Matlab
39,773,564
<p>Is there anyone who know some way to automate the correct indentation in coding in Python? For example, when I write codes as follows:</p> <pre><code>if condition1: print a else: print b </code></pre> <p>Then the codes should be formatted as follows:</p> <pre><code>if condition1: print a else: print b* </...
-3
2016-09-29T14:50:48Z
39,774,466
<p>I am new to python and doing scientific computing. I really like the <a href="https://www.jetbrains.com/pycharm/" rel="nofollow"> PyCharm IDE</a>. I am using the free community version, and it works great for me.</p> <p>In any case, I believe this is a function of the IDE.</p>
1
2016-09-29T15:31:58Z
[ "python", "indentation" ]
Modifying lines
39,773,601
<p>I'm looking to load a file and modify several predefined lines to certain values. The following is what I tried:</p> <pre><code>with open("test.txt",'w') as f: for i,line in f: if (i == 2): f.writelines(serial1) if (i == 3): ...
0
2016-09-29T14:53:19Z
39,773,654
<p>You open the file for write-only (<code>w</code> mode) and try to read it - which is done by the <code>for</code> statement.</p> <p>That is: iterating over a file with the <code>for</code> statement is done when you are reading the file.</p> <p>If you plan to write to it, <code>for</code> on the fileitself can't h...
1
2016-09-29T14:55:45Z
[ "python", "file", "file-handling" ]
Modifying lines
39,773,601
<p>I'm looking to load a file and modify several predefined lines to certain values. The following is what I tried:</p> <pre><code>with open("test.txt",'w') as f: for i,line in f: if (i == 2): f.writelines(serial1) if (i == 3): ...
0
2016-09-29T14:53:19Z
39,773,846
<p>As pointed out, your issue is that you try to read and write in the same file. The easiest way is to open a new file, and replace the first one when you have the desired output.</p> <p>To get the file lines number, you can use <a href="https://docs.python.org/2.3/whatsnew/section-enumerate.html" rel="nofollow">enum...
0
2016-09-29T15:03:51Z
[ "python", "file", "file-handling" ]
Modifying lines
39,773,601
<p>I'm looking to load a file and modify several predefined lines to certain values. The following is what I tried:</p> <pre><code>with open("test.txt",'w') as f: for i,line in f: if (i == 2): f.writelines(serial1) if (i == 3): ...
0
2016-09-29T14:53:19Z
39,773,883
<p>What you are doing is called editing in place. For that, Python standard library <code>fileinput</code> can help:</p> <pre><code>import fileinput for line in fileinput.input('test.txt', inplace=True): if fileinput.lineno() == 2: print serial1 elif fileinput.lineno() == 3: print serial2 ...
2
2016-09-29T15:05:29Z
[ "python", "file", "file-handling" ]
How to create a string interpreter in python that takes propositions and return an answer based on a given dictionary keys?
39,773,699
<p>So after 2 days of struggling with this problem i gave up. You are given two inputs the first one is a lists that contains propositions and the second one is a dictionary. </p> <p>example: </p> <pre><code>arg= [&lt;prop1&gt;, "OPERATOR", &lt;prop2&gt;] dicti= {&lt;prop1&gt;: key1, &lt;prop2394&gt;: key2394,&lt;pr...
1
2016-09-29T14:57:30Z
39,774,730
<p>You need to use recursion. Define a function <code>eval(prop, keys)</code> to evaluate the proposition. Then match the proposition with a case. For example,</p> <pre><code>['prop1', 'AND', 'prop2'] </code></pre> <p>If you see the above, you would evaluate it as </p> <pre><code>return eval(prop[:1], keys) and e...
0
2016-09-29T15:45:49Z
[ "python", "recursion", "functional-programming", "string-interpolation" ]
Parse an XML file to get a full tag by using Python's lxml package
39,773,780
<p>I've got the following XML file:</p> <pre><code>&lt;root&gt; &lt;scene name="scene1"&gt; &lt;view ath="0" atv="10"/&gt; &lt;image url="img1.jgp"/&gt; &lt;hotspot name="hot1"/&gt; &lt;/scene&gt; &lt;scene name="scene2"&gt; &lt;view ath="20" atv="10"/&gt; &lt;imag...
0
2016-09-29T15:01:06Z
39,774,292
<p>Your given XML source contains some errors; I fixed those, see my source below:</p> <pre><code>from lxml import etree source = """ &lt;root&gt; &lt;scene name="scene1"&gt; &lt;view ath="0" atv="10" /&gt; &lt;image url="img1.jgp" /&gt; &lt;hotspot name="hot1" /&gt; &lt;/scene&gt; &lt;scene name="...
0
2016-09-29T15:23:29Z
[ "python", "xml", "lxml" ]
Parse an XML file to get a full tag by using Python's lxml package
39,773,780
<p>I've got the following XML file:</p> <pre><code>&lt;root&gt; &lt;scene name="scene1"&gt; &lt;view ath="0" atv="10"/&gt; &lt;image url="img1.jgp"/&gt; &lt;hotspot name="hot1"/&gt; &lt;/scene&gt; &lt;scene name="scene2"&gt; &lt;view ath="20" atv="10"/&gt; &lt;imag...
0
2016-09-29T15:01:06Z
39,774,347
<p>The XML content is a string like this:</p> <pre><code>content = u"""\ &lt;root&gt; &lt;scene name="scene1"&gt; &lt;view ath="0" atv="10"/&gt; &lt;image url="img1.jgp"/&gt; &lt;hotspot name="hot1"/&gt; &lt;/scene&gt; &lt;scene name="scene2"&gt; &lt;view ath="20" atv="10"...
0
2016-09-29T15:26:03Z
[ "python", "xml", "lxml" ]
Using Pandas to "applymap" with access to index/column?
39,773,833
<p>I'm currently playing around with a few things involving pandas and I'm wondering what the most effective way to solve the following problem is. Here's a simplified example.</p> <p>Say I have some data in a data frame:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,10,s...
2
2016-09-29T15:03:16Z
39,773,894
<p>IIUC you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a> with <code>axis=0</code> plus you need to convert the <code>Index</code> object to a <code>Series</code> object using <a href="http://pandas.pydata.org/pandas-docs/stable/gen...
2
2016-09-29T15:05:51Z
[ "python", "python-3.x", "pandas" ]
Using Pandas to "applymap" with access to index/column?
39,773,833
<p>I'm currently playing around with a few things involving pandas and I'm wondering what the most effective way to solve the following problem is. Here's a simplified example.</p> <p>Say I have some data in a data frame:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0,10,s...
2
2016-09-29T15:03:16Z
39,774,519
<p>Here's how you can add the index to the dataframe</p> <pre><code>pd.DataFrame(df.values + df.index.values[:, None], df.index, df.columns) </code></pre>
1
2016-09-29T15:34:46Z
[ "python", "python-3.x", "pandas" ]
GCP python sdk running dev server with https protocol
39,773,865
<pre><code>/google-cloud-sdk/bin/dev_appserver.py --host example.com out/app_engine/ </code></pre> <p>This commands run development server with custom domain and with custom port as according to -h parameter. but there is no way to specify an ssl domain as it gives an error when i specify like <a href="https://exampl...
0
2016-09-29T15:04:41Z
39,881,763
<p><strong>This isn't possible at the moment</strong>: see <a href="https://code.google.com/p/googleappengine/issues/detail?id=960" rel="nofollow">here</a> for details.</p>
0
2016-10-05T19:02:03Z
[ "python", "ssl", "google-cloud-platform", "google-app-engine-python" ]
Unexpected behaviour with numpy advanced slicing in named arrays
39,773,922
<p>When using numpy named arrays I observe a different behaviour in the following two cases:</p> <ol> <li>case: first using an index array for advanced slicing and then selecting a subarray by name</li> <li>case: first selecting a subarray by name and then using an index array for advanced slicing</li> </ol> <p>The f...
3
2016-09-29T15:07:34Z
39,774,790
<p>Indexing with a list or array <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays" rel="nofollow">always returns a copy rather than a view</a>:</p> <pre><code>In [1]: np.may_share_memory(data, data[[1, 3, 4]]) Out[1]: False </code></pre> <p>Therefore the assignment <code>data[[1, 3, 4]]...
3
2016-09-29T15:48:50Z
[ "python", "numpy", "structured-array" ]
How to sum pivot data with a DIFF in time by one of the indexes
39,774,097
<p>Sorry the Title of the post isn't clear and that's probably why I'm struggling to google this in Python/Pandas. I'm wondering if I need to groupby and then diff data....</p> <p>I'm trying to find the total time a person is using a web site by finding the differences between page access time in an activity log. I'm ...
0
2016-09-29T15:15:01Z
39,774,545
<p>In the example you provided there are no common session IDs so your difference column will just have Null values but what you want is this:</p> <pre><code>df['diff'] = df.groupby(['A','B'])['C'].transform(lambda x:x - x.shift(-1)) </code></pre> <p>If you want to see difference of C by just Username and not usernam...
1
2016-09-29T15:35:50Z
[ "python", "pandas" ]
How to make a ball go around the edge of the screen continuously? (Python 2.7)
39,774,109
<p>I need help with my animation code. So far i have the ball go around 3 edges of the screen. But i don't know how to make it go around the last screen. </p> <pre><code>#------------------------------------------------------------------------------- # Name: U1A4.py # Purpose: To animate the ball going arou...
-1
2016-09-29T15:15:30Z
39,774,514
<p>The ball only changes directions in the corners, so you just need to cover four cases (two <code>if</code>'s nested in two <code>if</code>'s):</p> <pre><code>x += dx y += dy if x &gt;= 750: if y &gt;= 550: dx = 0 dy = -2 elif y &lt;= 50: dx = -2 dy = 0 elif x &lt;= 50: if y &gt;= 550: dx ...
0
2016-09-29T15:34:36Z
[ "python", "python-2.7", "pygame" ]
How to make a ball go around the edge of the screen continuously? (Python 2.7)
39,774,109
<p>I need help with my animation code. So far i have the ball go around 3 edges of the screen. But i don't know how to make it go around the last screen. </p> <pre><code>#------------------------------------------------------------------------------- # Name: U1A4.py # Purpose: To animate the ball going arou...
-1
2016-09-29T15:15:30Z
39,774,752
<p>Here's my stab at your problem:</p> <pre><code>import sys, pygame pygame.init() size = width, height = 800, 800 speed = [1, 0] black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.bmp") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type ==...
1
2016-09-29T15:47:07Z
[ "python", "python-2.7", "pygame" ]
Method that plots i all the x values to a given math function
39,774,168
<p>Hey i need help with programing a method that plots i all the x values to a given math function</p> <pre><code>def compute(expression): #The expression is where the math function is gonna be placed print("Evaluerer", expression) for i in range(0,1001): x=i/100.0 #This is all the x-values, which ne...
0
2016-09-29T15:18:06Z
39,774,583
<p>Define your function :</p> <pre><code>def f(x): return x #put here your expression of f(x) </code></pre> <p>Then plot your function as follow:</p> <pre><code>plt.plot([i/100.0 for i in range(0,1001)], map(lambda x: f(x),[i/100.0 for i in range(0,1001)])) </code></pre>
0
2016-09-29T15:37:57Z
[ "python" ]
Design pattern in Python with a lot of customer specific exceptions
39,774,231
<p>At this moment we are working on a large project. </p> <p>This project is supposed to create EDIFACT messages. This is not so hard at first but the catch is there are a lot of customers that have their own implementation of the standard. </p> <p>On top of that we are working with several EDIFACT standards (D96A an...
0
2016-09-29T15:20:54Z
39,774,658
<p>Why not put the all this in a resource file with the standard as default and each exception handle in a surcharged value, then you'll just need to read the right key for the right client and you code stay clean.</p>
0
2016-09-29T15:42:27Z
[ "python" ]
Design pattern in Python with a lot of customer specific exceptions
39,774,231
<p>At this moment we are working on a large project. </p> <p>This project is supposed to create EDIFACT messages. This is not so hard at first but the catch is there are a lot of customers that have their own implementation of the standard. </p> <p>On top of that we are working with several EDIFACT standards (D96A an...
0
2016-09-29T15:20:54Z
39,774,702
<p>I think your question is too broad to be answered properly (I was up to click the close button because of this but decided otherwise). The reason for this is the following:</p> <p>There is nothing wrong the code snippet you provided. It should be part of some kind of initialization routine, then this is just fine...
1
2016-09-29T15:44:35Z
[ "python" ]
Pandas pivot_table to calculate share of margin
39,774,314
<p>I have a <code>Pandas</code> <code>DataFrame</code> named <code>df</code> that contains <code>n</code> <code>columns</code>. One of the <code>columns</code> is named <code>COUNT</code>, which shows how many times values in <code>A</code> occurs. <code>A</code> contains unique identifiers so every row has the value <...
2
2016-09-29T15:24:58Z
39,774,942
<p>combine <code>groupby.size</code> with <code>groupby.transform</code></p> <pre><code>size = df.groupby(['B', 'E']).size() sums = size.groupby(level='E').transform(np.sum) aggd = pd.concat([size, size / sums], axis=1, keys=['total', 'share']) aggd.unstack().stack(0) </code></pre> <p><a href="http://i.stack.imgur.c...
2
2016-09-29T15:56:04Z
[ "python", "pandas", "pivot-table" ]
lasagne.layers.DenseLayer: "__init__() takes at least 3 arguments"
39,774,325
<p>I'm using Lasagne+Theano to create a ResNet and am struggling with the use of DenseLayer. If i use the example on <a href="http://lasagne.readthedocs.io/en/latest/modules/layers/dense.html" rel="nofollow">http://lasagne.readthedocs.io/en/latest/modules/layers/dense.html</a> it works.</p> <pre><code>l_in = InputLaye...
1
2016-09-29T15:25:24Z
39,774,510
<p><code>DenseLayer</code> takes two positional arguments: <code>incoming, num_units</code>. You are instantiating it like this:</p> <pre><code>DenseLayer(resnet['pool5'], num_filter=1000) </code></pre> <p>Note that this is different than the example code:</p> <pre><code>DenseLayer(l_in, num_units=50) </code></pre> ...
1
2016-09-29T15:34:23Z
[ "python", "deep-learning", "theano", "lasagne" ]
How to take a partial web snapshot in phantomjs using python?
39,774,342
<p>I'm using phantomjs to take a snapshot of a webpage (for example: <a href="http://www.baixaki.com.br/" rel="nofollow">http://www.baixaki.com.br/</a> ) using python.</p> <p>here is the code:</p> <pre><code>from selenium import webdriver driver = webdriver.PhantomJS() # or add to your PATH driver.get('http://www.ba...
1
2016-09-29T15:25:55Z
39,776,824
<p>You could try cropping the image (I'm using Python 3.5 so you may have to adjust to use StringIO if you're in Python 2.X):</p> <pre><code>from io import BytesIO from selenium import webdriver from PIL import Image if __name__ == '__main__': driver = webdriver.PhantomJS('C:&lt;Path to Phantomjs&gt;') driver...
3
2016-09-29T17:45:21Z
[ "python", "selenium", "phantomjs" ]
How to import Python dependancies in Serverless v1.0
39,774,436
<p>Language: Python Framework: <a href="https://serverless.com" rel="nofollow">Serverless</a> v1.0</p> <p>Typically I would run <code>pip freeze &gt; requirements.txt</code> in the project root</p> <p>How can I get these dependancies packaged into every deploy?</p>
0
2016-09-29T15:30:41Z
39,791,686
<ol> <li><p>create <code>requirements.txt</code></p> <p>pip freeze > requirements.txt</p></li> <li><p>create a folder with all the dependencies: </p> <p>pip install -t vendored -r requirements.txt</p></li> </ol> <p>Note that in order to use these dependencies in the code you'll need to add the following:</p> <pre>...
0
2016-09-30T12:35:44Z
[ "python", "serverless-framework" ]
Python- Boolean Cross-checking
39,774,444
<p>I have an assignment on using ONLY boolean statements for this question: "Can I register today? A student can register on Monday if Senior, on Tuesday if Junior, on Wednesday if Sophomore, and on Thursday if Freshman."</p> <p>Is there a simple way to cross check each and every day and status to see if they are eith...
0
2016-09-29T15:30:58Z
39,775,586
<p>Here is a solution using a Python dictionary and Boolean comparison. </p> <p>We use a dictionary to create <em>student status</em> to <em>day of week</em> associations. Then get user input and compare using a Boolean expression.</p> <pre><code>from datetime import date import calendar my_dict = {'Senior' : 'Mo...
1
2016-09-29T16:31:31Z
[ "python", "boolean" ]
Python- Boolean Cross-checking
39,774,444
<p>I have an assignment on using ONLY boolean statements for this question: "Can I register today? A student can register on Monday if Senior, on Tuesday if Junior, on Wednesday if Sophomore, and on Thursday if Freshman."</p> <p>Is there a simple way to cross check each and every day and status to see if they are eith...
0
2016-09-29T15:30:58Z
39,776,795
<p>Perhaps something like this??</p> <pre><code>from datetime import datetime def options(): print """ Are you a? [Enter 0-4] 0) Senior 1) Junior 2) Sophomore 3) Freshman 4) quit """ print "Can I register today?" while True: options() selection = raw_input("Enter status: ") try: selection = int(selectio...
0
2016-09-29T17:43:23Z
[ "python", "boolean" ]
Django __str__ function on many to one field is not returning the correct output
39,774,471
<p>I'm trying to define <code>__str__</code> function for models A and D for the purpose having human readable text in the admin site. The problem is in model D's <code>__str__</code> function where <code>__str__</code> will return a many_to_one related field, it does not return the format as intended instead it just ...
-1
2016-09-29T15:32:11Z
39,774,819
<p>You've got a typo in your method name. You wrote <code>__str_()</code> when it should be <code>__str__()</code>. So when you're calling <code>str()</code> on your model, it's calling the inherited <code>__str__()</code> method from the parent class.</p>
1
2016-09-29T15:50:19Z
[ "python", "django", "django-admin" ]
How to make two django projects share the same database
39,774,580
<p>I need to make two separate Django projects share the same database. In <code>project_1</code> I have models creating objects that I need to use in <code>project_2</code> (mostly images).</p> <p>The tree structure of <code>project_1_2</code> is:</p> <pre><code>project_1/ manage.py settings.py project_1...
0
2016-09-29T15:37:51Z
39,781,404
<p>You can simply define the same database in <code>DATABASES</code> in your settings.py. So, if your database is PostgreSQL, you could do something like this:</p> <pre><code># in project_1/settings.py DATABASES = { 'default': { 'NAME': 'common_db', 'ENGINE': 'django.db.backends.postgresql', ...
2
2016-09-29T23:12:15Z
[ "python", "django" ]
How to change priority in math order(asterisk)
39,774,694
<p>I want users to input math formula in my system. How can convert case1 formula to case2 formula using Python? In another word, I would like to change math order specifically for double asterisks.</p> <pre><code>#case1 3*2**3**2*5 &gt;&gt;&gt;7680 #case2 3*(2**3)**2*5 &gt;&gt;&gt;960 </code></pre>
0
2016-09-29T15:44:09Z
39,775,022
<p>Below is the example to achieve this using <code>re</code> as:</p> <pre><code>expression = '3*2**3**2*5' asterisk_exprs = re.findall(r"\d+\*\*\d+", expression) # List of all expressions matching the criterion for expr in asterisk_exprs: expression = expression.replace(expr, "({})".format(expr)) # Replace the e...
0
2016-09-29T15:59:59Z
[ "python", "python-2.7", "numpy", "math" ]
How to change priority in math order(asterisk)
39,774,694
<p>I want users to input math formula in my system. How can convert case1 formula to case2 formula using Python? In another word, I would like to change math order specifically for double asterisks.</p> <pre><code>#case1 3*2**3**2*5 &gt;&gt;&gt;7680 #case2 3*(2**3)**2*5 &gt;&gt;&gt;960 </code></pre>
0
2016-09-29T15:44:09Z
39,775,034
<p>Not only is this not something that Python supports, but really, why would you want to? Modifying BIDMAS or PEMDAS (depending on your location), would not only give you incorrect answers, but also confuse the hell out of any devs looking at the code.</p> <p>Just use brackets like in Case 2, it's what they're for.</...
1
2016-09-29T16:00:42Z
[ "python", "python-2.7", "numpy", "math" ]
How to change priority in math order(asterisk)
39,774,694
<p>I want users to input math formula in my system. How can convert case1 formula to case2 formula using Python? In another word, I would like to change math order specifically for double asterisks.</p> <pre><code>#case1 3*2**3**2*5 &gt;&gt;&gt;7680 #case2 3*(2**3)**2*5 &gt;&gt;&gt;960 </code></pre>
0
2016-09-29T15:44:09Z
39,775,261
<p>If users are supposed to enter formulas into your program, I would suggest keeping it as is. The reason is that exponentiation in mathematics is <a href="https://en.wikipedia.org/wiki/Operator_associativity" rel="nofollow">right-associative</a>, meaning the execution goes from the top level down. For example: <code>...
1
2016-09-29T16:13:35Z
[ "python", "python-2.7", "numpy", "math" ]
write csv in python based on sub-string condition
39,774,726
<p>I have the following <code>result</code> variable in a data frame (<code>df</code>) and I am trying to output a csv file for those that starts with "test"</p> <pre><code>abandoned static test_a_1 test_b_2 abandoned test_b_3 </code></pre> <p>The following code is not working. Thanks in advance for your insights</p>...
0
2016-09-29T15:45:38Z
39,774,847
<p>Just because "test_a_1" is in the list does not mean that "test" is, in Python logic.</p> <p>Example of how Python evaluates "if [string] in [list]" statements:</p> <pre><code>&gt;&gt;&gt; test = 'test1' &gt;&gt;&gt; testlist = ['test1', 'test2'] &gt;&gt;&gt; if 'test' in test: ... print('hi') ... hi &gt;&gt...
2
2016-09-29T15:51:49Z
[ "python", "string", "csv", "substring" ]
write csv in python based on sub-string condition
39,774,726
<p>I have the following <code>result</code> variable in a data frame (<code>df</code>) and I am trying to output a csv file for those that starts with "test"</p> <pre><code>abandoned static test_a_1 test_b_2 abandoned test_b_3 </code></pre> <p>The following code is not working. Thanks in advance for your insights</p>...
0
2016-09-29T15:45:38Z
39,774,901
<p>If what you mean is that you want to make a csv that only contains the rows for which result starta with 'test', use the following:</p> <pre><code>df[df.result.str.contains('^test.*')].to_csv("C:/Projects/result.csv",sep=',',index=False) </code></pre>
1
2016-09-29T15:54:13Z
[ "python", "string", "csv", "substring" ]
write csv in python based on sub-string condition
39,774,726
<p>I have the following <code>result</code> variable in a data frame (<code>df</code>) and I am trying to output a csv file for those that starts with "test"</p> <pre><code>abandoned static test_a_1 test_b_2 abandoned test_b_3 </code></pre> <p>The following code is not working. Thanks in advance for your insights</p>...
0
2016-09-29T15:45:38Z
39,774,954
<p>This would work :</p> <pre><code>df['temp'] = [1 if 'test' in df['result'][k] for k in df.index else 0] df['result'][df['temp']==1].to_csv("/your/path", sep=',', index=False) </code></pre>
0
2016-09-29T15:56:29Z
[ "python", "string", "csv", "substring" ]
Print Highest, Average, Lowest score of a file
39,774,785
<p>I'm trying to print the highest, average, and lowest score of a file in python. But I keep getting error </p> <pre><code>ValueError: invalid literal for int() with base 10. </code></pre> <p>My <em>results.txt</em> file looks like this:</p> <pre><code>Johnny-8.65 Juan-9.12 Joseph-8.45 Stacey-7.81 Aideen-8.05 Zack-...
-1
2016-09-29T15:48:28Z
39,774,855
<p>Values that you provided in file are not <code>int</code> type. For your approach you can use <code>float()</code>:</p> <pre><code>value = float(value) </code></pre> <p>If you need to extract integer:</p> <pre><code>s = "123" num = int(s) </code></pre> <blockquote> <p>num = 123</p> </blockquote> <p>If you nee...
0
2016-09-29T15:52:05Z
[ "python", "max", "average", "data-type-conversion", "min" ]
Print Highest, Average, Lowest score of a file
39,774,785
<p>I'm trying to print the highest, average, and lowest score of a file in python. But I keep getting error </p> <pre><code>ValueError: invalid literal for int() with base 10. </code></pre> <p>My <em>results.txt</em> file looks like this:</p> <pre><code>Johnny-8.65 Juan-9.12 Joseph-8.45 Stacey-7.81 Aideen-8.05 Zack-...
-1
2016-09-29T15:48:28Z
39,775,054
<p>As everyone on this thread suggested you should change <strong>int</strong> to <strong>float</strong>. Regarding your comment above. You use </p> <pre><code>value=int(float) ! </code></pre> <p>Float should be outside parentheses. Like this </p> <pre><code>value=float(value). </code></pre> <p>I run the code and ...
0
2016-09-29T16:01:49Z
[ "python", "max", "average", "data-type-conversion", "min" ]
Print Highest, Average, Lowest score of a file
39,774,785
<p>I'm trying to print the highest, average, and lowest score of a file in python. But I keep getting error </p> <pre><code>ValueError: invalid literal for int() with base 10. </code></pre> <p>My <em>results.txt</em> file looks like this:</p> <pre><code>Johnny-8.65 Juan-9.12 Joseph-8.45 Stacey-7.81 Aideen-8.05 Zack-...
-1
2016-09-29T15:48:28Z
39,775,360
<p>Try this:</p> <pre><code>scores={} highest_score=0.0 highest='' lowest_score=100.0 lowest='' average=0.0 sums=0.0 files=open("results.txt","r").readlines() for lines in files[0:]: line=lines.split("-") scores[line[0]]=line[1].strip() for key,value in scores.items(): if float(value)&lt;lowest_score: ...
0
2016-09-29T16:18:40Z
[ "python", "max", "average", "data-type-conversion", "min" ]
Pandas: how to draw a bar plot with two categories and four series each?
39,774,826
<p>I have the following dataframe, where <code>pd.concat</code> has been used to group the columns:</p> <pre><code> a b C1 C2 C3 C4 C5 C6 C7 C8 0 15 37 17 10 8 11 19 86 1 39 84 11 5 5 13 9 11 2 10 20 30 51 74 62 56 58 3 88 2 1 3 9 6 0 17 ...
3
2016-09-29T15:50:38Z
39,775,311
<p>Try <code>seaborn</code></p> <pre><code>import seaborn as sns import pandas as pd def r(df): return df.loc[df.name].reset_index(drop=True) data = df.mean().groupby(level=0).apply(r) \ .rename_axis(['grp', 'cat']).reset_index(name='mu') ax = sns.barplot(x='grp', y='mu', hue='cat', data=data) ax.lege...
2
2016-09-29T16:16:04Z
[ "python", "pandas", "matplotlib", "bar-chart", "categories" ]
Pandas: how to draw a bar plot with two categories and four series each?
39,774,826
<p>I have the following dataframe, where <code>pd.concat</code> has been used to group the columns:</p> <pre><code> a b C1 C2 C3 C4 C5 C6 C7 C8 0 15 37 17 10 8 11 19 86 1 39 84 11 5 5 13 9 11 2 10 20 30 51 74 62 56 58 3 88 2 1 3 9 6 0 17 ...
3
2016-09-29T15:50:38Z
39,776,042
<p>You could simply perform <code>unstack</code> after calculating the <code>mean</code> of the <code>DF</code> to render the bar plot.</p> <pre><code>import seaborn as sns sns.set_style('white') #color=0.75(grey) df.mean().unstack().plot.bar(color=list('rbg')+['0.75'], rot=0, figsize=(8,8)) </code></pre> <p><a hre...
2
2016-09-29T16:58:18Z
[ "python", "pandas", "matplotlib", "bar-chart", "categories" ]
Pythonic way to split string then split again on result?
39,774,926
<p>Is there a more pythonic way to do this</p> <pre><code>def parse_address(hostname, addresses): netmask='' for address in addresses: if hostname in address: _hostname, _netmask = address.strip().split('/') hostname = _hostname.split()[-1] netmask = '/' + _netmask.s...
0
2016-09-29T15:55:10Z
39,775,340
<pre><code>import re hostname = '127.0.0.1' stdout = [ "1: lo inet 127.0.0.1/8 scope host lo\ valid_lft forever preferred_lft forever", "3: wlp4s0 inet 192.168.2.133/24 brd 192.168.2.255 scope global dynamic wlp4s0\ valid_lft 58984sec preferred_lft 58984sec", "4: do...
0
2016-09-29T16:17:27Z
[ "python", "split", "idiomatic" ]
Pythonic way to split string then split again on result?
39,774,926
<p>Is there a more pythonic way to do this</p> <pre><code>def parse_address(hostname, addresses): netmask='' for address in addresses: if hostname in address: _hostname, _netmask = address.strip().split('/') hostname = _hostname.split()[-1] netmask = '/' + _netmask.s...
0
2016-09-29T15:55:10Z
39,775,365
<pre><code>def x(hostname,addresses): import re for address in addresses: result = re.search(hostname+r"/\d", address) if result: return result.group(0).split(hostname)[1] </code></pre> <p>Don't know if it's more 'Pythonic' but I would do it this way. It's readable to others, yet i...
1
2016-09-29T16:18:51Z
[ "python", "split", "idiomatic" ]
Pythonic way to split string then split again on result?
39,774,926
<p>Is there a more pythonic way to do this</p> <pre><code>def parse_address(hostname, addresses): netmask='' for address in addresses: if hostname in address: _hostname, _netmask = address.strip().split('/') hostname = _hostname.split()[-1] netmask = '/' + _netmask.s...
0
2016-09-29T15:55:10Z
39,777,252
<p>Would you be able to base it on code like this?</p> <pre><code>from urllib.parse import urlparse parseResult = urlparse('http://www.fake.ca/185') print ( parseResult ) </code></pre> <p>parseResult is a structure with elements that are revealed in the output of the print statement.</p> <p>ParseResult(scheme='http...
-1
2016-09-29T18:12:57Z
[ "python", "split", "idiomatic" ]
In class object, how to auto update attributes when you change only one entry of a list?
39,774,953
<p>I have seen this answer for a very similar question:</p> <p><a href="http://stackoverflow.com/a/14916491/5726899"><em>In class object, how to auto update attributes?</em></a></p> <p>I will paste the code here:</p> <pre><code>class SomeClass(object): def __init__(self, n): self.list = range(0, n) ...
0
2016-09-29T15:56:25Z
39,776,015
<p>One way you could do it is by having a private helper <code>_List</code> class which is almost exactly like the built-in <code>list</code> class, but also has a <code>owner</code> attribute. Every time one of a <code>_List</code> instance's elements is assigned a value, it can then modify the <code>listsquare</code>...
2
2016-09-29T16:56:48Z
[ "python", "class", "attributes" ]
In class object, how to auto update attributes when you change only one entry of a list?
39,774,953
<p>I have seen this answer for a very similar question:</p> <p><a href="http://stackoverflow.com/a/14916491/5726899"><em>In class object, how to auto update attributes?</em></a></p> <p>I will paste the code here:</p> <pre><code>class SomeClass(object): def __init__(self, n): self.list = range(0, n) ...
0
2016-09-29T15:56:25Z
39,776,083
<p>First of all I would recommend u not to change two, different attributes by accesing single list.setter. The reason why does:</p> <pre><code>&gt;&gt;&gt; c.list[0] = 5 &gt;&gt;&gt; c.list [5, 2, 3, 4] &gt;&gt;&gt; c.listsquare [1, 4, 9, 16] </code></pre> <p>not work, is that, you are accesing the c.list.__setitem_...
1
2016-09-29T17:01:38Z
[ "python", "class", "attributes" ]
FFT Speed on Noncubic meshes
39,774,971
<p>I need to repeatedly take the Fourier Transform/Inverse Fourier Transform of a 3d function in order to solve a differential equation. Something like:</p> <pre><code>import pyfftw.interfaces.numpy_fft as fftw for i in range(largeNumber): fFS = fftw.rfftn(f) # Do stuff f = fftw.irfftn(fFS) </code></pre> ...
1
2016-09-29T15:57:10Z
39,789,674
<p>If you really want to squeeze all the performance out you can, use the FFTW object directly (most easily accessed through <code>pyfftw.builders</code>). This way you get careful control over exactly what copies occur and whether the normalization is performed on inverse.</p> <p>Your code as-is will likely benefit f...
0
2016-09-30T10:45:09Z
[ "python", "performance", "fft", "fftw", "pyfftw" ]
AWS Lambda: failed execution with no errors
39,774,996
<p>I've written a Python script (<code>upload.py</code>) that is working independently of AWS Lambda. It uploads data as POST to an API. It has the following method to handle a Lambda execution:</p> <pre><code>def handler(event, context): print("Hello!") start() </code></pre> <p>When I call <code>start()</cod...
0
2016-09-29T15:58:45Z
39,775,092
<p>So it turns out that the "sys" library isn't permitted in a Lambda, which makes sense in hindsight. To deal with potential encoding issues I had the following code:</p> <pre><code>import sys reload(sys) sys.setdefaultencoding('utf-8') </code></pre> <p>As suggested in another Stack Overflow thread. This apparently ...
1
2016-09-29T16:04:03Z
[ "python", "amazon-web-services", "aws-lambda", "amazon-lambda" ]
Installing opencv-3.1.0 on MacOS Sierra to use with python
39,775,041
<p>I recently upgraded to MacOS Sierra and I have been dealing with many issues (I am mentioning it cause it may be relevant). I am trying to install opencv-3.1.0 to use with python 2.7. and it's been impossible. I downloaded opencv-3.1.0 from <a href="https://github.com/Itseez/opencv/archive/3.1.0.zip" rel="nofollow">...
0
2016-09-29T16:01:02Z
39,775,148
<p>After following the post <a href="https://github.com/Homebrew/homebrew-science/issues/4104#issuecomment-249362870" rel="nofollow">here</a> I was able to install it just fine by running:<br> <code>brew install opencv3 --HEAD --with-contrib</code></p> <p>The issue appears to be related with the QuickTime codecs. You ...
0
2016-09-29T16:07:04Z
[ "python", "osx", "opencv" ]
Separation of a String into Individual Words (Python)
39,775,070
<p>So I have this code here:</p> <pre><code>#assign a string to variable x = "example text" #create set to store separated words xset = [] #create base word xword = "" for letter in x: if letter == " ": #add word xset.append(xword) #add space xset.append(letter) #reset base ...
0
2016-09-29T16:02:17Z
39,775,154
<p>You need to have one more append after the loop to add the last word</p> <pre><code>#assign a string to variable x = "example text" #create set to store separated words xset = [] #create base word xword = "" for letter in x: if letter == " ": #add word xset.append(xword) #add space ...
0
2016-09-29T16:07:28Z
[ "python", "string", "python-2.7" ]