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 get SSE Last Event ID with CGI + Python
38,511,222
<p>I am using Server Sent Events (SSE) to push data to the front end. I was able to implement most of it just by researching its RFC <a href="https://www.w3.org/TR/2011/WD-eventsource-20111020/" rel="nofollow">https://www.w3.org/TR/2011/WD-eventsource-20111020/</a>. The only part I'm stuck on is if the SSE reconnects f...
0
2016-07-21T17:57:15Z
38,600,374
<p>I ended up figuring this out, so hopefully this will be useful for anyone in the future. The lastEventId is used silently in the back of the protocol. So, if the connection drops temporarily and then reconnects the lastEventId is used. All SSEs that were missed are queued up, and only the ones greater than the lastE...
0
2016-07-26T21:42:04Z
[ "python", "python-2.7", "lighttpd" ]
Constructing a method name
38,511,227
<p>How do I construct a method name to use with an instantiated class? I'm trying to run a method in a class 'jsonmaker' where the method corresponds to the datatype specified in the filein string.</p> <pre><code>for filein in filein_list: datatype = filein[(filein.find('_')):-8] method_name = pjoin(datatype +...
1
2016-07-21T17:57:36Z
38,511,258
<p>You can't reference the attribute of a class instance by putting a variable directly behind a dot reference. Not even when the variable references a string which is same as the name of the attribute.</p> <p>You could instead use <code>getattr</code> to get the <code>method</code> from the string and then call it wi...
2
2016-07-21T17:59:14Z
[ "python", "class", "methods" ]
Change the color of text within a pandas dataframe html table python using styles and css
38,511,373
<p>I have a pandas dataframe:</p> <pre><code>arrays = [['Midland','Midland','Hereford','Hereford','Hobbs','Hobbs','Childress','Childress','Reese','Reese', 'San Angelo','San Angelo'],['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']] tuples = list(zip(*arrays)) index = pd.MultiIndex...
6
2016-07-21T18:06:19Z
38,511,805
<p>This takes a few steps:</p> <p>First import <code>HTML</code> and <code>re</code></p> <pre><code>from IPython.display import HTML import re </code></pre> <p>You can get at the <code>html</code> pandas puts out via the <code>to_html</code> method.</p> <pre><code>df_html = df.to_html() </code></pre> <p>Next we ar...
10
2016-07-21T18:28:57Z
[ "python", "html", "css", "pandas", "dataframe" ]
Change the color of text within a pandas dataframe html table python using styles and css
38,511,373
<p>I have a pandas dataframe:</p> <pre><code>arrays = [['Midland','Midland','Hereford','Hereford','Hobbs','Hobbs','Childress','Childress','Reese','Reese', 'San Angelo','San Angelo'],['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']] tuples = list(zip(*arrays)) index = pd.MultiIndex...
6
2016-07-21T18:06:19Z
39,347,921
<p>Using pandas new styling functionality:</p> <pre><code>import numpy as np import pandas as pd arrays = [['Midland','Midland','Hereford','Hereford','Hobbs','Hobbs','Childress','Childress','Reese','Reese', 'San Angelo','San Angelo'],['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']] tu...
1
2016-09-06T11:25:30Z
[ "python", "html", "css", "pandas", "dataframe" ]
Extending a template thats already extended in Django
38,511,433
<p>I'm trying to figure out if there is a way to extend a partial view into a view that already extends base.html.</p> <p>Here is an example of what I'm trying to do:</p> <p><strong>my-template.html</strong></p> <pre><code>{% extends 'base.html '%} &lt;div class="row"&gt; &lt;div class="col-xs-12"&gt; &lt;ul ...
1
2016-07-21T18:09:03Z
38,512,524
<p>The typical way to solve this is by using the <code>include</code> template tag, not by extending with a new template.</p> <p><a href="https://docs.djangoproject.com/en/1.9/ref/templates/builtins/#include" rel="nofollow">Here is the Django doc describing this.</a></p> <p>You can even use a variable to define a dyn...
2
2016-07-21T19:09:21Z
[ "python", "django" ]
Python: download files from google drive using url
38,511,444
<p>I am trying to download files from google drive and all I have is the drive's url.</p> <p>I have read about google api that talks about some drive_service and MedioIO, which also requires some credentials( mainly json file/oauth). But I am unable to get any idea about how its working. </p> <p>Also, tried urllib2 u...
0
2016-07-21T18:09:36Z
38,516,081
<p><code>PyDrive</code> allows you to download a file with the function <code>GetContentFile()</code>. You can find the function's documentation <a href="https://googledrive.github.io/PyDrive/docs/_build/html/filemanagement.html#download-file-content" rel="nofollow">here</a>.</p> <p>See example below:</p> <pre><code>...
0
2016-07-21T23:47:23Z
[ "python", "download", "google-drive-sdk", "urllib2", "pydrive" ]
Python: download files from google drive using url
38,511,444
<p>I am trying to download files from google drive and all I have is the drive's url.</p> <p>I have read about google api that talks about some drive_service and MedioIO, which also requires some credentials( mainly json file/oauth). But I am unable to get any idea about how its working. </p> <p>Also, tried urllib2 u...
0
2016-07-21T18:09:36Z
39,225,272
<p>If by "drive's url" you mean the <strong>shareable link</strong> of a file on Google Drive, then the following might help:</p> <pre><code>import requests def download_file_from_google_drive(id, destination): URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = se...
0
2016-08-30T10:39:01Z
[ "python", "download", "google-drive-sdk", "urllib2", "pydrive" ]
How to modify nested JSON with python
38,511,586
<p>I need to update (CRUD) a nested JSON file using Python. To be able to call python function(s)(to update/delete/create) entires and write it back to the json file.</p> <p>Here is a <a href="https://www.dropbox.com/s/9j0pi6iiww0i9fi/InputJsonfile.json?dl=0" rel="nofollow">sample file</a>.</p> <p>I am looking at <a ...
0
2016-07-21T18:17:00Z
38,511,889
<p>I feel like I'm missing something in your question. In any event, what I understand is that you want to read a json file, edit the data as a python object, then write it back out with the updated data?</p> <p>Read the json file:</p> <pre><code>import json f = open("data.json") raw_data = f.read() f.close() data...
1
2016-07-21T18:33:39Z
[ "python", "json" ]
Matplotlib: error with "height" in grouped barchart
38,511,600
<p>I want to produce a barchart with two categories on the x axis and, for each category, 5 different series. I took inspiration from <a href="http://emptypipes.org/2013/11/09/matplotlib-multicategory-barchart/" rel="nofollow">here</a>, and amended the code as follows:</p> <pre><code>import numpy as np import matplot...
1
2016-07-21T18:17:29Z
38,521,130
<pre><code>import numpy as np import matplotlib.pyplot as plt from pylab import * myarray=np.array([['Series1', 'A',45], ['Series2', 'A',47], ['Series3', 'A',48], ['Series4','A',48], ['Series5', 'A',49], ['Series1','B',39], ['Series2','B',37], ...
1
2016-07-22T07:55:49Z
[ "python", "matplotlib" ]
cannot quit jupyter notebook server running
38,511,673
<p>I am using Jupyter Notebook for a project. Since I ssh into a linux cluster at work I use</p> <pre><code>ssh -Y -L 8000:localhost:8888 user@host </code></pre> <p>Then I start the notebook with <code>jupyter notebook --no-browser &amp;</code> so that I can continue using the terminal. Then on my local machine I ope...
0
2016-07-21T18:21:57Z
38,511,773
<p>Section 3.3 should be applicable to this. <a href="http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html" rel="nofollow">http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/execute.html</a></p> <blockquote> <p>When a notebook is opened, its “computational engine” (called the...
0
2016-07-21T18:26:53Z
[ "python", "server", "jupyter", "jupyter-notebook" ]
cannot quit jupyter notebook server running
38,511,673
<p>I am using Jupyter Notebook for a project. Since I ssh into a linux cluster at work I use</p> <pre><code>ssh -Y -L 8000:localhost:8888 user@host </code></pre> <p>Then I start the notebook with <code>jupyter notebook --no-browser &amp;</code> so that I can continue using the terminal. Then on my local machine I ope...
0
2016-07-21T18:21:57Z
38,513,158
<p>So I found a solution.</p> <p>Since <code>jupyter notebook list</code> tells you which ports the notebook servers are running on I looked for the PIDs using <code>netstat -tulpn</code> I got the information from <a href="http://www.cyberciti.biz/faq/what-process-has-open-linux-port/" rel="nofollow">http://www.cyber...
0
2016-07-21T19:49:10Z
[ "python", "server", "jupyter", "jupyter-notebook" ]
cannot quit jupyter notebook server running
38,511,673
<p>I am using Jupyter Notebook for a project. Since I ssh into a linux cluster at work I use</p> <pre><code>ssh -Y -L 8000:localhost:8888 user@host </code></pre> <p>Then I start the notebook with <code>jupyter notebook --no-browser &amp;</code> so that I can continue using the terminal. Then on my local machine I ope...
0
2016-07-21T18:21:57Z
40,136,334
<p>I ran into the same issue and followed the solution posted above. Just wanted to clearify the solution a little bit.</p> <pre><code>netstat -tulpn </code></pre> <p>will list all the active connections.</p> <pre><code>tcp 0 0 0.0.0.0:8888 0.0.0.0:* LISTEN 19524/python </code></pre> <p>you will need th...
0
2016-10-19T15:55:32Z
[ "python", "server", "jupyter", "jupyter-notebook" ]
OpenStack Error(Neutron network service)
38,511,699
<h1>My Enviroment</h1> <ul> <li>CentOS7</li> <li>OpenStack(Liberty)</li> </ul> <h1>Problem</h1> <p>neutron port-show net-ID</p> <p>Unable to find port with name 'net-ID'</p> <p>How do I fix this problem?? Please help</p> <hr> <h2>/etc/neutron/plugins/ml2/linuxbridge_agent.ini</h2> <pre><code>[linux_bridge] phys...
0
2016-07-21T18:23:20Z
39,857,815
<p>Execute the following command to get the net-ids.</p> <blockquote> <p>neutron port-list </p> </blockquote> <p>After getting the net-ids of different network devices(router, DHCP etc..), execute the following command with it.</p> <blockquote> <p>neutron port-show "net-id you got from previous command"</p> </bl...
0
2016-10-04T16:52:36Z
[ "python", "openstack", "centos7", "openstack-neutron" ]
Regrouping lines of a text file
38,511,706
<p>I am using a Python script to generate some Stata commands. The output is a text file. I would like to group lines belonging to a same observation, which is currently not the case, using Python.</p> <p>A typical line in this file (let's call it file.txt) is of the sort:</p> <pre><code>[something something] if a ==...
0
2016-07-21T18:23:41Z
38,512,203
<p>Sounds good to me. You could use a regex to extract the observations. For example, assuming that observations are made up of positive integers you could use:</p> <pre><code>import re line = 'replace k = 1 if a == 1 &amp; b == 2 &amp; c == 3 &amp; comments_1 == "test"' m = re.search(r'a == (\d+) &amp; b == (\d+) &am...
0
2016-07-21T18:51:16Z
[ "python", "sorting" ]
Regrouping lines of a text file
38,511,706
<p>I am using a Python script to generate some Stata commands. The output is a text file. I would like to group lines belonging to a same observation, which is currently not the case, using Python.</p> <p>A typical line in this file (let's call it file.txt) is of the sort:</p> <pre><code>[something something] if a ==...
0
2016-07-21T18:23:41Z
38,512,795
<p>That's a good approach, but since you want to retain all lines, I wouldn't bother grouping lines with the same triple: Just make a list of all lines and sort them with their value triple as the sort key.</p> <pre><code>def getvalues(line): """Extract a value triple from a line that matches the pattern""" m ...
0
2016-07-21T19:27:41Z
[ "python", "sorting" ]
Python while loop Syntax Error
38,511,856
<p>I am learning Python and while working on a simple while loop I get a syntax error but cannot figure out why. Below is my code and the error I get</p> <pre><code>products = ['Product 1', 'Product 2', 'Product 3'] quote_items = [] quote = input("What services are you interesting in? (Press X to quit)") while (quote....
1
2016-07-21T18:31:40Z
38,511,929
<p>Use <code>raw_input</code> instead of <code>input</code>. Python evaluates <code>input</code> as pure python code.</p> <pre><code>quote = raw_input("What services are you interesting in? (Press X to quit)") </code></pre>
1
2016-07-21T18:36:18Z
[ "python", "while-loop" ]
Python while loop Syntax Error
38,511,856
<p>I am learning Python and while working on a simple while loop I get a syntax error but cannot figure out why. Below is my code and the error I get</p> <pre><code>products = ['Product 1', 'Product 2', 'Product 3'] quote_items = [] quote = input("What services are you interesting in? (Press X to quit)") while (quote....
1
2016-07-21T18:31:40Z
38,512,098
<p>in <em>Python 3</em></p> <pre><code>products = ['Product 1', 'Product 2', 'Product 3'] quote_items = [] quote = input("What services are you interesting in? (Press X to quit)") while (quote.upper() != 'X'): product_found = quote in products if product_found: quote_items.append(quote) else: ...
4
2016-07-21T18:45:56Z
[ "python", "while-loop" ]
Add custom language for localization in Django app
38,511,925
<p><a href="http://stackoverflow.com/questions/19267886/adding-a-custom-language-to-django">adding a custom language to django</a></p> <p>I checked this question and did all the steps mentioned in the accepted answer. After doing all when I go to <code>/kjv/</code> then it redirects to <code>/en/kjv/</code> </p> <p>P...
0
2016-07-21T18:35:55Z
38,528,364
<p>If anyone come to this place and facing similar issue then don't forget to update/add LOCALE_PATHS in settings.py</p> <p>e.g</p> <pre><code>PROJECT_PATH = os.path.dirname(os.path.abspath(__file__)) LOCALE_PATHS = ( os.path.join(PROJECT_PATH, '../locale'), ) </code></pre> <p>You can point to anywhere, given ...
0
2016-07-22T13:59:15Z
[ "python", "django", "web-applications", "localization", "internationalization" ]
Python crashing with openGl2
38,511,963
<p>When I try to execute a function I wrote using mayavi, python will crash and give me a message:</p> <blockquote> <p>Error: In D:\Build\VTK-7.0.0\Rendering\OpenGL2\vtkOpenGLRenderWindow.cxx, line 545 vtkWin32OpenGLRenderWIndow(00002533B0F8): Gl version 2.1 with gpu_shader4 extension is not supported by your ...
-2
2016-07-21T18:37:57Z
38,528,694
<p>The issue was resolved by updating video card drivers and changing my work environnement out of remote desktop connection that was previously being used.</p>
0
2016-07-22T14:14:50Z
[ "python", "opengl", "vtk", "mayavi" ]
pyodbc: How to test whether it's possible to establish connection with SQL server without freezing up
38,511,979
<p>I am writing an app with <code>wxPython</code> that incorporates <code>pyodbc</code> to access SQL Server. A user must first establish a VPN connection before they can establish a connection with the SQL server. In cases where a user forgets to establish a VPN connection or is simply not authorized to access a parti...
1
2016-07-21T18:38:47Z
38,512,759
<p>See <a href="https://code.google.com/archive/p/pyodbc/wikis/Connection.wiki" rel="nofollow">https://code.google.com/archive/p/pyodbc/wikis/Connection.wiki</a> under <code>timeout</code></p> <blockquote> <p>Note: This attribute only affects queries. To set the timeout for the actual connection process, use the t...
1
2016-07-21T19:25:09Z
[ "python", "sql-server", "pyodbc" ]
pyodbc: How to test whether it's possible to establish connection with SQL server without freezing up
38,511,979
<p>I am writing an app with <code>wxPython</code> that incorporates <code>pyodbc</code> to access SQL Server. A user must first establish a VPN connection before they can establish a connection with the SQL server. In cases where a user forgets to establish a VPN connection or is simply not authorized to access a parti...
1
2016-07-21T18:38:47Z
38,516,742
<blockquote> <p>took a while before it threw an error message about server not existing or access being denied</p> </blockquote> <p>Your comment conflates two very different kinds of errors:</p> <ul> <li><p><em>server not existing</em> is a network error. Either the name has no address, or the address is unreachab...
1
2016-07-22T01:15:02Z
[ "python", "sql-server", "pyodbc" ]
change rolename and static ip in azure python update_role
38,512,129
<p>The Azure Python API update_role doesn't provide way to update the role name and set static ip, are there any alternative ways to do these operations.</p>
0
2016-07-21T18:47:04Z
38,522,309
<p>The <code>update_role</code> function of <code>azure.servicemanagement.servicemanagementservice</code> for Python is wrapped the REST API <a href="https://msdn.microsoft.com/en-us/library/azure/jj157187.aspx" rel="nofollow"><code>Update Role</code></a>. The role name is not an attribute of request body, so it could ...
0
2016-07-22T08:59:04Z
[ "python", "azure" ]
How to color-code 2D scatter plot based on a 3rd column
38,512,187
<p>I have a scatter plot with the x and y axes showing distance and temperature, respectively. The data was collected over multiple days, and I want to color-code the plot to see which data was collected on which date (e.g., 20160703). How can I add color based on the "date" column?</p>
-2
2016-07-21T18:50:29Z
38,512,661
<p>I assume your using xlsx as that is the newest excel file format. </p> <p>For xlsx you are going to want to use openpyxl.</p> <p>Documentation: <a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">https://openpyxl.readthedocs.io/en/default/</a></p> <p>Here is the specific documentation for color: ...
0
2016-07-21T19:18:51Z
[ "python" ]
Python Pandas - Segmentation Fault after renaming columns?
38,512,205
<p>So after I create a dataframe in pandas, I have a function that capitalizes the headers. But when I try to access the dataframe information after capitalizing, I get a segmentation fault error. If I try to access it before applying the function, I don't have any problems. What could I be doing wrong?</p> <pre><code...
2
2016-07-21T18:51:19Z
38,512,252
<p>If you uppercase all of the column names then accessing a column that has lowercase characters will throw an error.</p> <p>Specifically, the line</p> <pre><code>df.columns.values[i] = (df.columns.values[i]).upper() </code></pre> <p>converts <code>'columnname'</code> to <code>'COLUMNNAME'</code>. Column access in ...
2
2016-07-21T18:53:39Z
[ "python", "function", "pandas" ]
Starting wxPython and extending another class
38,512,227
<p>I am switching from tkinter to wxPython and I am confused on inheritance when using template wxPython scripts similar to the wxexample class below. Given my three scripts below (mainClass.py, wxexample.py, callbacks.py), how do I:</p> <p>1) properly start the wxPython window from the mainClass; </p> <p>2) have the...
0
2016-07-21T18:52:34Z
38,514,156
<p>All wxPython applications require the following, at a minimum:</p> <ol> <li>An instance of <code>wx.App</code> or a subclass derived from <code>wx.App</code></li> <li>An instance of a top-level UI element, such as a <code>wx.Frame</code>, <code>wx.Dialog</code> or a derived class, which has been shown</li> <li>An e...
1
2016-07-21T20:51:20Z
[ "python", "inheritance", "wxpython" ]
Ansible - How maintain a dynamic list of data
38,512,260
<p>I'm building a system to deploy an entire environment in AWS. However, in the case of failure, I want to tear down everything that's already been built. Since I was planning to deploy multiple, different environments, I figured it would be better to just keep a running list of what I've made in AWS up to that point....
0
2016-07-21T18:54:36Z
38,512,808
<blockquote> <p>So I want a way to store just a simple array of the names of each component, appending the names as each part is spun up in turn....</p> </blockquote> <p>You can create a temp file in <code>pre_task</code> and write data into it, so if something failed, you know what to delete. Alternatively you ...
0
2016-07-21T19:28:55Z
[ "python", "amazon-web-services", "ansible", "jinja2" ]
How to recognise urls starting with anchor(#) in urls.py file in django?
38,512,300
<p>I have starting building my application in angularJS and django, and after creating a login page, I am trying to redirect my application to a new url after successful login. I am using <code>$location</code> variable to redirect my page. Here is my code:</p> <pre><code>$scope.login = function() { $http({ ...
1
2016-07-21T18:56:40Z
38,512,413
<p>You have some major misunderstanding about and anchor in url. The anchor is called officially <a href="https://en.wikipedia.org/wiki/Fragment_identifier" rel="nofollow"><code>Fragment identifier</code></a>, it's not part of the main url, so if you have <code>#</code> when you visit an url like <code>http://localhost...
1
2016-07-21T19:02:47Z
[ "python", "angularjs", "django" ]
How to recognise urls starting with anchor(#) in urls.py file in django?
38,512,300
<p>I have starting building my application in angularJS and django, and after creating a login page, I am trying to redirect my application to a new url after successful login. I am using <code>$location</code> variable to redirect my page. Here is my code:</p> <pre><code>$scope.login = function() { $http({ ...
1
2016-07-21T18:56:40Z
38,537,851
<p>Using help from this <a href="http://stackoverflow.com/a/27941966/5159284">answer</a>, I figured a good redirection method through angular which doesn't append any anchor tag using $window:</p> <pre><code>$scope.login = function() { $http({ method: 'POST', data: { username: $scope.username, ...
0
2016-07-23T03:27:56Z
[ "python", "angularjs", "django" ]
Python: Locally assigning values to a global list
38,512,312
<p>I am currently in the process of programming a text-based adventure in Python as a learning exercise. I want "help" to be a global command, stored as values in a list, that can be called at (essentially) any time. As the player enters a new room, or the help options change, I reset the help_commands list with the ne...
0
2016-07-21T18:57:08Z
38,512,463
<p>It's creating a local variable with the same name as the global variable. All in all, it's not a very great way to program - you might want to have a global help object, instead... or not. In any event, in your help_test() function, start with:</p> <pre><code>global(help_commands) </code></pre> <p>And see if tha...
0
2016-07-21T19:05:26Z
[ "python", "python-2.7", "object" ]
How to Concat a DataFrame with String to a DataFrame with Unicode and normalize datatype
38,512,367
<p>I'm having issues when concatenating two dataframes with different types of strings in Python2. One has normal Py2 strings, the other a unicode string. The concatenation works, but the types inside the numpy arrays internally remain the same (by design I'm sure).</p> <pre><code>import pandas as pd from pandas impor...
2
2016-07-21T19:00:13Z
38,512,547
<p>Pandas has an astype method but it returns a series. This will work. </p> <pre><code> df2_copy = pd.DataFrame(d2.data.astype(str)) df2_copy.data.values array(['AAAAAAA'], dtype=object) </code></pre>
3
2016-07-21T19:11:11Z
[ "python", "python-2.7", "numpy", "pandas", "unicode" ]
How to Concat a DataFrame with String to a DataFrame with Unicode and normalize datatype
38,512,367
<p>I'm having issues when concatenating two dataframes with different types of strings in Python2. One has normal Py2 strings, the other a unicode string. The concatenation works, but the types inside the numpy arrays internally remain the same (by design I'm sure).</p> <pre><code>import pandas as pd from pandas impor...
2
2016-07-21T19:00:13Z
38,512,554
<p>Use <code>applymap</code> and <code>encode</code></p> <pre><code>df3.applymap(lambda s: s.encode('utf8')) </code></pre> <p><a href="http://i.stack.imgur.com/1DaBu.png" rel="nofollow"><img src="http://i.stack.imgur.com/1DaBu.png" alt="enter image description here"></a></p> <pre><code>df3.applymap(lambda s: s.encod...
2
2016-07-21T19:11:47Z
[ "python", "python-2.7", "numpy", "pandas", "unicode" ]
Kivy infinite scroll
38,512,411
<p>I want to create infinite scroll for my app. It's my code:</p> <pre><code>from kivy.app import App from kivy.uix.scrollview import ScrollView from kivy.uix.gridlayout import GridLayout from kivy.uix.image import AsyncImage IMAGES_URLS = ['https://upload.wikimedia.org/wikipedia/commons/c/c3/Jordan_by_Lipofsky_1657...
2
2016-07-21T19:02:43Z
38,552,444
<p>I found solution, I needed to override 2 variables (<code>scroll_y</code> and <code>effect_y</code>). It's issue on <a href="https://github.com/kivy/kivy/issues/2038#issuecomment-46158938" rel="nofollow">github</a> where I found solution. It's my fixed code.</p> <pre><code>def upload_images(self): layout = self...
1
2016-07-24T13:16:22Z
[ "android", "python", "kivy", "infinite-scroll" ]
How to insert breakpoint in django template?
38,512,458
<p>How I can insert <code>pdb.set_trace()</code> in django template? Or maybe run some another debug inside template.</p>
0
2016-07-21T19:05:08Z
38,515,446
<p>PyCharm Professional Edition supports graphical debugging of Django templates. More information about how to do that is here:</p> <p><a href="https://www.jetbrains.com/help/pycharm/2016.1/debugging-django-templates.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/2016.1/debugging-django-templates.html</...
1
2016-07-21T22:34:47Z
[ "python", "django", "django-templates" ]
Highlight specific points in matplotlib scatterplot
38,512,485
<p>I have a CSV with 12 columns of data. <a href="http://i.stack.imgur.com/7FGZE.png" rel="nofollow">I'm focusing on these 4 columns</a> </p> <p>Right now I've plotted "Pass def" and "Rush def". I want to be able to highlight specific points on the scatter plot. For example, I want to highlight 1995 DAL point on the p...
2
2016-07-21T19:07:12Z
38,512,830
<p>You can layer multiple scatters, so the easiest way is probably </p> <p><code> plt.scatter(x,y,facecolors='black',alpha=.55, s=100) plt.scatter(x, 2015.0, color="yellow") </code></p>
3
2016-07-21T19:30:26Z
[ "python", "pandas", "matplotlib" ]
Get values (point, vector, array, etc.) from `xr.Dataset` in Xarray ? (Python 3)
38,512,507
<p>I can't figure out how to actually pull the data out of a <code>xr.Dataset</code> object. I can't figure out how to access individual values. How can I pull the values (point values, vectors, arrays, etc.) out of the Datasets like I can with the DataArrays? </p> <pre><code>np.random.seed(0) DA_data = xr.DataArr...
1
2016-07-21T19:08:35Z
38,512,697
<p>It's a little confusing, but <code>.values</code> works differently on <code>Dataset</code> and <code>DataArray</code>:</p> <ul> <li><code>DataArray.values</code> returns a NumPy array. This behavior is consistent with pandas.</li> <li><code>Dataset.values()</code> returns a list (Python 2) or ValuesView (Python 3)...
2
2016-07-21T19:20:59Z
[ "python", "arrays", "multidimensional-array", "dataset", "python-xarray" ]
Nested function calls and missing input parameter, python
38,512,596
<p>I'm trying out some Text Classification tutorials <a href="https://github.com/abromberg/sentiment_analysis_python/blob/master/sentiment_analysis.py" rel="nofollow">here</a>:</p> <p>I don't understand the function calls in line 59 -- 65: </p> <pre><code>#creates a feature selection mechanism that uses all words def...
0
2016-07-21T19:14:37Z
38,512,638
<p>Without further context, it is a bit difficult to give a complete answer to your question. It seems that the <code>evaluate_features</code> method takes a function as parameter; in that case, you don't need to call the function which was passed in as a parameter. Only <code>evaluate_features</code> should do that. I...
1
2016-07-21T19:17:47Z
[ "python", "function-calls", "function-call" ]
python unicode errors convert to printed values
38,512,629
<p>If I have some unicode like this:</p> <pre><code>'\x00B\x007\x003\x007\x00-\x002\x00,\x001\x00P\x00W\x000\x000\x009\x00,\x00N\x00O\x00N\x00E\x00,\x00C\x00,\x005\x00,\x00J\x00,\x00J\x00,\x002\x009\x00,\x00G\x00A\x00R\x00Y\x00,\x00 \x00W\x00I\x00L\x00L\x00I\x00A\x00M\x00S\x00,\x00 \x00P\x00A\x00R\x00E\x00N\x00T\x00I\...
-2
2016-07-21T19:16:45Z
38,512,741
<p>You don't have Unicode. Not <em>yet</em>. You have a series of bytes, and those bytes use the UTF-16 <em>encoding</em>. You need to decode those bytes first:</p> <pre><code>data.decode('utf-16-be') </code></pre> <p>Printing it works only because your console ignores most of the big-endian pair of each UTF-16 codeu...
6
2016-07-21T19:24:12Z
[ "python", "unicode" ]
Is there a way to run a python script and still be able to use my Ubuntu server?
38,512,644
<p>I have a server I lease from Digital Ocean. I access it using Putty. I want to run my python script in the background so that I can still do other things on the machine. What is a terminal command I can use to have it run in the background so that I can still use the machine?</p> <p>Random information you might nee...
-1
2016-07-21T19:18:04Z
38,512,752
<p>It's more of a unix/linux question than python, but you can do it in a couple of different ways:</p> <pre><code>% python myprogram.py &amp; </code></pre> <p>The "&amp;" says to run it in the background.</p> <p>If you forgot, and just ran it, then you can type "^z" (control-Z) to suspend your program, then type:</...
1
2016-07-21T19:24:43Z
[ "python", "python-3.x", "ubuntu", "terminal", "ubuntu-14.04" ]
Python Issues swapping variables into a list
38,512,739
<p>This is what I'm assigned to do Start by filling a list with 10 random numbers. Show the list to the user. Ask the user to pick two numbers between 1 and 10. Swap the elements in the list that are in the two list locations the user used in #3 Check to see if the list is in order from smallest to largest. Repeat ste...
-2
2016-07-21T19:24:07Z
38,512,821
<p>The name of your list is numbers and not list. Once you make the change, your code will work.</p>
0
2016-07-21T19:30:06Z
[ "python", "python-3.x" ]
Python Issues swapping variables into a list
38,512,739
<p>This is what I'm assigned to do Start by filling a list with 10 random numbers. Show the list to the user. Ask the user to pick two numbers between 1 and 10. Swap the elements in the list that are in the two list locations the user used in #3 Check to see if the list is in order from smallest to largest. Repeat ste...
-2
2016-07-21T19:24:07Z
38,512,949
<pre><code>numbers = [4,2,5,5,6,4,7,6,9,5] print("Heres your current list", numbers) print("Pick a location between 1 and 10") num = int(input()) if num &lt;= 10 and num &gt;= 1: print("Please pick another location between 1 and 10") num1 = int(input()) temp1 = numbers[num-1] temp2 = numbers[num1-1] numbers...
0
2016-07-21T19:37:00Z
[ "python", "python-3.x" ]
How to fix size exceeds expected in python 3
38,512,813
<p>I am trying to loop over Excel files with python <code>pandas</code>. First I'm saving them to csv and then I open them again, slice and then saving them again. But I get an error: </p> <pre><code>"Workbook: size exceeds expected 10752 bytes; corrupt?" </code></pre> <p>I am relatively new to python.</p>
-1
2016-07-21T19:29:30Z
38,512,876
<p>I think you may have a cell that has more than 255 characters in it. </p> <p>See this article about data and file size limitations: <a href="http://kb.tableau.com/articles/knowledgebase/jet-data-file-size-limitations" rel="nofollow">http://kb.tableau.com/articles/knowledgebase/jet-data-file-size-limitations</a></p>...
0
2016-07-21T19:33:03Z
[ "python", "pandas" ]
Python socket test recv() data
38,512,817
<p>I have a problem with my python script using socket. I want to test if the client use the correct file, not an other tool like telnet. The server :</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while 1: conn, addr = s.accept() data = conn...
1
2016-07-21T19:29:45Z
38,520,949
<p>You can use <code>select</code> function to limit the time your server waits for new client connection or incoming data from client:</p> <pre><code>import socket import select s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while 1: # wait up to 60 seconds that a client ...
0
2016-07-22T07:45:16Z
[ "python", "sockets" ]
Chain two multiprocessing scripts - python
38,512,855
<p>I have two scripts, they are both multiprocessing utilized scripts.</p> <p><code>build.py</code> reads from a db and spits out a text file. Parallel jobs are launched to do this.</p> <p><code>push.py</code> inserts/updates this text file to a persistent DB. Again, this is multiprocessing too.</p> <p>Currently I h...
0
2016-07-21T19:31:58Z
38,513,306
<p>You can just use <a class='doc-link' href="http://stackoverflow.com/documentation/python/1393/subprocess-library#t=201607212000283295138"><code>subprocess</code></a></p> <p>In <code>build.py</code></p> <pre><code>import subprocess def main(): # Do multiprocessing code, wait for all processes to finish ......
1
2016-07-21T19:59:07Z
[ "python", "multiprocessing" ]
Can AxesGrid be used to plot two imshows (overlay) with two separate colorbars?
38,512,870
<p>I am using AxesGrid in matplotlib to create a plot that overlays two imshow plots, with a separate colourbar side by side for each image colourmap. While I can see in <a href="http://stackoverflow.com/questions/22128166/two-different-color-colormaps-in-the-same-imshow-matplotlib">this question/answer</a> that using ...
0
2016-07-21T19:32:45Z
38,518,065
<p>I think you may need to make two axes for the colorbars and use them:</p> <pre><code>from mpl_toolkits.axes_grid1 import make_axes_locatable # create an axes on the right side of ax. The width of cax will be 5% # of ax and the padding between cax and ax will be fixed at 0.05 inch. divider = make_axes_locatable(ax) ...
0
2016-07-22T04:17:01Z
[ "python", "matplotlib", "colorbar" ]
I have text file in which each row with single word. convert it into line using python
38,512,906
<p>I have a text file with a single word in each row.</p> <p>I want to convert it into line using Python.</p> <p>Input: <code>file.txt</code></p> <pre><code>word1 in row1 word2 in row2 word3 in row3 word4 in row4 </code></pre> <p>Expected Output: <code>['word1.Z', 'word2.Z', 'word3.Z', 'word4.Z']</code></p>
-1
2016-07-21T19:34:58Z
38,513,006
<p>This should get you started:</p> <pre><code>filename = 'test.txt' words = open(filename, 'r').readlines() </code></pre> <p><code>readlines()</code> creates a list where each element is one line of the file, so your <code>words</code> list will look like <code>['word1', 'word2', 'word3', 'word4']</code>.</p>
0
2016-07-21T19:40:13Z
[ "python" ]
I have text file in which each row with single word. convert it into line using python
38,512,906
<p>I have a text file with a single word in each row.</p> <p>I want to convert it into line using Python.</p> <p>Input: <code>file.txt</code></p> <pre><code>word1 in row1 word2 in row2 word3 in row3 word4 in row4 </code></pre> <p>Expected Output: <code>['word1.Z', 'word2.Z', 'word3.Z', 'word4.Z']</code></p>
-1
2016-07-21T19:34:58Z
38,513,029
<pre><code>['%s.Z'%s for s in open('myfile.txt').read().split()] </code></pre> <p>or if <code>myfile.txt</code> is big:</p> <pre><code>['%s.Z'%s for s in open('myfile.txt').readline().split()] </code></pre>
3
2016-07-21T19:41:53Z
[ "python" ]
I have text file in which each row with single word. convert it into line using python
38,512,906
<p>I have a text file with a single word in each row.</p> <p>I want to convert it into line using Python.</p> <p>Input: <code>file.txt</code></p> <pre><code>word1 in row1 word2 in row2 word3 in row3 word4 in row4 </code></pre> <p>Expected Output: <code>['word1.Z', 'word2.Z', 'word3.Z', 'word4.Z']</code></p>
-1
2016-07-21T19:34:58Z
38,513,073
<p>You can use this piece of code:</p> <p>It will read each line in <code>test.txt</code> and save it in a list called 'words'</p> <p>Then it will loop thought each word, remove <code>"\n"</code> and add <code>".Z"</code> to them.</p> <pre><code>filename = 'test.txt' words = open(filename, 'r').readlines() new_word...
0
2016-07-21T19:44:08Z
[ "python" ]
timing issue between data sending and receiving code
38,512,996
<p>I'm pretty new to Python and am trying to do something a bit tricky. So essentially I'm trying to send data over light; just a small amount of text. So I have a line of code to encode the ASCII to binary, and that works fine and leaves me with a list with the binary as strings like </p> <pre><code>n=['0','b','1','0...
1
2016-07-21T19:39:50Z
38,546,884
<p>I imagine the problem is that writing to a list may take slightly more or less time to complete as an action than setting a GPIO pin. So each loop cycle it gets more and more out of sync until it's not reading the right things. What I would do is add another LED and another photodiode, on the opposite raspberry pi t...
0
2016-07-23T22:15:52Z
[ "python", "raspberry-pi", "transmission" ]
python: Plotting data from multiple netCDF files
38,513,027
<p>long story short, I am plotting climate data from a netCDF file. My only problem, I have to plot data from tens of these files, each having over a hundred data points. Luckily, they are all identically formatted, and their names are in rising order (for example: file1.nc, file2.nc...). This is my code (unfinished as...
0
2016-07-21T19:41:41Z
38,513,534
<p>Make an empty array : </p> <pre><code>data =[] </code></pre> <p>Make a list of filenames : </p> <pre><code>flist=["001.dat","002.dat",...] </code></pre> <p>then iterate through that list: </p> <pre><code>for fn in flist: data.append( netcdf_file(fn,'r')) </code></pre> <p>Now you can refer to your da...
0
2016-07-21T20:14:09Z
[ "python", "matplotlib", "plot", "matplotlib-basemap", "colorbar" ]
python: Plotting data from multiple netCDF files
38,513,027
<p>long story short, I am plotting climate data from a netCDF file. My only problem, I have to plot data from tens of these files, each having over a hundred data points. Luckily, they are all identically formatted, and their names are in rising order (for example: file1.nc, file2.nc...). This is my code (unfinished as...
0
2016-07-21T19:41:41Z
38,517,404
<p>at the least, <code>plt.savefig("some unique name")</code> means you can generate them in a loop without having to save the plots/close them individually.</p> <p>I also suggest getting comfortable with the <a href="http://matplotlib.org/faq/usage_faq.html#figure" rel="nofollow">object oriented interface</a>:</p> <...
0
2016-07-22T02:53:08Z
[ "python", "matplotlib", "plot", "matplotlib-basemap", "colorbar" ]
direct access to msgpack'd element N from python
38,513,105
<p>I have a block of msgpack'd data is created as shown below:</p> <pre><code>#!/usr/bin/env python from io import BytesIO import msgpack packer = msgpack.Packer() buf = BytesIO() buf.write(packer.pack("foo")) buf.write(packer.pack("bar")) buf.write(packer.pack("baz")) </code></pre> <p>Later in my app (or a differ...
0
2016-07-21T19:45:23Z
38,696,555
<p>Since your packs will not be of constant size after doing a msgpack, you can use a identifiable set of bytes as a seperator of your packs. When you need direct access to Nth pack, still in packed state, you iterate over your byte array, and your Nth pack will lie after N-1 th seperator. Though this will have a O(n) ...
0
2016-08-01T10:29:28Z
[ "python", "msgpack" ]
direct access to msgpack'd element N from python
38,513,105
<p>I have a block of msgpack'd data is created as shown below:</p> <pre><code>#!/usr/bin/env python from io import BytesIO import msgpack packer = msgpack.Packer() buf = BytesIO() buf.write(packer.pack("foo")) buf.write(packer.pack("bar")) buf.write(packer.pack("baz")) </code></pre> <p>Later in my app (or a differ...
0
2016-07-21T19:45:23Z
38,726,237
<p>See <a href="http://pythonhosted.org/msgpack-python/api.html#msgpack.Unpacker.skip" rel="nofollow">http://pythonhosted.org/msgpack-python/api.html#msgpack.Unpacker.skip</a></p> <pre class="lang-py prettyprint-override"><code>packed_item3 = None def callback(b): global packed_item3 packed_item3 = b unpacker....
0
2016-08-02T16:47:22Z
[ "python", "msgpack" ]
How to return a fail value in python
38,513,225
<p>I'm looking to find a good convention on returning fail from a function if the function fails. I typically like to return None or False but in my case, the function's purpose is to read an IO, which could be bool (True/False), int or float.</p> <p>So in this case I can't return a False. I've tried to use None but I...
-2
2016-07-21T19:53:02Z
38,513,269
<p>You should raise an exception if the function fails. It is not good practice to have to check if your return value is invalid per the <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">EAFP</a> principle of Python.</p> <blockquote> <p>Easier to ask for forgiveness than permission. This com...
0
2016-07-21T19:56:43Z
[ "python", "function", "exception", "exception-handling" ]
Can I add permissions to media django media files?
38,513,295
<p>I want to build an app and let user to see some videos just if they have permissions or they paid for that video. I am using Django and I want to add ngnix and gunicorn to serve media files. I am not sure if once the user has the url of the video, how can I block him to not see the video if his payment expired or he...
0
2016-07-21T19:58:23Z
38,513,586
<p>You need to implement the so-called 'X-Sendfile feature'. Let's say your paid-for files will be served from location <code>/protected/</code> - you need to add to nginx's config:</p> <pre><code>location /protected/ { internal; root /some/path; } </code></pre> <p>then when you want to serve your user a fi...
0
2016-07-21T20:17:40Z
[ "python", "django", "nginx", "gunicorn" ]
Getting CERTIFICATE_VERIFY_FAILED. How to pass pem file to tinys3 ?
38,513,332
<p>I am trying to upload to aws s3. My python program using version 2.7.12</p> <pre><code>import tinys3 S3_ACCESS_KEY='' S3_SECRET_KEY='' conn = tinys3.Connection(S3_ACCESS_KEY,S3_SECRET_KEY,tls=True) f = open('D:\\poc\\dicomimage','rb') conn.upload('D:\\poc\\sampleimage',f,'development/system') </code></pre> <p>But...
0
2016-07-21T20:00:23Z
38,513,833
<p>You should specify the endpoint of your bucket</p> <pre><code>conn = tinys3.Connection(S3_ACCESS_KEY,S3_SECRET_KEY,tls=True,endpoint='s3-us-east-1.amazonaws.com') </code></pre> <p>change your endpoint to match the endpoint of your bucket, check <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_re...
0
2016-07-21T20:31:32Z
[ "python", "ssl", "amazon-s3" ]
Is it possible to see tensorboard over ssh?
38,513,333
<p>I am running tensorflow code remotely on a ssh server. (e.g., ssh -X account@server.address)</p> <p>On the remote server, it says <code>You can navigate to http://0.0.0.0:6006</code>.</p> <p>In this case, how can I check tensorboard? How can I navigate the address of a remote machine? I tried to search, but there...
0
2016-07-21T20:00:27Z
38,513,424
<p><code>0.0.0.0</code> is the wildcard address. Thus, you can use <strong>any</strong> address for the purpose unless the system's firewall is implementig something more restrictive.</p> <p>That said, let's assume that it <em>is</em> implementing firewall-based restrictions (if it weren't, you could just access <a hr...
3
2016-07-21T20:06:33Z
[ "python", "tensorflow", "tensorboard" ]
Pycharm will not recognize opencv3
38,513,429
<p>so guys after a painful day I have finally gotten opencv to be recognized in python 3 :</p> <pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import cv2 &gt;&...
2
2016-07-21T20:06:51Z
39,848,891
<p>An easy way to get PyCharm working with OpenCV 3 is as follows:</p> <ol> <li>Install Anaconda to a directory that doesn't require admin access from <a href="https://www.continuum.io/downloads" rel="nofollow">https://www.continuum.io/downloads</a></li> <li><p>Create a virtual environment (optional):</p> <p><code>co...
0
2016-10-04T09:35:14Z
[ "python", "opencv", "packages" ]
Inconsistency when trying to ignore SIGINT
38,513,495
<p>I am of the understanding that when you set a signal handler, all child processes inherit said handler by default.</p> <p>Thus, the following code runs as expected:</p> <pre><code>import subprocess, signal signal.signal( signal.SIGINT, signal.SIG_IGN ) # use the ignore handler subprocess.check_call( [ "sleep", "10...
0
2016-07-21T20:11:44Z
38,515,101
<blockquote> <p>I am of the understanding that when you set a signal handler, all child processes inherit said handler by default.</p> </blockquote> <p>As phrased, this is not quite right, though your example is fine.</p> <blockquote> <pre><code>signal.signal( signal.SIGINT, signal.SIG_IGN ) # use the ignore handle...
2
2016-07-21T22:03:53Z
[ "python", "git", "subprocess", "signals", "sigint" ]
No improvements using multiprocessing
38,513,640
<p>I tested the performance of <code>map</code>, <code>mp.dummy.Pool.map</code> and <code>mp.Pool.map</code></p> <pre><code>import itertools from multiprocessing import Pool from multiprocessing.dummy import Pool as ThreadPool import numpy as np # wrapper function def wrap(args): return args[0](*args[1:]) # make data ...
0
2016-07-21T20:20:21Z
38,515,922
<p>You are mapping <code>wrap</code> to <code>(a, b, c)</code>, where <code>a</code> is a function and <code>b</code> and <code>c</code> are 100K element vectors. All of this data is pickled when it is sent to the chosen process in the pool, then unpickled when it reaches it. This is to ensure that processes have mutua...
2
2016-07-21T23:24:52Z
[ "python", "multithreading", "multiprocessing", "threadpool", "python-multiprocessing" ]
What is an efficient way to return previous & next values of a looping list of objects in python?
38,513,644
<p>I have a list of python objects:</p> <pre><code>fruits = [ 'apple', 'orange', 'banana', 'grape', 'cherry' ] </code></pre> <p>I currently have a <code>for</code> loop in a class method that returns "prev_fruit" and "next_fruit" objects for a given object:</p> <pre><code>def get_prev_next(self, fruit_list): pre...
0
2016-07-21T20:20:45Z
38,513,729
<p>If the input is a list, then you're kind of stuck searching the list for the index of the fruit that you have and then getting the previous and next ones from that ...</p> <pre><code>def forgiving_getitem(lst, ix, default=None): if 0 &lt;= ix &lt; len(lst): return lst[ix] else: return defaul...
0
2016-07-21T20:25:17Z
[ "python", "loops" ]
Translate integers in a numpy array to a contiguous range 0...n
38,513,646
<p>I would like to translate arbitrary integers in a numpy array to a contiguous range 0...n, like this:</p> <pre><code>source: [2 3 4 5 4 3] translating [2 3 4 5] -&gt; [0 1 2 3] target: [0 1 2 3 2 1] </code></pre> <p>There must be a better way to than the following:</p> <pre><code>import numpy as np "translate ar...
0
2016-07-21T20:20:57Z
38,513,770
<p>IIUC you can simply use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a>'s optional argument <code>return_inverse</code>, like so -</p> <pre><code>np.unique(source,return_inverse=True)[1] </code></pre> <p>Sample run -</p> <pre><code>In [44]:...
3
2016-07-21T20:27:37Z
[ "python", "arrays", "numpy" ]
Multi-indexing - accessing the last time in every day
38,513,649
<p>New to multiindexing in Pandas. I have data that looks like this</p> <pre><code>Date Time value 2014-01-14 12:00:04 .424 12:01:12 .342 12:01:19 .341 ... 12:05:49 .23 2014-05-12 ... 1:02:42 .23 .... </code></pre> <p>For now, I want...
4
2016-07-21T20:21:18Z
38,513,946
<p>This sounds like a <code>groupby/max</code> operation. More specifically, you want to group by the <code>Date</code> and aggregate the <code>Time</code>s by taking the <code>max</code>. Since aggregation can only be done over <em>column</em> values, we'll need to change the <code>Time</code> index level into a colum...
3
2016-07-21T20:38:03Z
[ "python", "datetime", "pandas", "indexing" ]
Jupyter reveal based slideshow
38,513,660
<p>I want to create a presentation such <a href="http://www.slideviper.oquanta.info/tutorial/slideshow_tutorial_slides.html#/" rel="nofollow">this</a> starting from a simple Jupyter notebook. What I have looks like:</p> <p><a href="http://i.stack.imgur.com/Gy7WW.png" rel="nofollow"><img src="http://i.stack.imgur.com/G...
0
2016-07-21T20:21:54Z
38,664,675
<p>You may need to include a reference to the reveal.js package in your nbconvert command:</p> <pre><code>jupyter nbconvert --to slides --reveal-prefix="http://cdn.jsdelivr.net/reveal.js/2.5.0 mynotebook.ipynb --post serve </code></pre> <p>Or, for instructions on using a local version of reveal.js, see <a href="http:...
0
2016-07-29T17:45:30Z
[ "python", "jupyter-notebook", "reveal.js" ]
Get default value if key has falsy value in dict
38,513,683
<p>I am working in python, and was using <code>dict</code> in my code.</p> <p>I have case where I always need <code>default</code> value if the give <code>key</code> is not exist or if <code>key</code> exists and it has <code>falsy</code> value.</p> <p>for example</p> <pre><code>x = {'a': 'test', 'b': False, 'c': No...
0
2016-07-21T20:22:46Z
38,513,904
<p>Using <code>or</code> to <em>return</em> your default value is Pythonic. I'm not sure you will get a more <em>readable</em> workaround.</p> <p>About using <code>or</code> in the <a href="https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not" rel="nofollow">docs</a>:</p> <blockquote> <p>Th...
2
2016-07-21T20:34:59Z
[ "python", "dictionary", "default" ]
Get default value if key has falsy value in dict
38,513,683
<p>I am working in python, and was using <code>dict</code> in my code.</p> <p>I have case where I always need <code>default</code> value if the give <code>key</code> is not exist or if <code>key</code> exists and it has <code>falsy</code> value.</p> <p>for example</p> <pre><code>x = {'a': 'test', 'b': False, 'c': No...
0
2016-07-21T20:22:46Z
38,514,211
<p>Here is an ugly hack:</p> <pre><code>from collections import defaultdict x = {'a': 'test', 'b': False, 'c': None, 'd': ''} d = defaultdict(lambda : [], dict((k, v) if v is not None else (k, []) for k, v in x.items())) print(d['a']) # test print(d['b']) # False print(d['e']) # [] print(d['c']) # [] </code></pre>
0
2016-07-21T20:56:10Z
[ "python", "dictionary", "default" ]
How to sort queryset by
38,513,686
<p>There are two related classes in my code:</p> <pre><code>class TreeNode(MPTTModel): ... @property def last_payment(self): return self.annuities.last() class FilterPayment(models.Model): class Meta: verbose_name = 'взнос за фильтр' verbose_name_plural = 'взнÐ...
0
2016-07-21T20:22:54Z
38,513,866
<p>You cannot use a property to filter on Django Querysets. You can, though, do the following which will give you the desired result:</p> <pre><code>import datetime TreeNode.objects.filter(annuities__expected_date = datetime.datetime(YYYY, MM, DD)) </code></pre>
0
2016-07-21T20:33:04Z
[ "python", "django" ]
Unable to wait while iterating through webdriver dropdown
38,513,692
<p>I need assistance with web driver using python. I am trying to iterate through a dropdown list using a wait. A selected dropdown item automatically updates page so webdriverwait is needed to give the page time to update. Need to iterate through a dropdown of 10 items and wait between each item. Any examples on how t...
0
2016-07-21T20:23:11Z
38,515,680
<p>General pattern of what you want to do could be: </p> <ol> <li>Create a list of pairs <code>item to select, condition to wait for after selection</code> </li> <li>Loop on this list</li> </ol> <p>I am not very much of a python developer, so take the code below as pseudo-code with python flavour:</p> <pre><code>fro...
0
2016-07-21T22:59:28Z
[ "python", "selenium" ]
Is the continue statement necessary in a Python while loop?
38,513,718
<p>I'm confused about the use of the <code>continue</code> statement in a <code>while</code> loop.</p> <p>In this <a href="http://stackoverflow.com/a/23294659/1391441">highly upvoted answer</a>, <code>continue</code> is used inside a <code>while</code> loop to indicate that the execution should continue (obviously). I...
1
2016-07-21T20:24:34Z
38,513,752
<p><code>continue</code> just means skip to the next iteration of the loop. The behavior here is the same because nothing further happens after the <code>continue</code> statement anyways.</p> <p>The docs you quoted are just saying that you can <em>only</em> use <code>continue</code> inside of a loop structure - outsi...
2
2016-07-21T20:26:45Z
[ "python" ]
Is the continue statement necessary in a Python while loop?
38,513,718
<p>I'm confused about the use of the <code>continue</code> statement in a <code>while</code> loop.</p> <p>In this <a href="http://stackoverflow.com/a/23294659/1391441">highly upvoted answer</a>, <code>continue</code> is used inside a <code>while</code> loop to indicate that the execution should continue (obviously). I...
1
2016-07-21T20:24:34Z
38,513,811
<p>Here's a really simple example where <code>continue</code> actually does something measureable:</p> <pre><code>animals = ['dog', 'cat', 'pig', 'horse', 'cow'] while animals: a = animals.pop() if a == 'dog': continue elif a == 'horse': break print(a) </code></pre> <p>You'll notice th...
2
2016-07-21T20:30:31Z
[ "python" ]
Is the continue statement necessary in a Python while loop?
38,513,718
<p>I'm confused about the use of the <code>continue</code> statement in a <code>while</code> loop.</p> <p>In this <a href="http://stackoverflow.com/a/23294659/1391441">highly upvoted answer</a>, <code>continue</code> is used inside a <code>while</code> loop to indicate that the execution should continue (obviously). I...
1
2016-07-21T20:24:34Z
38,513,944
<p><code>continue</code> is only necessary if you want to jump to the next iteration of a loop without doing the rest of the loop. It has no effect if it's the last statement to be run.</p> <p><code>break</code> exits the loop altogether.</p> <p>An example:</p> <pre><code>items = [1, 2, 3, 4, 5] print('before loop')...
1
2016-07-21T20:37:48Z
[ "python" ]
Djano JSON field. 'module' object has no attribute 'JSONField'
38,513,827
<p>I am learning Django and was frustrated by creating a json field in a model. I was trying to create a json field in my model but got error: 'module' object has no attribute 'JSONField'. Here is my class in models.py:</p> <pre><code>class Question(models.Model): question_text = models.JSONField(max_length=200) ...
-2
2016-07-21T20:31:14Z
38,513,871
<p>There's no <code>JSONField</code> in <code>models</code> module, you need to:</p> <pre><code>from django.contrib.postgres.fields import JSONField class Question(models.Model): question_text = JSONField() </code></pre> <p>Django doc about <a href="https://docs.djangoproject.com/en/1.9/ref/contrib/postgres/fiel...
1
2016-07-21T20:33:36Z
[ "python", "django" ]
Djano JSON field. 'module' object has no attribute 'JSONField'
38,513,827
<p>I am learning Django and was frustrated by creating a json field in a model. I was trying to create a json field in my model but got error: 'module' object has no attribute 'JSONField'. Here is my class in models.py:</p> <pre><code>class Question(models.Model): question_text = models.JSONField(max_length=200) ...
-2
2016-07-21T20:31:14Z
38,513,931
<p>There's no <code>JSONField</code> in models. But there's a handy <code>jsonfield</code> package available to use <code>JSONField</code> in Django models. To install the package, do:</p> <pre><code>pip install jsonfield </code></pre> <p>Once installed, do:</p> <pre><code>from jsonfield import JSONField from django...
1
2016-07-21T20:36:49Z
[ "python", "django" ]
C++ DLL returning a pointer called from Python
38,513,929
<p>I am trying to access a C++ dll from python (I am new to Python). I overcame many calling convention issues and finally got it to run without any compile/linking error. However when I print the returning array from C++ dll in python it shows all random initialized values. It looks like the values were not correctly ...
1
2016-07-21T20:36:31Z
38,515,576
<p>Instead of </p> <pre><code>CalcDll.function1.restype = ctypes.c_double * 7 </code></pre> <p>there should be </p> <pre><code>CalcDll.function1.restype = ctypes.POINTER(ctypes.c_double) </code></pre> <p>and then</p> <pre><code>Areas = CalcDll.function1(ctypes.c_int(1), ctypes.c_int(6), arg3_py, ...
1
2016-07-21T22:47:59Z
[ "python", "c++", "pointers", "dll", "ctypes" ]
Python : calling __new__ method of superclass
38,513,986
<p>I have two python classes defined like follows : </p> <pre><code>class A(object) : def __init__(self, param) : print('A.__init__ called') self.param = param def __new__(cls, param) : print('A.__new__ called') x = object.__new__(A) x._initialize() # initializat...
0
2016-07-21T20:40:16Z
38,514,090
<p><code>convert_param</code> should either be a <code>staticmethod</code> or a <code>classmethod</code> and you don't want to be calling <code>object.__new__</code> from <code>B</code> (otherwise, you're essentially trying to create two new instances of <code>B</code> instead of just one). If <code>convert_param</cod...
2
2016-07-21T20:46:27Z
[ "python", "inheritance", "override", "subclass" ]
how to pass own dictionary to sub-template
38,514,001
<p>using <code>bottlepy</code> with the <code>simple template engine</code> i wonder how i could pass the entire dictionary that was <em>passed</em> to the template on to it's sub-templates.</p> <p>e.g. in my <code>main.py</code> i have:</p> <pre><code>@bottle.route('/') @bottle.view('main') def index(): """main ...
0
2016-07-21T20:41:01Z
38,514,098
<p>Just a thought, off the top of me head. (I.e., untested.)</p> <pre><code>@bottle.route('/') @bottle.view('main') def index(): """main page""" env = {"name": "main", "foo": 12, "flag": True} # same vars as before env["env"] = env # add a reference to the entire dict, for passing deeper into subtemplate...
2
2016-07-21T20:47:36Z
[ "python", "templates", "template-engine", "bottle" ]
Save a csr_matrix and a numpy array in one file
38,514,151
<p>I need to save a large sparse csr_matrix and a numpy array to be able to read them back later. Let X be the sparse csr_matrix and Y be the number array.</p> <p>Currently I take the following slightly insane route.</p> <pre><code>from scipy.sparse import csr_matrix import numpy as np def save_sparse_csr(filename,a...
0
2016-07-21T20:51:12Z
38,517,842
<p>So you are saving the 3 array attributes of the <code>csr</code> along with its shape. And that is sufficient to recreate the array, right?</p> <p>What's wrong with that? Even if you find a function that saves the <code>csr</code> for you, I bet it is doing the same thing - saving those same arrays.</p> <p>The n...
0
2016-07-22T03:48:11Z
[ "python", "numpy", "scipy" ]
Can you read first line from file with open(fname, 'a+')?
38,514,177
<p>I want to be able to open a file, append some text to the end, and then read only the first line. I know exactly how long the first line of the file is, and the file is large enough that I don't want to read it into memory all at once. I've tried using:</p> <pre><code>with open('./output files/log.txt', 'a+') as f:...
3
2016-07-21T20:53:45Z
38,514,309
<p>You need to go back to the start of the file using <code>seek(0)</code>, like so:</p> <pre><code>with open('./output files/log.txt', 'a+') as f_1: f_1.write('This is example text') f_1.seek(0) print(f_1.readline()) </code></pre>
1
2016-07-21T21:02:47Z
[ "python", "file", "python-3.x" ]
Can you read first line from file with open(fname, 'a+')?
38,514,177
<p>I want to be able to open a file, append some text to the end, and then read only the first line. I know exactly how long the first line of the file is, and the file is large enough that I don't want to read it into memory all at once. I've tried using:</p> <pre><code>with open('./output files/log.txt', 'a+') as f:...
3
2016-07-21T20:53:45Z
38,514,676
<p>When you open a file with the append flag <code>a</code>, it moves the file descriptor's pointer to the end of the file, so that the <code>write</code> call will add to the end of the file. </p> <p>The <code>readline()</code> function reads from the current pointer of the file until the next <code>'\n'</code> chara...
2
2016-07-21T21:28:40Z
[ "python", "file", "python-3.x" ]
Finding important features in a random forest is very slow
38,514,249
<p>I have a set of feature vectors associated with binary class labels, each of which has about 40,000 features. I train a RandomForest classifier using <code>RandomForestClassifier</code> from <code>sklearn</code> which takes about 10 minutes. I would however like to see which are the most important features.</p> <p>...
3
2016-07-21T20:58:26Z
38,514,640
<p>All you need to do is to store the results of <code>clf.feature_importances_</code> in an array and then use that to print out results. Like:</p> <pre><code>from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=50) clf = clf.fit(X, Y) featureImportance = clf.feature_importan...
1
2016-07-21T21:26:01Z
[ "python", "scikit-learn" ]
Finding important features in a random forest is very slow
38,514,249
<p>I have a set of feature vectors associated with binary class labels, each of which has about 40,000 features. I train a RandomForest classifier using <code>RandomForestClassifier</code> from <code>sklearn</code> which takes about 10 minutes. I would however like to see which are the most important features.</p> <p>...
3
2016-07-21T20:58:26Z
38,522,809
<p>I'm going to suggest a small variation, which should solve the problem automatically, because it obtains <code>feature_importances_</code> just one:</p> <pre><code>from sklearn.ensemble import RandomForestClassifier clf = RandomForestClassifier(n_estimators=50) clf = clf.fit(X, Y) for feature_importance in clf.feat...
1
2016-07-22T09:23:10Z
[ "python", "scikit-learn" ]
Can authentication via JS be faked? (Using 3rd party Authentication)
38,514,277
<p>I am looking to override the authentication for my Django backend with <a href="https://docs.fabric.io/web/fabric/overview.html" rel="nofollow">Twitter Fabric's Digits</a>. Digits allows you to sign in without a password, it is cellphone mobile authentication. </p> <p>The trick is, they provide an embed widget for ...
1
2016-07-21T21:00:30Z
38,514,461
<p>Option #1 isn't enough, but you do need to send the response to the server, and you don't need to do #2.</p> <p>If you just went with your first option and didn't do any server-side validation of the response, they could easily mock the response that you would've forwarded to the backend. Remember (ignoring firewal...
2
2016-07-21T21:13:46Z
[ "javascript", "python", "django", "authentication", "twitter-fabric" ]
Is it possible to have multiple tags in xpath, python
38,514,311
<p>I want to extract text from either an a tag or a p tag and wondering whether I can do them both in the same <code>XPATH</code>. </p> <p>XPATH would look like this: </p> <pre><code>'//*[contains(@id, "profile")]/div/div/div/div/a|h4/a' </code></pre> <p>where '|' means a tag or h4 tag</p>
0
2016-07-21T21:02:54Z
38,515,015
<p>Use <code>self</code> axis</p> <pre class="lang-none prettyprint-override"><code>//*[contains(@id, "profile")]/div/div/div/div/*[self::a or self::h4]/a </code></pre> <p>And if you want <code>.../div/a</code> or <code>.../div/h4/a</code>, use union of two Xpath</p> <pre class="lang-none prettyprint-override"><code...
1
2016-07-21T21:56:23Z
[ "python", "xpath" ]
What am I doing wrong here? Try and Except in Python
38,514,317
<p>Please read my code for better understanding of my question. I'm creating a to do list in python. In the while loop where there's try and except, I want to set the user input type as string. And if the user types in an integer I want to print out the message in the "except" block. But it doesn't execute the ValueErr...
0
2016-07-21T21:03:26Z
38,514,382
<p>Two problems with your assumptions:</p> <ol> <li>Calling <code>str</code> on an integer will not raise a <code>ValueError</code> because every integer can be represented as a string.</li> <li>Everything coming back from <code>input</code> (on Python 3 anyway, which it looks like you're using) is <em>already</em> a ...
2
2016-07-21T21:08:15Z
[ "python" ]
What am I doing wrong here? Try and Except in Python
38,514,317
<p>Please read my code for better understanding of my question. I'm creating a to do list in python. In the while loop where there's try and except, I want to set the user input type as string. And if the user types in an integer I want to print out the message in the "except" block. But it doesn't execute the ValueErr...
0
2016-07-21T21:03:26Z
38,514,384
<p><code>input</code> returns a string. See <a href="https://docs.python.org/3.5/library/functions.html#input" rel="nofollow">the docs</a> for the <code>input</code> function. Casting the result of this function to a string won't do anything.</p> <p>You could use <a href="https://docs.python.org/3/library/stdtypes.htm...
3
2016-07-21T21:08:42Z
[ "python" ]
What am I doing wrong here? Try and Except in Python
38,514,317
<p>Please read my code for better understanding of my question. I'm creating a to do list in python. In the while loop where there's try and except, I want to set the user input type as string. And if the user types in an integer I want to print out the message in the "except" block. But it doesn't execute the ValueErr...
0
2016-07-21T21:03:26Z
38,514,502
<p>In Python, <code>input</code> always returns a string. For example:</p> <pre><code>&gt;&gt;&gt; input('&gt;') &gt;4 '4' </code></pre> <p>So <code>str</code> won't throw a ValueError in this case--it's already a string.</p> <p>If you really want to check and make sure the user didn't enter just numbers you probab...
0
2016-07-21T21:16:46Z
[ "python" ]
pony.orm sort by newest Entity in relationship
38,514,429
<p>Let's say i have these tables mapped with <code>pony.orm</code>:</p> <pre><code>class Category(db.Entity): threads = Set("Thread") class Thread(db.Entity): category = Required("Category") posts = Set("Post") class Post(db.Entity): thread = Required("Thread") timestamp = Required(datetime) </co...
1
2016-07-21T21:11:23Z
38,515,885
<p>Try this:</p> <pre><code>select((p, t) for t in Thread for p in t.posts if p.id == max(p2.id for p2 in t.posts) ).order_by(lambda p, t: desc(p.id)) </code></pre>
1
2016-07-21T23:20:43Z
[ "python", "ponyorm" ]
Python - Populate dictionary from nested dictionary comprehension
38,514,485
<p>I want to populate a dictionary by iterating over two other dictionaries. I have a working example and i would like to know if there is a way to do it in dictionary comprehension (mainly for performance reasons) or make it more pythonic. First of all here is the code:</p> <pre><code>def get_replacement_map(dict_A,...
0
2016-07-21T21:15:38Z
38,514,587
<p>This is a complicated enough replacement schema that if you were to contain it all in a one-liner, it would be very difficult to read. Maintaining the structure and spacing relevant to making the flow understandable is the more pythonic way to solve this.</p> <p>As for performance gains, you likely won't see any as...
0
2016-07-21T21:22:49Z
[ "python", "python-3.x", "dictionary", "dictionary-comprehension" ]
Find shortest path from one geometry to other on shapely
38,514,607
<p>Given two lines line_a and line_b, how do I find the pair of points that represents the smaller route from line_a to line_b?</p>
0
2016-07-21T21:23:52Z
38,997,756
<p>Unfortunately, there is no shapely operation to do this. I was thinking about this problem when was asked to extend the solution in the question <a href="http://stackoverflow.com/questions/33311616/find-coordinate-of-closest-point-on-polygon-shapely/33324058#33324058">find-coordinate-of-closest-point-on-polygon-sha...
0
2016-08-17T13:16:00Z
[ "python", "shapely" ]
IPython Notebook with remote ipyparallel Controller
38,514,648
<p>I'm currently trying to setup a remote cluster on a group of servers I own using the ipyparallel library. I figured that if I share the $IPYTHONDIR between all ipcontrollers, ipengines and notebook that everything would just connect and work, but this is not the case for my current setup.</p> <p>What I'm attempting...
0
2016-07-21T21:26:40Z
40,042,575
<p>Yes this is possible if the notebook kernel is running on the same server as the ipcontroller. The notebook itself can be displayed from any browser. I use that functionality regularly.</p> <p>The way I have done it is to have an ipython profile available on the server. In my case it's a Windows server and the prof...
0
2016-10-14T11:54:37Z
[ "python", "ipython", "ipython-parallel" ]
How to use the output from OneHotEncoder in sklearn?
38,514,682
<p>I have a Pandas Dataframe with 2 categorical variables, and ID variable and a target variable (for classification). I managed to convert the categorical values with <code>OneHotEncoder</code>. This results in a sparse matrix. </p> <pre><code>ohe = OneHotEncoder() # First I remapped the string values in the categori...
2
2016-07-21T21:28:58Z
38,519,416
<p>I see you are already using Pandas, so why not using its <code>get_dummies</code> function?</p> <pre><code>import pandas as pd df = pd.DataFrame([['rick','young'],['phil','old'],['john','teenager']],columns=['name','age-group']) </code></pre> <p>result</p> <pre><code> name age-group 0 rick young 1 phil ...
1
2016-07-22T06:16:37Z
[ "python", "pandas", "scikit-learn", "classification", "one-hot-encoding" ]
How to use the output from OneHotEncoder in sklearn?
38,514,682
<p>I have a Pandas Dataframe with 2 categorical variables, and ID variable and a target variable (for classification). I managed to convert the categorical values with <code>OneHotEncoder</code>. This results in a sparse matrix. </p> <pre><code>ohe = OneHotEncoder() # First I remapped the string values in the categori...
2
2016-07-21T21:28:58Z
38,519,889
<p>Look at this example from scikit-learn: <a href="http://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html#example-ensemble-plot-feature-transformation-py" rel="nofollow">http://scikit-learn.org/stable/auto_examples/ensemble/plot_feature_transformation.html#example-ensemble-plot-feature-...
0
2016-07-22T06:46:55Z
[ "python", "pandas", "scikit-learn", "classification", "one-hot-encoding" ]
isinstance() returns false when the fully-qualified object class differs from the qualified class
38,514,730
<p>When a 3rd party library method uses <code>isinstance()</code> to compare an object with a class, it returns <code>False</code> because it compares the fully qualified class name of the object with a qualified class name that starts "higher" up. </p> <p>E.g.: <code>isinstance()</code> finds that the object class an...
0
2016-07-21T21:33:03Z
38,514,785
<p>For it to return True, the first argument to <code>isinstance</code> must be an <em>instance</em> of the second. Providing the same class for both arguments results in a False:</p> <pre><code>&gt;&gt;&gt; isinstance( int, int) False &gt;&gt;&gt; isinstance( int(1), int) True </code></pre> <p>Here, <code>int</code...
5
2016-07-21T21:36:58Z
[ "python", "python-2.7" ]
isinstance() returns false when the fully-qualified object class differs from the qualified class
38,514,730
<p>When a 3rd party library method uses <code>isinstance()</code> to compare an object with a class, it returns <code>False</code> because it compares the fully qualified class name of the object with a qualified class name that starts "higher" up. </p> <p>E.g.: <code>isinstance()</code> finds that the object class an...
0
2016-07-21T21:33:03Z
38,516,793
<p>As far as Python is concerned, the classes <code>network.mhistory.service.mhistory_messages.MHistoryActivityViewMessage</code> and <code>backend.network.mhistory.service.mhistory_messages.MHistoryActivityViewMessage</code> are not the same. That's true even if they have exactly the same definition because they were ...
2
2016-07-22T01:22:58Z
[ "python", "python-2.7" ]
Is this a bad use of django class based views?
38,514,784
<p>sometimes I have a hard time seeing if I am doing something the right way or not. Here is how I am using class based views in a project of mine. </p> <pre><code>class View(View): def get(self, request): if request.GET.get('something'): ...do something elif request.GET.get('bar'): ...
1
2016-07-21T21:36:52Z
38,514,835
<p>When you use POST to send a form, you don't need to validate every single field in your view, you can do this in your form class. Check <a href="https://docs.djangoproject.com/es/1.9/ref/forms/validation/#form-and-field-validation" rel="nofollow">docs</a>.</p>
2
2016-07-21T21:41:05Z
[ "python", "django" ]
Is this a bad use of django class based views?
38,514,784
<p>sometimes I have a hard time seeing if I am doing something the right way or not. Here is how I am using class based views in a project of mine. </p> <pre><code>class View(View): def get(self, request): if request.GET.get('something'): ...do something elif request.GET.get('bar'): ...
1
2016-07-21T21:36:52Z
38,514,892
<p>To handle POST data, you should rather use a <a href="https://docs.djangoproject.com/en/stable/ref/class-based-views/generic-editing/#formview" rel="nofollow"><code>FormView</code></a> or even a "model edit" view such as <a href="https://docs.djangoproject.com/en/stable/ref/class-based-views/generic-editing/#createv...
1
2016-07-21T21:46:22Z
[ "python", "django" ]
python Timedelta overflow
38,514,856
<p>I am trying to return a timedelta but when time_value is too large it overflows and gives an error. I can use a check to see if time_value is too large but I would prefer a wrapper that handles the error and returns a default. I have included the code for what I'm doing right now. Is there a version of timedelta or ...
1
2016-07-21T21:43:22Z
38,514,955
<p>You could use <a href="https://docs.python.org/2/library/datetime.html#datetime.timedelta.min" rel="nofollow"><code>datetime.timedelta.min</code></a> and <a href="https://docs.python.org/2/library/datetime.html#datetime.timedelta.max" rel="nofollow"><code>datetime.timedelta.max</code></a>. Note that these two are no...
0
2016-07-21T21:51:17Z
[ "python", "python-2.7", "integer-overflow", "timedelta" ]
String to Integer error on file name
38,514,874
<p>I'm trying to add 59 to the 3 digits in a specific position in all the files in my folder, but it gives this error:</p> <p><strong>ValueError: invalid literal for int() with base 10: ''</strong></p> <p>I have checked with prints, and is indeed a 3 char string, containing only digits(by the looks)</p> <p>Code :</p...
1
2016-07-21T21:44:46Z
38,515,391
<p>Your code is very fragile, and functions like <code>left</code>, <code>mid</code>, and <code>right</code> suggest you are more used to another language.</p> <p>Among other things, this only works if your current directory contains the files, because <code>listdir</code> only returns the file name, not it's path. So...
1
2016-07-21T22:29:31Z
[ "python", "python-2.7", "operating-system" ]
convert txt file to xls in python and add new columns
38,514,894
<p>I have a text file like this content :</p> <pre><code>28179 49172 40180 36228 29337 </code></pre> <p>I want to convert text file to excel output <strong>".xls"</strong> that <strong>has two columns</strong> as follow :</p> <pre><code>ID ---- Code 1 ---- 28179 2 ---- 49172 3 ---- 40180 4...
0
2016-07-21T21:46:26Z
38,515,266
<p>First import the <a href="https://pypi.python.org/pypi/xlwt" rel="nofollow">xlwt library</a> and read the file and save it in an array:</p> <pre><code>import xlwt data = [] with open("data.txt") as f: for line in f: data.append(line) </code></pre> <p>Then copy that array and write the new column to an...
0
2016-07-21T22:18:31Z
[ "python", "excel", "text", "xls" ]
convert txt file to xls in python and add new columns
38,514,894
<p>I have a text file like this content :</p> <pre><code>28179 49172 40180 36228 29337 </code></pre> <p>I want to convert text file to excel output <strong>".xls"</strong> that <strong>has two columns</strong> as follow :</p> <pre><code>ID ---- Code 1 ---- 28179 2 ---- 49172 3 ---- 40180 4...
0
2016-07-21T21:46:26Z
39,353,126
<p>suppose you have the data saved in '<strong>data.txt</strong>' and if you could install,</p> <pre><code>pip install pyexcel-io pip install pyexcel-xls </code></pre> <p>you can use the following code:</p> <pre><code>from pyexcel_io import save_data SYMBOL = '----' def data_gen(text_file): yield ['ID', SYMBOL...
0
2016-09-06T15:51:25Z
[ "python", "excel", "text", "xls" ]
what is the order of the dictionary in python
38,514,915
<p>I have a question about the order of the dictionary in python. I am in python 2.7</p> <pre><code>array ={"dad":"nse","cat":"error","bob":"das","nurse":"hello"} for key in array: print key </code></pre> <p>why result shows </p> <pre><code>dad bob nurse cat </code></pre> <p>NOT</p> <pre><code>dad cat bob nu...
-4
2016-07-21T21:47:58Z
38,514,943
<p>In the standard Python implementation, CPython, dictionaries have no guaranteed order, <a href="https://docs.python.org/2/library/stdtypes.html#dict.items" rel="nofollow">per the docs</a>.</p>
1
2016-07-21T21:49:55Z
[ "python", "python-2.7", "dictionary" ]