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
Speed up conversion of timestamp to datetime Python
37,756,648
<p>I'm working on making a futures market tick data replay system using python and pytables with a pretty large dataset (+200GB). </p> <p>As far as I can tell, pytables can only store numpy datetime64 objects for my timestamps. This is an issue because I need to convert them to datetime objects or pandas timestamps ...
0
2016-06-10T20:23:34Z
37,756,960
<p>Try this:</p> <pre><code>import numpy from datetime import datetime npdt = numpy.datetime64(datetime.utcnow()) dt = npdt.astype(datetime) </code></pre> <p>I found it to be an order of magnitude faster:</p> <pre><code>from datetime import datetime import numpy import pandas import timeit foo = numpy.datetime64(d...
1
2016-06-10T20:49:07Z
[ "python", "datetime", "cython", "hdf5", "pytables" ]
Django still stuck (Many to Many)
37,756,778
<p>the idea is that students can send a ping to their teacher if they do not understand something, but first I am trying to get the student, teacher and whatever class they are in relationship so in my models after a few attempts I have come up with this </p> <p><strong>Models</strong></p> <pre><code>from django.db i...
0
2016-06-10T20:33:47Z
37,757,129
<p>I'm not entirely sure that you need explicit intermediary relationships (Teacher_of_class and part_of_class). Instead, you should try utilizing fields within the other models to do what you want. For example, will a lecture generally have more than one teacher, or just one? You could model either of those with a fie...
1
2016-06-10T21:04:01Z
[ "python", "django", "many-to-many" ]
Django still stuck (Many to Many)
37,756,778
<p>the idea is that students can send a ping to their teacher if they do not understand something, but first I am trying to get the student, teacher and whatever class they are in relationship so in my models after a few attempts I have come up with this </p> <p><strong>Models</strong></p> <pre><code>from django.db i...
0
2016-06-10T20:33:47Z
37,757,754
<p>If you just want to have a lecture that can have multiple students and multiple lecturers, you do not need to have the intermediate models, Django will handle this for you if you don't specify any. I would only use the intermediate tables if you wanted to store something with that relationship.</p> <p>Also when tr...
0
2016-06-10T22:05:32Z
[ "python", "django", "many-to-many" ]
Python (scipy) import time from text file
37,756,963
<p>I have the text file:</p> <pre><code>2010-05-16 2010-09-26 2011-04-28 </code></pre> <p>Each line is a string: <code>YYYY-MM-dd</code></p> <p>My goal is to read this text file and to write this information to array.</p> <pre><code>import scipy as sp x=sp.empty(200,ftype=sp.datetime64) file=open(place,'r') fo...
2
2016-06-10T20:49:18Z
37,757,087
<p>Try this:</p> <pre><code>import numpy as np x = np.empty(200, dtype='datetime64[D]') with open(place, 'r') as f: for i, date in enumerate(f): x[i] = date.strip() </code></pre> <p>Firstly, it's a <code>dtype</code>, not an <code>ftype</code>. Then, we need to use <code>datetime64[D]</code> since this...
1
2016-06-10T20:59:58Z
[ "python", "arrays", "numpy", "text", "scipy" ]
How do I to turn my .tar.gz file into a file-like object for shutil.copyfileobj?
37,756,986
<p>My goal is to extract a file out of a <code>.tar.gz</code> file without also extracting out the sub directories that precede the desired file. I am trying to module my method off this <a href="http://stackoverflow.com/questions/4917284/extract-files-from-zip-without-keeping-the-structure-using-python-zipfile">questi...
2
2016-06-10T20:51:02Z
37,757,105
<p><code>fileobj</code> isn't a documented property of <code>TarFile</code>. It's probably an internal object used to represent the whole tar file, not something specific to the current file.</p> <p>Use <code>TarFile.extractfile()</code> to get a file-like object for a specific member:</p> <pre><code>… source = tar...
2
2016-06-10T21:01:19Z
[ "python", "python-3.x", "gzip", "tar", "shutil" ]
Best way to join two large datasets in Pandas
37,756,991
<p>I'm downloading two datasets from two different databases that need to be joined. Each of them separately is around 500MB when I store them as CSV. Separately the fit into the memory but when I load both I sometimes get a memory error. I definitely get into trouble when I try to merge them with pandas. </p> <p>What...
2
2016-06-10T20:51:18Z
37,757,496
<p>This seems like a task that <a href="http://dask.pydata.org/en/latest/index.html" rel="nofollow"><code>dask</code></a> was designed for. Essentially, <code>dask</code> can do <code>pandas</code> operations out-of-core, so you can work with datasets that don't fit into memory. The <code>dask.dataframe</code> API is...
1
2016-06-10T21:37:16Z
[ "python", "pandas", "memory-management" ]
Best way to join two large datasets in Pandas
37,756,991
<p>I'm downloading two datasets from two different databases that need to be joined. Each of them separately is around 500MB when I store them as CSV. Separately the fit into the memory but when I load both I sometimes get a memory error. I definitely get into trouble when I try to merge them with pandas. </p> <p>What...
2
2016-06-10T20:51:18Z
37,846,032
<p>I would recommend you to use RDBMS like MySQL for that...</p> <p>So you would need to <a href="http://stackoverflow.com/a/11077961/5741205">load your CSV files into tables</a> first.</p> <p>After that you can perform your checks:</p> <p>which products and versions are in the left table only</p> <pre><code>SELECT...
1
2016-06-15T21:24:19Z
[ "python", "pandas", "memory-management" ]
Override a field in parent class with property in child class
37,757,037
<p>Where I am now looks like this:</p> <pre><code>class A(object): def __init__(self, val): self.x=val self.y=42 # other fields class B(object): def __init__(self): self.a=22 # other fields class C(A,B): def __init__(self, val): super(C,self).__init__(val) ...
0
2016-06-10T20:55:59Z
37,757,084
<p>The line <code>self.x = val</code> in the <code>A.__init__</code> method will simply invoke your <code>C.x</code> <em>setter</em>. You already have everything handled here. You are handling <em>per instance</em> attributes here, not attributes on a class that are inherited by subclasses.</p> <p>All you need to do i...
2
2016-06-10T20:59:46Z
[ "python", "python-2.7", "inheritance", "properties" ]
Pipe Twisted Request Content to STDIN of Process
37,757,061
<p>I'm looking to pipe the content of a HTTP POST or PUT to STDIN of a process. I'm using the Klein library and have the following code:</p> <pre><code>from klein import run, route from twisted.internet import reactor, defer, protocol import os class CurlProcProtocol(protocol.ProcessProtocol): def __init__(se...
0
2016-06-10T20:58:03Z
37,822,029
<p>I ended up dumping Klein and going with just Twisted</p> <pre><code>from twisted.web import server, resource from twisted.internet import reactor, protocol import os class CurlProcProtocol(protocol.ProcessProtocol): def __init__(self, request): self.request = request def connectionMade(self): ...
0
2016-06-14T21:02:12Z
[ "python", "twisted", "twisted.web", "twisted.internet" ]
The 'sphinx-build' command was not found.
37,757,151
<p>This was our processes of installing Sphinx.</p> <pre><code>&gt; choco install python -y -f &gt; pip install sphinx </code></pre> <p>We know that sphinx installed because of the following output. </p> <pre><code>&gt; pip show sphinx --- Metadata-Version: 2.0 Name: Sphinx Version: 1.4.3 Summary: Python documentati...
1
2016-06-10T21:05:50Z
37,757,302
<p>We added the wrong directory to the path. </p> <p>Wrong:</p> <pre><code>c:\programdata\chocolatey\lib\python3\tools\lib\site-packages </code></pre> <p>Right: </p> <pre><code>c:\programdata\chocolatey\lib\python3\tools\Scripts </code></pre>
0
2016-06-10T21:17:48Z
[ "python", "windows-10", "python-sphinx", "chocolatey" ]
Finding and utilizing eigenvalues and eigenvectors from PCA in scikit-learn
37,757,172
<p>I have been utilizing PCA implemented in scikit-learn. However, I want to find the eigenvalues and eigenvectors that result after we fit the training dataset. There is no mention of both in the docs.</p> <p>Secondly, can these eigenvalues and eigenvectors themselves be utilized as features for classification purpos...
0
2016-06-10T21:07:43Z
37,759,714
<p>I am assuming here that by EigenVectors you mean the Eigenvectors of the Covariance Matrix. </p> <p>Lets say that you have n data points in a p-dimensional space, and X is a p x n matrix of your points then the directions of the principal components are the Eigenvectors of the Covariance matrix XX<sup>T</sup>. You ...
0
2016-06-11T03:48:52Z
[ "python", "machine-learning", "scikit-learn", "pca" ]
Python: How do you use lxml to parse xml tags with periods?
37,757,193
<p>I am attempting to parse Jenkin's job XML files using the lxml module for Python. It looks like this:</p> <pre><code>&lt;triggers&gt; &lt;hudson.triggers.TimerTrigger&gt; &lt;spec&gt;H H(6-21)/3 * * *&lt;/spec&gt; &lt;/hudson.triggers.TimerTrigger&gt; </code></pre> <p></p> <p>I like using lxml's handy ...
0
2016-06-10T21:09:23Z
37,757,573
<p>The following code using <code>lxml</code>'s <a href="http://lxml.de/tutorial.html" rel="nofollow"><code>etree</code></a> module worked for me to get the text from <code>&lt;spec&gt;</code>:</p> <pre><code>from lxml import etree root = etree.parse("37757193.xml").getroot() spec = root.xpath("//triggers/hudson.trig...
1
2016-06-10T21:44:39Z
[ "python", "jenkins", "lxml" ]
Python: How do you use lxml to parse xml tags with periods?
37,757,193
<p>I am attempting to parse Jenkin's job XML files using the lxml module for Python. It looks like this:</p> <pre><code>&lt;triggers&gt; &lt;hudson.triggers.TimerTrigger&gt; &lt;spec&gt;H H(6-21)/3 * * *&lt;/spec&gt; &lt;/hudson.triggers.TimerTrigger&gt; </code></pre> <p></p> <p>I like using lxml's handy ...
0
2016-06-10T21:09:23Z
37,759,660
<p>It does make sense that <code>triggers.hudson.triggers.TimerTrigger</code> interpreted as trying to access <code>&lt;TimerTrigger&gt;</code> element in the following structure, hence it complained about <code>hudson</code> child element not found when given OP's actual XML :</p> <pre><code>&lt;triggers&gt; &lt;h...
1
2016-06-11T03:36:58Z
[ "python", "jenkins", "lxml" ]
Get non-matching data when comparing python dicts and store them
37,757,230
<p>I have 2 python dicts... I'm currently checking if they match. But how can I get the non-matched keys and values from items and store them?</p> <pre><code>data1 = {'first_name': 'John', 'last_name': 'Doe', 'username': 'johndoe'} data2 = {'first_name': 'John', 'last_name': 'Doe', 'username': 'johohoho'} for (key, ...
0
2016-06-10T21:12:00Z
37,757,333
<p>You can use xor for non matching entries just like you are catching matched entries:</p> <pre><code>&gt;&gt;&gt; for (key, value) in set(data1.items()) ^ set(data2.items()): ... print(key, value) ... ('username', 'johndoe') ('username', 'johohoho') </code></pre> <p>Note: this won't work for nested dictio...
1
2016-06-10T21:21:10Z
[ "python" ]
Scrapy installed, but won't run from the command line
37,757,233
<p>I'm trying to run a scraping program I wrote for in python using scrapy on an ubuntu machine. Scrapy is installed. I can import until python no problem and when try <code>pip install scrapy</code> I get </p> <blockquote> <p>Requirement already satisfied (use --upgrade to upgrade): scrapy in /system/linux/lib/pyth...
0
2016-06-10T21:12:07Z
37,760,337
<p>scrapy crawl is not how you start a scrapy program. You start it by doing </p> <pre><code>scrapy startproject myprojectname </code></pre> <p>Then to actually start a scrapy program go into myprojectname/spiders and then you can call </p> <pre><code>scrapy crawl "yourspidername" </code></pre> <p>To have scrapy c...
0
2016-06-11T05:36:27Z
[ "python", "scrapy" ]
Scrapy installed, but won't run from the command line
37,757,233
<p>I'm trying to run a scraping program I wrote for in python using scrapy on an ubuntu machine. Scrapy is installed. I can import until python no problem and when try <code>pip install scrapy</code> I get </p> <blockquote> <p>Requirement already satisfied (use --upgrade to upgrade): scrapy in /system/linux/lib/pyth...
0
2016-06-10T21:12:07Z
37,914,201
<p>I had the same issue. <code>sudo pip install scrapy</code> fixed my problem, although I don't know why must use <code>sudo</code>.</p>
0
2016-06-20T03:23:09Z
[ "python", "scrapy" ]
Copying all files of a directory to one text file in python
37,757,271
<p>My intention is to copy the text of all my c# (and later aspx) files to one final text file, but it doesn't work.</p> <p>For some reason, the "yo.txt" file is not created.</p> <p>I know that the iteration over the files works, but I can't write the data into the .txt file. </p> <p>The variable 'data' eventually d...
0
2016-06-10T21:14:47Z
37,757,391
<p>You have to ensure the directory the file is created has sufficient write permissions, if not run</p> <pre><code> chmod -R 777 . </code></pre> <p>to make the directory writable.</p>
0
2016-06-10T21:27:11Z
[ "python", "file" ]
Django - Rendering Markdown Sanitizied with Bleach
37,757,474
<p>I have a Django site that allows for user inputted Markdown text. I'd like to sanitize and display the text, but I can't get it to display correctly.</p> <p>templatetags.py:</p> <pre><code>from django import template import markdown import re import bleach register = template.Library() @register.filter def markd...
0
2016-06-10T21:35:01Z
37,758,663
<p>You need to mark the <code>bleach</code>ed HTML as safe</p> <pre><code>from django.utils.safestring import mark_safe ... return mark_safe(bleach.clean(markdown.markdown(text))) </code></pre> <p>But, there is also <a href="https://bitbucket.org/ionata/django-bleach.git/" rel="nofollow">django-bleach</a> that p...
1
2016-06-11T00:03:27Z
[ "python", "html", "django", "html5", "markdown" ]
How do I mark the percentage change between two lines in matplotlib?
37,757,523
<p>I plot two lines with matplotlib and would like to mark the maximum improvements. I use <code>ax.annotate</code> and got the following undesirable result,</p> <p><a href="http://i.stack.imgur.com/XkbT5.png" rel="nofollow"><img src="http://i.stack.imgur.com/XkbT5.png" alt="enter image description here"></a></p> <p>...
1
2016-06-10T21:39:48Z
37,757,928
<p>I would split the text and the arrow into seperate pieces.</p> <pre><code>#!/bin/python from __future__ import division import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2) x = range(10) y1 = range(10) y2 = [2*i for i in range(10)] # plot line graphs ax1.plot(x, y1) ax1.plot(x, y2) # the maximu...
2
2016-06-10T22:22:34Z
[ "python", "matplotlib", "annotations" ]
How do I mark the percentage change between two lines in matplotlib?
37,757,523
<p>I plot two lines with matplotlib and would like to mark the maximum improvements. I use <code>ax.annotate</code> and got the following undesirable result,</p> <p><a href="http://i.stack.imgur.com/XkbT5.png" rel="nofollow"><img src="http://i.stack.imgur.com/XkbT5.png" alt="enter image description here"></a></p> <p>...
1
2016-06-10T21:39:48Z
37,757,980
<p>I agree with @hobenkr. You have to split your annotation on two another annotationa: the first is an arrow and the second is a text label. For text you may set <code>bold</code> weight.</p> <pre><code>from __future__ import division import matplotlib.pyplot as plt fig, (ax1, ax2) = plt.subplots(1, 2) x = range(10...
1
2016-06-10T22:28:55Z
[ "python", "matplotlib", "annotations" ]
Sum numpy array values based on labels in a separate array
37,757,555
<p>I have arrays similar to the following:</p> <pre><code>a=[["tennis","tennis","golf","federer","cricket"], ["federer","nadal","woods","sausage","federer"], ["sausage","lion","prawn","prawn","sausage"]] </code></pre> <p>I then have a matrix of the following weights</p> <pre><code>w=[[1,3,3,4,5], [2,3,2,3,4...
2
2016-06-10T21:43:15Z
37,757,740
<p>Try:</p> <pre><code>print pd.DataFrame( {i: a.loc[i, row.sort_values(ascending=False).index[:3]].values for i, row in w.iterrows()} ).T 0 1 2 0 cricket federer golf 1 federer sausage nadal 2 lion sausage prawn </code></pre>
3
2016-06-10T22:04:04Z
[ "python", "numpy" ]
Sum numpy array values based on labels in a separate array
37,757,555
<p>I have arrays similar to the following:</p> <pre><code>a=[["tennis","tennis","golf","federer","cricket"], ["federer","nadal","woods","sausage","federer"], ["sausage","lion","prawn","prawn","sausage"]] </code></pre> <p>I then have a matrix of the following weights</p> <pre><code>w=[[1,3,3,4,5], [2,3,2,3,4...
2
2016-06-10T21:43:15Z
37,757,805
<p>See <a href="http://stackoverflow.com/a/37757740/2607571">piRSquared answer</a> for numpy arrays.</p> <p>This is a pure python approach:</p> <pre><code>for i in range(4): if a[i].count(a[i][0]) == len(a[i]): res = [a[1][0], "", ""] else: res = [x[0] for x in sorted(zip(a[i], w[i]), key=lamb...
3
2016-06-10T22:10:24Z
[ "python", "numpy" ]
Sum numpy array values based on labels in a separate array
37,757,555
<p>I have arrays similar to the following:</p> <pre><code>a=[["tennis","tennis","golf","federer","cricket"], ["federer","nadal","woods","sausage","federer"], ["sausage","lion","prawn","prawn","sausage"]] </code></pre> <p>I then have a matrix of the following weights</p> <pre><code>w=[[1,3,3,4,5], [2,3,2,3,4...
2
2016-06-10T21:43:15Z
37,766,381
<p>I managed to get it to work using below code:</p> <pre><code>def myf(a,w): lookupTable, indexed_dataSet = np.unique(a, return_inverse=True) y= np.bincount(indexed_dataSet,w) lookupTable[y.argsort()] res=(lookupTable[y.argsort()][::-1][:3]) ret=np.empty((3)) ret.fill(res[-1]) ret[0:res.s...
1
2016-06-11T17:04:54Z
[ "python", "numpy" ]
Scrape webpage after form fill
37,757,578
<p>Im trying to scrape the response to this website using a pre-filled zip: <a href="http://zipwho.com/?zip=77098&amp;mode=zip" rel="nofollow">zip who</a> (i.e. the zip code is already filled in.) I tried to do this using the scrapy shell as follows </p> <pre><code>scrapy shell http://zipwho.com/?zip=77098&amp;mode=...
1
2016-06-10T21:45:00Z
37,758,254
<p>The reason that you can't find this data in the HTML is that it's generated dynamically with a script. If you look at the first script in the HTML, you'll see a function called <code>getData</code> that contains the data that you want. Another script later uses this function to build what you see in your browser.</p...
1
2016-06-10T23:03:42Z
[ "python", "web-scraping", "scrapy" ]
Scrape webpage after form fill
37,757,578
<p>Im trying to scrape the response to this website using a pre-filled zip: <a href="http://zipwho.com/?zip=77098&amp;mode=zip" rel="nofollow">zip who</a> (i.e. the zip code is already filled in.) I tried to do this using the scrapy shell as follows </p> <pre><code>scrapy shell http://zipwho.com/?zip=77098&amp;mode=...
1
2016-06-10T21:45:00Z
37,764,311
<p>The data is inside a script tag which you can parse with a regex but your approach is not going to work in scrapy or using requests, there is nothing posted to the page, the data is retrieved with a <em>get</em> where the <em>params</em> passed are <em>mode</em> and <em>zip</em>, a working example: </p> <pre><code...
1
2016-06-11T13:29:26Z
[ "python", "web-scraping", "scrapy" ]
Scrape webpage after form fill
37,757,578
<p>Im trying to scrape the response to this website using a pre-filled zip: <a href="http://zipwho.com/?zip=77098&amp;mode=zip" rel="nofollow">zip who</a> (i.e. the zip code is already filled in.) I tried to do this using the scrapy shell as follows </p> <pre><code>scrapy shell http://zipwho.com/?zip=77098&amp;mode=...
1
2016-06-10T21:45:00Z
37,768,825
<p>With thanks and a bit of both previous answers, a fully functioning solution is as follows:</p> <pre><code>url = 'http://zipwho.com/?zip=77098&amp;mode=zip' response = requests.post(url) tree = lh.document_fromstring(response.content) scriptText = tree.xpath("//script[contains(., 'function getData()')]")[0].text ...
0
2016-06-11T21:53:25Z
[ "python", "web-scraping", "scrapy" ]
Can we use a Pandas function in a Spark DataFrame column ? If so, how?
37,757,587
<p>I have a pandas dataframe called "pd_df".</p> <p>I want to modify it's column , so I do something like this:</p> <pre><code> import pandas as pd pd_df['notification_dt'] = pd.to_datetime(pd_df['notification_dt'], format="%Y-%m-%d") </code></pre> <p>It works.</p> <p>On the same database, I created a spark...
0
2016-06-10T21:46:01Z
37,759,717
<p>So, got it fixed.</p> <pre><code> udf = UserDefinedFunction(lambda x: pd.to_datetime(x, format="%Y-%m-%d"), TimestampType()) </code></pre> <p>should be</p> <pre><code> udf = UserDefinedFunction(lambda x: str(pd.to_datetime(x, format="%Y-%m-%d")), TimestampType()) </code></pre> <p>It was basically failing to conv...
0
2016-06-11T03:49:27Z
[ "python", "pandas", "apache-spark", "pyspark" ]
Can we use a Pandas function in a Spark DataFrame column ? If so, how?
37,757,587
<p>I have a pandas dataframe called "pd_df".</p> <p>I want to modify it's column , so I do something like this:</p> <pre><code> import pandas as pd pd_df['notification_dt'] = pd.to_datetime(pd_df['notification_dt'], format="%Y-%m-%d") </code></pre> <p>It works.</p> <p>On the same database, I created a spark...
0
2016-06-10T21:46:01Z
37,766,144
<p>Use this to manipulate dataframes in spark. </p> <p><a href="http://www.nodalpoint.com/dataframes-from-csv-files-in-spark-1-5-automatic-schema-extraction-neat-summary-statistics-elementary-data-exploration/" rel="nofollow">http://www.nodalpoint.com/dataframes-from-csv-files-in-spark-1-5-automatic-schema-extraction-...
1
2016-06-11T16:38:43Z
[ "python", "pandas", "apache-spark", "pyspark" ]
OSError: [Errno 13] Permission denied installing TensorFlow with Anaconda
37,757,678
<p>I followed the instruction from TensorFlow's official site:</p> <pre><code>sudo pip install --upgrade https://storage.googleapis.com/tensorflow/mac/tensorflow-0.8.0-py2-none-any.whl </code></pre> <p>But I got this error:</p> <pre><code>OSError: [Errno 13] Permission denied: '/Users/myname/anaconda/lib/python2.7/...
0
2016-06-10T21:57:10Z
39,575,464
<pre><code>pip install --upgrade --ignore-installed https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.10.0-cp35-cp35m-linux_x86_64.whl </code></pre> <p>use "--ignore-installed" flag to prevent errors about easy_install.</p>
0
2016-09-19T14:19:04Z
[ "python", "tensorflow", "anaconda" ]
Generate a python parser for a particular JSON format
37,757,686
<p>I'm using a file format. The format is, effectively, JSON with a particular structure. The format comes with a validator, which is great, and gives helpful error messages. However, the validator fails when the error causes the input to be invalid JSON, and gives a very poor error message. </p> <p>I can use this...
1
2016-06-10T21:57:55Z
37,757,873
<p>If I understand you right, the validator uses a json library to read the file, and then makes some additional checks.. This sounds like a good design to me; why reinvent the wheel? If invalid JSON gives error messages that are too cryptic, how about catching them in a <code>try ... except</code> block and formulatin...
0
2016-06-10T22:17:35Z
[ "python", "json", "validation", "parsing" ]
Generate a python parser for a particular JSON format
37,757,686
<p>I'm using a file format. The format is, effectively, JSON with a particular structure. The format comes with a validator, which is great, and gives helpful error messages. However, the validator fails when the error causes the input to be invalid JSON, and gives a very poor error message. </p> <p>I can use this...
1
2016-06-10T21:57:55Z
38,311,258
<p>The appropriate way to assert that a JSON file follows a particular format is to use <a href="http://json-schema.org/" rel="nofollow">JSON schema</a>. This is supported across many languages and has good libraries in Python. There's also helpful online tools to generate, validate, and test schema.</p>
1
2016-07-11T15:54:21Z
[ "python", "json", "validation", "parsing" ]
Python Regex Date
37,757,691
<p>I'm trying create a regex that looks for all dates in the format MM-DD-YYYY, and this is what I came up with so far:</p> <pre><code>dateRegex = re.compile(r''' (0[1-9]|1[0-2]) # Month - (10|20|[0-2][1-9]|3[01]) # Day: not [0-2][0-9]|...
-1
2016-06-10T21:58:34Z
37,757,801
<p>You can use the regex that you have created to extract all such records, seems fine and then perhaps store all the max days of a given month in a list, say:</p> <hr> <p>days = [31, 28, 31, 30, etc.]</p> <hr> <p>Then for February specifically you might create a function to detect if the given year is leap and use...
1
2016-06-10T22:10:08Z
[ "python", "regex" ]
Python Regex Date
37,757,691
<p>I'm trying create a regex that looks for all dates in the format MM-DD-YYYY, and this is what I came up with so far:</p> <pre><code>dateRegex = re.compile(r''' (0[1-9]|1[0-2]) # Month - (10|20|[0-2][1-9]|3[01]) # Day: not [0-2][0-9]|...
-1
2016-06-10T21:58:34Z
37,757,806
<p>I agree with jonrsharpe that the way to do this is to combine regex with datetime. I used a simple regex that is going to match anything that <em>could</em> be a date in the format, then try to parse them with datetime. </p> <pre><code>import re import datetime def yield_valid_dates(dateStr): for match in re.f...
0
2016-06-10T22:10:35Z
[ "python", "regex" ]
Python/MySQL "Insert into" with variables
37,757,747
<p>I have a problem with inserting new rows to the MySQL table. The name of the table will change, so it must be a variable and with that I have the most trouble. How can I change name of the table "second" with variable? Any idea?</p> <pre><code>add_word = ("INSERT INTO second " "(name, surname) " ...
0
2016-06-10T22:05:01Z
37,757,819
<p>You are not going to be able to have the table name be data. You will have to put it in the sql statement. Maybe like this:</p> <pre><code>add_word = ("INSERT INTO {table} " "(name, surname) " "VALUES (%s, %s)") table1 = 'second' data_word = (name1, surname1) cursor.execute(add_word.format...
1
2016-06-10T22:11:36Z
[ "python", "mysql", "variables", "table", "insert-into" ]
Python/MySQL "Insert into" with variables
37,757,747
<p>I have a problem with inserting new rows to the MySQL table. The name of the table will change, so it must be a variable and with that I have the most trouble. How can I change name of the table "second" with variable? Any idea?</p> <pre><code>add_word = ("INSERT INTO second " "(name, surname) " ...
0
2016-06-10T22:05:01Z
37,757,874
<p>You do it like this:</p> <pre><code>add_word = "INSERT INTO %s (name, surname) VALUES ('%s', '%s')"%('table_name','name','surname1') </code></pre> <p>and then you don't need data_word:</p> <pre><code>cursor.execute(add_word, params=None, multi=False) </code></pre>
0
2016-06-10T22:17:35Z
[ "python", "mysql", "variables", "table", "insert-into" ]
Append string in the middle of a query in python
37,757,804
<p>I'm trying to build a query in python, I'm looking for an elegant way to append a WHERE condition in the middle of a string:</p> <pre><code>def get_raw_queryset(frequency=None, where_condition=None): qs = "SELECT id, COUNT(*) AS count FROM user_transaction_log " \ # I WANT TO APPEND A WHERE ONLY IF not...
1
2016-06-10T22:10:18Z
37,757,827
<p>This will work as long as you can safely evaluate the WHERE string even if <code>where_condition</code> is not a string:</p> <pre><code>"SELECT ..." + bool(where_condition) * ("WHERE ...") + "GROUP ..." </code></pre> <p>I hope you're being extremely careful to avoid SQL injection.</p>
4
2016-06-10T22:12:37Z
[ "python", "string", "format" ]
Access class hierarchy attribute
37,757,810
<p>Given a class named <code>DataStream</code></p> <pre><code>class DataStream(object): def __init__(self): self.start = start self.input_val = input_val </code></pre> <p>and a class named <code>InDataStream</code>:</p> <pre><code>class InDataStream(DataStream): def __init__(self): s...
0
2016-06-10T22:10:55Z
37,757,888
<p>If you're looking to access an instance of <code>DataStream</code> from an instance of class <code>InDataStream</code>, then you may consider using composition instead of inheritance:</p> <pre><code>class InDataStream(object): def __init__(self): self.ready = ready self.datastream = DataStream()...
0
2016-06-10T22:18:51Z
[ "python", "python-3.x", "class-hierarchy", "class-attributes" ]
Looping through a paginated api asynchronously
37,757,839
<p>I'm currently ingesting data through an API that returns close to 100,000 documents in a paginated fashion (100 per page). I currently have some code that roughly functions as follows:</p> <pre><code>while c &lt;= limit: if not api_url: break req = urllib2.Request(api_url) opener = urllib2.buil...
2
2016-06-10T22:13:34Z
37,758,749
<p>What you have here is that you do not know up front about what will be read next unless you will call an API. Think of this like, what you can do in parallel?</p> <p>I do not know how much you can do in parallel and which tasks, but lets try...</p> <p>some assumptions: - you can retrieve data from the API without ...
0
2016-06-11T00:15:47Z
[ "python", "api", "asynchronous", "pagination", "twisted" ]
pandas df.loc[z,x]=y how to improve speed?
37,757,844
<p>I have identified one pandas command </p> <pre><code>timeseries.loc[z, x] = y </code></pre> <p>to be responsible for most of the time spent in an iteration. And now I am looking for better approaches to accelerate it. The loop covers not even 50k elements (and production goal is ~250k or more), but already needs a...
2
2016-06-10T22:14:17Z
37,760,261
<p>I always think <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.at.html" rel="nofollow"><code>at</code></a> is the fastest, but not. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> is faster:</p> <pre><code>im...
3
2016-06-11T05:25:27Z
[ "python", "pandas", "optimization" ]
pandas df.loc[z,x]=y how to improve speed?
37,757,844
<p>I have identified one pandas command </p> <pre><code>timeseries.loc[z, x] = y </code></pre> <p>to be responsible for most of the time spent in an iteration. And now I am looking for better approaches to accelerate it. The loop covers not even 50k elements (and production goal is ~250k or more), but already needs a...
2
2016-06-10T22:14:17Z
37,761,363
<p>@jezrael has provided an interesting comparison and i decided to repeat it using more indexing methods and against 10M rows DF (actually the size doesn't matter in this particular case):</p> <p>setup:</p> <pre><code>In [15]: df = pd.DataFrame(np.random.rand(10**7, 5), columns=list('abcde')) In [16]: df.info() &lt...
2
2016-06-11T07:58:32Z
[ "python", "pandas", "optimization" ]
can python and php access same mysqldb?
37,757,927
<p>Is it possible to access same mysql database using python and php.Beacause I am developing a video searching website which based on semantics. Purposely I have to use python and JavaEE. So I have to make a datbase to store video data. But it should be accessed through both python and javaEE, I can use php to interfa...
0
2016-06-10T22:22:33Z
37,759,626
<p>It's a database. It doesn't care what language or application you're using too access it. That's one of the benefits of having standards like the MySQL protocol, SQL in general, or even things like TCP/IP: They allow different systems to seamlessly inter-operate.</p>
1
2016-06-11T03:26:03Z
[ "php", "python", "mysql" ]
can python and php access same mysqldb?
37,757,927
<p>Is it possible to access same mysql database using python and php.Beacause I am developing a video searching website which based on semantics. Purposely I have to use python and JavaEE. So I have to make a datbase to store video data. But it should be accessed through both python and javaEE, I can use php to interfa...
0
2016-06-10T22:22:33Z
37,760,285
<p>Like @tadman said, yes. All you care about is making a new connection and obtaining a cursor in each of your program (no matter what language). The cursor is what does what you want (analogous to executing an actual query in whatever program you're using).</p>
0
2016-06-11T05:29:16Z
[ "php", "python", "mysql" ]
Use alias for column name in SQLAlchemy
37,758,128
<p>Suppose if I have a SQLAlchemy table as follows -</p> <pre><code>class Employee(Base): id = Column(Integer, primary_key=True) employee_desgination = Column(String) </code></pre> <p>I remember going through the docs once and seeing some way of using aliases for long column names and use shorter ones instead...
1
2016-06-10T22:46:12Z
37,758,696
<p>You can specify the <a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/basic_use.html#defining-attributes" rel="nofollow">actual column name</a> (if different from the attribute name) as the first argument to <code>Column</code>:</p> <pre><code>emp_d = Column("employee_desgination", String) </...
0
2016-06-11T00:07:46Z
[ "python", "sqlalchemy" ]
Sha256 returning incorrect hash values?
37,758,167
<p>I'm trying to hash a bitcoin private key to get the checksum, and two different libraries in python (hashlib + pycrypto) are returning the same incorrect result (after just 1 hash). </p> <p>In linux terminal, I get the correct hash result with the line:</p> <pre><code>echo -n 8018ac3e7343f016890c510e93f935261169d9...
0
2016-06-10T22:52:57Z
37,758,233
<pre><code>import hashlib print( hashlib.sha256("8018ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4").hexdigest() ) print( hashlib.sha256("8018ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4".decode("hex")).hexdigest() ) </code></pre> <p>Notice the difference:</p> <p>The first...
2
2016-06-10T23:01:56Z
[ "python", "linux", "bitcoin" ]
unbound method must be called with instance as first argument
37,758,200
<p>I am trying to build simple fraction calculator in python2.x</p> <pre><code>from fractions import Fraction class Thefraction: def __init__(self,a,b): self.a = a self.b =b def add(self): return a+b def subtract(self,a,b): return a-b def divide(self,a,b): retur...
1
2016-06-10T22:57:28Z
37,758,248
<p>It's meant to be done like this:</p> <pre><code>thefraction = Thefraction(a, b) if choice == 1: print(thefraction.add()) </code></pre> <p>Then in your class:</p> <pre><code>def add(self): return self.a + self.b </code></pre> <p>and so on. Don't include <code>a</code> and <code>b</code> as parameters in t...
3
2016-06-10T23:03:13Z
[ "python", "instantiation" ]
unbound method must be called with instance as first argument
37,758,200
<p>I am trying to build simple fraction calculator in python2.x</p> <pre><code>from fractions import Fraction class Thefraction: def __init__(self,a,b): self.a = a self.b =b def add(self): return a+b def subtract(self,a,b): return a-b def divide(self,a,b): retur...
1
2016-06-10T22:57:28Z
37,758,286
<p>If you want to use it like you are using it, you should define your class methods as @classmethod and you do not need an init:</p> <pre><code>class TheFraction: @classmethod def add(cls, a, b): return a+b </code></pre> <p>This way of declaring methods indicate that they are not to be run in instanc...
0
2016-06-10T23:08:09Z
[ "python", "instantiation" ]
unbound method must be called with instance as first argument
37,758,200
<p>I am trying to build simple fraction calculator in python2.x</p> <pre><code>from fractions import Fraction class Thefraction: def __init__(self,a,b): self.a = a self.b =b def add(self): return a+b def subtract(self,a,b): return a-b def divide(self,a,b): retur...
1
2016-06-10T22:57:28Z
37,758,342
<p>You haven't put <code>()</code> in front of your <code>theFraction</code> object. Even if you did, you will be faced by another calamity..You initialize your object with two variables (a,b) which means you will to call your object like </p> <pre><code>Thefraction(a,b).add(a,b) </code></pre> <p>I dont think you wan...
2
2016-06-10T23:12:58Z
[ "python", "instantiation" ]
Python TypeError: 'type' object does not support item assignment
37,758,228
<p>I have to design and implement a <code>TwoSum</code> class. It should support the following operations:</p> <ul> <li><code>add</code> - Add the number to an internal data structure.</li> <li><code>find</code> - Find if there exists any pair of numbers which sum is equal to the value.</li> </ul> <p>Here is my code:...
1
2016-06-10T23:01:21Z
37,758,352
<p>The <code>dict</code> at the class level and the <code>dict</code> in the method are different</p> <p>In the method, <code>dict</code> is the builtin python type. If you want to modify the <code>dict</code> on the class, you could try something like <code>type(self).dict[n] = n</code></p> <p>Also, for what it's w...
1
2016-06-10T23:15:00Z
[ "python" ]
Python TypeError: 'type' object does not support item assignment
37,758,228
<p>I have to design and implement a <code>TwoSum</code> class. It should support the following operations:</p> <ul> <li><code>add</code> - Add the number to an internal data structure.</li> <li><code>find</code> - Find if there exists any pair of numbers which sum is equal to the value.</li> </ul> <p>Here is my code:...
1
2016-06-10T23:01:21Z
37,758,362
<p>Lot of issues here, I'll try to go through them one by one</p> <h3>The data structure</h3> <pre><code>dict = {} </code></pre> <p>Not only is this <s>overwriting python's dict</s>, (see mgilson's comment) but this is the wrong data structure for the project. You should use a list instead (or a set if you have uniq...
3
2016-06-10T23:17:09Z
[ "python" ]
Python TypeError: 'type' object does not support item assignment
37,758,228
<p>I have to design and implement a <code>TwoSum</code> class. It should support the following operations:</p> <ul> <li><code>add</code> - Add the number to an internal data structure.</li> <li><code>find</code> - Find if there exists any pair of numbers which sum is equal to the value.</li> </ul> <p>Here is my code:...
1
2016-06-10T23:01:21Z
37,758,374
<pre><code>class TwoSum(object): def __init__(self): self.__data = [] def __repr__(self): return repr(self.__data) def add(self, n): self.__data.append(n) def find(self, n): for i, v in enumerate(self.__data): for x, v2 in enumerate(self.__data): ...
1
2016-06-10T23:17:59Z
[ "python" ]
Python TypeError: 'type' object does not support item assignment
37,758,228
<p>I have to design and implement a <code>TwoSum</code> class. It should support the following operations:</p> <ul> <li><code>add</code> - Add the number to an internal data structure.</li> <li><code>find</code> - Find if there exists any pair of numbers which sum is equal to the value.</li> </ul> <p>Here is my code:...
1
2016-06-10T23:01:21Z
37,758,662
<blockquote> <p>Here is my solution, just another reference for any potential people who may see this question. Basically, I combined all above answers to get this solution. Credits to @Keatinge, @mgilson, @TheLazyScripter. Thank you guys all.</p> </blockquote> <pre><code>class TwoSum(object): def __init__...
0
2016-06-11T00:03:19Z
[ "python" ]
python: Dowloading and caching XML files - how to handle encoding declaration?
37,758,231
<pre><code>from urllib.request import urlopen from lxml import objectify </code></pre> <p>I am trying to write a program that will download XML files into a cache and then open them using <code>objectify</code>. If I download the files using <code>urlopen()</code> then I can read them in using <code>objectify.fromstr...
1
2016-06-10T23:01:37Z
37,758,475
<p>The file needs to be opened in binary mode rather than text mode.</p> <pre><code>open(my_file, 'rb') # b stands for binary </code></pre> <p>as suggested by the exception: <code>... Please use bytes input ...</code></p>
2
2016-06-10T23:32:05Z
[ "python", "xml", "unicode", "encoding", "lxml.objectify" ]
iterate through a dictionary that has a list within lists
37,758,384
<p>I'm trying to figure out a way to match a value in a nested list in a dictionary. Let's say I have this structure;</p> <pre><code>dict2 = {'key1': [ 2, ['value1', 3], ['value2', 4] ], 'key2' : [1, ['value1', 2], ['value2', 5] ], 'key3' : [7, ['value1', 6], ['value2', 2], ['value3', 3] ] } </code></pre> <p>Now let'...
0
2016-06-10T23:19:31Z
37,758,458
<p>If you're confident that the given nested dictionary always has this format, then we can do something like:</p> <pre><code>def find_value(nested_dict, value): for key, nested_list in nested_dict.items(): # If Python 2, use .iteritems() instead. for inner_list in nested_list[1:]: if value ==...
1
2016-06-10T23:30:33Z
[ "python", "list", "dictionary" ]
iterate through a dictionary that has a list within lists
37,758,384
<p>I'm trying to figure out a way to match a value in a nested list in a dictionary. Let's say I have this structure;</p> <pre><code>dict2 = {'key1': [ 2, ['value1', 3], ['value2', 4] ], 'key2' : [1, ['value1', 2], ['value2', 5] ], 'key3' : [7, ['value1', 6], ['value2', 2], ['value3', 3] ] } </code></pre> <p>Now let'...
0
2016-06-10T23:19:31Z
37,758,472
<p>Try this instead:</p> <pre><code>if 'value1' in d['key1'][1]: print('Value 1 found') if 'value2' in d['key1'][2]: print('Value 1 found') </code></pre>
0
2016-06-10T23:31:49Z
[ "python", "list", "dictionary" ]
iterate through a dictionary that has a list within lists
37,758,384
<p>I'm trying to figure out a way to match a value in a nested list in a dictionary. Let's say I have this structure;</p> <pre><code>dict2 = {'key1': [ 2, ['value1', 3], ['value2', 4] ], 'key2' : [1, ['value1', 2], ['value2', 5] ], 'key3' : [7, ['value1', 6], ['value2', 2], ['value3', 3] ] } </code></pre> <p>Now let'...
0
2016-06-10T23:19:31Z
37,758,504
<p>The code in your question is using a numeric index instead of the string 'key1'. Here's a modified version that should work:</p> <pre><code>if 'value1' in {array[0] for array in dict2.get('key1', [])[1:]}: print 'true' else: print 'false' </code></pre> <p>That looks at all of the elements after the first ...
2
2016-06-10T23:36:44Z
[ "python", "list", "dictionary" ]
iterate through a dictionary that has a list within lists
37,758,384
<p>I'm trying to figure out a way to match a value in a nested list in a dictionary. Let's say I have this structure;</p> <pre><code>dict2 = {'key1': [ 2, ['value1', 3], ['value2', 4] ], 'key2' : [1, ['value1', 2], ['value2', 5] ], 'key3' : [7, ['value1', 6], ['value2', 2], ['value3', 3] ] } </code></pre> <p>Now let'...
0
2016-06-10T23:19:31Z
37,758,611
<p>If you are looking only inside the lists you may do something like this:</p> <pre><code>for key, value in my_dict.items(): for item in value: if isintance(item, list): if desired_value in item: return item # Here it is! </code></pre>
0
2016-06-10T23:55:24Z
[ "python", "list", "dictionary" ]
iterate through a dictionary that has a list within lists
37,758,384
<p>I'm trying to figure out a way to match a value in a nested list in a dictionary. Let's say I have this structure;</p> <pre><code>dict2 = {'key1': [ 2, ['value1', 3], ['value2', 4] ], 'key2' : [1, ['value1', 2], ['value2', 5] ], 'key3' : [7, ['value1', 6], ['value2', 2], ['value3', 3] ] } </code></pre> <p>Now let'...
0
2016-06-10T23:19:31Z
37,758,884
<p>Try this: </p> <pre><code>for x,v in dict2.items(): if x == "key1": for i, e in enumerate(v): try: if e[0] == 'value2': print "True" else: print "False" except:pass </code></pre>
0
2016-06-11T00:41:56Z
[ "python", "list", "dictionary" ]
Amend column values according to timedelta and index
37,758,448
<p>I would like to change my data in a pandas dataframe.</p> <p>The data I collect needs to be assigned a step value. The conditions of what triggers a step change are occasionally time or high pressure or temperature values. I cannot get past the first step: When the row is over a certain pressure (1100 psi) and unde...
2
2016-06-10T23:28:56Z
37,758,584
<p>use <code>.loc</code> instead of <code>.ix</code></p> <pre><code>df.loc[(df.press &gt; 1100) &amp; (df.temp &lt; 40), 'proc'] = 'dilute' </code></pre>
2
2016-06-10T23:49:20Z
[ "python", "numpy", "pandas" ]
Amend column values according to timedelta and index
37,758,448
<p>I would like to change my data in a pandas dataframe.</p> <p>The data I collect needs to be assigned a step value. The conditions of what triggers a step change are occasionally time or high pressure or temperature values. I cannot get past the first step: When the row is over a certain pressure (1100 psi) and unde...
2
2016-06-10T23:28:56Z
37,758,594
<p>Try this </p> <pre><code>df['press'].astype('float') df['temp'].astype('float') df['proc'] = np.where((df['press'] &gt; 1100) &amp; (df['temp'] &lt; 40),'dilute', "pressurized") </code></pre>
4
2016-06-10T23:51:17Z
[ "python", "numpy", "pandas" ]
Is this an issue with my method of recursion?
37,758,507
<p>In response to <a href="http://cs.stackexchange.com/questions/59429/efficient-algorithm-for-getting-from-1-to-n-with-3-specific-operations">this question</a> I tried to come up with my own solution. </p> <h2>My solution in python 3.X</h2> <pre><code>def efficientalgo(number, x): print("Start with this number.....
1
2016-06-10T23:37:08Z
37,758,720
<p>number should be set <code>= efficientalgo(..)</code> to not <code>+=</code>:</p> <pre><code>def efficientalgo(number): print("Start with this number... " + str(number)) # See if a number is dividable by three, if so then divide by 3 if number % 3 == 0: print("Dividing three...") number ...
1
2016-06-11T00:11:00Z
[ "python", "recursion", "big-o" ]
Traits for SortedListWithKey
37,758,544
<p>I am using a <code>SortedListWithKey</code> class from the new <code>sortedcontainers</code> module (<a href="http://www.grantjenks.com/docs/sortedcontainers/sortedlistwithkey.html" rel="nofollow">link</a>). Is there a way to adapt the List trait to specify that I want a <code>SortedListWithKey(Instance(SomeClass), ...
0
2016-06-10T23:43:17Z
37,779,032
<p>After looking at your question again, I think what you are looking to for is a way of accessing the <code>SortedListWithKey</code> object as if it were a list and using the <code>Traits</code> or <code>TraitsUI</code> machinery to be able to validate/view/modify it. The <a href="https://traits.readthedocs.io/en/late...
0
2016-06-12T20:59:14Z
[ "python", "traits", "enthought" ]
Serialize/Deserialize list of objects using json and python
37,758,665
<p>How do i serialize a list of objects(Person) to a json file and then read that json file back and deserialize them back into objects? I know how to write to a json file but i'm not clear on how to convert my objects to json properly.</p> <p>Below is my simplified snippet of code. I have a list containing two people...
0
2016-06-11T00:03:38Z
37,758,771
<p>The <code>json</code> module expects lists, dicts, strings, numbers, booleans, and None, not custom classes. You need to make a dictionary out of your <code>People</code> instance. A simple way to do this is with <code>vars(A)</code>.</p>
1
2016-06-11T00:19:54Z
[ "python", "json", "serialization" ]
Serialize/Deserialize list of objects using json and python
37,758,665
<p>How do i serialize a list of objects(Person) to a json file and then read that json file back and deserialize them back into objects? I know how to write to a json file but i'm not clear on how to convert my objects to json properly.</p> <p>Below is my simplified snippet of code. I have a list containing two people...
0
2016-06-11T00:03:38Z
37,758,782
<p>You cannot serialize custom classes using JSON. </p> <p>You should use the <code>pickle</code> module instead. From the docs:</p> <p><a href="https://docs.python.org/3/library/pickle.html#comparison-with-json" rel="nofollow">https://docs.python.org/3/library/pickle.html#comparison-with-json</a></p> <blockquote> ...
1
2016-06-11T00:22:56Z
[ "python", "json", "serialization" ]
Serialize/Deserialize list of objects using json and python
37,758,665
<p>How do i serialize a list of objects(Person) to a json file and then read that json file back and deserialize them back into objects? I know how to write to a json file but i'm not clear on how to convert my objects to json properly.</p> <p>Below is my simplified snippet of code. I have a list containing two people...
0
2016-06-11T00:03:38Z
37,758,807
<p>add to_dict method to your person class. try this</p> <pre><code>In [2]: class Person(object): ...: def __init__(self, name, nickname): ...: self.name = name ...: self.age = 0 ...: self.nickname = nickname ...: def to_dict(self): ...:...
1
2016-06-11T00:27:47Z
[ "python", "json", "serialization" ]
Fastest way from logic matrix to list of sets
37,758,740
<p>I need to convert a sparse logic matrix into a list of sets, where each list[i] contains the set of rows with nonzero values for column[i]. The following code works, but I'm wondering if there's a faster way to do this. The actual data I'm using is approx 6000x6000 and much more sparse than this example.</p> <pre><...
3
2016-06-11T00:13:49Z
37,758,786
<p>If you represent the sparse array as a <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.html" rel="nofollow"><code>csc_matrix</code></a>, you can use the <code>indices</code> and <code>indptr</code> attributes to create the sets.</p> <p>For example,</p> <pre><code>In [93]: A Out...
4
2016-06-11T00:23:46Z
[ "python", "numpy", "matrix", "scipy", "set" ]
Fastest way from logic matrix to list of sets
37,758,740
<p>I need to convert a sparse logic matrix into a list of sets, where each list[i] contains the set of rows with nonzero values for column[i]. The following code works, but I'm wondering if there's a faster way to do this. The actual data I'm using is approx 6000x6000 and much more sparse than this example.</p> <pre><...
3
2016-06-11T00:13:49Z
37,758,832
<p>I don't know if increases speed much, but your iteration can streamlined with</p> <pre><code>for i,j in zip(*C): D[j].add(i) </code></pre> <p>A defaultdict could add a nice touch to this task:</p> <pre><code>In [58]: from collections import defaultdict In [59]: D=defaultdict(set) In [60]: for i,j in zip(*...
1
2016-06-11T00:32:47Z
[ "python", "numpy", "matrix", "scipy", "set" ]
Fastest way from logic matrix to list of sets
37,758,740
<p>I need to convert a sparse logic matrix into a list of sets, where each list[i] contains the set of rows with nonzero values for column[i]. The following code works, but I'm wondering if there's a faster way to do this. The actual data I'm using is approx 6000x6000 and much more sparse than this example.</p> <pre><...
3
2016-06-11T00:13:49Z
37,758,928
<p>Since you already called <code>np.nonzero</code> on <code>A</code>, see if this works faster:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; C = np.transpose(np.nonzero(A.T)) &gt;&gt;&gt; [{i[1] for i in g} for _, g in groupby(C, key=lambda x: x[0])] [{0, 2, 3, 4, 5}, {1, 3, 4}, {1, 2, 6, 7}...
2
2016-06-11T00:53:05Z
[ "python", "numpy", "matrix", "scipy", "set" ]
Text formatting on pandas pivot table
37,758,768
<p>I am creating a dataframe and then converting that dataframe into a pivot table. The text and the column headers in the pivot table are aligned to center in my result. I would like to set the text justify as "left". Could you please help with this ? I've tried <code>df.to_string(justify = 'true')</code> but it throw...
0
2016-06-11T00:19:10Z
37,760,218
<p>I think you need set parameter <code>justify</code> to <code>left</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_string.html" rel="nofollow"><code>to_string</code></a>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Customer': ['Ann Green', 'Joseph Smith', 'Ann...
0
2016-06-11T05:18:00Z
[ "python", "pandas", "pymongo" ]
New to programming and trying to finish this task for school, I can't seem to add numbers in a list together
37,758,812
<p>I have a bit of code thats for a task we have to complete for school. I'm trying to add some numbers in a list so I can average that number. Whenever I try to do this it just tells me its an unsupported operand type for int and str. I think what I have to do is convert the inputs into floats rather than strings but ...
1
2016-06-11T00:28:32Z
37,758,966
<p>You can convert the input straight into a float</p> <pre><code> judgeScore = float(input("Enter the judge score here: ")) </code></pre> <p>But it might be best to check if the user has supplied a number first by prehaps using isdigit() I don't want to give too much away but that should help</p>
3
2016-06-11T01:00:24Z
[ "python" ]
How can these javascript links be traversed with Selenium or BeautifulSoup?
37,758,866
<p>I’ve opted for Selenium since the links’ hrefs are generated dynamically, although some method via bs4 would be preferred.</p> <p>I'm using PhantomJS but have tried Firefox as well</p> <p>When attempting to click a link, nothing happens.</p> <p>For instance,</p> <pre><code>url = 'http://www.achema.de/de/auss...
1
2016-06-11T00:39:19Z
37,759,002
<p>I'm not quite sure I know what you're trying to click but I clicked the first listing on the page "Agora Pavillon C7" with the following code.</p> <pre><code>from selenium import webdriver def so_test(): driver = webdriver.Firefox() def connect(): driver.get('http://www.achema.de/de/ausstellung/a...
1
2016-06-11T01:08:21Z
[ "python", "selenium", "beautifulsoup" ]
How can these javascript links be traversed with Selenium or BeautifulSoup?
37,758,866
<p>I’ve opted for Selenium since the links’ hrefs are generated dynamically, although some method via bs4 would be preferred.</p> <p>I'm using PhantomJS but have tried Firefox as well</p> <p>When attempting to click a link, nothing happens.</p> <p>For instance,</p> <pre><code>url = 'http://www.achema.de/de/auss...
1
2016-06-11T00:39:19Z
37,759,374
<p>As Orenthal indicated, I found that the link was being clicked. However, the page to be loaded was completely dynamic, so a sleep of at least 2 seconds needed to occur before attempting to extract from that link.</p>
2
2016-06-11T02:30:30Z
[ "python", "selenium", "beautifulsoup" ]
pip not working Windows
37,758,896
<p>pip is not working on Windows its giving me an empty output using<code>pip install virtualenv</code> but when I try and use virtualenv i get virtualenv is not recognized as an internal or external command, operable program or batch file. <a href="http://i.stack.imgur.com/aNDz6.png" rel="nofollow"><img src="http://i....
-1
2016-06-11T00:44:29Z
37,760,163
<p>Try updating pip. You can do this by:</p> <pre><code>pip install --upgrade pip </code></pre> <p>Make sure you run this as administrator. Additionally check if virtualenv is installed via </p> <pre><code>pip list </code></pre>
0
2016-06-11T05:11:01Z
[ "python", "pip" ]
pip not working Windows
37,758,896
<p>pip is not working on Windows its giving me an empty output using<code>pip install virtualenv</code> but when I try and use virtualenv i get virtualenv is not recognized as an internal or external command, operable program or batch file. <a href="http://i.stack.imgur.com/aNDz6.png" rel="nofollow"><img src="http://i....
-1
2016-06-11T00:44:29Z
37,769,702
<p>Maybe try use the following command if You can run python via cmd.</p> <pre><code>python -m pip install virtualenv </code></pre>
1
2016-06-12T00:34:08Z
[ "python", "pip" ]
Pyomo: How to use the final data point in an abstract model's objective?
37,758,954
<p>I have a Pyomo model which has the form:</p> <pre><code>from pyomo.environ import * from pyomo.dae import * m = AbstractModel() m.t = ContinuousSet(bounds=(0,120)) m.T = Param(default=120) m.S = Var(m.t, bounds=(0,None)) m.Sdot = DerivativeVar(m.S) m.obj = Objective(expr=m.S[120],sense=maximize) </...
0
2016-06-11T00:58:23Z
39,111,744
<p>You are hitting on two somewhat separate issues:</p> <pre><code>TypeError: unhashable type: 'SimpleParam' </code></pre> <p>Is due to a bug in Pyomo 4.3 where you cannot directly use simple <code>Param</code>s as indexes into other components. That said, the fix for this particular problem will not fix your exampl...
1
2016-08-23T22:37:09Z
[ "python", "optimization", "pyomo" ]
Merge dictionaries from multiple lists in Python
37,759,059
<p>I have three list with multiple dictionaries inside.</p> <pre><code>list1 = [{'question': u'Fan offline information can be found on what Screen under General Menu? '}, {'question': u'What is the tool for F5 BIGIP to get packet traces. '}, {'question': u'On a HTTP Health Monitor configuration. If Receive string and ...
2
2016-06-11T01:18:54Z
37,759,160
<p><code>zip</code> the dictionary items in the lists. Transform the dictionaries into a list of key-value <code>tuples</code>, merge the lists using <code>+</code>, then transform the merged list back into a dictionary:</p> <pre><code>[dict(i.items()+j.items()+k.items()) for i, j, k in zip(list1, list2, list3)] </cod...
2
2016-06-11T01:39:29Z
[ "python", "dictionary" ]
Merge dictionaries from multiple lists in Python
37,759,059
<p>I have three list with multiple dictionaries inside.</p> <pre><code>list1 = [{'question': u'Fan offline information can be found on what Screen under General Menu? '}, {'question': u'What is the tool for F5 BIGIP to get packet traces. '}, {'question': u'On a HTTP Health Monitor configuration. If Receive string and ...
2
2016-06-11T01:18:54Z
37,759,169
<p>Just loop it, keep it simple and readable:</p> <pre><code>res = [] # keep results for vals in zip(list1, list2, list3): # grab each entry d = {} # tmp dictionary for subv in vals: d.update(subd) # update tmp dictionary res.append(d) # add to result...
2
2016-06-11T01:41:16Z
[ "python", "dictionary" ]
Merge dictionaries from multiple lists in Python
37,759,059
<p>I have three list with multiple dictionaries inside.</p> <pre><code>list1 = [{'question': u'Fan offline information can be found on what Screen under General Menu? '}, {'question': u'What is the tool for F5 BIGIP to get packet traces. '}, {'question': u'On a HTTP Health Monitor configuration. If Receive string and ...
2
2016-06-11T01:18:54Z
37,759,303
<p>I think the following looks pretty nice for the second configuration you offerred. It would need some variable renaming though to be clearer in my opinion.</p> <pre><code>[dict(question=a, answer=b, correct_answer=c) for (a, b, c) in zip(list1, list2, list3)] </code></pre> <p>NOTE:</p> <p>The above solution could...
1
2016-06-11T02:17:24Z
[ "python", "dictionary" ]
Deleted rows from reflected table with SQLAlchemy
37,759,161
<p>I have a table that I'm trying to delete data from. I have been using a Session() object to query data, and it works just fine. But when I go to delete a list of data, it fails.</p> <pre><code># load engine and reflect. engine = create_engine("...") metadata = MetaData() Session = sessionmaker(autoflush=True, autoc...
0
2016-06-11T01:40:03Z
37,759,375
<p>The query interface is part of the SQLAlchemy ORM, and <code>table</code> isn't mapped to a class.</p> <p>The answer you linked to uses bound metadata (discouraged in modern SQLAlchemy). The following should work:</p> <pre><code>stmt = table.delete().where(table.c.column.in_([1,2,3,4,5])) with engine.connect() as...
1
2016-06-11T02:30:33Z
[ "python", "postgresql", "sqlalchemy" ]
sympy and mpmath give "TypeError: cannot create mpf" when using the erf() function within solveset()
37,759,214
<p>I have 4 input variables (floats):</p> <ul> <li>Xmax</li> <li>Xmin</li> <li>percentage</li> <li>mode</li> </ul> <p>and I want to solve the following (rather long) equation for s:</p> <pre><code>&gt; (1/2+1/2*erf((log(Xmax)-(log(mode)+s**2))/(sqrt(2)*s))-(1/2+1/2*erf((log(Xmin)-(log(mode)+s**2))/(sqrt(2)*s))) - pe...
0
2016-06-11T01:51:05Z
37,774,061
<p>Losing the <code>mpmath</code> import of <code>erf</code>, and use the sympy version resolves your error.</p> <pre><code>from sympy import Symbol, solveset, S, erf, log, sqrt percentage = 0.95 mode = 2 Xmin = 1. Xmax = 1.5 s = Symbol('s', real=True) eqn = (1/2+1/2*erf((log(Xmax)-(log(mode)+s**2))/(sqrt(2)*s))-(1/...
1
2016-06-12T12:09:01Z
[ "python", "sympy", "mpmath" ]
xml parsing issue encoding error
37,759,279
<p>I have an xml file like this</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;tw&gt; &lt;tweet&gt; &lt;yazi&gt;atılacak tweet 1&lt;/yazi&gt; &lt;resim&gt;resim.png&lt;/resim&gt; &lt;/tweet&gt; &lt;tweet&gt; &lt;yazi&gt;atılacak tweet 2&lt;/yazi&gt; &lt;re...
0
2016-06-11T02:10:43Z
37,762,514
<pre><code># -*- coding: utf-8 -*- import xml.etree.ElementTree as ett e = ett.parse("tweet.xml").getroot() print(e.tag) for altindakiler in e: print(altindakiler.tag, altindakiler.attrib) </code></pre>
-1
2016-06-11T10:13:06Z
[ "python", "xml-parsing", "python-3.4" ]
xml parsing issue encoding error
37,759,279
<p>I have an xml file like this</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;tw&gt; &lt;tweet&gt; &lt;yazi&gt;atılacak tweet 1&lt;/yazi&gt; &lt;resim&gt;resim.png&lt;/resim&gt; &lt;/tweet&gt; &lt;tweet&gt; &lt;yazi&gt;atılacak tweet 2&lt;/yazi&gt; &lt;re...
0
2016-06-11T02:10:43Z
37,769,642
<p>you probably have an invalid utf-8 char in your file, e.g. the xml file is iso-8859-1 encoded... or you can try utf-8 instead of UTF-8</p>
0
2016-06-12T00:19:23Z
[ "python", "xml-parsing", "python-3.4" ]
Django - No Post matches the given query
37,759,325
<p>Ive been building a blog via a tutorial in the book 'django by example'.</p> <p>Im working on the part where a blog post can be shared via email, everything works fine when I run it until I click the 'share post' link under an entry and then I get the following 404</p> <pre><code>Page not found (404) Request Metho...
-1
2016-06-11T02:21:22Z
37,759,399
<p>You are having a simple typo in your code:</p> <pre><code>post = get_object_or_404(Post, id=post_id, status='pubished') </code></pre> <p>I guess it should be <code>'published'</code>.</p>
2
2016-06-11T02:36:09Z
[ "python", "django" ]
How to resolve : Very large size tasks in spark
37,759,385
<p>Here I am pasting my python code which I am running on spark in order to perform some analysis on data. I am able to run the following program on small amount of data-set. But when coming large data-set, it is saying "Stage 1 contains a task of very large size (17693 KB). The maximum recommended task size is 100 KB"...
3
2016-06-11T02:32:46Z
37,766,979
<p>When Spark serializes tasks, it recursively serializes the full closure context. In this case, the logical culprit seems to be <code>unicodedata</code> which you use in <code>tokenize</code>. I may be wrong but I don't see any other heavy data structures in the code. (Caveat, I typically use Spark with Scala and my ...
1
2016-06-11T18:04:26Z
[ "python", "apache-spark" ]
Beautiful Soup Returning Unwanted Characters
37,759,397
<p>I'm using Beautiful Soup to scrape pages trying to get the height of certain athletes:</p> <pre><code>req = requests.get(url) soup = BeautifulSoup(req.text, "html.parser") height = soup.find_all("strong") height = height[2].contents print height </code></pre> <p>Unfortunately, this is what gets returned:</p> <p>[...
-1
2016-06-11T02:35:40Z
37,759,421
<p>Those aren't "extra characters". <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children" rel="nofollow"><code>.contents</code> returns a list</a>, the element you chose only has one child, and so you're getting a list containing one element. Python prints a list as pseudo Python code...
0
2016-06-11T02:40:38Z
[ "python", "beautifulsoup", "python-unicode" ]
Beautiful Soup Returning Unwanted Characters
37,759,397
<p>I'm using Beautiful Soup to scrape pages trying to get the height of certain athletes:</p> <pre><code>req = requests.get(url) soup = BeautifulSoup(req.text, "html.parser") height = soup.find_all("strong") height = height[2].contents print height </code></pre> <p>Unfortunately, this is what gets returned:</p> <p>[...
-1
2016-06-11T02:35:40Z
37,762,815
<p>If you just want the third <em>strong</em> tag you don't need to find everyone, you can use a css selector <code>nth-of-type</code>, once you have the element you just need to call <code>.text</code>:</p> <pre><code>req = requests.get(url) soup = BeautifulSoup(req.content, "html.parser") height = soup.select_one("...
0
2016-06-11T10:46:44Z
[ "python", "beautifulsoup", "python-unicode" ]
Trying to remove top row from excel spreadsheet using Python
37,759,455
<p>this is my first question here so if I don't follow perfect etiquette please forgive me. I have been searching for an answer for about 6 hours so I figured it was time to ask. I'm new to Python, and I'm trying to automate data entry with Selenium. I'm doing well, but stuck at the part where I pull data from Excel. T...
2
2016-06-11T02:47:37Z
37,759,849
<p>Look at example below: </p> <ul> <li>missing engine='xlsxwriter'</li> <li>missing sheet_name='Sheet1</li> </ul> <p>Look at this:</p> <pre><code> import pandas as pd #Create a Pandas dataframe from the data. df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]}) #...
1
2016-06-11T04:14:44Z
[ "python", "excel" ]
scatter plot same point repeated several times python
37,759,475
<p>I am trying to draw a scatter plot from a dictionary bellow:</p> <pre><code>data_dict = {12: [1, 17, 11, 17, 1, 14, 38], 13: [13, 6, 4, 6], 14: [15, 8, 20, 8, 7], 15: [2, 3, 3, 1], 16: [62, 13, 36, 3, 8, 99, 54], 17: [1], 18: [44, 30, 36, 14, 21, 13, 44, 1, 62, 36], 19: [5, 5], 20: [27, 42, 42, 18, 31, 55, 31, 55],...
1
2016-06-11T02:51:47Z
37,759,557
<p>You can get the .count() for each item and calculate the size based off that, then use the named parameter <code>s</code> to specify those sizes. Btw change <code>.items()</code> to <code>.iteritems()</code> if you are on python 2</p> <p><a href="http://i.stack.imgur.com/yOLK5.png" rel="nofollow"><img src="http://i...
1
2016-06-11T03:12:54Z
[ "python", "matplotlib", "scatter-plot", "plotly" ]
naming of Django Foreign Keys in order to request correct column
37,759,520
<p>I'm using Django (I'm new to it). I want to define a foreign key, and I'm not sure how to go about it. </p> <p>I have a table called stat_types: </p> <pre><code>class StatTypes(models.Model): stat_type = models.CharField(max_length=20) </code></pre> <p>Now I want to define a foreign key in the overall_stats t...
0
2016-06-11T03:05:02Z
37,759,696
<p>it does not matter what name you give to FK column name. Django figures it out that it is a ForeignKey and appends <code>_id</code> to the field. So you do not need <code>_id</code> here. I think this is good enough</p> <pre><code>stat_type = models.ForeignKey('beta.StatTypes') </code></pre> <p><a href="https://do...
1
2016-06-11T03:45:08Z
[ "python", "django", "postgresql" ]
How can i add a level 2 in my game?
37,759,589
<p>I am making a space invaders-like game. I have finished the first first level which has 4 rows of 10 aliens. I want to add another level where there are 4 rows of 17 aliens to make it difficult and reduce the time limit. I have made a separate module name 'LEVEL2' which is what i have tried to import and run after l...
-1
2016-06-11T03:18:42Z
37,759,630
<p>Take all that stuff in Level 1 <em>except</em> the class definitions, and put it into functions with reasonable names like "init" and "playGame." Let them be members of a class called "Level."</p> <p>Note what aspects are different in Level 1 and Level 2. Make these things that are different into parameters into ...
0
2016-06-11T03:27:13Z
[ "python", "pygame" ]
Python NLTK :: Intersecting words and sentences
37,759,610
<p>I'm using NLTK - a specific toolkit for manipulating corpus texts, and I've defined a function to intersect user inputs with Shakespeare's words.</p> <pre><code>def shakespeareOutput(userInput): user = userInput.split() user = random.sample(set(user), 3) #here is NLTK's method play = gutenberg.sen...
0
2016-06-11T03:23:12Z
37,760,560
<p>Your way of evaluating <code>currentCount</code> is wrong. Set intersection returns the number of distinct elements matched, not the count of the matched elements.</p> <pre><code>&gt;&gt;&gt; s = [1,1,2,3,3,4] &gt;&gt;&gt; u = set([1,4]) &gt;&gt;&gt; u.intersection(s) set([1, 4]) # the len is 2, however the tota...
2
2016-06-11T06:08:31Z
[ "python", "nltk", "nested-lists" ]
Django how to properly submit form and handle request?
37,759,623
<p>I'm new to Django/Python and working on a webapp that queries a DB of cars based on selects/dropdowns on the home page and sends the user to a details page about the car they selected. This is done through a 'make', 'model', and 'trim' dropdown box. What I'm having trouble understanding and getting errors doing, is ...
0
2016-06-11T03:25:43Z
37,759,972
<p>That error:</p> <pre><code>Reverse for 'search' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['search/(?P&lt;trim&gt;\\d+)/$'] </code></pre> <p>means that you didn't give the id parameter (you called it trim). It should be part of the arguments or keyword arguments.</p> <p>I as...
1
2016-06-11T04:36:19Z
[ "javascript", "jquery", "python", "django" ]
Django how to properly submit form and handle request?
37,759,623
<p>I'm new to Django/Python and working on a webapp that queries a DB of cars based on selects/dropdowns on the home page and sends the user to a details page about the car they selected. This is done through a 'make', 'model', and 'trim' dropdown box. What I'm having trouble understanding and getting errors doing, is ...
0
2016-06-11T03:25:43Z
37,761,272
<p>The solution to the problem I was having lied in my url patterns. By taking out the ID portion of the <strong>search</strong> URL, and changing the view as such: </p> <pre><code>def search(request): trim = request.GET['selectedTrim'] selectedTrim = get_object_or_404(Trim, id=trim) context = {'trim': se...
0
2016-06-11T07:47:07Z
[ "javascript", "jquery", "python", "django" ]
Regex - Match each item between multiple occurrences of delimiter
37,759,635
<p>I would like to match the values between a given delimiter using a Regex expression in Python. I would like this to ignore surrounding white space. For example:</p> <ul> <li><p>The string <code>1, b cc, "a"</code>and delimiter <code>,</code> will return three matches of <code>1</code>,<code>b cc</code>,<code>"a"</c...
0
2016-06-11T03:28:02Z
37,759,650
<pre><code>import re line = '1, b cc, "a"' re.split(r'[;,]\s*', line) Out[7]: ['1', 'b cc', '"a"'] line = '4 + 5 + 2 +1' re.split(r'\s*[+]\s*', line) Out[10]: ['4', '5', '2', '1'] </code></pre> <p>The <code>re.split()</code> function is useful because you can specify multiple patterns for the separator. </p> <p...
2
2016-06-11T03:34:04Z
[ "python", "regex" ]
Regex - Match each item between multiple occurrences of delimiter
37,759,635
<p>I would like to match the values between a given delimiter using a Regex expression in Python. I would like this to ignore surrounding white space. For example:</p> <ul> <li><p>The string <code>1, b cc, "a"</code>and delimiter <code>,</code> will return three matches of <code>1</code>,<code>b cc</code>,<code>"a"</c...
0
2016-06-11T03:28:02Z
37,759,651
<p>You can do this with the <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a> method.</p> <pre><code>import re re.split('\s*,\s*', '1, b cc, "a"') re.split('\s*\+\s*', '4 + 5 + 2 +1') </code></pre>
2
2016-06-11T03:34:17Z
[ "python", "regex" ]
How does python order values in a heap?
37,759,711
<p>For example, a list of random numbers:</p> <pre><code>&gt;&gt;&gt; x = [1,24,5,1,5,1,23,6] &gt;&gt;&gt; heapq.heapify(x) [1, 1, 1, 6, 5, 5, 23, 24] </code></pre> <p>Why does it arbitrarily do 6,5,5 and not 5,5,6 or 5,6,5? </p>
0
2016-06-11T03:48:24Z
37,759,828
<p>Python docs contain following description of <a href="https://docs.python.org/2/library/heapq.html#module-heapq" rel="nofollow"><code>heapq</code></a>:</p> <blockquote> <p>Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for ...
2
2016-06-11T04:09:59Z
[ "python", "python-2.7", "heap" ]
Cannot achieve consistency level LOCAL_ONE info={required_replicas 1 alive_replicas: 0, consistency: LOCAL_ONE}
37,759,770
<p>My cluster size is 6 machines. My data amount is very small only like 30.000. But I frequently have read,write,delete and update operations which might be costly although the data amount is low. I don't get why this error message occurs since data amount is very low. Any answers are really appreciated.</p> <p>When ...
0
2016-06-11T03:58:51Z
37,778,551
<p>You have a wrong replication configuration. You have a replication factor of 6 on your datacenter Analytics but this datacenter doesn't exist. Change it to Ana and add your solr cluster. Or you can change it in your snitch configuration. And don't use a replication factor of 6. Use 3 or maybe 4 instead. You have onl...
1
2016-06-12T20:02:40Z
[ "python", "cassandra", "datastax", "datastax-enterprise" ]
Python IDLE is refusing to save and is the crashing when I try to save a file with a specific comment
37,759,950
<p>I am running Python 2.7. I wrote some code in the IDLE. I found that it would not save the file. If I repeatedly try to save, IDLE just crashes completely. I found that if I removed the following comment, it would save:</p> <pre><code>#Add a fourth parameter, end, to the find function that specifies where to stop l...
0
2016-06-11T04:32:39Z
37,760,117
<p>Try again after Restarting your computer.</p> <p>If not-resolved Try visiting </p> <blockquote> <blockquote> <p><a href="https://bugs.python.org/issue14996" rel="nofollow">https://bugs.python.org/issue14996</a></p> </blockquote> </blockquote>
0
2016-06-11T05:02:42Z
[ "python", "python-2.7", "crash", "save", "comments" ]
Python IDLE is refusing to save and is the crashing when I try to save a file with a specific comment
37,759,950
<p>I am running Python 2.7. I wrote some code in the IDLE. I found that it would not save the file. If I repeatedly try to save, IDLE just crashes completely. I found that if I removed the following comment, it would save:</p> <pre><code>#Add a fourth parameter, end, to the find function that specifies where to stop l...
0
2016-06-11T04:32:39Z
37,824,399
<p>I have exactly the same problem as you do. I found that apparently IDLE overloads or some sort after you type in more than 10 characters and save. I try to save Ctrl+S every time i write a word, that seems to be the only way it is able to save. If you find any other way to fix the problem be sure to notify!</p>
0
2016-06-15T00:46:42Z
[ "python", "python-2.7", "crash", "save", "comments" ]
Update label based on Key in Dropdown menu Tkinter Python
37,759,978
<p>Hi I am trying to update a label based on the key selected from a drop down menu (using a dictionary). I am unsure as to how i can update the label. Thankyou. I have made an attempt as below however I am obviously doing it wrong due to lack of knowledge. Thankyou </p> <pre><code>from tkinter import * from tkinter...
1
2016-06-11T04:36:56Z
37,760,466
<p>Try this: </p> <pre><code>from Tkinter import * from ttk import * import csv class DictionaryGui: '''Display a GUI allowing key-&gt;value lookup''' def __init__(self, parent, row, column, dictionary): self.dictionary = dictionary self.selection = StringVar() self.value = StringVar() username_labe...
1
2016-06-11T05:55:42Z
[ "python", "tkinter" ]
Python Flow Controls Not Working
37,760,118
<p>Ok so in this I have an issue where if the answer is <code>"N"</code> then it will still continue to the <code>else</code> statement. How do I fix this? (this is all in a function, edit: with other if statements that work fine)</p> <pre><code> if command == "Exit": exit = 1 while exit == 1: print("Q...
0
2016-06-11T05:02:53Z
37,760,203
<p>The Code Seems To work Fine.</p> <p>I assumed what you Want to do is : on Entering Exit ask user Y or N if user enters Y you quit the program if user enters N you want to break out of while loop. It works fine for both the cases can you add something else to the question to illustrate the problem.</p> <p>I would a...
1
2016-06-11T05:16:17Z
[ "python", "python-3.x", "if-statement" ]