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 |
|---|---|---|---|---|---|---|---|---|---|
Latex command \bar not working properly in Python docstring | 37,470,072 | <p>I have a function with a docstring as follows,</p>
<pre><code>def func(x):
'''Boring function
Notes
-----
Let :math:`\bar{x}_k = \sum_{i=1}^{n_k}x_{ik}`,
'''
return x
</code></pre>
<p>But the <code>\bar</code> command in Latex renders as "ar",</p>
<p><a href="http://i.stack.imgur.com/62... | 2 | 2016-05-26T20:07:55Z | 37,470,187 | <p>Python is interpreting the backslashes. You need to pass the backslashes through so LaTeX can interpret them; you should use a <a href="http://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-in-python-and-what-are-raw-string-l">raw string</a> to do so:</p>
<pre><code>def func(x):
# ... | 3 | 2016-05-26T20:16:37Z | [
"python",
"latex",
"docstring"
] |
Plot3d in Python | 37,470,076 | <p>I have an OBJ File Generated by Meshlab with Vertices and Faces data.
In MATLAB i used the function ''patch'' with Vertices data in 1 array (5937x3) and Faces (11870x3) data in another and the result is this:</p>
<pre><code>Simplified version of the code
[V,F] = read_vertices_and_faces_from_obj_file(filename);
pa... | 2 | 2016-05-26T20:08:10Z | 37,470,951 | <p>Your best bet would be to make use of the <a href="http://matplotlib.org/mpl_toolkits/mplot3d/" rel="nofollow"><code>mplot3d</code> toolkit</a> from the <code>matplotlib</code> library.</p>
<p>A similar question was asked <a href="http://stackoverflow.com/questions/4622057/plotting-3d-polygons-in-python-matplotlib"... | 2 | 2016-05-26T21:02:29Z | [
"python",
"matlab",
"mplot3d"
] |
Python Filter Specific Post Response | 37,470,182 | <p>My Python code sends JSON POST request to a service and it gets back a JSON with information.</p>
<p>My Code: </p>
<pre><code>for username in data:
for text in data[username]:
body = json.dumps({ "text": text['text'], "extract_type": "mitie"})
r = requests.post('http://localhost:3003/api/extrac... | 0 | 2016-05-26T20:16:14Z | 37,470,637 | <p>In requests, the repsonse <code>content</code> is the raw response, which is a string. You are trying to use it as a dict, which is why <code>r.content['tag']</code> raises a TypeError. </p>
<p>In order to use the response json data, you need to decode the json response using <a href="http://docs.python-requests.or... | 0 | 2016-05-26T20:44:20Z | [
"python",
"json",
"http-post",
"httprequest"
] |
Speed up openpyxl reading | 37,470,392 | <p>I am working on a quite large program that is taking data from again, quite a large excel spreadsheet.
For some strange reason it takes though ages to load this big excel file, and I was hoping to speed it up somehow.
I did my own research and tried read_only, but that didnt allow me to read any cells (at least th... | -1 | 2016-05-26T20:28:28Z | 37,518,724 | <p>As I've already said, you're working against the API. If the dimension of the worksheet are known then you can access them otherwise you can build your own counters there is little point.</p>
<p>Read-only mode is very fast for individual lookups, but as <strong>each</strong> lookup involves parsing all cells in the... | 0 | 2016-05-30T06:11:40Z | [
"python",
"openpyxl"
] |
PyCharm can no longer find my Python installation | 37,470,399 | <p>My PyCharm ver was working fine, but I broke it.</p>
<p>I wanted to have the matplotlib, so I uninstalled my Python installation and installed <a href="https://winpython.github.io/" rel="nofollow">WinPython</a>, which works fine. But it was installed in the folder where installation program was (i.e. download folde... | -1 | 2016-05-26T20:28:52Z | 37,470,938 | <p>It's <strong>Project: (project name)</strong> â <strong>Project Interpreter</strong> â "Gear" icon â <strong>Add local</strong>.</p>
<p><a href="http://i.stack.imgur.com/V1c2m.png" rel="nofollow"><img src="http://i.stack.imgur.com/V1c2m.png" alt="Project: (project name) â Project Interpreter â **Gear** ic... | 0 | 2016-05-26T21:01:48Z | [
"python",
"pycharm"
] |
Display a pandas data frame with Bokeh | 37,470,415 | <p>Is there a nice way to display data frames with Bokeh? I have a bunch of table-based text I'd like to display and dynamically update along with some graphs, but I haven't found a good way to do this yet.</p>
| 1 | 2016-05-26T20:30:16Z | 37,471,054 | <p>You want to use bokeh.models.widgets.DataTable:</p>
<p><a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#data-table" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#data-table</a></p>
| 0 | 2016-05-26T21:08:42Z | [
"python",
"bokeh"
] |
Display a pandas data frame with Bokeh | 37,470,415 | <p>Is there a nice way to display data frames with Bokeh? I have a bunch of table-based text I'd like to display and dynamically update along with some graphs, but I haven't found a good way to do this yet.</p>
| 1 | 2016-05-26T20:30:16Z | 37,477,705 | <p>You should take a look into bokeh.models.widgets.DataTable (<a href="http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#data-table" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/user_guide/interaction.html#data-table</a>)</p>
<p>Example:</p>
<pre><code>from datetime import date
from random ... | 1 | 2016-05-27T07:44:40Z | [
"python",
"bokeh"
] |
Fast way of slicing columns from tuples | 37,470,451 | <p>I have a huge list of tuples from which I want to extract individual columns. I have tried two methods.
Assuming the name of the list name is <strong>List</strong> and I want to extract the <strong>jth column.</strong></p>
<p>First one is</p>
<pre><code>column=[item[j] for item in List]
</code></pre>
<p>Second on... | 1 | 2016-05-26T20:32:39Z | 37,470,527 | <p>this is something numpy does well </p>
<pre><code>A = np.array(Lst) # this step may take a while now ... maybe you should have Lst as a np.array before you get to this point
sliced = A[:,[j]] # this should be really quite fast
</code></pre>
<p>that said </p>
<pre><code>newList=zip(*List)
column=newList[j]
</code... | 1 | 2016-05-26T20:36:56Z | [
"python",
"python-2.7"
] |
Producing Empty TKinter GUIs | 37,470,493 | <p>The following TKinter code is producing an empty TK window. I cannot figure out why. I am packing everything appropriately. The map is the first Frame that is supposed to come up but when it launches there is only the top bar without any image or button. I also tried launching the hydra level frame first and it prod... | 0 | 2016-05-26T20:34:59Z | 37,471,095 | <blockquote>
<p>I am packing everything appropriately</p>
</blockquote>
<p>No, you are not. You aren't calling <code>pack</code>, <code>place</code> or <code>grid</code> on <code>the</code>Map<code>or</code>Hydra` objects.</p>
| 0 | 2016-05-26T21:11:14Z | [
"python",
"user-interface",
"tkinter"
] |
How to make "value is in dateframe column" quicker | 37,470,503 | <p>I have code which has <code>userID</code>, <code>categoryID</code> and <code>date</code> as input values. I want to check if the entries are valid, e.g. if the <code>userID</code> does even exist in my dataset.
It works the way I do it, but I have to wait a few seconds(!) until the main programm is executed.</p>
<... | 1 | 2016-05-26T20:35:20Z | 37,470,832 | <p>What do you mean by </p>
<blockquote>
<p>But df_data['UserID'].unique.tolist() doesn't work.</p>
</blockquote>
<p>?</p>
<p>Do you mean the command is failing? That's probably because unique is a function, you have to call it</p>
<pre><code>df_data['UserID'].unique().tolist()
</code></pre>
<p>Or do you mean i... | 1 | 2016-05-26T20:55:50Z | [
"python",
"pandas",
"dataframe",
"runtime",
"iteration"
] |
How to make "value is in dateframe column" quicker | 37,470,503 | <p>I have code which has <code>userID</code>, <code>categoryID</code> and <code>date</code> as input values. I want to check if the entries are valid, e.g. if the <code>userID</code> does even exist in my dataset.
It works the way I do it, but I have to wait a few seconds(!) until the main programm is executed.</p>
<... | 1 | 2016-05-26T20:35:20Z | 37,470,840 | <p>For these kind of containment checks you should make User (and Category) an index:</p>
<pre><code>if (~var_uid in df_data['UserID'].values) :
elif (~df_data['CategoryID'].str.contains(var_catid).any()) :
</code></pre>
<p>once these are in the index (Note: this should be done outside of this block, not every time)... | 1 | 2016-05-26T20:56:02Z | [
"python",
"pandas",
"dataframe",
"runtime",
"iteration"
] |
How to make "value is in dateframe column" quicker | 37,470,503 | <p>I have code which has <code>userID</code>, <code>categoryID</code> and <code>date</code> as input values. I want to check if the entries are valid, e.g. if the <code>userID</code> does even exist in my dataset.
It works the way I do it, but I have to wait a few seconds(!) until the main programm is executed.</p>
<... | 1 | 2016-05-26T20:35:20Z | 37,471,141 | <p>Consider creating lookup indexes, then you get log-speed access. Here's an example:</p>
<pre><code>import pandas as pd
import numpy as np
n = int(1e6)
np.random.seed(0)
df = pd.DataFrame({
'uid': np.arange(n),
'catid': np.repeat('foo bar baz', n),
})
</code></pre>
<p>The slower version:</p>
<pre><code>&... | 1 | 2016-05-26T21:15:10Z | [
"python",
"pandas",
"dataframe",
"runtime",
"iteration"
] |
How to make "value is in dateframe column" quicker | 37,470,503 | <p>I have code which has <code>userID</code>, <code>categoryID</code> and <code>date</code> as input values. I want to check if the entries are valid, e.g. if the <code>userID</code> does even exist in my dataset.
It works the way I do it, but I have to wait a few seconds(!) until the main programm is executed.</p>
<... | 1 | 2016-05-26T20:35:20Z | 37,471,692 | <p>Thanks a lot to all contributors! For my <code>UserID</code> I used the solution with setting it as the index. For my <code>CategoryID</code> I created the set and stored it in my programm. </p>
<p>Plus, I found another bottleneck which was even worse:</p>
<pre><code>s_all = df_data[df_data.columns[7]]
s_all_datet... | 0 | 2016-05-26T21:57:05Z | [
"python",
"pandas",
"dataframe",
"runtime",
"iteration"
] |
New to Python and working on it to mess with JSON files | 37,470,661 | <p>So I'm new to phython, and I was wondering on how I could modify(adding or subtracting) each individual "x" in one go.</p>
<pre><code> "Position": {
"7,-5": {
"id": "58",
"y": -5,
"x": 7
},
"2,-4": {
"id":... | 0 | 2016-05-26T20:45:49Z | 37,470,714 | <pre><code>for value in position_data['Position'].values():
value['x'] += 1
</code></pre>
<p>Use <code>itervalues</code> in Python 2 for better efficiency.</p>
<p>Demo (since I got downvoted without explanation):</p>
<pre><code>from pprint import pprint
position_data = {
"Position": {
"7,-5": {
... | 3 | 2016-05-26T20:49:13Z | [
"python",
"json"
] |
New to Python and working on it to mess with JSON files | 37,470,661 | <p>So I'm new to phython, and I was wondering on how I could modify(adding or subtracting) each individual "x" in one go.</p>
<pre><code> "Position": {
"7,-5": {
"id": "58",
"y": -5,
"x": 7
},
"2,-4": {
"id":... | 0 | 2016-05-26T20:45:49Z | 37,470,758 | <p>you could do something like this:</p>
<pre><code>for key in position_data['Position'].keys():
position_data['Position'][key]['x'] += 1
</code></pre>
| 3 | 2016-05-26T20:52:03Z | [
"python",
"json"
] |
Overlay plots and scroll independently matplotlib | 37,470,835 | <p>The problem I have can be described as follows:
Two different datasets with two different x and y axes (lets call them t1,y1,t2, and y2), t1 and t2 can be the same.</p>
<p>What I need to do is to overlay/plot both plots together (i.e, not in subplots, or in subplots that are the same size and exactly overlap one an... | 2 | 2016-05-26T20:55:55Z | 37,471,240 | <p>Here's a basic example I can get working with two random datasets where you can vary the x-axis position of the two datasets independently on the same plot.</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
t = np.linspace(0, 10, 101)
y1, y2 = np.random.rand(2, 101)
fig, ax1 = p... | 2 | 2016-05-26T21:22:44Z | [
"python",
"numpy",
"matplotlib",
"plot"
] |
Python thinks a file is empty when opened in binary read | 37,470,886 | <p>I'm running Python 3.5.1 on Windows. I am attempting to find duplicate source code files in a directory by computing their hash. The problem is that Python seems to think some files are empty. Here is the relevant code snippet:</p>
<pre><code>with open(path, 'rb') as afile:
hasher = hashlib.md5()
data = afi... | 2 | 2016-05-26T20:59:40Z | 37,470,955 | <p>I think you should computer the hash by calling hashlib.md5 on the files them self</p>
<pre><code>import hashlib
hashlib.md5("filename").hexdigest()
</code></pre>
<p>Let me know if that continues to suggest files are empty</p>
| -1 | 2016-05-26T21:02:40Z | [
"python"
] |
Python thinks a file is empty when opened in binary read | 37,470,886 | <p>I'm running Python 3.5.1 on Windows. I am attempting to find duplicate source code files in a directory by computing their hash. The problem is that Python seems to think some files are empty. Here is the relevant code snippet:</p>
<pre><code>with open(path, 'rb') as afile:
hasher = hashlib.md5()
data = afi... | 2 | 2016-05-26T20:59:40Z | 37,485,264 | <p>I'll just delete this answer if it is not the case, but it's something you need to check. Put this directly before the open block</p>
<pre><code>print("the path is {!r}".format(path))
print("path exists: ", os.path.exists(path))
print("it is a file: ", os.path.isfile(path))
print("file size is: ", os.path.getsize(p... | 2 | 2016-05-27T13:52:37Z | [
"python"
] |
Trying to Implement Python-Style len() in JavaScript | 37,470,907 | <p>I've been reading a lot about <code>call()</code> and <code>bind()</code> in JavaScript, specifically the <strong>Creating Shorcuts</strong> section on this <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind" rel="nofollow">MDN article</a>.</p>
<p>I'm trying to i... | 1 | 2016-05-26T21:00:51Z | 37,471,943 | <p>When you're setting the variable <code>len</code>, in your code, you're actually setting <code>len</code> to a copy of the function <code>Function.prototype.call</code>, with a <code>this</code> (context) of <code>Array.prototype.slice.length</code>.</p>
<p>I think you're misunderstanding the use of bind(). Say I h... | 1 | 2016-05-26T22:16:07Z | [
"javascript",
"python",
"call",
"bind",
"apply"
] |
Getting more than 700k followers ID from twitter using python | 37,470,945 | <p>I was able to get the number of 75,000. After that, It keeps on pulling duplicate IDs. Here is my code. Can I get any suggestions so that I can correctly pull the large amount of follower Ids without duplicates?</p>
<pre><code>import tweepy
import time
access_token = "..."
access_token_secret = "..."
consumer_key ... | 0 | 2016-05-26T21:02:09Z | 37,471,805 | <p>I don't know why you are getting duplicates, but you could put the values into a set rather than a list to remove them efficiently. </p>
<p>Just change <code>ids = []</code> to <code>ids = set()</code></p>
<p>and <code>ids.extend(page)</code> to <code>ids.update(page)</code></p>
| 0 | 2016-05-26T22:06:07Z | [
"python",
"twitter"
] |
Removing stopwords from list using python3 | 37,470,966 | <p>I have been trying to remove stopwords from a csv file that im reading using python code but my code does not seem to work. I have tried using a sample text in the code to validate my code but it is still the same . Below is my code and i would appreciate if anyone can help me rectify the issue.. here is the code be... | 0 | 2016-05-26T21:03:09Z | 37,471,058 | <p>Your <code>tokenized_models</code> is a list of tokenized sentences, so a list of lists. Ergo, the following line tries to match a list of words to a stopword:</p>
<pre><code>stop_models = [i for i in tokenized_models if str(i).lower() not in stopset]
</code></pre>
<p>Instead, iterate again through words. Somethin... | 1 | 2016-05-26T21:08:55Z | [
"python",
"python-3.x",
"nltk",
"stop-words"
] |
Removing stopwords from list using python3 | 37,470,966 | <p>I have been trying to remove stopwords from a csv file that im reading using python code but my code does not seem to work. I have tried using a sample text in the code to validate my code but it is still the same . Below is my code and i would appreciate if anyone can help me rectify the issue.. here is the code be... | 0 | 2016-05-26T21:03:09Z | 37,471,067 | <p><code>word_tokenize(str(i))</code> returns a list of words, so <code>tokenized_models</code> is a list of lists. You need to flatten that list, or better yet just make <code>article</code> a single string, since I don't see why it's a list at the moment.</p>
<p>This is because the <code>in</code> operator won't sea... | 0 | 2016-05-26T21:09:26Z | [
"python",
"python-3.x",
"nltk",
"stop-words"
] |
correcting the rectangular mask for any tilt using opencv | 37,471,012 | <p>I have to extract a rectangular object from a grayscale image. I am using thresholding to extract rectangular mask as shown below</p>
<p><a href="http://i.stack.imgur.com/JEln9.png" rel="nofollow"><img src="http://i.stack.imgur.com/JEln9.png" alt="enter image description here"></a></p>
<p>Sometimes, the rectangula... | 2 | 2016-05-26T21:05:56Z | 37,471,526 | <p>You should be able to do something with <code>getPerspectiveTransform</code>, I used it <a href="https://github.com/JulienPalard/grid-finder/blob/master/grid_finder.py#L407" rel="nofollow">in a grid finder</a>, my usage is not really the exact same as yours, but you can certainly learn enough by reading it. I'm no o... | 1 | 2016-05-26T21:44:18Z | [
"python",
"opencv",
"image-rotation",
"affinetransform"
] |
error with persisted sklearn.feature_extraction.text.TfidfVectorizer | 37,471,052 | <p>I persisted a TfidfVectorizer using the module joblib. The object that I run through the method fit_transform was a list of strings.
The resulting matrix had a dimensionality of 263744 columns.</p>
<p>I am running a list of strings through the transform method, and I get the following error.</p>
<p>Any clues?</p>
... | 1 | 2016-05-26T21:08:35Z | 38,960,281 | <p>Assuming you are persisting the trained transformer or pipeline to disk, and then reloading it before seeing the error, you could:</p>
<ol>
<li><p>Try saving the original (working) object using the <strong>compress</strong> keyword argument parameter to <code>joblib.dump</code>, with an integer value greater than 0... | 0 | 2016-08-15T17:53:27Z | [
"python",
"scikit-learn",
"joblib"
] |
Python in ArcGIS to utilize python-docx - IOError: [Errno 13] Permission denied: | 37,471,079 | <p>I am still relatively new to python and I am attempting to translate the output from a Script Tool I designed in Python to produce a Microsoft Word Doc.<br>
I keep receiving:</p>
<p>IOError: [Errno 13] Permission denied: '5_26_2016.docx'</p>
<p>Can anyone explain what I have done or how I could possibly fix this. ... | 0 | 2016-05-26T21:10:32Z | 37,491,320 | <p>Always double check your pathnames to the parent folder. It was that it wouldn't open. It could not find the folder it needed to in order to open it. </p>
| 0 | 2016-05-27T19:55:09Z | [
"python",
"arcpy",
"errno",
"python-docx"
] |
How do I write words and their frequencies into two separate columns in CSV file | 37,471,219 | <p>I have the desired input (a <code>Counter</code> object, from my <a href="http://stackoverflow.com/questions/37423684/how-do-i-split-a-list-of-phrases-into-words-so-i-can-use-counter-on-them">previous question</a>), which looks like this:</p>
<pre><code> (u'twice', 4302),
(u'thru', 4286),
(u'mailing', 4276),
... | 0 | 2016-05-26T21:21:13Z | 37,471,267 | <p>Iterating through a <code>Counter</code> is like iterating through a dictionary - you only get the keys. <code>writerow()</code> requires a sequence, so <code>val</code> isn't enough, but wrapping it in brackets to make a <code>list</code> with <code>[val]</code> just allows you to write that key as a single column.... | 1 | 2016-05-26T21:24:58Z | [
"python",
"csv",
"two-columns"
] |
Determining Python version with platform.version | 37,471,289 | <p>I'm trying to run a Python package (ig-markets-api-python-library, it has a share price streaming function), which I've had running before, and am loosing my mind trying to figure out why I can't get it working again. This might be a bit of a noob question, so thanks for the help. I'm running Python 3.5.1 with Anaco... | 0 | 2016-05-26T21:26:16Z | 37,471,361 | <p>Looks like they got a bit confused.</p>
<pre><code>>>> platform.python_version()
'2.7.10'
</code></pre>
| 1 | 2016-05-26T21:32:07Z | [
"python",
"bunch"
] |
Determining Python version with platform.version | 37,471,289 | <p>I'm trying to run a Python package (ig-markets-api-python-library, it has a share price streaming function), which I've had running before, and am loosing my mind trying to figure out why I can't get it working again. This might be a bit of a noob question, so thanks for the help. I'm running Python 3.5.1 with Anaco... | 0 | 2016-05-26T21:26:16Z | 37,471,374 | <p>You should change:</p>
<pre><code>import platform
_IS_PYTHON_3 = (platform.version() >= '3')
</code></pre>
<p>to:</p>
<pre><code>import sys
_IS_PYTHON_3 = (sys.version >= '3')
</code></pre>
| 1 | 2016-05-26T21:32:44Z | [
"python",
"bunch"
] |
Determining Python version with platform.version | 37,471,289 | <p>I'm trying to run a Python package (ig-markets-api-python-library, it has a share price streaming function), which I've had running before, and am loosing my mind trying to figure out why I can't get it working again. This might be a bit of a noob question, so thanks for the help. I'm running Python 3.5.1 with Anaco... | 0 | 2016-05-26T21:26:16Z | 38,332,809 | <p>Confirm: under Ubuntu, <code>pip install trading_ig</code> does install an old version.
Under Mac it does not occur.</p>
<p>So the right way to install the module is:</p>
<p>(only if you have already installed the module with pip)</p>
<pre><code>$ pip uninstall trading_ig
</code></pre>
<p>(and then)</p>
<pre><c... | 1 | 2016-07-12T15:12:33Z | [
"python",
"bunch"
] |
setup_requires with Cython? | 37,471,313 | <p>I'm creating a <code>setup.py</code> file for a project with some Cython extension modules.</p>
<p>I've already gotten this to work:</p>
<pre><code>from setuptools import setup, Extension
from Cython.Build import cythonize
setup(
name=...,
...,
ext_modules=cythonize([ ... ]),
)
</code></pre>
<p>This ... | 1 | 2016-05-26T21:28:16Z | 37,471,428 | <p>You must wrap the <code>from Cython.Build import cythonize</code> in a <code>try-except</code>, and in the <code>except</code>, define <code>cythonize</code> as a dummy function. This way the script can be loaded without failing with an <code>ImportError</code>.</p>
<p>Then later when the <code>setup_requires</code... | 1 | 2016-05-26T21:37:04Z | [
"python",
"build",
"cython",
"setuptools",
"software-distribution"
] |
setup_requires with Cython? | 37,471,313 | <p>I'm creating a <code>setup.py</code> file for a project with some Cython extension modules.</p>
<p>I've already gotten this to work:</p>
<pre><code>from setuptools import setup, Extension
from Cython.Build import cythonize
setup(
name=...,
...,
ext_modules=cythonize([ ... ]),
)
</code></pre>
<p>This ... | 1 | 2016-05-26T21:28:16Z | 38,057,196 | <p>Starting from <a href="https://github.com/pypa/setuptools/blob/master/CHANGES.rst#180" rel="nofollow">18.0</a> release of <code>setuptools</code> (released on 2015-06-23) it is possible to specify <code>Cython</code> in <code>setup_requires</code> and pass <code>*.pyx</code> modules sources for regular <code>setupto... | 1 | 2016-06-27T14:56:30Z | [
"python",
"build",
"cython",
"setuptools",
"software-distribution"
] |
Can I use a generator expression to print key,value pairs of a list of dictionaries? | 37,471,488 | <p>I have a list of dictionaries:</p>
<pre><code>dictlist = [{'key1':'value1', 'key2':'value2'}, {'key3':'value3', 'key4':'value4'}]
</code></pre>
<p>I currently print key, value pairs like this:</p>
<pre><code>for d in dictlist:
for key in d:
print .format('{} ---> {}').format(key,d[key])
</code></pre>
<p... | 1 | 2016-05-26T21:41:53Z | 37,471,561 | <p>You could use a generator expression and <code>itertools</code> to one-line it.</p>
<pre><code>from itertools import chain, imap
print '\n'.join('{} ---> {}'.format(k,v) for k, v in chain.from_iterable(d.iteritems() for d in dictlist))
</code></pre>
<p><code>d.itervalues()</code> returns a generator of all the... | -1 | 2016-05-26T21:47:21Z | [
"python",
"dictionary",
"list-comprehension",
"generator-expression"
] |
Can I use a generator expression to print key,value pairs of a list of dictionaries? | 37,471,488 | <p>I have a list of dictionaries:</p>
<pre><code>dictlist = [{'key1':'value1', 'key2':'value2'}, {'key3':'value3', 'key4':'value4'}]
</code></pre>
<p>I currently print key, value pairs like this:</p>
<pre><code>for d in dictlist:
for key in d:
print .format('{} ---> {}').format(key,d[key])
</code></pre>
<p... | 1 | 2016-05-26T21:41:53Z | 37,471,563 | <p>There would be no real benefit to making your code horizontal instead of vertical, but you can do so as follows:</p>
<pre><code>from __future__ import print_function
from itertools import imap
print(*(' ---> '.join(imap(str, item)) for dic in dictlist for item in dic.iteritems()), sep='\n')
</code></pre>
<p>Res... | 2 | 2016-05-26T21:47:28Z | [
"python",
"dictionary",
"list-comprehension",
"generator-expression"
] |
Can I use a generator expression to print key,value pairs of a list of dictionaries? | 37,471,488 | <p>I have a list of dictionaries:</p>
<pre><code>dictlist = [{'key1':'value1', 'key2':'value2'}, {'key3':'value3', 'key4':'value4'}]
</code></pre>
<p>I currently print key, value pairs like this:</p>
<pre><code>for d in dictlist:
for key in d:
print .format('{} ---> {}').format(key,d[key])
</code></pre>
<p... | 1 | 2016-05-26T21:41:53Z | 37,471,573 | <p>Umm, what you have is probably the most readable version. I'd probably go with it.</p>
<p>But if you want a more compact version, how about:</p>
<pre><code>>>> dictlist = [{'key1':'value1', 'key2':'value2'}, {'key3':'value3', 'key4':'value4'}]
>>> list((k,v) for d in dictlist for k,v in d.iterite... | 1 | 2016-05-26T21:47:55Z | [
"python",
"dictionary",
"list-comprehension",
"generator-expression"
] |
Can I use a generator expression to print key,value pairs of a list of dictionaries? | 37,471,488 | <p>I have a list of dictionaries:</p>
<pre><code>dictlist = [{'key1':'value1', 'key2':'value2'}, {'key3':'value3', 'key4':'value4'}]
</code></pre>
<p>I currently print key, value pairs like this:</p>
<pre><code>for d in dictlist:
for key in d:
print .format('{} ---> {}').format(key,d[key])
</code></pre>
<p... | 1 | 2016-05-26T21:41:53Z | 37,471,749 | <p>If you <em>really</em> want to, you can iterate over a generator expression that prints the stuff itself, and just discard what you iterate over:</p>
<pre><code>for _ in (print('{} ---> {}'.format(key,dict[key])) for dict in dictlist for key in dict):
pass
</code></pre>
<p>I really don't see a reason to do ... | 0 | 2016-05-26T22:00:58Z | [
"python",
"dictionary",
"list-comprehension",
"generator-expression"
] |
Can I use a generator expression to print key,value pairs of a list of dictionaries? | 37,471,488 | <p>I have a list of dictionaries:</p>
<pre><code>dictlist = [{'key1':'value1', 'key2':'value2'}, {'key3':'value3', 'key4':'value4'}]
</code></pre>
<p>I currently print key, value pairs like this:</p>
<pre><code>for d in dictlist:
for key in d:
print .format('{} ---> {}').format(key,d[key])
</code></pre>
<p... | 1 | 2016-05-26T21:41:53Z | 37,471,871 | <p>Take a look at the <a href="https://docs.python.org/2/reference/expressions.html" rel="nofollow">python docs on expressions</a>. These are all things that just represent values of one sort or another, of various complexity. They are not side-effect inducing things (like I/O) or transformations on mutable data. Gener... | 3 | 2016-05-26T22:10:50Z | [
"python",
"dictionary",
"list-comprehension",
"generator-expression"
] |
Setting the last column in a 3D matrix to the sum of all the other columns using Numpy | 37,471,628 | <p>For the matrix P below, I want to set the last element in each row to the sum across all the other elements of that row. For example:</p>
<p>Original matrix:</p>
<pre><code>In [70]: print P
[[[1 2 3 0]
[4 1 2 0]
[7 1 2 0]]
[[7 2 5 0]
[8 2 4 0]
[6 3 1 0]]]
</code></pre>
<p>After summing:</p>
<pre><code>I... | 3 | 2016-05-26T21:51:18Z | 37,472,306 | <p>Try:</p>
<pre><code>p[:, :, -1] = p[:, :, :-1].sum(axis=2)
</code></pre>
<p>If you were to start without the zeroed column, you could:</p>
<pre><code>np.concatenate([p, p.sum(axis=2)[:, :, None]], axis=2)
</code></pre>
| 2 | 2016-05-26T22:52:10Z | [
"python",
"numpy",
"matrix",
"sum"
] |
Python: Argument Parsing Validation Best Practices | 37,471,636 | <p>Is it possible when using the argparse module to add validation when parsing arguments?</p>
<pre><code>from argparse import ArgumentParser
parser = ArgumentParser(description='Argument parser for PG restore')
parser.add_argument('--database', dest='database',
default=None, required=False, help... | 4 | 2016-05-26T21:51:56Z | 37,471,954 | <p>Surely! You just have to specify a custom action as a class, and override <code>__call__(..)</code>. <a href="https://docs.python.org/2/library/argparse.html#action" rel="nofollow">Link to documentation.</a></p>
<p>Something like:</p>
<pre><code>import argparse
class FooAction(argparse.Action):
def __call__(s... | 4 | 2016-05-26T22:17:19Z | [
"python",
"validation",
"argparse"
] |
Python: Argument Parsing Validation Best Practices | 37,471,636 | <p>Is it possible when using the argparse module to add validation when parsing arguments?</p>
<pre><code>from argparse import ArgumentParser
parser = ArgumentParser(description='Argument parser for PG restore')
parser.add_argument('--database', dest='database',
default=None, required=False, help... | 4 | 2016-05-26T21:51:56Z | 37,472,037 | <p>The <code>argparse.FileType</code> is a <code>type</code> factory class that can open a file, and of course, in the process raise an error if the file does not exist or cannot be created. You could look at its code to see how to create your own class (or function) to test your inputs.</p>
<p>The argument <code>typ... | 4 | 2016-05-26T22:26:29Z | [
"python",
"validation",
"argparse"
] |
How to drop and add a new list of columns to a .csv file? | 37,471,649 | <p>I am saving to a .csv file a preprocessed file with pandas <code>to_csv()</code> function as follows:</p>
<pre><code>return df.to_csv(output_file, sep = '|')
</code></pre>
<p>The output of the <code>.csv</code> file looks like this:</p>
<pre><code>|id|content|content2
0|id1|some content|some content
1|id1|some co... | 0 | 2016-05-26T21:52:58Z | 37,471,714 | <p>It looks like you just wish to remove the index from the output</p>
<pre><code>df.to_csv(output_file, sep = '|', index=False)
</code></pre>
| 2 | 2016-05-26T21:59:02Z | [
"python",
"python-2.7",
"python-3.x",
"csv",
"pandas"
] |
Is it possible to store authentication token in a separate file? | 37,471,681 | <p>I am building a command line tool using python that interfaces with an RESTful api. The API uses oauth2 for authentication. Rather than asking for access_token every time user runs the python tool. Can I store the access_token in some way so that I can use it till its lifespan? If it is then how safe it is. </p>
| 1 | 2016-05-26T21:56:33Z | 37,472,254 | <p>You can store the access token in a file on your user's desktop.</p>
<p>You can do so using a storage. Assuming you use <code>oauth2client</code>:</p>
<pre><code># Reading credentials
store = oauth2client.file.Storage(cred_path)
credentials = store.get()
# Writing credentials
creds = client.AccessTokenCredentials... | 1 | 2016-05-26T22:45:44Z | [
"python",
"oauth2"
] |
How do I get the correspondent day of the quarter from a date field? | 37,471,704 | <p>I have a dataset where the dates are between <code>5/1/2016</code> and <code>5/21/2016</code>. I would like to create a new variable <code>day_quarter</code> which will be the correspondent day of the quarter.
For example: </p>
<p>The first day in the Q2 is April 1st so, May 15th would be 45/91 for example.</p>
<p... | 3 | 2016-05-26T21:58:03Z | 37,471,920 | <p>Try this code:</p>
<pre><code>import datetime
def day_in_quarter(date):
q2 = (datetime.datetime.strptime("4/1/{0:4d}".format(date.year), "%m/%d/%Y")).timetuple().tm_yday
q3 = (datetime.datetime.strptime("7/1/{0:4d}".format(date.year), "%m/%d/%Y")).timetuple().tm_yday
q4 = (datetime.datetime.strptime("10... | 2 | 2016-05-26T22:14:03Z | [
"python",
"date"
] |
global name 'get_user_model' is not defined | 37,471,735 | <p><strong>NameError</strong> at <em>/project/reset_password_confirm/MTQ-4c8-65d880f1c28996091226/</em></p>
<pre><code>global name 'get_user_model' is not defined
Request Method: POST
Django Version: 1.9.1
Exception Type: NameError
Exception Value:
global name 'get_user_model' is not defined
Exception Location: /r... | 1 | 2016-05-26T22:00:29Z | 37,471,778 | <p>You need to add the import to your <code>views.py</code>.</p>
<pre><code>from django.contrib.auth import get_user_model
</code></pre>
| 1 | 2016-05-26T22:03:36Z | [
"python",
"django",
"django-models",
"django-views",
"nameerror"
] |
generalized series splitting (one to many mapping) in pandas | 37,471,739 | <p>I would like to split a tuple or a dictionary contained in a cell of <code>pandas.Series</code> into two columns. I know that there is a <a href="http://stackoverflow.com/questions/37357727/pandas-write-tab-separated-dataframe-with-literal-tabs-with-no-quotes">method for strings</a> that split string cells.</p>
<p>... | 1 | 2016-05-26T22:00:37Z | 37,471,821 | <p>A refined solition based @Andy Hayden's answer:</p>
<pre><code>def split_dict(cell, keys, default_value = None):
value_tuple = [cell[y] if y in cell else default_value for y in keys]
return pd.Series( value_tuple, index = keys)
ds_dict = ds.map(json.loads)
ds_dict.apply(lambda ds: split_dict(ds, ["a", "b",... | 1 | 2016-05-26T22:07:05Z | [
"python",
"pandas"
] |
generalized series splitting (one to many mapping) in pandas | 37,471,739 | <p>I would like to split a tuple or a dictionary contained in a cell of <code>pandas.Series</code> into two columns. I know that there is a <a href="http://stackoverflow.com/questions/37357727/pandas-write-tab-separated-dataframe-with-literal-tabs-with-no-quotes">method for strings</a> that split string cells.</p>
<p>... | 1 | 2016-05-26T22:00:37Z | 37,471,900 | <p>If you return an Series in your apply it splits it into columns (returns a DataFrame):</p>
<pre><code>In [11]: ds.map(json.loads).apply(lambda x: pd.Series([x["a"] if "a" in x else None, x["b"] if "b" in x else None]))
Out[11]:
0 1
TNFRSF18 0.0 0.0
SDF4 NaN 0.0
TNFRSF4 0.0 NaN
B3GALT6 ... | 2 | 2016-05-26T22:13:11Z | [
"python",
"pandas"
] |
Python assign variable names to if else function | 37,471,741 | <pre><code># Determine price per pound
if quantity >= 40:
print('Cost of coffee $', format(quantity * 7.50,'.2f'),sep='')
else:
if quantity >= 20:
print ('Cost of coffee $', format(quantity * 8.75, '.2f'), sep='')
else:
if quantity >= 10:
print ('Cost of coffee $', forma... | 0 | 2016-05-26T22:00:40Z | 37,471,877 | <p>So you'll need to use another variable to keep track of the total cost, for this I'll use total. Then we can set that equal to <code>quantity * price</code> using the flow controls. For this you'll want to look further into using <a href="https://docs.python.org/3.5/tutorial/controlflow.html#if-statements" rel="nofo... | 1 | 2016-05-26T22:11:37Z | [
"python",
"variables",
"if-statement"
] |
GPIO Raspberry Pi pin maintain last status when interrupt script and restart it | 37,471,744 | <p>I am working with MQTT and GPIO, and i have noticed that the pin maintain the last status like a memory, i make an example this is my script:</p>
<pre><code>#!/usr/bin/python3
#required libraries
import sys
import ssl
import paho.mqtt.client as mqtt
import RPi.GPIO as gpio
import j... | 0 | 2016-05-26T22:00:42Z | 37,472,313 | <p>If you want the client to effectively remember the last state when it is restarted then you should publish the control messages with the <em>retained</em> flag set to true.</p>
<p>This will mean that the broker will deliver the last published message to the client when it subscribes.</p>
<p>This is something that ... | 0 | 2016-05-26T22:53:07Z | [
"python",
"raspberry-pi",
"mqtt",
"gpio"
] |
QuantLib import failed in IPython notebook | 37,471,755 | <p>Good evening all,
I'm writing my thesis and I'm new with the use of QuantLib.
I installed Boost, Quantlib and Swig with HomeBrew on Mac OSX El Capitan but when it try to import QuantLib in my jupyter (IPhyton) notebook in this way:
import QuantLib as ql </p>
<p>I always get an error message saying that no quantlib... | 0 | 2016-05-26T22:01:19Z | 37,471,826 | <p>It sounds like you don't have it correctly installed. Modules are just python code, so if python can't find it then it likely isn't in the source dir. Check by opening a python command and running</p>
<pre><code>import sys
print sys.path
</code></pre>
<p>This will give you your system paths that python looks at. Y... | 1 | 2016-05-26T22:07:47Z | [
"python",
"ipython",
"osx-elcapitan",
"quantlib"
] |
Association object handling, appending children to parent, concealsing the usage of a âmiddleâ table | 37,471,873 | <p>I'm looking for convenient way to create ModelView, used to append a number of children to a parent when creating it.
For example, I've got models:</p>
<pre><code>class Order(db.Model):
__tablename__ = 'order'
id = db.Column(db.Integer, primary_key=True)
things = db.relationship('OrderList', back_popula... | 0 | 2016-05-26T22:11:03Z | 37,482,372 | <p>From what I am understanding , you want to define a many to many relationship on <code>Order</code> and <code>Thing</code> . </p>
<p>Rather than declaring <code>OrderList</code> class , I think you should declare the many to many relation like this</p>
<ol>
<li><p><a href="http://flask-sqlalchemy.pocoo.org/2.0/mod... | 0 | 2016-05-27T11:30:34Z | [
"python",
"flask",
"sqlalchemy",
"many-to-many",
"flask-admin"
] |
Hide a Button Under an Image TKinter | 37,471,878 | <p>I am wondering how within a <code>Frame</code> I can hide a button under an image without distorting the image size. I assume I will need to use gridding but I am not sure how to make the image fit into that without its aspect ratio going crazy. It does not seem possible to create invisible buttons in a grid with <c... | 0 | 2016-05-26T22:11:45Z | 37,492,936 | <p>You can't hide elements under each other like that with Tkinter. However, you can obtain similar results by defining rectangles representing different "button" areas of the image and determining if any of them were clicked yourself. In Tkinter terms I made the image a <code>Label</code> widget and bound <code><Bu... | 0 | 2016-05-27T22:07:47Z | [
"python",
"tkinter"
] |
Using sqlalchemy dburi with Oracle using External Password Store? | 37,471,892 | <p>I am trying to get a oracle sqlalchemy dburi working with an external password store (Oracle Wallet)</p>
<p>I have tried using the standard sqlplus syntax for a external password store with no luck..</p>
<pre><code>sqlalchemy.dburi="oracle:///@PROD"
</code></pre>
<p>I can connect successfully using sqlplus as fol... | 0 | 2016-05-26T22:12:55Z | 37,485,277 | <p>Off the top comment: Make sure you are running version 5.2.1+ of cx_oracle (<a href="http://cx-oracle.readthedocs.io/en/latest/releasenotes.html" rel="nofollow">http://cx-oracle.readthedocs.io/en/latest/releasenotes.html</a>). Prior to that a bug in SessionPools existed. </p>
| 0 | 2016-05-27T13:53:16Z | [
"python",
"oracle",
"sqlalchemy",
"turbogears"
] |
How to get fields from parent object model in serializer - django rest framework | 37,471,960 | <p>I have two models.. The Discussion extend GenericModel.</p>
<pre><code>class GenericModel(models.Model):
content_type = models.ForeignKey(
ContentType,
on_delete=models.CASCADE
)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
abs... | 0 | 2016-05-26T22:17:55Z | 37,474,473 | <p>Well, it's a <code>HyperlinkedModelSerializer</code> and your serializer will try to resolve the URL for the related <code>GenericModel</code> on your <code>Discussion</code>.</p>
<p>I believe a solution would be to define the <code>GenericModel</code> field on your <code>DiscussionSerializer/DiscussionListSerializ... | 0 | 2016-05-27T03:43:26Z | [
"python",
"django",
"django-rest-framework"
] |
wpull creating multiple unique captures per warc file | 37,472,004 | <p>I'm using wpull to grab customer sites and save them as WARC files.</p>
<p>The issue I'm having is that, for some reason, it's creating multiple captures of sites. Sometimes it only does one, but others it ranges from 2 to 6 to 15 captures of the same site. I don't think the capture code is really the issue ... <... | 0 | 2016-05-26T22:22:22Z | 37,488,196 | <p>Ok, there's a weird nuance in wpull with the --recursive. If set, it will follow any and every http:// link and do a full pull. Adding in -D site.com will limit those pulls to the specified domain(s).</p>
<p>However this creates a weird scenario where it will follow every http(s) link to the same domain, from the... | 0 | 2016-05-27T16:18:53Z | [
"python"
] |
Create buttons in tkinter from an array Python | 37,472,121 | <p>What I'm looking for is how to create a grid of buttons automatically with an iteration.</p>
<p>For example I have this array</p>
<pre><code>Array =
[[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
</code></pr... | 1 | 2016-05-26T22:34:10Z | 37,476,856 | <p>Let us put in an <a href="http://stackoverflow.com/help/mcve">MCVE</a> what <strong>@BryanOakley</strong> advised you to do using object-oriented concepts.</p>
<p>In below code, initialize() method creates a 6x7 <a href="http://www.numpy.org/" rel="nofollow"><code>numpy</code></a> array of zeros (as yours), then lo... | 2 | 2016-05-27T07:01:57Z | [
"python",
"arrays",
"python-3.x",
"button",
"tkinter"
] |
Python syntax - what do two less-signs and one equal sign mean | 37,472,203 | <p>I've searched for an example to convert <a href="https://support.microsoft.com/en-us/kb/167296" rel="nofollow">WINAPI FILETIME</a> values into UNIX time_t (for a new Golang project) and found an <a href="https://code.activestate.com/recipes/511425-filetime-to-datetime/" rel="nofollow">example in Python</a>. </p>
<p... | 1 | 2016-05-26T22:41:35Z | 37,472,219 | <p>They are the augmented assignment versions of the bit shift operator <code><<</code> and the bitwise or <code>|</code>, just like <code>+=</code> is the augmented <code>+</code>, so:</p>
<pre><code>timestamp <<= 32
</code></pre>
<p>is the equivalent of</p>
<pre><code>timestamp = timestamp << 32
... | 2 | 2016-05-26T22:43:09Z | [
"python",
"syntax",
"numeric"
] |
Python syntax - what do two less-signs and one equal sign mean | 37,472,203 | <p>I've searched for an example to convert <a href="https://support.microsoft.com/en-us/kb/167296" rel="nofollow">WINAPI FILETIME</a> values into UNIX time_t (for a new Golang project) and found an <a href="https://code.activestate.com/recipes/511425-filetime-to-datetime/" rel="nofollow">example in Python</a>. </p>
<p... | 1 | 2016-05-26T22:41:35Z | 37,472,224 | <p>This is taken from C. It is the '<<' or '|' operator (bitwise shift left and bitwise or, respectively) plus the assignment operator:</p>
<pre><code>a <<= b
</code></pre>
<p>Is the same as</p>
<pre><code>a = a << b
</code></pre>
<p>Similarly for |=.</p>
| 3 | 2016-05-26T22:43:39Z | [
"python",
"syntax",
"numeric"
] |
Implementing a 2-sample KS test with 3D data in Python | 37,472,228 | <p>I have two 3D distributions and I want to run a <a href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test#The_Kolmogorov.E2.80.93Smirnov_statistic_in_more_than_one_dimension" rel="nofollow">KolmogorovâSmirnov test</a> on these two samples to measure their similarity. scipy.stats has an implementation ... | 1 | 2016-05-26T22:43:52Z | 37,493,221 | <p>The KS test is not easily generalized to multiple dimensions; see <a href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test#The_Kolmogorov.E2.80.93Smirnov_statistic_in_more_than_one_dimension" rel="nofollow">the Wikipedia article on the KS test on that question</a>. Even if you can find or create a suit... | 0 | 2016-05-27T22:37:37Z | [
"python",
"scipy",
"statistics",
"similarity"
] |
Python 3: How to move an item from list x to list y and remove it from list x? | 37,472,312 | <p>I am trying to <code>.append</code> a random card from list <code>Deck</code> to <code>MyHand</code>, while removing it from <code>Deck</code>.</p>
<pre><code>import random
Deck = []
MyHand = []
CardsPicked = 0
for Cards in range(1, 101):
Deck.append(Cards)
while(CardsPicked < 8):
MyHand.append(random... | 1 | 2016-05-26T22:53:01Z | 37,472,325 | <pre><code>MyHand.append(Deck.pop(random.choice(range(len(Deck)))))
</code></pre>
<p>(<code>pop</code> takes an index to remove and returns the item removed)</p>
<p>Something closer to your code would be:</p>
<pre><code>card = random.choice(Deck)
Deck.remove(card)
MyHand.append(card)
</code></pre>
| 5 | 2016-05-26T22:54:44Z | [
"python",
"list",
"python-3.x",
"random",
"append"
] |
Python 3: How to move an item from list x to list y and remove it from list x? | 37,472,312 | <p>I am trying to <code>.append</code> a random card from list <code>Deck</code> to <code>MyHand</code>, while removing it from <code>Deck</code>.</p>
<pre><code>import random
Deck = []
MyHand = []
CardsPicked = 0
for Cards in range(1, 101):
Deck.append(Cards)
while(CardsPicked < 8):
MyHand.append(random... | 1 | 2016-05-26T22:53:01Z | 37,472,327 | <p>you typcally shuffle the deck</p>
<pre><code>Deck.shuffle()
</code></pre>
<p>then you just remove cards from one end</p>
<pre><code>hand.append(Deck.pop())
</code></pre>
<p>normally when you deal cards do you draw from random places in the deck or do you shuffle and pass the cards around</p>
| 3 | 2016-05-26T22:54:57Z | [
"python",
"list",
"python-3.x",
"random",
"append"
] |
How do I check if a string is a negative number before passing it through int()? | 37,472,361 | <p>I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.</p>
<p>This is what I have so far:</p>
<pre><code>def contestTest():
# Neutral point fo... | 1 | 2016-05-26T22:59:16Z | 37,472,375 | <p>You can easily remove the characters from the left first, like so:</p>
<pre><code>choice.lstrip('-+').isdigit()
</code></pre>
<p>However it would probably be better to handle exceptions from invalid input instead:</p>
<pre><code>print x
while True:
choice = raw_input("> ")
try:
y = int(choice)
... | 3 | 2016-05-26T23:00:47Z | [
"python",
"python-2.7"
] |
How do I check if a string is a negative number before passing it through int()? | 37,472,361 | <p>I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.</p>
<p>This is what I have so far:</p>
<pre><code>def contestTest():
# Neutral point fo... | 1 | 2016-05-26T22:59:16Z | 37,472,456 | <p>Instead of checking if you can convert the input to a number you can just try the conversion and do something else if it fails: </p>
<pre><code>choice = raw_input("> ")
try:
y = int(choice)
x += y
except ValueError:
print "Invalid input."
</code></pre>
| 1 | 2016-05-26T23:10:00Z | [
"python",
"python-2.7"
] |
How do I check if a string is a negative number before passing it through int()? | 37,472,361 | <p>I'm trying to write something that checks if a string is a number or a negative. If it's a number (positive or negative) it will passed through int(). Unfortunately isdigit() won't recognize it as a number when "-" is included.</p>
<p>This is what I have so far:</p>
<pre><code>def contestTest():
# Neutral point fo... | 1 | 2016-05-26T22:59:16Z | 37,472,488 | <p>You can solve this by using <code>float(str)</code>. float should return an ValueError if it's not a number. If you're only dealing with integers you can use <code>int(str)</code></p>
<p>So instead of doing </p>
<pre><code>if choise.isdigit():
#operation
else:
#operation
</code></pre>
<p>You can try</p>
<p... | 1 | 2016-05-26T23:13:13Z | [
"python",
"python-2.7"
] |
How to aggregate plots into figure with subplots | 37,472,398 | <p>I've read the answers related to this already and have followed this:</p>
<pre><code>fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
</code></pre>
<p>Which is great, now I have a figure with f... | 1 | 2016-05-26T23:02:48Z | 37,472,483 | <p>Is it principal to draw before creating subplots? If no, try this code:</p>
<pre><code>fig = plt.figure()
fig.add_subplot(221) #top left
plt1 = plt.scatter(foo,bar)
fig.add_subplot(222) #top right
plt2 = plt.line(bar, baz)
fig.add_subplot(223) #bottom left
plt3 = plt.scatter(you, get)
fig.add_subplot(224) #... | 1 | 2016-05-26T23:12:46Z | [
"python",
"matplotlib"
] |
How to aggregate plots into figure with subplots | 37,472,398 | <p>I've read the answers related to this already and have followed this:</p>
<pre><code>fig = plt.figure()
fig.add_subplot(221) #top left
fig.add_subplot(222) #top right
fig.add_subplot(223) #bottom left
fig.add_subplot(224) #bottom right
plt.show()
</code></pre>
<p>Which is great, now I have a figure with f... | 1 | 2016-05-26T23:02:48Z | 37,472,835 | <p>You need to keep track the Axes objects returned by <code>add_subplot</code>. </p>
<pre><code>fig = plt.figure()
ax1 = fig.add_subplot(221) #top left
ax2 = fig.add_subplot(222) #top right
ax3 = fig.add_subplot(223) #bottom left
ax4 = fig.add_subplot(224) #bottom right
</code></pre>
<p>And then you can do:... | 3 | 2016-05-27T00:00:48Z | [
"python",
"matplotlib"
] |
Speed Static Methods vs Class Method | 37,472,419 | <p>Is there any speed difference between class Methods and Static Methods? I am aware of the different use cases, but sometimes i could completely get rid of a class method and would like to know speed differences</p>
| 0 | 2016-05-26T23:05:47Z | 37,472,489 | <p>Test it. This is going to be an implementation detail of whichever Python interpreter (and version of said interpreter) you happen to be running. For my interpreter (Python 3.5, Windows, 64 bit):</p>
<pre><code>>>> class Foo:
... @classmethod
... def bar(cls):
... pass
... @staticmethod... | 3 | 2016-05-26T23:13:19Z | [
"python"
] |
Which API KEY do I use for HTTP GET request from ios APP | 37,472,495 | <p>On this page, <a href="https://cloud.google.com/storage/docs/json_api/v1/objects/get#http-request" rel="nofollow">https://cloud.google.com/storage/docs/json_api/v1/objects/get#http-request</a></p>
<p>It allows you to input the name of your bucket and the name of the object that you would like to download. It return... | 0 | 2016-05-26T23:13:47Z | 38,270,366 | <p>The IOS API should be used with the iOS SDK.
If you are requesting the URL directly, i think that you should use the server or browser API.</p>
| 0 | 2016-07-08T15:27:03Z | [
"python",
"google-cloud-storage"
] |
TCP Server Response | 37,472,523 | <p>I'm writing a TCP python script that will act as a client and retrieve a temperature reading from a LakeShore336 Temperature Controller (which is acting as the server). I need to pass a command to the server from the client and output the response. I get outputs up to 'Spot 2' after the command is sent but when s.re... | 0 | 2016-05-26T23:18:15Z | 37,488,847 | <p>The reason why your code is "stuck" is because recv() is a blocking call. Your process is waiting for an inbound TCP packet and you've allocated a buffer of 4096 bytes (which means it can handle up to that amount of bytes). </p>
<p>Once that packet is received your code will proceed and the connection will be close... | 0 | 2016-05-27T17:01:00Z | [
"python",
"sockets",
"tcp",
"recv"
] |
TCP Server Response | 37,472,523 | <p>I'm writing a TCP python script that will act as a client and retrieve a temperature reading from a LakeShore336 Temperature Controller (which is acting as the server). I need to pass a command to the server from the client and output the response. I get outputs up to 'Spot 2' after the command is sent but when s.re... | 0 | 2016-05-26T23:18:15Z | 37,489,668 | <p>You are sending the literal string <code>[term]</code> instead of sending a message terminator. The protocol documentation uses the string "[term]" to mean a message terminator, it does not mean the literal string "[term]"!</p>
<p>Since you have not sent a message (because a message ends with a message terminator s... | 0 | 2016-05-27T17:56:04Z | [
"python",
"sockets",
"tcp",
"recv"
] |
Functional/idiomatic way to express this Python in Clojure | 37,472,530 | <p>I have a data transformation that is leaving me a bit stymied. I wasn't able to express myself in Clojure and even my Python, that I'm fluent in, still feels quite gross.</p>
<p>I need a data structure like:</p>
<pre><code>[1, 2, [3, 4], 5, 6]
</code></pre>
<p>to generate a structure like this:</p>
<pre><code>[[... | 1 | 2016-05-26T23:18:58Z | 37,472,882 | <p>I'm sure there are other ways to do this, but here is one way.</p>
<pre><code>user.core=> (def x [1, 2, [3, 4], 5, 6])
#'user.core/x
user.core=> (defn create-vecs [x]
=> (let [sub (first (filter vector? x))
=> all (remove vector? x)]
=> (vec (map #(vec (sort (co... | 1 | 2016-05-27T00:06:57Z | [
"python",
"clojure",
"transformation"
] |
Functional/idiomatic way to express this Python in Clojure | 37,472,530 | <p>I have a data transformation that is leaving me a bit stymied. I wasn't able to express myself in Clojure and even my Python, that I'm fluent in, still feels quite gross.</p>
<p>I need a data structure like:</p>
<pre><code>[1, 2, [3, 4], 5, 6]
</code></pre>
<p>to generate a structure like this:</p>
<pre><code>[[... | 1 | 2016-05-26T23:18:58Z | 37,473,327 | <p>An important feature of many of the Clojure core library functions is the ability to handle lazy (potentially infinite) sequences; therefore, I would think that a good (idiomatic) Clojure solution would be able to properly expand an input containing subsequences that are infinite lazy sequences. For example:</p>
<p... | 2 | 2016-05-27T01:17:33Z | [
"python",
"clojure",
"transformation"
] |
Conditional embedded document for mongodb objects | 37,472,557 | <p>I need help with thinking about data modeling (I am using python and mongoengine). I have an object that I would like to apply different classes of embedded documents to depending on another attribute the object has. </p>
<pre><code>class RunningSettings(EmbeddedDocument):
max_distance = DecimalField()
spee... | 1 | 2016-05-26T23:22:51Z | 37,578,101 | <p>This sounds like a good candidate for using inheritance:</p>
<pre><code>class RunningSettings(EmbeddedDocument):
max_distance = DecimalField()
speed = DecimalField()
class Workout(Document):
name = StringField()
description = StringField()
date_created = DateTimeField(default=datetime.utcnow())... | 0 | 2016-06-01T20:22:14Z | [
"python",
"mongodb",
"embedded-documents"
] |
Extracting some SIP headers | 37,472,560 | <p>I am using this regular expression for SIP (Session Initiation Protocol) URIs to extract the different internal variables.</p>
<pre><code>_syntax = re.compile('^(?P<scheme>[a-zA-Z][a-zA-Z0-9\+\-\.]*):' # scheme
+ '(?:(?:(?P<user>[a-zA-Z0-9\-\_\.\!\~\*\'\(\)&=\+\$,;\?\/\%]+)' # user
+ '(?::(... | 0 | 2016-05-26T23:23:08Z | 37,473,058 | <p>I would suggest taking advantage of the intentional similarities between SIP header format and RFC822.</p>
<pre><code>from email.parser import Parser
msg = Parser().parsestr(m.group('headers'))
</code></pre>
<p>...thereafter:</p>
<pre><code>>>> msg.keys()
['Content-Length', 'Via', 'From', 'Supported', 'U... | 1 | 2016-05-27T00:33:44Z | [
"python",
"python-2.7",
"sip"
] |
Error 404 Raised by a View | 37,472,562 | <p>When I click on the laboratory link to open a form to add information to it, I get this error.
I have change the url to call a diferente view and still get the same error. Can someone tell me what may be happening? Is not the view, cause as you see I use it for other urls and in those It works perfect.</p>
<pre><co... | 1 | 2016-05-26T23:23:13Z | 37,472,683 | <p><em>Your URL endpoints all have the same name</em> - <code>createexternalservice</code>. This is confusing the URL routing system and <a href="https://docs.djangoproject.com/en/1.9/topics/http/urls/#naming-url-patterns" rel="nofollow">there is no guarantee</a> which URL would be called when you look it up by name. A... | 3 | 2016-05-26T23:38:36Z | [
"python",
"django",
"django-views",
"django-urls"
] |
how to activate the ananconda's env python in emacs? | 37,472,595 | <p>I install the python3.5 and python 2.7 in anaconda. the anaconda manager python version and package is convenvient. activate pyx.x in win10's cmd.
In emacs's python-mode, c-c c-p (start interpreter) only open the default python version. how switch python version ?</p>
| 0 | 2016-05-26T23:27:07Z | 37,489,343 | <p>You didn't seem to explain your self much so I'm going to try and guess what you want.</p>
<p>You want to be able to switch conda python versions and conda virtual environments depending on what files you're editing. I recently set this up using the <a href="https://github.com/jorgenschaefer/pyvenv" rel="nofollow">... | 0 | 2016-05-27T17:34:01Z | [
"python",
"emacs",
"anaconda"
] |
Pipelining or Otherwise Transferring Data Between Languages in Realtime | 37,472,688 | <p>I'm working on a project, which I am not at liberty to discuss the core, but I have reached a stumbling block. I need data to be transferred from C++ to some other language, preferably Java or Python, in realtime (~10ms latency).</p>
<p>We have a sensor that <strong>HAS</strong> to be parsed in C++. We are planni... | 2 | 2016-05-26T23:39:08Z | 37,472,839 | <p>It seems like you are looking for a IPC (Inter-process communication). The easiest ones to implement are the socket and Pipes. I have added links which will help you decide which one to use. I have implemented named pipes and socket to transfer data at every 1ms. I did these implementations in python, c and pascal. ... | 0 | 2016-05-27T00:01:07Z | [
"java",
"python",
"c++",
"pipelining"
] |
Pipelining or Otherwise Transferring Data Between Languages in Realtime | 37,472,688 | <p>I'm working on a project, which I am not at liberty to discuss the core, but I have reached a stumbling block. I need data to be transferred from C++ to some other language, preferably Java or Python, in realtime (~10ms latency).</p>
<p>We have a sensor that <strong>HAS</strong> to be parsed in C++. We are planni... | 2 | 2016-05-26T23:39:08Z | 37,495,749 | <p>We had same issue where we had to share sensor data between one Java app to other multiple apps including Java,Python and R.</p>
<p>First we tried Socket connections but socket communication were not fault tolerant. Restarting or failure in one app affected other.
Then we tried RMI calls between them but again we w... | 0 | 2016-05-28T06:00:06Z | [
"java",
"python",
"c++",
"pipelining"
] |
Filling rectangles with colors in python using turtle | 37,472,761 | <p>How can I draw a rectangle where: the smallest is 5 in height and each consecutive rectangle adds the first rectangles height, i.e. 5, 10, 15, â¦. The width of each rectangle is 200. The color of the lines are blue and the fill color, from top to bottom is grey0, grey14, grey28, â¦.
How can I do this and make sure... | 2 | 2016-05-26T23:50:09Z | 37,473,138 | <pre><code>def filled_rectangle(t, l, w):
t.begin_fill()
for i in range(2):
t.right(90)
t.forward(l)
t.right(90)
t.forward(w)
t.endfill()
</code></pre>
| 1 | 2016-05-27T00:45:26Z | [
"python",
"turtle-graphics"
] |
Reducing the amount of imported libraries in Python | 37,472,815 | <p>I am using the Button, Entry, Label element, as well as using winfo_screenwidth(), winfo_screenwidth(), and the geometry() function for my main window. On the Entry elements I am only using the get() and delete() functions.</p>
<pre><code>from Tkinter import *
def main():
window = Tk()
window.title('cool st... | 0 | 2016-05-26T23:58:14Z | 37,511,767 | <p>There is nothing you can do to make the tkinter imports 'weigh less", if by that you mean a smaller memory footprint.</p>
<p>You must import all of Tkinter in order for it to be usable; you can't pick and choose a subset of widgets from Tkinter. The bulk of the tkinter code isn't even python; tkinter is a thin wrap... | 0 | 2016-05-29T15:37:51Z | [
"python",
"import",
"minimize"
] |
Timing out when I use a proxy | 37,472,840 | <p>I am trying to implement proxies into my web crawler. Without the proxies, my code has no problem connecting to the website, however when I try to add in proxies, suddenly it won't connect! It doesn't look like anybody in python-requests has made a post about this problem, so I'm hoping you all can help me!</p>
<p>... | 0 | 2016-05-27T00:01:07Z | 37,473,382 | <p>It looks like you'll need to use a http or https proxy that will respond to requests.</p>
<p>The <code>10.10.1.10:3128</code> in your code seems to be from examples in the <a href="http://docs.python-requests.org/en/master/user/advanced/#proxies%20As%20it'" rel="nofollow">requests documentation</a></p>
<p>Taki... | 0 | 2016-05-27T01:26:29Z | [
"python",
"proxy",
"python-requests"
] |
Unable to mock function call in Python | 37,472,868 | <p>I am writing unit tests for my application that uses the Facebook Ads api. I am trying to mock the remote create function using the following:</p>
<pre><code>CustomAudience.remote_create = Mock(return_value="some value")
</code></pre>
<p>However when I call remote_create on an instance of CustomAudience it seems t... | 0 | 2016-05-27T00:05:18Z | 37,473,011 | <p>ahh, wrong import. I was mocking the wrong function.</p>
| 0 | 2016-05-27T00:26:05Z | [
"python",
"unit-testing",
"facebook-graph-api"
] |
login_user fails to get user id | 37,472,870 | <p>My app fails whenever I call <code>login_user</code> with the error <code>NotImplementedError: No 'id' attribute - override 'get_id'</code>. My user has an id attribute. Why does this fail?</p>
<pre><code>if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is ... | 0 | 2016-05-27T00:05:32Z | 37,473,078 | <p><code>login_user</code> calls <code>get_id</code> on the user instance. <code>UserMixin</code> provides a <code>get_id</code> method that returns the <code>id</code> attribute or raises an exception. You did not define an <code>id</code> attribute, you named it (redundantly) <code>user_id</code>. Name your attrib... | 0 | 2016-05-27T00:36:18Z | [
"python",
"flask",
"flask-login"
] |
statmodels in python package, How exactly duplicated features are handled? | 37,472,963 | <p>I am a heavy R user and am recently learning python.
I have a question about how statsmodels.api handles duplicated features.
In my understanding, this function is a python version of glm in R package. So I am expecting that the function returns the maximum likelihood estimates (MLE).</p>
<p>My question is which al... | -1 | 2016-05-27T00:17:36Z | 37,499,160 | <p>The short answer: </p>
<p>GLM is using the Moore-Penrose generalized inverse, pinv, in this case, which corresponds to a principal component regression where components with zero eigenvalues are dropped. zero eigenvalue is defined by the default threshold (rcond) in numpy.linalg.pinv.</p>
<p>statsmodels does not h... | 1 | 2016-05-28T12:46:15Z | [
"python",
"glm",
"logistic-regression"
] |
Getting values from JSON file | 37,473,093 | <p>I am trying to get the values from count and add them to find the total sum.
The code I have written is:</p>
<pre><code>import json
data= '''
{
"note":" sample data ",
"comments":
[
{
"School":"UCLA",
"count":97
},
{
"School":"MIT",
"count":97
},
{
"School":"R... | 2 | 2016-05-27T00:38:35Z | 37,473,106 | <p>This:</p>
<blockquote>
<pre><code>for i in info:
</code></pre>
</blockquote>
<p>iterates over the dict, which yields keys, which are strings. Access <code>info</code> directly instead.</p>
| 2 | 2016-05-27T00:40:57Z | [
"python",
"json"
] |
Getting values from JSON file | 37,473,093 | <p>I am trying to get the values from count and add them to find the total sum.
The code I have written is:</p>
<pre><code>import json
data= '''
{
"note":" sample data ",
"comments":
[
{
"School":"UCLA",
"count":97
},
{
"School":"MIT",
"count":97
},
{
"School":"R... | 2 | 2016-05-27T00:38:35Z | 37,473,114 | <p>The top-level JSON object is not an array, so you shouldn't iterate over it. The array is in <code>info["comments"]</code>, so do</p>
<pre><code>for i in info["comments"]:
a = float(i["count"])
b += a
print b
</code></pre>
| 1 | 2016-05-27T00:41:58Z | [
"python",
"json"
] |
Getting values from JSON file | 37,473,093 | <p>I am trying to get the values from count and add them to find the total sum.
The code I have written is:</p>
<pre><code>import json
data= '''
{
"note":" sample data ",
"comments":
[
{
"School":"UCLA",
"count":97
},
{
"School":"MIT",
"count":97
},
{
"School":"R... | 2 | 2016-05-27T00:38:35Z | 37,473,124 | <p>You should be looping over <code>info["comments"]</code> which is a list. You can also use the <code>sum</code> function to total the values</p>
<pre><code>b = sum(float(i["count"]) for i in info["comments"])
</code></pre>
| 3 | 2016-05-27T00:43:28Z | [
"python",
"json"
] |
Getting values from JSON file | 37,473,093 | <p>I am trying to get the values from count and add them to find the total sum.
The code I have written is:</p>
<pre><code>import json
data= '''
{
"note":" sample data ",
"comments":
[
{
"School":"UCLA",
"count":97
},
{
"School":"MIT",
"count":97
},
{
"School":"R... | 2 | 2016-05-27T00:38:35Z | 37,473,263 | <p>This is python list comprehension:</p>
<pre><code>tt = sum([float(row['count']) for row in info['comments']])
print tt
</code></pre>
<p>or this is "for" loops </p>
<pre><code>tt = []
for row in info['comments']:
tt.append(float(row['count']))
b = sum(tt)
print b
</code></pre>
<p>List comprehension is usual... | 2 | 2016-05-27T01:04:15Z | [
"python",
"json"
] |
How do you add environment variables to your django project | 37,473,108 | <p>I'm trying to set up my project so that it can use environment variables locally</p>
<p>Ive tried adding it to the end of my activate file and a list of other things. I'm trying to use this</p>
<pre><code>from .base import *
if os.environ['DJANGO_SERVER_TYPE'] == 'local':
try:
from .local ... | 2 | 2016-05-27T00:41:12Z | 37,473,279 | <p>Install the environ library and add the following code to your settings file:</p>
<pre><code>root_path = environ.Path(__file__) - 2
env = environ.Env(DEBUG=(bool, False), DJANGO_ENV=(str, 'dev')) # set default values and casting
environ.Env.read_env(root_path('.env'))
</code></pre>
<p>Add a file called .env on... | 0 | 2016-05-27T01:09:01Z | [
"python",
"django",
"bash",
"environment-variables",
"development-environment"
] |
How do you add environment variables to your django project | 37,473,108 | <p>I'm trying to set up my project so that it can use environment variables locally</p>
<p>Ive tried adding it to the end of my activate file and a list of other things. I'm trying to use this</p>
<pre><code>from .base import *
if os.environ['DJANGO_SERVER_TYPE'] == 'local':
try:
from .local ... | 2 | 2016-05-27T00:41:12Z | 37,473,332 | <p>If you're running it through the Django web server, you can pass environment variables the same way you would to any other command:</p>
<pre><code>DJANGO_SERVER_TYPE="local" ./manage.py runserver
</code></pre>
<p>If you're running it through a web server like Apache, you can set environment variables through your ... | 0 | 2016-05-27T01:18:15Z | [
"python",
"django",
"bash",
"environment-variables",
"development-environment"
] |
How do you add environment variables to your django project | 37,473,108 | <p>I'm trying to set up my project so that it can use environment variables locally</p>
<p>Ive tried adding it to the end of my activate file and a list of other things. I'm trying to use this</p>
<pre><code>from .base import *
if os.environ['DJANGO_SERVER_TYPE'] == 'local':
try:
from .local ... | 2 | 2016-05-27T00:41:12Z | 37,473,364 | <p>I have a settings module that contains something like the following:</p>
<pre><code>â¦
import os
from django.core.exceptions import ImproperlyConfigured
â¦
def _require_env(name):
"""Raise an error if the environment variable isn't defined"""
value = os.getenv(name)
if value is None:
raise Im... | 0 | 2016-05-27T01:23:34Z | [
"python",
"django",
"bash",
"environment-variables",
"development-environment"
] |
Python: Reading two csv files combining into a new cvs file , error: too many values to unpack | 37,473,142 | <p>I'm trying to combine two datasets in python 2.7. They deal with different variables (windspd, winddir in one and co2 and h2o in the other) but match in date and time. </p>
<p>All of the data is originating in two csv files and I need it written to a new csv file but I keep getting the "error: too many values to un... | 3 | 2016-05-27T00:46:15Z | 37,473,253 | <p>np.arrays are indexed by row first. So you are trying to fit all your rows into your column variables.
Try transposing first:</p>
<pre><code>winddir, windspd, month, day, year, hour, minute=np.loadtxt('E:\Wind05032014_08312015_flag_full.csv', delimiter=',',unpack=True,dtype='str',skiprows=1).T
</code></pre>
<p>Usi... | 0 | 2016-05-27T01:02:44Z | [
"python",
"csv",
"numpy",
"pandas"
] |
Python: Reading two csv files combining into a new cvs file , error: too many values to unpack | 37,473,142 | <p>I'm trying to combine two datasets in python 2.7. They deal with different variables (windspd, winddir in one and co2 and h2o in the other) but match in date and time. </p>
<p>All of the data is originating in two csv files and I need it written to a new csv file but I keep getting the "error: too many values to un... | 3 | 2016-05-27T00:46:15Z | 37,473,283 | <p>You can do this to find out where the problem is:</p>
<pre><code>NUM_COLS = 7
rows = np.loadtxt(...)
print [x for x in rows if len(x) > NUM_COLS]
</code></pre>
| 0 | 2016-05-27T01:09:44Z | [
"python",
"csv",
"numpy",
"pandas"
] |
Python: Reading two csv files combining into a new cvs file , error: too many values to unpack | 37,473,142 | <p>I'm trying to combine two datasets in python 2.7. They deal with different variables (windspd, winddir in one and co2 and h2o in the other) but match in date and time. </p>
<p>All of the data is originating in two csv files and I need it written to a new csv file but I keep getting the "error: too many values to un... | 3 | 2016-05-27T00:46:15Z | 37,473,534 | <p>Would use pandas, instead of numpy to read these csv's. Pandas has what seems to be more error checking. (And for beginners, line up "=" signs it makes your code more readable. </p>
<p>Try this:</p>
<pre><code>mydata=np.loadtxt('E:\CO2_05032014_03182015_flag_full.csv',delimiter=',',unpack=True,dtype='str',skiprow... | 0 | 2016-05-27T01:47:21Z | [
"python",
"csv",
"numpy",
"pandas"
] |
Python: Reading two csv files combining into a new cvs file , error: too many values to unpack | 37,473,142 | <p>I'm trying to combine two datasets in python 2.7. They deal with different variables (windspd, winddir in one and co2 and h2o in the other) but match in date and time. </p>
<p>All of the data is originating in two csv files and I need it written to a new csv file but I keep getting the "error: too many values to un... | 3 | 2016-05-27T00:46:15Z | 37,474,751 | <p>The <code>unpacking</code> error is the result of a mismatch between the number of variables on the left and the number of columns read by <code>loadtxt</code>. </p>
<p>You have 7 variables on the left. We don't know how many columns there are in your file.</p>
<pre><code>co2m, h2om, day_1, month_1, year_1, ho... | 1 | 2016-05-27T04:15:36Z | [
"python",
"csv",
"numpy",
"pandas"
] |
How to remove dates from a list in Python | 37,473,219 | <p>I have a list of tokenized text (list_of_words) that looks something like this:</p>
<pre><code>list_of_words =
['08/20/2014',
'10:04:27',
'pm',
'complet',
'vendor',
'per',
'mfg/recommend',
'08/20/2014',
'10:04:27',
'pm',
'complet',
...]
</code></pre>
<p>and I'm trying to strip out all the instances of ... | 6 | 2016-05-27T00:57:40Z | 37,473,314 | <p>if you want math the time and date string in your list, maybe you can try below regex:</p>
<pre><code>[0-9]{2}[\/,:][0-9]{2}[\/,:][0-9]{2,4}
</code></pre>
<p><a href="http://i.stack.imgur.com/I6zR9.png"><img src="http://i.stack.imgur.com/I6zR9.png" alt="enter image description here"></a></p>
<p>add the python cod... | 6 | 2016-05-27T01:15:05Z | [
"python",
"regex",
"nltk"
] |
How to remove dates from a list in Python | 37,473,219 | <p>I have a list of tokenized text (list_of_words) that looks something like this:</p>
<pre><code>list_of_words =
['08/20/2014',
'10:04:27',
'pm',
'complet',
'vendor',
'per',
'mfg/recommend',
'08/20/2014',
'10:04:27',
'pm',
'complet',
...]
</code></pre>
<p>and I'm trying to strip out all the instances of ... | 6 | 2016-05-27T00:57:40Z | 37,473,347 | <p>Try this:</p>
<pre><code>import re
list_of_words = ['08/20/2014',
'10:04:27',
'pm',
'complet',
'vendor',
'per',
'mfg/recommend',
'08/20/2014',
'10:04:27',
'pm', '... | 1 | 2016-05-27T01:21:18Z | [
"python",
"regex",
"nltk"
] |
How to remove dates from a list in Python | 37,473,219 | <p>I have a list of tokenized text (list_of_words) that looks something like this:</p>
<pre><code>list_of_words =
['08/20/2014',
'10:04:27',
'pm',
'complet',
'vendor',
'per',
'mfg/recommend',
'08/20/2014',
'10:04:27',
'pm',
'complet',
...]
</code></pre>
<p>and I'm trying to strip out all the instances of ... | 6 | 2016-05-27T00:57:40Z | 37,475,489 | <h1>Description</h1>
<pre><code>^(?:(?:[0-9]{2}[:\/,]){2}[0-9]{2,4}|am|pm)$
</code></pre>
<p><img src="https://www.debuggex.com/i/kju2fjhDVN-ug0CI.png" alt="Regular expression visualization"></p>
<p>This regular expression will do the following:</p>
<ul>
<li>find strings which look like dates <code>12/23/2016</code... | 4 | 2016-05-27T05:29:05Z | [
"python",
"regex",
"nltk"
] |
Bypass Flask's SERVER_NAME for a single route | 37,473,272 | <p>I'm working on a Flask application with many routes under different subdomains. It uses the <code>SERVER_NAME</code> setting and sets subdomains on different blueprints to do initial routing based on the subdomain.</p>
<p>I'm trying to configure a route that bypasses the requirement for the host to match <code>SERV... | 4 | 2016-05-27T01:06:47Z | 37,561,956 | <p>Any route is just an extension/implementation of <a href="http://werkzeug.pocoo.org/docs/0.11/routing/#werkzeug.routing.Rule">Werkzeug's Rule</a>. So just set <code>subdomain=None</code> for docs see: <a href="http://flask.pocoo.org/docs/0.11/api/#url-route-registrations">FLASK Route</a>.</p>
<p>It's a pretty nice ... | 5 | 2016-06-01T07:20:01Z | [
"python",
"flask"
] |
Python Multiprocessing Will Not Continue Past Number of CPUs/Cores | 37,473,281 | <p>I'm learning how to use multiple cores in Python. In the following script, I tried to scrape the title from a list of webpages.</p>
<pre><code>import multiprocessing
import requests
from bs4 import BeautifulSoup
sites = (
'http://penny-arcade.com/',
'http://reallifecomics.com/',
'http://si... | 1 | 2016-05-27T01:09:22Z | 37,473,654 | <p>Your <code>scrape_site</code> method scrapes exactly one site - it doesn't loop trying to pull more and more events from the queue. And you dispatch exactly 4 workers here:</p>
<pre><code>for w in xrange(workers):
p = multiprocessing.Process(target=scrape_site, args=(q, ))
p.start()
processe... | 2 | 2016-05-27T02:01:57Z | [
"python",
"multiprocessing",
"python-multiprocessing"
] |
How to Explicitly Specify File Directory in Python Script | 37,473,287 | <p>I'm trying to make my Python scripts run directly by typing the filenames into the run dialog on Windows, but I haven't been able to do it effectively. I have two simple scripts that I created after reading the Automate book on Python: one, a clipboard that's supposed to take command line arguments and another, a sc... | 0 | 2016-05-27T01:10:47Z | 37,622,437 | <p>After some digging around, I found this to be the simplest answer to my question:</p>
<pre><code>import random
import os
import sys
os.chdir(os.path.dirname(sys.argv[0]))
</code></pre>
<p>This changes the working directory to the first command line argument (the script's name) when the script is run.</p>
| 0 | 2016-06-03T19:58:08Z | [
"python",
"windows",
"file",
"file-io",
"path"
] |
How can I declare a Column as a categorical feature in a DataFrame for use in ml | 37,473,380 | <p>How can I declare that a given Column in my <code>DataFrame</code> contains categorical information?</p>
<p>I have a Spark SQL <code>DataFrame</code> which I loaded from a database. Many of the columns in this <code>DataFrame</code> have categorical information, but they are encoded as Longs (for privacy). </p>
<p... | 1 | 2016-05-27T01:25:33Z | 37,480,283 | <blockquote>
<p>I would prefer to avoid the hassle of encoding and decoding,</p>
</blockquote>
<p>You cannot really avoid this completely. Required metadata for categorical variable is actually a mapping between value and index. Still, there is no need to do it manually or to <a href="https://stackoverflow.com/quest... | 2 | 2016-05-27T09:50:25Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-ml"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.