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 |
|---|---|---|---|---|---|---|---|---|---|
Django JSON not sending proper data | 39,133,537 | <p>I am developing a django python web application. In my webpage, I am sending a request to my API by sending a 'term' and my API is supposed to return the 'content' field of the search.</p>
<p>My content contains 'xxx is good' in my database.</p>
<p>Here is my code in views.py</p>
<pre><code>def get_RuleStatement(request):
if request.is_ajax():
q = request.GET.get('term', '')
rule_statements = RuleStatement.objects.filter(content__icontains = q )[:1]
results = []
for rule_statement in rule_statements:
rule_statement_json = {}
rule_statement_json['content'] = rule_statement.content
results.append(rule_statement_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
</code></pre>
<p>For some reason, whenever I send the following request: <a href="http://website.com/api/get_RuleStatement/?term=xxx" rel="nofollow">http://website.com/api/get_RuleStatement/?term=xxx</a></p>
<p>It returns 'fail' even through my database contains data 'xxx is good'. Can anyone suggest where I am going wrong?</p>
| 0 | 2016-08-24T21:47:25Z | 39,134,328 | <p>The only reason possible for it is <code>is_ajax()</code> is return False. That means your are not making the <code>AJAX</code> request. I believe you are making normal HTTP call to your endpoint.</p>
| 0 | 2016-08-24T23:06:47Z | [
"python",
"json",
"django"
] |
Django JSON not sending proper data | 39,133,537 | <p>I am developing a django python web application. In my webpage, I am sending a request to my API by sending a 'term' and my API is supposed to return the 'content' field of the search.</p>
<p>My content contains 'xxx is good' in my database.</p>
<p>Here is my code in views.py</p>
<pre><code>def get_RuleStatement(request):
if request.is_ajax():
q = request.GET.get('term', '')
rule_statements = RuleStatement.objects.filter(content__icontains = q )[:1]
results = []
for rule_statement in rule_statements:
rule_statement_json = {}
rule_statement_json['content'] = rule_statement.content
results.append(rule_statement_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
</code></pre>
<p>For some reason, whenever I send the following request: <a href="http://website.com/api/get_RuleStatement/?term=xxx" rel="nofollow">http://website.com/api/get_RuleStatement/?term=xxx</a></p>
<p>It returns 'fail' even through my database contains data 'xxx is good'. Can anyone suggest where I am going wrong?</p>
| 0 | 2016-08-24T21:47:25Z | 39,134,355 | <p>See the <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.HttpRequest.is_ajax" rel="nofollow">django documentation</a> and check that your HTTP request has the HTTP header <code>HTTP_X_REQUESTED_WITH</code> set with the string 'XMLHttpRequest'. Then <code>request.is_ajax()</code> will return <code>True</code>.</p>
<p>Note modern libraries like jQuery will automatically set this HTTP header for you; e.g., if you get jquery and do</p>
<pre><code><script>
$.get('/api/get_RuleStatement', {'term': 'xxx'})
</script>
</code></pre>
<p>Alternatively, you can get rid of the <code>if request.is_ajax():</code> line and make it</p>
<pre><code>def get_RuleStatement(request):
q = request.GET.get('term', '')
rule_statements = RuleStatement.objects.filter(content__icontains = q)[:1]
results = []
for rule_statement in rule_statements:
results.append({'content': rule_statement.content})
data = json.dumps(results)
mimetype = 'application/json'
return HttpResponse(data, mimetype)
</code></pre>
<p>if you don't care about it being an ajax call and want to be able to see the response otherwise. Also you may want to consider using <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#jsonresponse-objects" rel="nofollow"><code>JsonResponse</code></a> instead of HttpResponse so you don't have to serialize or set MIME-type yourself. E.g., </p>
<pre><code>def get_RuleStatement(request):
q = request.GET.get('term', '')
rule_statements = RuleStatement.objects.filter(content__icontains = q)[:1]
results = []
for rule_statement in rule_statements:
results.append({'content': rule_statement.content})
return JsonResponse(results, safe=False)
# the safe = False is neccessary when
# you serialize non-dicts like results which is a list
</code></pre>
| 0 | 2016-08-24T23:11:41Z | [
"python",
"json",
"django"
] |
Automatic db router for migrations in django | 39,133,559 | <p>I am building a Django powered site and I want to have separate databases for some of the apps, I build a flexible router that routes each app to predefined database, this works fine.
The problem is that when I am migrating my models I have to set the <code>--database</code> parameter every time and I find this annoying and redundant. Also many times I flooded my default database with tables from migrated app (by forgetting to add <code>--database</code>).
I experimented with <code>allow_migrate(...)</code> function in my router but all I could achieve is safety mechanism that will not run the migration if I forget to specify the database.
My question is: is there a way to set up a automatic database selection for models migrations in Django?
My approach might be wrong, it surprises me that no one seems to have done that before.</p>
| 1 | 2016-08-24T21:49:32Z | 39,134,659 | <p>I don't know of any way to do that automatically. However, a simple approach might be to <a href="https://docs.djangoproject.com/en/dev/howto/custom-management-commands/" rel="nofollow">write your own version</a> of the <code>migrate</code> command that calls the Django <code>migrate</code> command multiple times with the appropriate <code>--database</code> and app arguments.</p>
<p>According to the author of Django migrations, this is <a href="https://code.djangoproject.com/ticket/23273#comment:7" rel="nofollow">a conscious design decision</a>, so I wouldn't expect it to change: "Just like syncdb, migrate only runs on one database at a time, so you must execute it individually for each database, as you suggest. This is by design."</p>
| 1 | 2016-08-24T23:51:53Z | [
"python",
"django",
"django-migrations"
] |
Automatic db router for migrations in django | 39,133,559 | <p>I am building a Django powered site and I want to have separate databases for some of the apps, I build a flexible router that routes each app to predefined database, this works fine.
The problem is that when I am migrating my models I have to set the <code>--database</code> parameter every time and I find this annoying and redundant. Also many times I flooded my default database with tables from migrated app (by forgetting to add <code>--database</code>).
I experimented with <code>allow_migrate(...)</code> function in my router but all I could achieve is safety mechanism that will not run the migration if I forget to specify the database.
My question is: is there a way to set up a automatic database selection for models migrations in Django?
My approach might be wrong, it surprises me that no one seems to have done that before.</p>
| 1 | 2016-08-24T21:49:32Z | 39,152,567 | <p>For anyone facing the issue I was having, here is what I finally settled on:</p>
<p>routers.py:</p>
<pre><code>from django.conf import settings
class DatabaseAppsRouter(object):
def db_for_read(self, model, **hints):
# your db routing
def db_for_write(self, model, **hints):
# your db routing
def allow_relation(self, obj1, obj2, **hints):
# your db routing
def allow_syncdb(self, db, model):
# your db routing
def allow_migrate(self, db, app_label, model_name=None, **hints):
if db in settings.DATABASE_APPS_MAPPING.values():
return settings.DATABASE_APPS_MAPPING.get(app_label) == db
elif app_label in settings.DATABASE_APPS_MAPPING:
return False
</code></pre>
<hr>
<p>settings.py</p>
<pre><code>DATABASE_ROUTERS = ['project.routers.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {'contenttypes': 'default',
'auth': 'default',
'admin': 'default',
'sessions': 'default',
'messages': 'default',
'staticfiles': 'default',
'myapp': 'mydb',
}
</code></pre>
<hr>
<p>this setup lets me to run two commands:</p>
<pre><code>python manage.py migrate
python manage.py migrate --database=mydb
</code></pre>
<p>which is still one to many but at least now I cannot mistakenly migrate myapp to the default database which happened more times that I want to admit. </p>
<hr>
<p>Warning - rant:</p>
<p>Up to this point I was finding the Django design to be quircky but very logical and programmer friendly, like python itself. But the way that migrations interact with multiple database setups is really inconvenient makes it so easy to flood your default database with unwanted tables.
Discussion linked by kevin in his answer shows that I am not the only one to have this kind of difficulties. </p>
| 0 | 2016-08-25T18:39:38Z | [
"python",
"django",
"django-migrations"
] |
Fastest way to expose C strings to numpy? | 39,133,578 | <p>I'm working on converting some old text logs to a usable format in Python. The files are huge, so I'm writing my own C extensions to run through the files as quickly as possible and parse out the relevant fields with regular expressions. My ultimate goal is to export these fields into numpy arrays of strings.</p>
<p>I know it's possible to create the numpy array as a PyObject in C and then call SetItem on each element, but I'm looking to optimize as much as I can. Can I use something like memcpy or PyBuffer_FromMemory to read the C strings into a numpy string array directly? I know numpy arrays are internally similar to C arrays, but do I have to ensure the numpy array will be contiguously allocated?</p>
<p>I intend to use the numpy arrays to build columns Pandas for statistical analysis. As I understand it, Pandas uses numpy arrays to store columns in a dataframe so I won't have a large overhead going from numpy into Pandas. I'd like to avoid cython if possible.</p>
| 3 | 2016-08-24T21:50:54Z | 39,134,223 | <p>To give a sense of how an array of strings is stored, I'll make one, and view it in several ways:</p>
<pre><code>In [654]: np.array(['one','two','three','four'],dtype='S5')
Out[654]:
array([b'one', b'two', b'three', b'four'],
dtype='|S5')
In [655]: x=np.array(['one','two','three','four'],dtype='S5')
In [656]: x.tostring()
Out[656]: b'one\x00\x00two\x00\x00threefour\x00'
In [657]: x.view(np.uint8)
Out[657]:
array([111, 110, 101, 0, 0, 116, 119, 111, 0, 0, 116, 104, 114,
101, 101, 102, 111, 117, 114, 0], dtype=uint8)
</code></pre>
<p>So its databuffer consists of 20 bytes (4*S5). For strings that are shorter than 5, it puts (or leaves) <code>0</code> in the byte.</p>
<p>Yes, there are <code>C</code> functions for creating new arrays of a given size and dtype. And functions for copying blocks of data to those arrays. Look at the <code>C</code> side of the numpy documentation, or look at some of the numpy code on it's github repository.</p>
<p>Regarding the <code>pandas</code> transfer, beware that <code>pandas</code> readily changes the dtype of its columns. For example if you put <code>None</code> or <code>nan</code> in a column it is likely to change it to object dtype.</p>
<p>Object arrays store pointers in the databuffer.</p>
<pre><code>In [658]: y=np.array(['one','two','three','four'],dtype=object)
In [659]: y
Out[659]: array(['one', 'two', 'three', 'four'], dtype=object)
In [660]: y.tostring()
Out[660]: b'\xe0\x0f\xc5\xb5\xa0\xfah\xb5\x80\x0b\x8c\xb4\xc09\x8b\xb4'
</code></pre>
<p>If I interpret that right, the databuffer has 16 bytes - 4 4byte pointers. The strings are stored elsewhere in memory as regular Python strings (in this case unicode strings (Py3)).</p>
<p>=================</p>
<p><code>fromstring</code> and <code>frombuffer</code> lets me recreate an array from a buffer</p>
<pre><code>In [696]: x=np.array(['one','two','three','four'],dtype='S5')
In [697]: xs=x.tostring()
In [698]: np.fromstring(xs,'S5')
Out[698]:
array([b'one', b'two', b'three', b'four'],
dtype='|S5')
In [700]: np.frombuffer(xs,'S5')
Out[700]:
array([b'one', b'two', b'three', b'four'],
dtype='|S5')
</code></pre>
<p>This works without copying the buffer.</p>
<p>However, if the are multiple strings in different parts of memory, then building an array from them will require copying into on contiguous buffer.</p>
| 3 | 2016-08-24T22:55:43Z | [
"python",
"c",
"arrays",
"numpy",
"cython"
] |
movie imdb get the id of the actor | 39,133,599 | <p>I have an actor object, and it has both name and id, i could take the name, but it couldn't take the id</p>
<p>look please</p>
<pre><code>>>> actor
<Person id:0000199[http] name:_Pacino, Al_>
>>> actor["name"]
u'Al Pacino'
>>> actor["id"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IMDbPY-5.0-py2.7-macosx-10.6-intel.egg/imdb/utils.py", line 1469, in __getitem__
rawData = self.data[key]
KeyError: 'id'
>>>
</code></pre>
| 1 | 2016-08-24T21:52:31Z | 39,133,618 | <p>Use the <code>.personID</code> property of a <code>Person</code> object:</p>
<pre><code>actor.personID
</code></pre>
| 3 | 2016-08-24T21:53:56Z | [
"python",
"imdb",
"imdbpy"
] |
Add child of child to python xml | 39,133,613 | <p>I create a code which writes the data to xml file.But it is not working properly. It gives a error called "TypeError: must be Element, not None
"</p>
<p>Here is my code:</p>
<pre><code>import xml.etree.cElementTree as ET
import lxml.etree
import lxml.builder
class create_xml:
def __init__(self):
pass
def write_xml(predicted_list, image_list):
print predicted_list
print image_list
i = 0
root = ET.Element("video_data")
for image in image_list:
doc = ET.SubElement(root, 'frame').set('name', image)
predicted_item = predicted_list[i]
ET.SubElement(doc, predicted_item) **Gives error in here**
# doc.text = predicted_list[i]
i += 1
tree = ET.ElementTree(root)
tree.write("/opt/lampp/htdocs/video_frames/test.xml")
</code></pre>
<p>I need the out put as below,</p>
<pre><code><video_data>
<frame name="">
<predicted_item>output</predicted_item>
</frame>
</video_data>
</code></pre>
<p>But without the error occuring code segment it gives the output as below:</p>
<pre><code> <video_data><frame name="/opt/lampp/htdocs/video_frames/bb/frame48.jpg" /></video_data>
</code></pre>
<p>please help me to solve this, Thank you</p>
| 0 | 2016-08-24T21:53:36Z | 39,133,655 | <p>The problem is that <code>doc</code> becomes <code>None</code> since it equals to the result of <code>set()</code> call. Instead, you meant to have <code>doc</code> pointing to the <code>SubElement</code> instance: </p>
<pre><code>doc = ET.SubElement(root, 'frame')
doc.set('name', image)
</code></pre>
| 1 | 2016-08-24T21:57:18Z | [
"python",
"xml"
] |
Python 2.7, Requests library, can't get unicode | 39,133,669 | <p>Documentation for Request library says that requests.get() method returns unicode always. But when I try to know what an encoding was returned, I see "windows-1251". That's a problem. When I try to get requests.get(url).text, there's an error, because current url's content has a Cyrillic symbols.</p>
<pre><code>import requests
url = 'https://www.weblancer.net/jobs/'
r = requests.get(url)
print r.encoding
print r.text
</code></pre>
<p>I got something like that:</p>
<pre><code>windows-1251
UnicodeEncodeError: 'ascii' codec can't encode characters in position 256-263: ordinal not in range(128)
</code></pre>
<p>Is it a problem of Python 2.7 or there is not a problem at all ?
Help me</p>
| -1 | 2016-08-24T21:59:04Z | 39,133,988 | <p>From the <a href="http://docs.python-requests.org/en/master/user/quickstart/#response-content" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Requests will automatically decode content from the server. Most
unicode charsets are seamlessly decoded.</p>
<p>When you make a request, Requests makes educated guesses about the
encoding of the response based on the HTTP headers.</p>
</blockquote>
<p><code>requests.get().encoding</code> is telling you the encoding that was used to convert the bitstream from the server into the Unicode text that is in the response.</p>
<p>In your case it is correct: the headers in the response say that the character set is windows-1251</p>
<p>The error you are having is after that. The python you are using is trying to encode the Unicode into ascii to print it, and failing.</p>
<p>You can say print <code>r.text.encode(r.encoding)</code> ... which is the same result as Padraic's suggestion in comments - that is <code>r.content</code>.</p>
<hr>
<p>Note:
<code>requests.get().encoding</code> is an lvar: you can set it to what you want, if it guessed wrongly.</p>
| 1 | 2016-08-24T22:30:53Z | [
"python",
"parsing",
"unicode",
"python-requests"
] |
How to Import multiple CSV files then make a Master Table? | 39,133,678 | <p>I am a research chemist and have carried out a measurement where I record 'signal intensity' vs 'mass-to-charge (<em>m/z</em>)' . I have repeated this experiment 15x, by changing a specific parameter (Collision Energy). As a result, I have 15 CSV files and would like to align/join them within the same range of <em>m/z</em> values and same interval values. Due to the instrument thresholding rules, certain <em>m/z</em> values were not recorded, thus I have files that cannot simply be exported into excel and copy/pasted. The data looks a bit like the tables posted below</p>
<pre><code>Dataset 1: x | y Dataset 2: x | y
--------- ---------
0.0 5 0.0 2
0.5 3 0.5 6
2.0 7 1.0 9
3.0 1 2.5 1
3.0 4
</code></pre>
<p>Using matlab I started with this code:</p>
<pre><code>%% Create a table for the set m/z range with an interval of 0.1 Da
mzrange = 50:0.1:620;
mzrange = mzrange';
mzrange = array2table(mzrange,'VariableNames',{'XThompsons'});
</code></pre>
<p>Then I manually imported 1 X/Y CSV (Xtitle=XThompson, Ytitle=YCounts) to align with the specified <em>m/z</em> range.</p>
<pre><code>%% Join/merge the two tables using a common Key variable 'XThompson' (m/z value)
mzspectrum = outerjoin(mzrange,ReserpineCE00,'MergeKeys',true);
% Replace all NaN values with zero
mzspectrum.YCounts(isnan(mzspectrum.YCounts)) = 0;
</code></pre>
<p>At this point I am stuck because repeating this process with a separate file will overwrite my YCounts column. The title of the YCounts column doesnt matter to me as I can change it later, however I would like to have the table continue as such:</p>
<pre><code> XThompson | YCounts_1 | YCounts_2 | YCounts_3 | etc...
--------------------------------------------------------
</code></pre>
<p>How can I carry this out in Matlab so that this is at least semi-automated? I've had posted earlier describing a similar scenario but it turned out that it could not carry out what I need. I must admit that my mind is not of a programmer so I have been struggling with this problem quite a bit.</p>
<p>PS- Is this problem best executed in Matlab or Python?</p>
| 0 | 2016-08-24T22:00:21Z | 39,134,006 | <p>I don't know or use matlab so my answer is pure python based. I think python and matlab should be equally well suited to read csv files and generate a master table.</p>
<p>Please consider this answer more as pointer to how to address the problem in python.</p>
<p>In python one would typically address this problem using the <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> package. This package provides "high-performance, easy-to-use data structures and data analysis tools" and can read natively a large set of file formats including CSV files. A master table from two CSV files "foo.csv" and "bar.csv" could be generated e.g. as follows:</p>
<pre><code>import pandas as pd
df = pd.read_csv('foo.csv')
df2 = pd.read_csv('bar.cvs')
master_table = pd.concat([df, df2])
</code></pre>
<p>Pandas further allows to group and structure the data in many ways. The <a href="http://pandas.pydata.org/pandas-docs/stable/index.html" rel="nofollow">pandas documentation</a> has very good descriptions of its various features.</p>
<p>One can install pandas with the python package installer <code>pip</code>:</p>
<pre><code>sudo pip install pandas
</code></pre>
<p>if on Linux or OSX.</p>
| 0 | 2016-08-24T22:33:45Z | [
"python",
"matlab"
] |
How to Import multiple CSV files then make a Master Table? | 39,133,678 | <p>I am a research chemist and have carried out a measurement where I record 'signal intensity' vs 'mass-to-charge (<em>m/z</em>)' . I have repeated this experiment 15x, by changing a specific parameter (Collision Energy). As a result, I have 15 CSV files and would like to align/join them within the same range of <em>m/z</em> values and same interval values. Due to the instrument thresholding rules, certain <em>m/z</em> values were not recorded, thus I have files that cannot simply be exported into excel and copy/pasted. The data looks a bit like the tables posted below</p>
<pre><code>Dataset 1: x | y Dataset 2: x | y
--------- ---------
0.0 5 0.0 2
0.5 3 0.5 6
2.0 7 1.0 9
3.0 1 2.5 1
3.0 4
</code></pre>
<p>Using matlab I started with this code:</p>
<pre><code>%% Create a table for the set m/z range with an interval of 0.1 Da
mzrange = 50:0.1:620;
mzrange = mzrange';
mzrange = array2table(mzrange,'VariableNames',{'XThompsons'});
</code></pre>
<p>Then I manually imported 1 X/Y CSV (Xtitle=XThompson, Ytitle=YCounts) to align with the specified <em>m/z</em> range.</p>
<pre><code>%% Join/merge the two tables using a common Key variable 'XThompson' (m/z value)
mzspectrum = outerjoin(mzrange,ReserpineCE00,'MergeKeys',true);
% Replace all NaN values with zero
mzspectrum.YCounts(isnan(mzspectrum.YCounts)) = 0;
</code></pre>
<p>At this point I am stuck because repeating this process with a separate file will overwrite my YCounts column. The title of the YCounts column doesnt matter to me as I can change it later, however I would like to have the table continue as such:</p>
<pre><code> XThompson | YCounts_1 | YCounts_2 | YCounts_3 | etc...
--------------------------------------------------------
</code></pre>
<p>How can I carry this out in Matlab so that this is at least semi-automated? I've had posted earlier describing a similar scenario but it turned out that it could not carry out what I need. I must admit that my mind is not of a programmer so I have been struggling with this problem quite a bit.</p>
<p>PS- Is this problem best executed in Matlab or Python?</p>
| 0 | 2016-08-24T22:00:21Z | 39,196,660 | <p>The counts from the different analyses should be named differently, i.e., YCounts_1, YCounts_2, and YCounts_3 from analyses 1, 2, and 3, respectively, in the different datasets before joining them. However, the M/Z name (i.e., XThompson) should be the same since this is the key that will be used to join the datasets. The code below is for MATLAB.</p>
<p>This step is not needed (just recreates your tables) and I copied dataset2 to create dataset3 for illustration. You could use 'readtable' to import your data i.e., imported_data = readtable('filename'); </p>
<pre><code> dataset1 = table([0.0; 0.5; 2.0; 3.0], [5; 3; 7; 1], 'VariableNames', {'XThompson', 'YCounts_1'});
dataset2 = table([0.0; 0.5; 1.0; 2.5; 3.0], [2; 6; 9; 1; 4], 'VariableNames', {'XThompson', 'YCounts_2'});
dataset3 = table([0.0; 0.5; 1.0; 2.5; 3.0], [2; 6; 9; 1; 4], 'VariableNames', {'XThompson', 'YCounts_3'});
</code></pre>
<p>Merge tables using outerjoin. You could use loop if you have many datasets.</p>
<pre><code> combined_dataset = outerjoin(dataset1,dataset2, 'MergeKeys', true);
</code></pre>
<p>Add dataset3 to the combined_dataset</p>
<pre><code> combined_dataset = outerjoin(combined_dataset,dataset3, 'MergeKeys', true);
</code></pre>
<p>You could export the combined data as Excel Sheet by using writetable</p>
<pre><code> writetable(combined_dataset, 'joined_icp_ms_data.xlsx');
</code></pre>
| 0 | 2016-08-28T23:19:32Z | [
"python",
"matlab"
] |
How to Import multiple CSV files then make a Master Table? | 39,133,678 | <p>I am a research chemist and have carried out a measurement where I record 'signal intensity' vs 'mass-to-charge (<em>m/z</em>)' . I have repeated this experiment 15x, by changing a specific parameter (Collision Energy). As a result, I have 15 CSV files and would like to align/join them within the same range of <em>m/z</em> values and same interval values. Due to the instrument thresholding rules, certain <em>m/z</em> values were not recorded, thus I have files that cannot simply be exported into excel and copy/pasted. The data looks a bit like the tables posted below</p>
<pre><code>Dataset 1: x | y Dataset 2: x | y
--------- ---------
0.0 5 0.0 2
0.5 3 0.5 6
2.0 7 1.0 9
3.0 1 2.5 1
3.0 4
</code></pre>
<p>Using matlab I started with this code:</p>
<pre><code>%% Create a table for the set m/z range with an interval of 0.1 Da
mzrange = 50:0.1:620;
mzrange = mzrange';
mzrange = array2table(mzrange,'VariableNames',{'XThompsons'});
</code></pre>
<p>Then I manually imported 1 X/Y CSV (Xtitle=XThompson, Ytitle=YCounts) to align with the specified <em>m/z</em> range.</p>
<pre><code>%% Join/merge the two tables using a common Key variable 'XThompson' (m/z value)
mzspectrum = outerjoin(mzrange,ReserpineCE00,'MergeKeys',true);
% Replace all NaN values with zero
mzspectrum.YCounts(isnan(mzspectrum.YCounts)) = 0;
</code></pre>
<p>At this point I am stuck because repeating this process with a separate file will overwrite my YCounts column. The title of the YCounts column doesnt matter to me as I can change it later, however I would like to have the table continue as such:</p>
<pre><code> XThompson | YCounts_1 | YCounts_2 | YCounts_3 | etc...
--------------------------------------------------------
</code></pre>
<p>How can I carry this out in Matlab so that this is at least semi-automated? I've had posted earlier describing a similar scenario but it turned out that it could not carry out what I need. I must admit that my mind is not of a programmer so I have been struggling with this problem quite a bit.</p>
<p>PS- Is this problem best executed in Matlab or Python?</p>
| 0 | 2016-08-24T22:00:21Z | 39,277,031 | <p>I managed to create a solution to my problem based on learning through everyone's input and taking an online matlab courses. I am not a natural coder so my script is not as elegant as the geniuses here, but hopefully it is clear enough for other non-programming scientists to use.</p>
<p>Here's the result that works for me:</p>
<p>% Reads a directory containing *.csv files and corrects the x-axis to an evenly spaced (0.1 unit) interval.</p>
<pre><code>% Create a matrix with the input x range then convert it to a table
prompt = 'Input recorded min/max data range separated by space \n(ex. 1 to 100 = 1 100): ';
inputrange = input(prompt,'s');
min_max = str2num(inputrange)
datarange = (min_max(1):0.1:min_max(2))';
datarange = array2table(datarange,'VariableNames',{'XAxis'});
files = dir('*.csv');
for q=1:length(files);
% Extract each XY pair from the csvread cell and convert it to an array, then back to a table.
data{q} = csvread(files(q).name,2,1);
data1 = data(q);
data2 = cell2mat(data1);
data3 = array2table(data2,'VariableNames',{'XAxis','YAxis'});
% Join the datarange table and the intensity table to obtain an evenly spaced m/z range
data3 = outerjoin(datarange,data3,'MergeKeys',true);
data3.YAxis(isnan(data3.YAxis)) = 0;
data3.XAxis = round(data3.XAxis,1);
% Remove duplicate values
data4 = sortrows(data3,[1 -2]);
[~, idx] = unique(data4.XAxis);
data4 = data4(idx,:);
% Save the file as the same name in CSV without underscores or dashes
filename = files(q).name;
filename = strrep(filename,'_','');
filename = strrep(filename,'-','');
filename = strrep(filename,'.csv','');
writetable(data4,filename,'FileType','text');
clear data data1 data2 data3 data4 filename
end
clear
</code></pre>
| 0 | 2016-09-01T16:55:10Z | [
"python",
"matlab"
] |
numpy convert array of strings to integers or boolean (for masking) | 39,133,682 | <p>I'm new to Python and I'm challenged with converting an array of strings to numbers.
My data was extracted from a larger data set of numbers and strings. It looks like:</p>
<pre><code>array([b'Single', b'', b'', b'', b'', b'Single', b'Single',
b'', b'Single', ...])
</code></pre>
<p>I would like to use this data to create a mask, basically if 'Single' exists I would like to have a False or 0, so that I can mask the original data set. I don't know why there are b's there. </p>
<p>I've found similar questions answered but not string-to-number or string-to-boolean, only the reverse or converting a "string of numbers" to an integer.</p>
<p>My closest solution is something like:</p>
<pre><code>np.where(modMask = 'Single' [False, True])
</code></pre>
<p>But then I get the error:</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-64-4ad8a8f10b9b> in <module>()
----> 1 np.where(modMask = 'Single' [False, True])
TypeError: string indices must be integers
</code></pre>
| 1 | 2016-08-24T22:00:37Z | 39,134,509 | <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html" rel="nofollow">numpy.vectorize</a></p>
<pre><code>import numpy as np
def f(x):
return not x == b'Single'
vfunc = np.vectorize(f)
x = np.array([b'Single', b'', b'', b'', b'', b'Single'])
result = vfunc(x)
</code></pre>
<p>where</p>
<pre><code>result = [False True True True True False]
</code></pre>
| 0 | 2016-08-24T23:31:54Z | [
"python",
"arrays",
"string",
"numpy"
] |
PyQt: QLineEdit with attached label | 39,133,740 | <p>This is probably a very silly question, but anyway I am struck by it :-(</p>
<p>I have a window with two side-by-side lists and a line edit control with a label below them (see the attached image). What I want is to have the line edit field placed just after the corresponding label and not below the second list.</p>
<p><a href="http://i.stack.imgur.com/J530M.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/J530M.jpg" alt="enter image description here"></a></p>
<p>Here is my test code:</p>
<pre><code>import sys
from PyQt4 import Qt, QtCore, QtGui
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
centralLayout = QtGui.QGridLayout()
centralLayout.setSpacing(2)
treelist1 = QtGui.QTreeWidget()
treelist2 = QtGui.QTreeWidget()
treelist1.setColumnCount(1)
treelist1.setHeaderLabels(["List 1"])
treelist2.setColumnCount(1)
treelist2.setHeaderLabels(["List 2"])
label = QtGui.QLabel("Line:")
linedit = QtGui.QLineEdit()
centralLayout.setRowStretch(0, 8)
centralLayout.setRowStretch(1, 1)
centralLayout.addWidget(treelist1, 0, 0)
centralLayout.addWidget(treelist2, 0, 1)
centralLayout.addWidget(label, 1, 0)
centralLayout.addWidget(linedit, 1, 1)
self.setLayout(centralLayout)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
</code></pre>
<p>Thanks in advance for any assistance you can provide!</p>
| 0 | 2016-08-24T22:06:11Z | 39,133,834 | <p>What you need here is:</p>
<ul>
<li>Set the widget up in a vertical layout, not grid layout</li>
<li>In that vertical layout, add two horizontal layouts</li>
<li>Add the two tree widgets to the first horizontal layout</li>
<li>Add your label and lineedit to the second horizontal layout</li>
</ul>
| 1 | 2016-08-24T22:15:20Z | [
"python",
"pyqt"
] |
PyQt: QLineEdit with attached label | 39,133,740 | <p>This is probably a very silly question, but anyway I am struck by it :-(</p>
<p>I have a window with two side-by-side lists and a line edit control with a label below them (see the attached image). What I want is to have the line edit field placed just after the corresponding label and not below the second list.</p>
<p><a href="http://i.stack.imgur.com/J530M.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/J530M.jpg" alt="enter image description here"></a></p>
<p>Here is my test code:</p>
<pre><code>import sys
from PyQt4 import Qt, QtCore, QtGui
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
centralLayout = QtGui.QGridLayout()
centralLayout.setSpacing(2)
treelist1 = QtGui.QTreeWidget()
treelist2 = QtGui.QTreeWidget()
treelist1.setColumnCount(1)
treelist1.setHeaderLabels(["List 1"])
treelist2.setColumnCount(1)
treelist2.setHeaderLabels(["List 2"])
label = QtGui.QLabel("Line:")
linedit = QtGui.QLineEdit()
centralLayout.setRowStretch(0, 8)
centralLayout.setRowStretch(1, 1)
centralLayout.addWidget(treelist1, 0, 0)
centralLayout.addWidget(treelist2, 0, 1)
centralLayout.addWidget(label, 1, 0)
centralLayout.addWidget(linedit, 1, 1)
self.setLayout(centralLayout)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
</code></pre>
<p>Thanks in advance for any assistance you can provide!</p>
| 0 | 2016-08-24T22:06:11Z | 39,134,248 | <p>Here is the answer to my question, based on the suggestion by ypnos:</p>
<pre><code>import sys
from PyQt4 import Qt, QtCore, QtGui
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
verticalLayout = QtGui.QVBoxLayout()
verticalLayout.setSpacing(2)
horizontalLayout1 = QtGui.QHBoxLayout()
horizontalLayout2 = QtGui.QHBoxLayout()
treelist1 = QtGui.QTreeWidget()
treelist2 = QtGui.QTreeWidget()
treelist1.setColumnCount(1)
treelist1.setHeaderLabels(["List 1"])
treelist2.setColumnCount(1)
treelist2.setHeaderLabels(["List 2"])
label = QtGui.QLabel("Line:")
linedit = QtGui.QLineEdit()
horizontalLayout1.addWidget(treelist1)
horizontalLayout1.addWidget(treelist2)
horizontalLayout2.addWidget(label)
horizontalLayout2.addWidget(linedit)
verticalLayout.addLayout(horizontalLayout1)
verticalLayout.addLayout(horizontalLayout2)
self.setLayout(verticalLayout)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
sys.exit(app.exec_())
</code></pre>
<p><a href="http://i.stack.imgur.com/VTOrv.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/VTOrv.jpg" alt="enter image description here"></a></p>
| 1 | 2016-08-24T22:58:06Z | [
"python",
"pyqt"
] |
How to attach a component in a specific line of GtkBox? | 39,133,741 | <p>I created a <code>GtkBox</code> with Glade, I added some components at the beginning and end of the <code>GtkBox</code> and left a empty line in the middle.
Now, how do I add a new component in the empty line through code? E.g:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.18.3 -->
<interface>
<requires lib="gtk+" version="3.12"/>
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<child>
<object class="GtkBox" id="box1">
<property name="visible">True</property>
<property name="can_focus">False</property>
<property name="orientation">vertical</property>
<child>
<object class="GtkButton" id="button1">
<property name="label" translatable="yes">button</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">0</property>
</packing>
</child>
<child>
<placeholder/>
</child>
<child>
<object class="GtkEntry" id="entry1">
<property name="visible">True</property>
<property name="can_focus">True</property>
</object>
<packing>
<property name="expand">False</property>
<property name="fill">True</property>
<property name="position">2</property>
</packing>
</child>
</object>
</child>
</object>
</interface>
</code></pre>
<p>How do I add a component in position one of the <code>GtkBox</code>, through code?</p>
<p><strong>EDIT:</strong>
Apparently <code>GtkBox</code> does not have a method, like <a href="http://lazka.github.io/pgi-docs/index.html#Gtk-3.0/classes/Grid.html#Gtk.Grid.attach" rel="nofollow">attach</a> of <code>GtkGrid</code></p>
| 0 | 2016-08-24T22:06:12Z | 39,158,925 | <p>There are multiple solutions to your problem:</p>
<ol>
<li>Containers store their children's packing properties (stuff like <code>expand</code> and <code>fill</code> and, you guessed it, <code>position</code>). You can use <code>container_widget.child_set_property(child_widget, 'position', index)</code> to change the position of a child widget.</li>
<li>Use a Grid instead of a Box. You can choose where to add a child widget if you use the <code>grid.attach</code> method, or add widgets as if it were a Box (because both inherit from GtkContainer).</li>
<li>Instead of leaving the spot empty, insert another (invisible) container widget. This way you can easily add child widgets, and without needing to hard-code their position in the box.</li>
</ol>
| 3 | 2016-08-26T05:33:43Z | [
"python",
"python-3.x",
"gtk",
"gtk3"
] |
Operations on Large Python Sets | 39,133,758 | <p><strong>UPDATE 1</strong></p>
<p>Both sets contain strings of maximum length 20 and can only take values from 'abcdefghijklmnopqrstuvwxyz'</p>
<p><strong>UPDATE 2</strong></p>
<p>I constructed the sets by reading 2 files from disk using a library called ujson (similar to simplejson) and then converting the returned lists into sets . </p>
<hr>
<p>I am trying to take the difference of 2 sets containing 100 million elements each.</p>
<p>This code executes in 2 minutes:</p>
<pre><code>temp = set() #O(1)
for i in first_100_million_set: #O(N)
temp.add(i) #O(1)
</code></pre>
<p>This code executes in 6 hours:</p>
<pre><code>temp = set() #O(1)
for i in first_100_million_set: #O(N)
if i in second_100_million_set: #O(1)
temp.add(i) #O(1)
</code></pre>
<p>All I did was add membership check which , if I am not mistaken is done in O(1)? Where is this massive reduction coming from ?</p>
<p><em>I know about set(a) - set(b) , it is practically doing exactly what my second block of code is doing , takes 6 hours to complete as well, I just wanted to write the whole procedure to demonstrate my point of confusion.</em></p>
<p><strong>Do you think there is a better solution for what I am trying to do ?</strong></p>
| 2 | 2016-08-24T22:08:34Z | 39,133,943 | <p>When talking about 100 million element sets, I'd worry about data being evicted from RAM (going to swap/pagefile). A 100M element <code>set</code> on Python 3.5 built for a 64 bit processor (which you're using, because you couldn't even create such a <code>set</code> in a 32 bit build of Python) uses 4 GB of memory just for the <code>set</code> overhead (ignoring the memory used by the objects it contains).</p>
<p>Your code that creates a new <code>set</code> without membership testing the second <code>set</code> accesses this memory sequentially, so the OS can predict the access patterns and it's likely pulling data into the cache before you need it even if most of the <code>set</code> is paged out. The only random access occurs in the building of the second <code>set</code> (but conveniently, the objects being inserted are already in cache because you pulled them from the original <code>set</code>). So you grow from no random access to maybe 4 GB (plus size of contained objects) worth of memory that is being accessed randomly and <em>must</em> not be paged out w/o causing performance problems.</p>
<p>In your second case, the <code>set</code> being membership tested is accessed randomly on every test, and it has to load every object in the bucket collision chain with a matching hash (admittedly, with good hash generation, there shouldn't be too many of these matches). But it means the size of your randomly accessed memory went from growing from 0 to 4 GB to growing from 4 to as much as 8 GB (depending on how much overlap exists between the <code>set</code>s; again, ignoring the access to the stored objects themselves). I wouldn't be surprised if this pushed you from performing mostly RAM accesses to incurring page faults requiring reads from the page file, which is several orders of magnitude slower than RAM access. Not coincidentally, that code is taking a few orders of magnitude longer to execute.</p>
<p>For the record, the <code>set</code> overhead is likely to be a fraction of the cost of the objects stored. The smallest useful objects in Python are <code>float</code>s (24 bytes a piece on Python 3.5 x64) though they're poor choices for <code>set</code>s due to issues with exact equality testing. <code>int</code>s that require less than 30 bits of magnitude are conceivably useful, and eat 28 bytes a piece (add 4 bytes for every full 30 bits required to store the value). So a 100M element set might "only" use 4 GB for the data structure itself, but the values are another 2.6 GB or so minimum; if they're not Python built-in types, user-defined objects, even using <code>__slots__</code>, would at least double this (quintuple it if not using <code>__slots__</code>), before they even pay the RAM for their attributes. I've got 12 GB of RAM on my machine, and your second use case would cause massive page thrashing on it, while your first case would run just fine for a <code>set</code> initialized with <code>range(100000000)</code> (though it would cause most of the other processes to page out; Python with two <code>set</code>s plus the <code>int</code>s shared between them use ~11 GB).</p>
<p>Update: Your data (strings from 1-20 ASCII characters) would use 50-69 bytes each on Python 3.5 x64 (probably a little more including allocator overhead), or 4.65-6.43 GB per <code>set</code> (assuming none of the strings are shared, that's 9-13 GB for the raw data). Add the three <code>set</code>s involved, and you're looking at up to 25 GB of RAM (you don't pay again for the members of the third <code>set</code> since they're shared with the first <code>set</code>). I wouldn't try to run your code on any machine with less than 32 GB of RAM.</p>
<p>As for "is there a better solution?" it depends on what you need. If you don't actually need the original <code>set</code>s, just the resulting difference, streaming your data would help. For example:</p>
<pre><code>with open(file1) as f:
# Assume one string per line with newlines separating
myset = set(map(str.rstrip, f))
with open(file2) as f:
myset.difference_update(map(str.rstrip, f))
</code></pre>
<p>That would peak at about 10-11 GB of memory, then drop as elements from the second input were removed, leaving you with just the difference <code>set</code> and nothing else. Other options include using sorted <code>list</code>s of data, which would reduce the overhead from 4 GB per <code>set</code> to ~850 MB per <code>list</code>, then iterate them both in parallel (but not simultaneously; <code>zip</code> is no good here) to find the elements that exist in the first <code>list</code> but not the second, removing some of the random access costs too.</p>
| 9 | 2016-08-24T22:27:39Z | [
"python",
"set"
] |
Operations on Large Python Sets | 39,133,758 | <p><strong>UPDATE 1</strong></p>
<p>Both sets contain strings of maximum length 20 and can only take values from 'abcdefghijklmnopqrstuvwxyz'</p>
<p><strong>UPDATE 2</strong></p>
<p>I constructed the sets by reading 2 files from disk using a library called ujson (similar to simplejson) and then converting the returned lists into sets . </p>
<hr>
<p>I am trying to take the difference of 2 sets containing 100 million elements each.</p>
<p>This code executes in 2 minutes:</p>
<pre><code>temp = set() #O(1)
for i in first_100_million_set: #O(N)
temp.add(i) #O(1)
</code></pre>
<p>This code executes in 6 hours:</p>
<pre><code>temp = set() #O(1)
for i in first_100_million_set: #O(N)
if i in second_100_million_set: #O(1)
temp.add(i) #O(1)
</code></pre>
<p>All I did was add membership check which , if I am not mistaken is done in O(1)? Where is this massive reduction coming from ?</p>
<p><em>I know about set(a) - set(b) , it is practically doing exactly what my second block of code is doing , takes 6 hours to complete as well, I just wanted to write the whole procedure to demonstrate my point of confusion.</em></p>
<p><strong>Do you think there is a better solution for what I am trying to do ?</strong></p>
| 2 | 2016-08-24T22:08:34Z | 39,134,693 | <p>Checking if an element is in a set does appear to be O(1), see below code. A set must be internally made with a hash function. The rate of success of hash tables depends on the key's you use, and the way Python guesses what you did. using a <code>range(n)</code> for a set is then sort of ideal. </p>
<pre><code>import time
def foo(n):
myset = set(range(n))
to = time.time()
for e in myset: #O(n)
if e in myset: #O(n) or O(1)?
pass
else:
raise "Error!"
print time.time() - to
return
>>> foo(10**6)
0.0479998588562
>>> foo(10**7)
0.476000070572
</code></pre>
<p>Thus the function foo executes in O(n) and the check if the element is in the set used O(1) only.</p>
| -1 | 2016-08-24T23:56:17Z | [
"python",
"set"
] |
How to pass 'self' parameter of one class to another class | 39,133,820 | <p>I am trying to incorporate matplotlib into tkinter by having multiple frames. I need to pass the entry inputs from <code>StartPage</code> frame to update the plot in <code>GraphPage</code> once the button in <code>StartPage</code> is clicked. Therefore, I'm trying to bind the update function of <code>GraphPage</code> to the button in <code>StartPage</code>, but the update function requires <code>self</code> parameter which I can't get. Here's the set up of my code right now:</p>
<pre><code>import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk
from tkinter import ttk
class PeakFitting(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, GraphPage):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def get_page(self, classname):
'''Returns an instance of a page given it's class name as a string'''
for page in self.frames.values():
if str(page.__class__.__name__) == classname:
return page
return None
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
# Setting up frame and widget
self.entry1 = tk.Entry(self)
self.entry1.grid(row=4, column=1)
button3 = ttk.Button(self, text="Graph Page",
command=self.gpUpdate())
button3.grid(row=7, columnspan=2)
def gpUpdate(self):
graphPage = self.controller.get_page("GraphPage")
GraphPage.update(graphPage)
self.controller.show_frame("GraphPage")
class GraphPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
fig = Figure(figsize=(5, 5), dpi=100)
self.a = fig.add_subplot()
canvas = FigureCanvasTkAgg(fig, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
startpage = self.controller.get_page("StartPage")
def update(self):
startpage = self.controller.get_page("StartPage")
self.iso = startpage.entry1.get()
##Calculation code for analysis not needed for question
app = PeakFitting()
app.mainloop()
</code></pre>
<p>for <code>gpUpdate</code> function in <code>StartPage</code>, I tried to pass <code>graphPage</code> as <code>self</code>, but got an Error that it's a <code>NoneType</code>. I also tried <code>GraphPage.update(GraphPage)</code> but get 'type object 'GraphPage' has no attribute 'controller'' Error. </p>
<p>I'm very sorry if my explanation wasn't clear, but I am very new to Python and has been struggling for weeks now to pass the entries to GraphPage class after the button is clicked but still can't do it... Can anyone please help me with this problem?</p>
<p>Thank you so much!!!</p>
<p>EDIT: I guess my main problem is how to call a function of one class in another class, because I don't know what the <code>self</code> parameter should be :(</p>
<p>EDIT2: Changes to code thanks to suggestion:</p>
<pre><code>def gpUpdate(self):
self.parent = PeakFitting()
self.grpage = GraphPage(self.parent.container, self.parent)
self.grpage.update()
self.controller.show_frame(GraphPage)
</code></pre>
<p>However, when I input something in the entry and hit the button, the <code>self.iso</code> field still remains empty...</p>
| 0 | 2016-08-24T22:13:23Z | 39,133,968 | <p>This is the problem:</p>
<pre><code>GraphPage.update(graphPage)
</code></pre>
<p>You call the method on the class itself. You need to create an instance of that class and then call the <code>update</code> method with a parent and a controller, for example:</p>
<pre><code>self.grpage = GraphPage(parent, controller)
</code></pre>
<p>And then:</p>
<pre><code>self.grpage.update()
</code></pre>
<p>Aside from this, you have another problem <code>in button3</code>- change this:</p>
<pre><code>command=self.gpUpdate()
</code></pre>
<p>to this:</p>
<pre><code>command=self.gpUpdate
</code></pre>
<p>without parenthesis. This is a function that you pass to the button, and will be invoked upon button click. </p>
| 3 | 2016-08-24T22:29:42Z | [
"python",
"python-3.x",
"matplotlib",
"tkinter"
] |
Smart-on-FHIR Python Client with Bundles | 39,133,855 | <p>So I have a FHIR patient bundle json from the "$everything" operation:
<a href="https://www.hl7.org/fhir/operation-patient-everything.html" rel="nofollow">https://www.hl7.org/fhir/operation-patient-everything.html</a></p>
<p>I am now interested in using the Smart on FHIR Python Client Models to make working with the json file a lot easier. An example given is the following:</p>
<pre><code>import json
import fhirclient.models.patient as p
with open('path/to/patient.json', 'r') as h:
pjs = json.load(h)
patient = p.Patient(pjs)
patient.name[0].given
# prints patient's given name array in the first `name` property
</code></pre>
<p>Would it be possible to do instantiate something with just a generic bundle object class to be able access different resources inside the bundle?</p>
| 2 | 2016-08-24T22:18:05Z | 39,137,796 | <p>Yes, you can instantiate a <code>Bundle</code> like you can instantiate any other model, either manually from JSON or by a <code>read</code> from the server. Every <code>search</code> returns a Bundle as well. Then you can just iterate over the bundle's entries and work with them, like put them in an array:</p>
<pre><code>resources = []
if bundle.entry is not None:
for entry in bundle.entry:
resources.append(entry.resource)
</code></pre>
<p>p.s.
It should be possible to execute any <code>$operation</code> with the client, returning the <code>Bundle</code> you mention, but I have to check if we've exposed that or if it has not been committed.</p>
<hr>
<p>Command line example:</p>
<pre><code>import fhirclient.models.bundle as b
import json
with open('fhir-parser/downloads/bundle-example.json', 'r') as h:
js = json.load(h)
bundle = b.Bundle(js)
bundle.entry
[<fhirclient.models.bundle.BundleEntry object at 0x10f40ae48>,
<fhirclient.models.bundle.BundleEntry object at 0x10f40ac88>]
for entry in bundle.entry:
print(entry.resource)
// prints
<fhirclient.models.medicationorder.MedicationOrder object at 0x10f407390>
<fhirclient.models.medication.Medication object at 0x10f407e48>
</code></pre>
| 1 | 2016-08-25T06:06:41Z | [
"python",
"json",
"hl7-fhir"
] |
docker + django : loop + break using forms | 39,133,927 | <p>I am using django in a docker container. I have a page with two buttons: 'Run' and 'Stop'. When someone presses 'Run' it should start an optimisation process, when you press 'Stop', it should stop.</p>
<p><strong>views.py</strong></p>
<pre><code>def runGA(request):
#read from database and initate form
rundata = RunModel.objects.get(SID=sid)
runform = RunForm(request.POST or None, instance = rundata)
form = runform.save(commit=False) # initiating the form, to allow writing form.stop to db.stop
if request.method=="POST":
if request.POST.get("GA")=="Stop":
form.stop = True
if request.POST.get("GA")=="Run":
for iteration in range(cycles):
*optimise something with iteration*
rundata = RunModel.objects.get(SID=sid)
if rundata.stop == True:
break
form.stop = False
form.save()
return render(request,"runGA.html",{})
</code></pre>
<p>This works when I don't use the docker container but just run it locally. This structure allows to interrupt a loop, but it also allows to show an updating figure while running, or to check settings on other pages while running, etc...
(so I need a solution that would work for all those problems as well)</p>
<p>However, if I run this code in the docker container, it seems as though there's a problem with the request.POST. It executes all the requests <strong>after</strong> the loop is done, and not <strong>during</strong> as it should be. And this <strong>only</strong> happens when I run this in a docker container. </p>
<p>Any ideas how come?</p>
<p>Thanks!</p>
<p><strong>Docker version:</strong></p>
<pre><code> Client:
Version: 1.11.1
API version: 1.23
Go version: go1.6.2
Git commit: 5604cbe
Built: Wed Apr 27 15:27:26 UTC 2016
OS/Arch: darwin/amd64
Server:
Version: 1.12.0
API version: 1.24
Go version: go1.6.3
Git commit: 8eab29e
Built: Thu Jul 28 23:54:00 2016
OS/Arch: linux/amd64
</code></pre>
<p>Docker file probably doesn't matter, but is here: <a href="https://github.com/neuropower/neuropower-web/blob/development/neuropower/Dockerfile" rel="nofollow">https://github.com/neuropower/neuropower-web/blob/development/neuropower/Dockerfile</a>.</p>
| 0 | 2016-08-24T22:25:46Z | 39,259,636 | <p>Found the solution ! Number of threads in the uwsgi.ini was only 1. Increasing this solved the problem.</p>
<p><strong>uwsgi.ini</strong></p>
<pre><code>[uwsgi]
master = true
processes = 4
threads = 4
socket = :3031
chdir = /code/
post-buffering = true
log-date = true
max-requests = 5000
wsgi-file = neuropowertools/wsgi.py
</code></pre>
| 0 | 2016-08-31T21:57:24Z | [
"python",
"django",
"loops",
"docker",
"interrupt"
] |
Multiple Python Scripts in Docker | 39,133,956 | <p>This is quite a basic question but I haven't been able to get an answer from researching on Google, although I think its more due to my lack of understanding, than the answer not being out there.</p>
<p>I am getting to grips with Docker and have a python Flask Admin script and a postgres db both in two separate containers but under on docker-compose file. I would like another python script to run at the same time which will be scraping a website. I have the file all set up but how do I include it in the same Docker-Compose or DockerFile? </p>
<pre><code>version: '2'
services:
db:
image: postgres
environment:
- PG_PASSWORD=XXXXX
dev:
build: .
volumes:
- ./app:/code/app
- ./run.sh:/code/run.sh
ports:
- "5000:5000"
depends_on:
- db
</code></pre>
| 0 | 2016-08-24T22:28:14Z | 39,134,645 | <p>Exactly what to write depends on your directory configuration, but you basically want</p>
<pre><code>version: '2'
services:
db:
image: postgres
environment:
- PG_PASSWORD=XXXXX
dev:
build: <path-to-dev>
volumes:
- ./app:/code/app
- ./run.sh:/code/run.sh
ports:
- "5000:5000"
depends_on:
- db
scraper:
build: <path-to-scraper>
depends_on:
- db
</code></pre>
<p>The two paths might be the same. You might push an image and then reference that instead of building it on the fly. You might do the same business of just mounting the code directory instead of building it into the image (but don't do that for actual deployment).</p>
| 1 | 2016-08-24T23:50:01Z | [
"python",
"docker"
] |
Generator expression makes binary string generator freeze forever | 39,134,067 | <p>I have written a function to generate binary strings starting from a given list <code>s</code> (all binary strings that end in one of <code>s</code> items):</p>
<pre><code>def binary_strings(s):
yield from s
while True:
s = [b + x for x in s for b in "01"]
yield from s
</code></pre>
<p>It works as you can see from the output:</p>
<pre><code>>>> for i in binary_strings(["10", "01"]): print(i)
10
01
010
110
001
101
0010
1010
0110
1110
0001
1001
0101
1101
00010
10010
01010
11010
00110
10110
01110
11110
00001
10001
01001
11001
00101
10101
01101
11101
000010
100010
... # Output is infinite so I must truncate it.
</code></pre>
<p>Now I modify <code>s</code> and use a generator expression for it instead of a list:</p>
<pre><code>def binary_strings(s):
yield from s
while True:
s = (b + x for x in s for b in "01")
yield from s
</code></pre>
<p>Now the execution abruptly stops after exhausting the 3-length possibilities:</p>
<pre><code>>>> for i in binary_strings(["10","01"]): print(i)
10
01
010
110
001
101
# Output is not truncated, the function freezes at this points
# and yield no more output
</code></pre>
<p>I expected the second version to work just as well as the first because I never use list methods on <code>s</code> and I just iterate through it, why isn't the second version working?</p>
| 3 | 2016-08-24T22:39:30Z | 39,134,115 | <p>I found the answer, the line <code>yield from s</code> was exhausting the generator so the line <code>yield from s</code> yielded from an empty generator (the comprehension before yields empty as <code>s</code> is empty) hence freezeing forever.</p>
<p>A list instead can be iterated arbitrarly many times so this problem does not appear.</p>
<p>The problem appears only after an iteration because at the start <code>s</code> is a list and becomes a generator afterwards.</p>
| 1 | 2016-08-24T22:45:00Z | [
"python",
"python-3.x",
"generator",
"generator-expression"
] |
Copy HTML, save all images on that page and redirect the images in the html | 39,134,172 | <p>Here's what I want to do:</p>
<p>Hit a url,
save all of the html to a .html file
save all of the images
create a copy of that .html where all of the images are redirected to the local copy.</p>
<p>At this point, I can now open the second file while my computer is disconnected from the internet.</p>
<p>Here's what I'm doing right now just to pull the HTML:</p>
<pre><code>urllib.urlretrieve(pageURL, "fileName.html")
</code></pre>
<p>Is there something I can just plug in to get this to work? I haven't managed to find any utilities.</p>
| 0 | 2016-08-24T22:51:29Z | 39,135,091 | <p>Doesn't need to be Python? Great. Try downloading <a href="http://gnuwin32.sourceforge.net/packages/wget.htm" rel="nofollow">Wget for Windows</a> and doing</p>
<p><code>wget -p -k http://the-site-you-want.com/fileName.html</code></p>
| 0 | 2016-08-25T00:52:58Z | [
"python",
"html"
] |
Python Dictionary convert to HTML in flask | 39,134,183 | <p>I have python dictionary that have a list of dictionaries inside. I am trying to convert this to an HTML table that I can give to Flask render_template</p>
<p>My dictionary format is:</p>
<pre><code>{'sentiment_analysis_result': [{'article_title': u'These Digital Locks Help Keep Tabs on Tenants', 'score': u'0.139613', 'type': u'positive'}, {'article_title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads', 'score': u'0.239663', 'type': u'positive'}]}
</code></pre>
<p>I want the key to be title and values to be values. Any help would be much apprecited!</p>
<p>After trying @EliasMP 's answer the format of the table is:</p>
<p><a href="http://i.stack.imgur.com/iQ0Fz.png" rel="nofollow"><img src="http://i.stack.imgur.com/iQ0Fz.png" alt="enter image description here"></a></p>
| 0 | 2016-08-24T22:52:22Z | 39,134,339 | <p>Not the most efficient but gets the job done if you want to just pass the table already rendered as html as a variable to the view. A better way would be to pass just the data then have the template use template logic to loop over and output variables in the places you want.</p>
<pre><code>data = {'sentiment_analysis_result': [{'article_title': u'These Digital Locks Help Keep Tabs on Tenants', 'score': u'0.139613', 'type': u'positive'}, {'article_title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads', 'score': u'0.239663', 'type': u'positive'}]}
table_string = '<table>'
for key, value in data.iteritems():
table_string += '<thead>'
table_string += '<th>' + key + '</th>'
table_string += '</thead>'
table_string += '<tbody>'
for i, d in enumerate(value):
if i == 0:
table_string += '<tr>'
for k in d.iterkeys():
table_string += '<td>' + k + '</td>'
table_string += '</tr>'
table_string += '<tr>'
for v in d.itervalues():
table_string += '<td>' + v + '</td>'
table_string += '</tr>'
table_string += '</tbody>'
table_string += '</table>'
print(table_string)
</code></pre>
| 0 | 2016-08-24T23:08:38Z | [
"python",
"html",
"dictionary",
"flask"
] |
Python Dictionary convert to HTML in flask | 39,134,183 | <p>I have python dictionary that have a list of dictionaries inside. I am trying to convert this to an HTML table that I can give to Flask render_template</p>
<p>My dictionary format is:</p>
<pre><code>{'sentiment_analysis_result': [{'article_title': u'These Digital Locks Help Keep Tabs on Tenants', 'score': u'0.139613', 'type': u'positive'}, {'article_title': u'You Can Get a $50 Phone From Amazon, If You Don\u2019t Mind the Ads', 'score': u'0.239663', 'type': u'positive'}]}
</code></pre>
<p>I want the key to be title and values to be values. Any help would be much apprecited!</p>
<p>After trying @EliasMP 's answer the format of the table is:</p>
<p><a href="http://i.stack.imgur.com/iQ0Fz.png" rel="nofollow"><img src="http://i.stack.imgur.com/iQ0Fz.png" alt="enter image description here"></a></p>
| 0 | 2016-08-24T22:52:22Z | 39,134,353 | <p>Just pass the dictionary from controller to template and loop it twice. First one for recovering each element of dictionary (key and value respectly), and the second one for recovering each element of each list (value recovered before), paint them using html (table tag, div formatted as a table would be the proper way, table´s tag are being obsolete) </p>
<pre><code><table>
<tr>
<th>name_of_list</th>
<th>values</th>
</tr>
{% for key, values in your_dictionary.items() %}
<tr>
<td>{{key}}</td>
<td>
<table>
<tr>
<th>article_title</th>
<th>score</th>
<th>type</th>
</tr>
<tr>
{% for articles in values %}
<td>{{article.article_title}}</td>
<td>{{article.score}}</td>
<td>{{article.type}}</td>
{% endfor %}
</tr>
</td>
</tr>
{% endfor %}
</table>
</code></pre>
| 1 | 2016-08-24T23:11:31Z | [
"python",
"html",
"dictionary",
"flask"
] |
Jet API bulk JSON upload: The magic number in GZip header is not correct | 39,134,305 | <p>I attempted to contact Jet directly and was told to âtry using 7zip to gzip the fileâ and then received no further responses (despite further questions).</p>
<p>Here's the error code:</p>
<pre><code>"error_excerpt": [
"Error parsing file: The magic number in GZip header is not correct. Make sure you are passing in a GZip stream."
],
</code></pre>
<p>Here's what I'm trying:</p>
<pre><code>def file_upload_url(self, url, filename, data):
headers = {"x-ms-blob-type": "blockblob"}
magic_number = open(filename, 'rb').read(2) # shows that magic number is correct for .gz file
print `magic_number`
with open(filename, 'rb') as f:
file_data=f.read()
response = requests.put(url, headers=headers, files={ "test.json.gz": file_data })
# i've also tried data={"test.json.gz": file_data}
</code></pre>
<p>Which then you check with another call. The file was gzipped from the Ubuntu command line (to rule out Python's gzip module causing the problem).</p>
<p>Here is the documentation provided: <a href="https://developer.jet.com/docs/" rel="nofollow">https://developer.jet.com/docs/</a></p>
<p>I've implemented every other function without the slightest hiccup but this is just not working. Only thing I can think of is that I'm somehow sending the file data incorrectly. But I can't seem to figure out how.</p>
<p>The <code>.json</code> file was confirmed to be valid from the Jet representative. </p>
| 0 | 2016-08-24T23:03:58Z | 39,137,065 | <p>Figured out the answer. Must make sure to ONLY put the binary data (not a dictionary, like for files) inside the data parameter in requests. </p>
<p>making it:</p>
<pre><code>def file_upload_url(self, url, filename, data):
headers = {"x-ms-blob-type": "blockblob"}
with open(filename, 'rb') as f:
file_data=f.read()
response = requests.put(url, headers=headers, data=file_data)
</code></pre>
<p>Nice and easy.</p>
| 1 | 2016-08-25T05:07:37Z | [
"python",
"python-requests",
"jet.com-apis"
] |
how to install PIL on python shell on OS X 10.9.5 | 39,134,324 | <p>I am new to Python.
I try to install PIL using Python 3.5.2 shell.
I input <code>pip install PIL</code> into python interpreter first. It didn't work and showed me this: <code>SyntaxError: invalid syntax</code>.</p>
<p>Then I searched online and tried this: <code>pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL</code>. Still a syntax error. </p>
<p>Finally I tried this: <code>install PIL</code> and didn't work either. </p>
<p>I wonder if a shell command is different with the terminal command? I am using OS X 10.9.5 at the moment and if I using terminal to write python it will be Python 2.7.X and because it's related to some system files so I can't change it.
I want to ask how can I install PIL or other modules using a Python shell?</p>
<p>This question is different with other questions related to "How to install PIL". I am trying to ask how to use Python 3.5 shell to install PIL. If I install PIL using terminal command then it will be installed into my system default python, which is Python 2.7.X.</p>
| 0 | 2016-08-24T23:05:43Z | 39,134,481 | <p>You should run the <code>pip</code> command from a system terminal (BASH prompt), not from inside Python. Normally you would open /Applications/Utilities/Terminal.app, and then type <code>pip install PIL</code>. If that installs packages for Python 2.7 instead of 3.5, you could try this instead: <code>python3 $(which pip) install PIL</code>.</p>
<p>Or from within Python 3.5 you could try this (from <a href="http://stackoverflow.com/questions/12332975/installing-python-module-within-code">Installing python module within code</a>):</p>
<pre><code>import pip
pip.main(['install', 'PIL'])
</code></pre>
<p>A longer-term solution would be to install pip to work with Python 3.5 instead of 2.7. To do that, you would run these commands from the system terminal:</p>
<pre><code>curl --remote-name https://bootstrap.pypa.io/get-pip.py
python3 get-pip.py
</code></pre>
<p>Then <code>pip install PIL</code> should install PIL in your 3.5 installation.</p>
| 1 | 2016-08-24T23:27:33Z | [
"python",
"osx",
"shell"
] |
how to install PIL on python shell on OS X 10.9.5 | 39,134,324 | <p>I am new to Python.
I try to install PIL using Python 3.5.2 shell.
I input <code>pip install PIL</code> into python interpreter first. It didn't work and showed me this: <code>SyntaxError: invalid syntax</code>.</p>
<p>Then I searched online and tried this: <code>pip install --no-index -f http://dist.plone.org/thirdparty/ -U PIL</code>. Still a syntax error. </p>
<p>Finally I tried this: <code>install PIL</code> and didn't work either. </p>
<p>I wonder if a shell command is different with the terminal command? I am using OS X 10.9.5 at the moment and if I using terminal to write python it will be Python 2.7.X and because it's related to some system files so I can't change it.
I want to ask how can I install PIL or other modules using a Python shell?</p>
<p>This question is different with other questions related to "How to install PIL". I am trying to ask how to use Python 3.5 shell to install PIL. If I install PIL using terminal command then it will be installed into my system default python, which is Python 2.7.X.</p>
| 0 | 2016-08-24T23:05:43Z | 39,154,914 | <pre><code>pip install pillow
</code></pre>
<p><code>pillow</code> is a wrapper to an old <code>PIL</code> package and it works like a charm.</p>
| 0 | 2016-08-25T21:22:11Z | [
"python",
"osx",
"shell"
] |
Use Regex to parse out some part of URL using python | 39,134,347 | <p>Suppose I am having some like as the following,</p>
<pre><code>URL
http://hostname.com/as/ck$st=fa+gw+hw+ek+ei/
http://hostname.com/wqs/ck$st=fasd+/
http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav
</code></pre>
<p>I want to check for first + symbol in the url and move backward until we find a special character such as / or ? or = or any other special character and start from that and go on until we find a space or end of line or & or /.</p>
<p>The regex which I wrote with the help of stackoverflow forums is as follows,</p>
<pre><code>re.search(r"[^\w\+ ]([\w\+ ]+\+[\w\+ ]+)(?:[^\w\+ ]|$)", x).group(1)
</code></pre>
<p>This one works with the first row. But does not parse anything with second row. Also in the third row, I want to check for multiple patterns like this in the row. The current regex checks only for one pattern.</p>
<p>My output should be,</p>
<pre><code>parsed
fa+gw+hw+ek+ei
fasd
fa+gq+hf+kg+is gl+jh+ke+oj+kp
</code></pre>
<p>Can anybody help me to modify the regex which is already there to suit this needs?</p>
<p>Thanks</p>
| 0 | 2016-08-24T23:10:35Z | 39,134,454 | <p>If you change <code>[^\w\+ ]([\w\+ ]+\+[\w\+ ]+)(?:[^\w\+ ]|$)</code> to <code>[^\w\+ ]([\w\+ ]+\+[\w\+ ]*)(?:[^\w\+ ]|$)</code> it will match the second URL as well.</p>
<p>It will include the trailing '+', which isn't included in your desired output but does seem to meet the criteria you had mentioned, so this may take some modifying if you don't want any trailing '+'s.</p>
| 0 | 2016-08-24T23:23:24Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Use Regex to parse out some part of URL using python | 39,134,347 | <p>Suppose I am having some like as the following,</p>
<pre><code>URL
http://hostname.com/as/ck$st=fa+gw+hw+ek+ei/
http://hostname.com/wqs/ck$st=fasd+/
http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav
</code></pre>
<p>I want to check for first + symbol in the url and move backward until we find a special character such as / or ? or = or any other special character and start from that and go on until we find a space or end of line or & or /.</p>
<p>The regex which I wrote with the help of stackoverflow forums is as follows,</p>
<pre><code>re.search(r"[^\w\+ ]([\w\+ ]+\+[\w\+ ]+)(?:[^\w\+ ]|$)", x).group(1)
</code></pre>
<p>This one works with the first row. But does not parse anything with second row. Also in the third row, I want to check for multiple patterns like this in the row. The current regex checks only for one pattern.</p>
<p>My output should be,</p>
<pre><code>parsed
fa+gw+hw+ek+ei
fasd
fa+gq+hf+kg+is gl+jh+ke+oj+kp
</code></pre>
<p>Can anybody help me to modify the regex which is already there to suit this needs?</p>
<p>Thanks</p>
| 0 | 2016-08-24T23:10:35Z | 39,134,492 | <p>I used regexr to come up with this (<a href="http://regexr.com/3e3go" rel="nofollow">regexr link</a>):</p>
<p><code>([\w\+]*\+[\w\+]*)(?:[^\w\+]|$)</code></p>
<p>Matches:</p>
<p><code>fa+gw+hw+ek+ei
fasd+
fa+gq+hf+kg+is
gl+jh+ke+oj+kp
</code></p>
<p>EDIT: Instead of using re.search, try using re.findall instead:</p>
<pre><code>>>> s = "http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav"
>>> re.findall("([\w\+]+\+[\w\+]*)(?:[^\w\+]|$)", s)
['fa+gq+hf+kg+is', 'gl+jh+ke+oj+kp']
</code></pre>
| 2 | 2016-08-24T23:28:58Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Use Regex to parse out some part of URL using python | 39,134,347 | <p>Suppose I am having some like as the following,</p>
<pre><code>URL
http://hostname.com/as/ck$st=fa+gw+hw+ek+ei/
http://hostname.com/wqs/ck$st=fasd+/
http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav
</code></pre>
<p>I want to check for first + symbol in the url and move backward until we find a special character such as / or ? or = or any other special character and start from that and go on until we find a space or end of line or & or /.</p>
<p>The regex which I wrote with the help of stackoverflow forums is as follows,</p>
<pre><code>re.search(r"[^\w\+ ]([\w\+ ]+\+[\w\+ ]+)(?:[^\w\+ ]|$)", x).group(1)
</code></pre>
<p>This one works with the first row. But does not parse anything with second row. Also in the third row, I want to check for multiple patterns like this in the row. The current regex checks only for one pattern.</p>
<p>My output should be,</p>
<pre><code>parsed
fa+gw+hw+ek+ei
fasd
fa+gq+hf+kg+is gl+jh+ke+oj+kp
</code></pre>
<p>Can anybody help me to modify the regex which is already there to suit this needs?</p>
<p>Thanks</p>
| 0 | 2016-08-24T23:10:35Z | 39,134,555 | <p>After trying to use unsuccesfully <a href="https://docs.python.org/2/library/urlparse.html" rel="nofollow">urlparse</a> it seems the best way to get the info you want is using regular expressions:</p>
<pre><code>import urlparse
import re
urls = [
"http://hostname.com/as/ck$st=fa+gw+hw+ek+ei/",
"http://hostname.com/wqs/ck$st=fasd+/",
"http://hostname.com/as/ck$st=fa+gq+hf+kg+is&sadfnlslkdfn&gl+jh+ke+oj+kp sfav"
]
for myurl in urls:
parsed = urlparse.urlparse(myurl)
print 'scheme :', parsed.scheme
print 'netloc :', parsed.netloc
print 'path :', parsed.path
print 'params :', parsed.params
print 'query :', parsed.query
print 'fragment:', parsed.fragment
print 'username:', parsed.username
print 'password:', parsed.password
print 'hostname:', parsed.hostname, '(netloc in lower case)'
print 'port :', parsed.port
print urlparse.parse_qs(parsed.query)
print re.findall(r'([\w\+]+\+[\w\+]*)(?:[^\w\+]|$)', parsed.path)
print '-' * 80
</code></pre>
| 0 | 2016-08-24T23:37:29Z | [
"python",
"regex",
"python-2.7",
"python-3.x"
] |
Pythonic way to add values to a set within a dictionary | 39,134,400 | <p>Lets say i have a dictionary of sets:</p>
<pre><code>d = {"foo":{1,2,3},
"bar":{3,4,5}}
</code></pre>
<p>Now lets say I want to add the value <code>7</code> to the set found within the key <code>foo</code>. This would be easy:</p>
<pre><code>d["foo"].add(7)
</code></pre>
<p>but what if we were unsure of the key already existing? It doesn't feel very pythonic to check beforehand:</p>
<pre><code>if "baz" in dict:
d["baz"].add(7)
else:
d["baz"] = {7}
</code></pre>
<p>I tried to be clever and do something like</p>
<pre><code>d["baz"] = set(d["baz"]).add(7)
</code></pre>
<p>but then you just get a <code>KeyError</code> trying to access a bad key in the <code>set</code> constructor.</p>
<p>Am i missing something, or do I need to just bite the bullet and look before I leap? I would understand if that were the case, it would just be neat if there were a simple way to say "Add this value to the set found at this location, or if there isn't a set at that location, make one, and then put it in.</p>
| 1 | 2016-08-24T23:16:52Z | 39,134,412 | <p>Use <code>defaultdict</code></p>
<pre><code>>>> from collections import defaultdict
>>> d = defaultdict(set)
>>> d
defaultdict(<class 'set'>, {})
>>> d['foo'].add(1)
>>> d['foo'].add(2)
>>> d
defaultdict(<class 'set'>, {'foo': {1, 2}})
>>> d['bar'].add(3)
>>> d['bar'].add(4)
>>> d
defaultdict(<class 'set'>, {'foo': {1, 2}, 'bar': {3, 4}})
>>>
</code></pre>
<p>Also, if you must use plain dict, you can use the <code>.setdefault</code> method:</p>
<pre><code>>>> d2 = {}
>>> d2.setdefault('foo',set()).add(1)
>>> d2.setdefault('foo',set()).add(2)
>>> d2
{'foo': {1, 2}}
>>> d2.setdefault('bar',set()).add(3)
>>> d2.setdefault('bar',set()).add(4)
>>> d2
{'foo': {1, 2}, 'bar': {3, 4}}
>>>
</code></pre>
<h2>Edit to add time comparisons</h2>
<p>You should note that using <code>defaultdict</code> is faster:</p>
<pre><code>>>> setup = "gen = ((letter,k) for letter in 'abcdefghijklmnopqrstuvwxyx' for k in range(100)); d = {}"
>>> s = """for l,n in gen:
... d.setdefault(l,set()).add(n)"""
>>> setup2 = "from collections import defaultdict; gen = ((letter,k) for letter in 'abcdefghijklmnopqrstuvwxyx' for k in range(100)); d = defaultdict(set)"
>>> s2 = """for l,n in gen:
... d[l]=n"""
>>>
>>> import timeit
>>> timeit.timeit(stmt=s, setup=setup, number=10000)
0.005325066005752888
>>> timeit.timeit(stmt=s2, setup=setup2, number=10000)
0.0014927469965186901
</code></pre>
| 8 | 2016-08-24T23:18:48Z | [
"python",
"dictionary"
] |
Pythonic way to add values to a set within a dictionary | 39,134,400 | <p>Lets say i have a dictionary of sets:</p>
<pre><code>d = {"foo":{1,2,3},
"bar":{3,4,5}}
</code></pre>
<p>Now lets say I want to add the value <code>7</code> to the set found within the key <code>foo</code>. This would be easy:</p>
<pre><code>d["foo"].add(7)
</code></pre>
<p>but what if we were unsure of the key already existing? It doesn't feel very pythonic to check beforehand:</p>
<pre><code>if "baz" in dict:
d["baz"].add(7)
else:
d["baz"] = {7}
</code></pre>
<p>I tried to be clever and do something like</p>
<pre><code>d["baz"] = set(d["baz"]).add(7)
</code></pre>
<p>but then you just get a <code>KeyError</code> trying to access a bad key in the <code>set</code> constructor.</p>
<p>Am i missing something, or do I need to just bite the bullet and look before I leap? I would understand if that were the case, it would just be neat if there were a simple way to say "Add this value to the set found at this location, or if there isn't a set at that location, make one, and then put it in.</p>
| 1 | 2016-08-24T23:16:52Z | 39,134,464 | <p>trying to keep this simple, how about this</p>
<pre><code>dict['baz'] = dict.get('baz', set())
dict['baz'].add(7)
</code></pre>
| 1 | 2016-08-24T23:25:05Z | [
"python",
"dictionary"
] |
plot sensor boolean data matplotlib | 39,134,407 | <p>I have data from two sensors that I want to visualize. Both sensors take only 0/1 values. How can I change the xaxis labels to show the time series and y axis should have 2 labels 0 and 1 representing the value of sensors along the time series.</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
def drawgraph(inputFile):
df=pd.read_csv(inputFile)
fig=plt.figure()
ax=fig.add_subplot(111)
y = df[['sensor1']]
x=df.index
plt.plot(x,y)
plt.show()
</code></pre>
| 0 | 2016-08-24T23:18:11Z | 39,136,103 | <p>You should have explained what you tried before asking a question for this to be meaningful. Anyway, below is the example.</p>
<pre><code>%matplotlib inline
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
trange = pd.date_range("11:00", "21:30", freq="30min")
df = pd.DataFrame({'time':trange,'sensor1':np.round(np.random.rand(len(trange))),\
'sensor2':np.round(np.random.rand(len(trange)))})
df = df.set_index('time')
df.plot(yticks=[0,1],ylim=[-0.1,1.1],style={'sensor1':'ro','sensor2':'bx'})
</code></pre>
<p><a href="http://i.stack.imgur.com/HJQSp.png" rel="nofollow"><img src="http://i.stack.imgur.com/HJQSp.png" alt="enter image description here"></a></p>
| 1 | 2016-08-25T03:09:39Z | [
"python",
"pandas",
"matplotlib",
"time-series"
] |
Selenium webdriver python find element by xpath - Could not find element | 39,134,440 | <p>I m trying to write a script with selenium webdriver python.
When I try to do a </p>
<pre><code>find_element_by_xpath("//*[@id='posted_1']/div[3]")
</code></pre>
<p>it says </p>
<blockquote>
<p>NoElementFoundException.</p>
</blockquote>
<p>Can someone please help me here?</p>
<p>Regards
Bala</p>
| 1 | 2016-08-24T23:21:57Z | 39,134,498 | <p>that exception, unsurprisingly, means that that element wasn't available on the DOM. There are a couple of options here:</p>
<pre><code>driver.implicitly_wait(10)
</code></pre>
<p>will tell the driver to wait 10 seconds (or any amount of time) after an element is not found/not clickable etc., and tries again after. Sometimes elements don't load right away, so an implicit wait fixes those types of problems.</p>
<p>The other option here is to do an explicit wait. This will wait until the element appears, and until the existence of that element is confirmed, the script will not move on to the next line:</p>
<pre><code>from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id='posted_1']/div[3]")))
</code></pre>
<p>In my experience, an implicit wait is usually fine, but imprecise.</p>
| 0 | 2016-08-24T23:30:08Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Selenium webdriver python find element by xpath - Could not find element | 39,134,440 | <p>I m trying to write a script with selenium webdriver python.
When I try to do a </p>
<pre><code>find_element_by_xpath("//*[@id='posted_1']/div[3]")
</code></pre>
<p>it says </p>
<blockquote>
<p>NoElementFoundException.</p>
</blockquote>
<p>Can someone please help me here?</p>
<p>Regards
Bala</p>
| 1 | 2016-08-24T23:21:57Z | 39,134,540 | <p>If you are getting <code>NoSuchElementException</code> as your provided exception, There may be following reasons :-</p>
<ul>
<li><p>May be you are locating with incorrect locator, So you need to share HTML for better locator solution. </p></li>
<li><p>May be when you are going to find element, it would not be present on the <code>DOM</code>, So you should implement <code>WebDriverWait</code> to wait until element visible as below :-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='posted_1']/div[3]")))
</code></pre></li>
<li><p>May be this element is inside any <code>frame</code> or <code>iframe</code>. If it is, you need to switch that <code>frame</code> or <code>iframe</code> before finding the element as below :-</p>
<pre><code>driver.switch_to_frame("frame/iframe I'd or name")
wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.XPATH, "//*[@id='posted_1']/div[3]")))
#Once all your stuff done with this frame need to switch back to default
driver.switch_to_default_content();
</code></pre></li>
</ul>
| 0 | 2016-08-24T23:35:39Z | [
"python",
"selenium",
"selenium-webdriver"
] |
using Python, How to group a column in Dataframe by the hour? | 39,134,523 | <p>I have a python dataframe (<code>df1</code>) which has a column time. I converted the column into a datetime series using <code>pd.to_datetime(df1['time'])</code>. Now I get a column like this:</p>
<pre><code>2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:01 2016-08-13 00:00:01
2016-08-24 00:00:01 2016-08-13 00:00:01
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
....
2016-08-24 23:59:59 2016-08-13 00:00:02
</code></pre>
<p>Essentially, I want the first column to be grouped by the hour, so that I can see how many entries are there in 1 hour. Any help will be great.</p>
| 3 | 2016-08-24T23:33:50Z | 39,135,260 | <p>You can use <code>pandas.DatetimeIndex</code> as follows.</p>
<pre><code>import numpy as np
import pandas as pd
# An example of time period
drange = pd.date_range('2016-08-01 00:00:00', '2016-09-01 00:00:00',
freq='10min')
N = len(drange)
# The number of columns without 'time' is three.
df = pd.DataFrame(np.random.rand(N, 3))
df['time'] = drange
time_col = pd.DatetimeIndex(df['time'])
gb = df.groupby([time_col.year,
time_col.month,
time_col.day,
time_col.hour])
for col_name, gr in gb:
print(gr) # If you want to see only the length, use print(len(gr))
</code></pre>
<p>[References]
<a href="http://stackoverflow.com/questions/16266019/python-pandas-group-datetime-column-into-hour-and-minute-aggregations">Python Pandas: Group datetime column into hour and minute aggregations</a></p>
| 1 | 2016-08-25T01:15:12Z | [
"python",
"datetime",
"pandas",
"dataframe",
"group-by"
] |
using Python, How to group a column in Dataframe by the hour? | 39,134,523 | <p>I have a python dataframe (<code>df1</code>) which has a column time. I converted the column into a datetime series using <code>pd.to_datetime(df1['time'])</code>. Now I get a column like this:</p>
<pre><code>2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:01 2016-08-13 00:00:01
2016-08-24 00:00:01 2016-08-13 00:00:01
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
....
2016-08-24 23:59:59 2016-08-13 00:00:02
</code></pre>
<p>Essentially, I want the first column to be grouped by the hour, so that I can see how many entries are there in 1 hour. Any help will be great.</p>
| 3 | 2016-08-24T23:33:50Z | 39,137,005 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a>:</p>
<pre><code>#pandas version 0.18.0 and higher
df = df.resample('H').size()
#pandas version below 0.18.0
#df = df.resample('H', 'size')
print (df)
2016-08-24 00:00:00 1
2016-08-24 01:00:00 3
2016-08-24 02:00:00 1
Freq: H, dtype: int64
</code></pre>
<p>If need output as <code>DataFrame</code>:</p>
<pre><code>df = df.resample('H').size().rename('count').to_frame()
print (df)
count
2016-08-24 00:00:00 1
2016-08-24 01:00:00 3
2016-08-24 02:00:00 1
</code></pre>
<hr>
<p>Or you can remove from <code>DatetimeIndex</code> <code>minutes</code> and <code>seconds</code> by converting to <code><M8[h]</code> and then aggregating <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html" rel="nofollow"><code>size</code></a>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'time': {pd.Timestamp('2016-08-24 01:00:00'): pd.Timestamp('2016-08-13 00:00:00'), pd.Timestamp('2016-08-24 01:00:01'): pd.Timestamp('2016-08-13 00:00:01'), pd.Timestamp('2016-08-24 01:00:02'): pd.Timestamp('2016-08-13 00:00:02'), pd.Timestamp('2016-08-24 02:00:02'): pd.Timestamp('2016-08-13 00:00:02'), pd.Timestamp('2016-08-24 00:00:00'): pd.Timestamp('2016-08-13 00:00:00')}})
print (df)
time
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 01:00:00 2016-08-13 00:00:00
2016-08-24 01:00:01 2016-08-13 00:00:01
2016-08-24 01:00:02 2016-08-13 00:00:02
2016-08-24 02:00:02 2016-08-13 00:00:02
df= df.groupby([df.index.values.astype('<M8[h]')]).size()
print (df)
2016-08-24 00:00:00 1
2016-08-24 01:00:00 3
2016-08-24 02:00:00 1
dtype: int64
</code></pre>
| 2 | 2016-08-25T05:01:59Z | [
"python",
"datetime",
"pandas",
"dataframe",
"group-by"
] |
using Python, How to group a column in Dataframe by the hour? | 39,134,523 | <p>I have a python dataframe (<code>df1</code>) which has a column time. I converted the column into a datetime series using <code>pd.to_datetime(df1['time'])</code>. Now I get a column like this:</p>
<pre><code>2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:00 2016-08-13 00:00:00
2016-08-24 00:00:01 2016-08-13 00:00:01
2016-08-24 00:00:01 2016-08-13 00:00:01
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
2016-08-24 00:00:02 2016-08-13 00:00:02
....
2016-08-24 23:59:59 2016-08-13 00:00:02
</code></pre>
<p>Essentially, I want the first column to be grouped by the hour, so that I can see how many entries are there in 1 hour. Any help will be great.</p>
| 3 | 2016-08-24T23:33:50Z | 39,137,189 | <p>Using @jezrael setup. </p>
<pre><code>df.resample(rule='H', how='count').rename(columns = {'time':'count'})
count
2016-08-24 00:00:00 1
2016-08-24 01:00:00 3
2016-08-24 02:00:00 1
</code></pre>
| 3 | 2016-08-25T05:17:50Z | [
"python",
"datetime",
"pandas",
"dataframe",
"group-by"
] |
custom iterator or generator to execute closeout after break | 39,134,524 | <p>I'm implementing customized loop behavior, where I need things to happen on entering the loop, at every loop start, at every loop end, and on exiting the loop area. So far this is beautifully simple in Python (2.7):</p>
<pre><code>def my_for(loop_iterable):
enter_loop()
for i in loop_iterable:
loop_start()
yield i
loop_end()
exit_loop()
for i in my_for([1, 2, 3]):
print "i: ", i
if i == 2:
break
</code></pre>
<p>The problem I'm having is in getting <code>loop_end()</code> and <code>exit_loop()</code> to execute after the <code>break</code>. I have solved this by defining another function, which the user must put before break:</p>
<pre><code>def break_loop():
loop_end()
exit_loop()
for i in my_for([1, 2, 3]):
print "i: ", i
if i == 2:
break_loop()
break
</code></pre>
<p>But I would really like not to have the user have to remember to add that line. I think if I re-write the generator function as an iterator class, maybe there is a way to still execute code on a <code>break</code>?</p>
<p>Incidentally, <code>continue</code> works just fine as is!</p>
| 0 | 2016-08-24T23:34:17Z | 39,134,601 | <p>You may use <code>__enter__</code> and <code>__exit__</code> magic function by defining it in class. To make a call, you may use it with <code>with</code>. <code>__enter__</code> method will be called before executing the code within <code>with</code> block and and when the <code>with</code> block will be exited, <code>__exit__</code> function will be called. For example:</p>
<pre><code>>>> class MyTestWrapper(object):
... def __enter__(self):
... print 'I am in __enter__'
... def __exit__(self, type, value, traceback):
... print 'I am in __exit__'
...
>>> with MyTestWrapper() as s:
... print 'My Loop Logic'
...
I am in __enter__
My Loop Logic
I am in __exit__
</code></pre>
<p>Now in order to make it as iterator, you have to define <code>__iter__</code> function. With this, you can call it as an iterator. Updated code will be:</p>
<pre><code>>>> class MyIterator(object):
... def __init__(self, iterable):
... self.iterable = iterable
... self.need_to_end = False
... def __enter__(self):
... print 'I am in __enter__'
... return self
... def __exit__(self, type, value, traceback):
... self.loop_end()
... print 'I am in __exit__'
... def loop_start(self):
... self.need_to_end = True
... print 'Starting Loop . . . '
... def loop_end(self):
... self.need_to_end = False
... print 'Ending Loop . . . '
... def __iter__(self):
... for i in self.iterable:
... self.loop_start()
... yield i
... self.loop_end()
...
>>> with MyIterator([1,2,3, 4]) as my_iterator:
... for i in my_iterator:
... print 'I am: ', i
... if i == 2:
... break
...
I am in __enter__
Starting Loop . . .
I am: 1
Ending Loop . . .
Starting Loop . . .
I am: 2
Ending Loop . . .
I am in __exit__
</code></pre>
<p>Refer <a href="https://docs.python.org/2/reference/datamodel.html#context-managers" rel="nofollow">Python's Context Manager</a> for more information on these and other inbuilt functions.</p>
| 0 | 2016-08-24T23:44:21Z | [
"python",
"loops",
"iterator",
"generator",
"break"
] |
custom iterator or generator to execute closeout after break | 39,134,524 | <p>I'm implementing customized loop behavior, where I need things to happen on entering the loop, at every loop start, at every loop end, and on exiting the loop area. So far this is beautifully simple in Python (2.7):</p>
<pre><code>def my_for(loop_iterable):
enter_loop()
for i in loop_iterable:
loop_start()
yield i
loop_end()
exit_loop()
for i in my_for([1, 2, 3]):
print "i: ", i
if i == 2:
break
</code></pre>
<p>The problem I'm having is in getting <code>loop_end()</code> and <code>exit_loop()</code> to execute after the <code>break</code>. I have solved this by defining another function, which the user must put before break:</p>
<pre><code>def break_loop():
loop_end()
exit_loop()
for i in my_for([1, 2, 3]):
print "i: ", i
if i == 2:
break_loop()
break
</code></pre>
<p>But I would really like not to have the user have to remember to add that line. I think if I re-write the generator function as an iterator class, maybe there is a way to still execute code on a <code>break</code>?</p>
<p>Incidentally, <code>continue</code> works just fine as is!</p>
| 0 | 2016-08-24T23:34:17Z | 39,134,622 | <p>You could use a <a href="https://docs.python.org/2/reference/datamodel.html#context-managers" rel="nofollow">context manager</a>:</p>
<pre><code>class Looper(object):
def __init__(self, iterable):
self.iterable = iterable
self.need_to_end = False
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
self.exit_loop()
# Handle exceptions or swallow them by returning True
def enter_loop(self):
print 'enter_loop'
def loop_start(self):
self.need_to_end = True
print 'loop_start'
def loop_end(self):
self.need_to_end = False
print 'loop_end'
def exit_loop(self):
if self.need_to_end:
self.loop_end()
print 'exit_loop'
def __iter__(self):
self.enter_loop()
for i in self.iterable:
self.loop_start()
yield i
self.loop_end()
</code></pre>
<p>Your code would get a little longer, but you can deal with exceptions and other things more cleanly:</p>
<pre><code>with Looper([1, 2, 3, 4, 5, 6]) as loop:
for i in loop:
print i
if i == 2:
continue
elif i == 3:
break
</code></pre>
<p>It works as you'd expect:</p>
<pre><code>enter_loop
loop_start
1
loop_end
loop_start
2
loop_end
loop_start
3
loop_end
exit_loop
</code></pre>
| 0 | 2016-08-24T23:47:16Z | [
"python",
"loops",
"iterator",
"generator",
"break"
] |
Network model of document similarity | 39,134,571 | <p>Thanks in advance for your help. Briefly, I have been asked to help my organization in an accreditation process that repeats every 5 years. The document we need to compile is roughly 50 pages long (150 or so questions, total), so we would like to reuse as much of the content we produced in our last round as possible. </p>
<p><strong>The problem</strong>: The order and wording of the questions changed in this last round, but not completely (e.g., "Please describe your organization's commitment to diversity" vs. "What policies are in place to ensure organizational diversity?"). Thus, we need a way to find out which questions from the old round map onto the new round, or at least mostly (they don't need to be a perfect match, just similar).</p>
<p><strong>My thought</strong> was to establish a bipartite network, with old questions and new questions as the vertex sets of the network. Edges would be weighted by some measure of word overlap in their questions or answers. </p>
<p><strong><em>Does anyone know how to start to tackle this problem?</em></strong></p>
<p>Again, thank you, any help you offer will likely save hours of time.</p>
<p>PS - I am totally open to alternative solutions too. In case it helps, a picture of how I initially thought about modelling the problem is below.</p>
<p><a href="http://i613.photobucket.com/albums/tt220/iancero/Untitled%20drawing_zpst3ektl8j.png" rel="nofollow">an example solution</a></p>
| 0 | 2016-08-24T23:40:09Z | 39,135,049 | <p>Bit of an outline, but the overall steps for a quick solution are:
1. Convert your words to a format more suitable for machine processing with a tool like <a href="http://www.nltk.org/api/nltk.stem.html" rel="nofollow">http://www.nltk.org/api/nltk.stem.html</a>
2. Follow the steps outlined here to calculate the tf-idf similarity: <a href="http://stackoverflow.com/questions/8897593/similarity-between-two-text-documents">Similarity between two text documents</a>
3. Use np.argsort() to extract the most similar items.</p>
| 0 | 2016-08-25T00:45:55Z | [
"python",
"nlp",
"graph-theory",
"bipartite"
] |
Network model of document similarity | 39,134,571 | <p>Thanks in advance for your help. Briefly, I have been asked to help my organization in an accreditation process that repeats every 5 years. The document we need to compile is roughly 50 pages long (150 or so questions, total), so we would like to reuse as much of the content we produced in our last round as possible. </p>
<p><strong>The problem</strong>: The order and wording of the questions changed in this last round, but not completely (e.g., "Please describe your organization's commitment to diversity" vs. "What policies are in place to ensure organizational diversity?"). Thus, we need a way to find out which questions from the old round map onto the new round, or at least mostly (they don't need to be a perfect match, just similar).</p>
<p><strong>My thought</strong> was to establish a bipartite network, with old questions and new questions as the vertex sets of the network. Edges would be weighted by some measure of word overlap in their questions or answers. </p>
<p><strong><em>Does anyone know how to start to tackle this problem?</em></strong></p>
<p>Again, thank you, any help you offer will likely save hours of time.</p>
<p>PS - I am totally open to alternative solutions too. In case it helps, a picture of how I initially thought about modelling the problem is below.</p>
<p><a href="http://i613.photobucket.com/albums/tt220/iancero/Untitled%20drawing_zpst3ektl8j.png" rel="nofollow">an example solution</a></p>
| 0 | 2016-08-24T23:40:09Z | 39,155,334 | <p>First thought on my mind: For 50 pages of work, you might save more time by just doing it with a human.</p>
<p>But, if you have a good data scientist in your team, you can try gensim. The most recent technology of comparing two different phrases is word embedding. You can think of it as converting words to high-dimensional vectors (from 200 to 1000 dimensions) by training on millions of documents.</p>
<p>For example, if your string is "Human computer interaction", you would be looking for something like this.</p>
<pre><code>[(2, 0.99844527), # The EPS user interface management system
(0, 0.99809301), # Human machine interface for lab abc computer applications
(3, 0.9865886), # System and human system engineering testing of EPS
(1, 0.93748635), # A survey of user opinion of computer system response time
(4, 0.90755945), # Relation of user perceived response time to error measurement
(8, 0.050041795), # Graph minors A survey
(7, -0.098794639), # Graph minors IV Widths of trees and well quasi ordering
(6, -0.1063926), # The intersection graph of paths in trees
(5, -0.12416792)] # The generation of random binary unordered trees
</code></pre>
<p>from: <a href="https://radimrehurek.com/gensim/tut3.html" rel="nofollow">https://radimrehurek.com/gensim/tut3.html</a></p>
| 1 | 2016-08-25T21:54:58Z | [
"python",
"nlp",
"graph-theory",
"bipartite"
] |
How do I set the DJANGO_SETTINGS_MODULE env variable? | 39,134,580 | <p>I'm trying to fix a bug I'm seeing in a django application where it isn't sending mail. Please note that the application works great, it's only the mail function that is failing. I've tried to collect error logs, but I can't come up with any errors related to sending the mail. So, I made a example to try and force the errors. Here is the example:</p>
<pre><code>from django.core.mail import send_mail
send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False)
</code></pre>
<p>When I run the above code, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "dmail.py", line 14, in <module>
send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False)
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 59, in send_mail
fail_silently=fail_silently)
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 29, in get_connection
path = backend or settings.EMAIL_BACKEND
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/conf/__init__.py", line 39, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
</code></pre>
<p>I managed to fix my test example by changing the code to this:</p>
<pre><code>from django.core.mail import send_mail
from django.conf import settings
settings.configure(TEMPLATE_DIRS=('/path_to_project',), DEBUG=False, TEMPLATE_DEBUG=False)
send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False)
</code></pre>
<p>However, when I try to add those settings to send_mail.py, I'm still not getting any mail from my actual application. Can someone explain to me, clearly, how I setup the DJANGO_SETTINGS_MODULE so that both my example and my application can see it? Failing that, can someone tell me how to setup meaningful logging in django so I actually see mail related errors in the logs? Any tips or guidance would be greatly appreciated. </p>
| 1 | 2016-08-24T23:40:58Z | 39,134,595 | <p>Are you on Mac or Linux? Then simply <code>export DJANGO_SETTINGS_MODULE="project_name.settings.your_settings_file"</code>
Make sure that if your settings file is in a folder, that there is also an <code>__init__.py</code> file in there.</p>
<p>On windows, I believe the equivalent is <code>SET DJANGO_SETTINGS_MODULE="project_name.settings.your_settings_file</code>, but I could be mistaken.</p>
<p>For django logging, see <a href="https://docs.djangoproject.com/en/1.10/topics/logging/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/logging/</a></p>
| 0 | 2016-08-24T23:42:59Z | [
"python",
"django",
"python-2.7",
"email"
] |
How do I set the DJANGO_SETTINGS_MODULE env variable? | 39,134,580 | <p>I'm trying to fix a bug I'm seeing in a django application where it isn't sending mail. Please note that the application works great, it's only the mail function that is failing. I've tried to collect error logs, but I can't come up with any errors related to sending the mail. So, I made a example to try and force the errors. Here is the example:</p>
<pre><code>from django.core.mail import send_mail
send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False)
</code></pre>
<p>When I run the above code, I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "dmail.py", line 14, in <module>
send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False)
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 59, in send_mail
fail_silently=fail_silently)
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/core/mail/__init__.py", line 29, in get_connection
path = backend or settings.EMAIL_BACKEND
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/data/servers/calendar_1/lib/python2.7/site-packages/django/conf/__init__.py", line 39, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
</code></pre>
<p>I managed to fix my test example by changing the code to this:</p>
<pre><code>from django.core.mail import send_mail
from django.conf import settings
settings.configure(TEMPLATE_DIRS=('/path_to_project',), DEBUG=False, TEMPLATE_DEBUG=False)
send_mail('hi', 'hi', 'test@test.com', ['myname@yeah.com'], fail_silently=False)
</code></pre>
<p>However, when I try to add those settings to send_mail.py, I'm still not getting any mail from my actual application. Can someone explain to me, clearly, how I setup the DJANGO_SETTINGS_MODULE so that both my example and my application can see it? Failing that, can someone tell me how to setup meaningful logging in django so I actually see mail related errors in the logs? Any tips or guidance would be greatly appreciated. </p>
| 1 | 2016-08-24T23:40:58Z | 39,134,636 | <p>Do not set it from outside the application. Make a entry for <code>DJANGO_SETTINGS_MODULE</code> variable within your <code>wsgi</code> file. Everytime your server will be started, this variable will be set automatically.</p>
<p>For example:</p>
<pre><code>import os
os.environ['DJANGO_SETTINGS_MODULE'] = '<project_name>.settings'
</code></pre>
| 2 | 2016-08-24T23:48:51Z | [
"python",
"django",
"python-2.7",
"email"
] |
random colours in the spectrum | 39,134,696 | <p>Hi I am new to programming and I am writing a program that will ask the user to type in a colour. The program will then tell the user if that colour is a primary colour for paint, light, both or neither. </p>
<p>primary colours are red, blue and yellow</p>
<p>primary colours for light are red, blue and green.</p>
<p>This is my code so far:</p>
<pre><code>a = input("Enter Colour: ")
if 'Yellow' in a:
print('Yellow is a primary coulour for paint.')
elif 'Green' in a:
print('Green is a primary colour for light.')
elif 'blue' in a:
print('blue is a primary colour for light and paint.')
elif 'red' in a:
print('red is a primary colour for light and paint')
else:
print(a,'is not a primary colour.')
</code></pre>
<p>The problem I am having with this code is when I use different cases.
For example the input blue should give the same output as Blue or BLUe.</p>
<p>So I want the program to ignore the case.</p>
<p>Anything would help thanks.</p>
| 0 | 2016-08-24T23:56:32Z | 39,134,730 | <p>Try this:</p>
<pre><code>a = input("Enter Colour: ").lower()
if 'yellow' in a:
print('Yellow is a primary coulour for paint.')
elif 'green' in a:
print('Green is a primary colour for light.')
elif 'blue' in a:
print('blue is a primary colour for light and paint.')
elif 'red' in a:
print('red is a primary colour for light and paint')
else:
print(a,'is not a primary colour.')
</code></pre>
<p>By converting the input to lowercase, you can check for just the lowercase version of the colors.</p>
| 2 | 2016-08-24T23:59:30Z | [
"python"
] |
random colours in the spectrum | 39,134,696 | <p>Hi I am new to programming and I am writing a program that will ask the user to type in a colour. The program will then tell the user if that colour is a primary colour for paint, light, both or neither. </p>
<p>primary colours are red, blue and yellow</p>
<p>primary colours for light are red, blue and green.</p>
<p>This is my code so far:</p>
<pre><code>a = input("Enter Colour: ")
if 'Yellow' in a:
print('Yellow is a primary coulour for paint.')
elif 'Green' in a:
print('Green is a primary colour for light.')
elif 'blue' in a:
print('blue is a primary colour for light and paint.')
elif 'red' in a:
print('red is a primary colour for light and paint')
else:
print(a,'is not a primary colour.')
</code></pre>
<p>The problem I am having with this code is when I use different cases.
For example the input blue should give the same output as Blue or BLUe.</p>
<p>So I want the program to ignore the case.</p>
<p>Anything would help thanks.</p>
| 0 | 2016-08-24T23:56:32Z | 39,135,042 | <p>Try:</p>
<pre><code>a = input("Enter Colour: ").strip()
color = a.lower()
if color in ["red", "blue"]:
print(color, "is a primary colour for light and paint.")
elif color in ["yellow"]:
print("Yellow is a primary colour for paint.")
elif color in ["green"]:
print("Green is a primary colour for light.")
else:
print(a, "is not a primary colour.")
</code></pre>
| 1 | 2016-08-25T00:45:07Z | [
"python"
] |
how to add a package to sys path for testing | 39,134,718 | <p>This question is occasioned by instructions in the <a href="http://docs.python-guide.org/en/latest/writing/structure/" rel="nofollow">python guide</a> for adding a project to sys path to use in tests, which do not seem to work unless I am misunderstanding the instructions</p>
<p>I have a directory structure for a python project like this</p>
<pre><code>sample/a.py
sample/b.py
sample/c.py
sample/__init__.py
test/context.py
test/test_something.py
test/__init__.py
docs
</code></pre>
<p>According to <a href="http://docs.python-guide.org/en/latest/writing/structure/" rel="nofollow">the python guide</a>, I should create a test/context.py file and add this</p>
<pre><code>import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import sample
</code></pre>
<p>Then, in my <code>test/test_something.py</code> file, it says I can do this</p>
<pre><code>from .context import sample
</code></pre>
<p>The guide says "This will always work as expected".</p>
<p>but, when I <code>cd</code> into test and run</p>
<pre><code>python -m unittest test_something
</code></pre>
<p>I get an error</p>
<pre><code>ValueError: Attempted relative import in non-package
</code></pre>
<p>and the error message specifically refers to this: <code>from .context import sample</code></p>
<p>Question: How can I add my sample package to the sys path correctly? </p>
<p>When answering, can you also clarify if the solution will handle absolute imports within the sample package. For example, my sample.a imports sample.b etc. When I had my tests structured a different way, I did an absolute import of sample.a, but since it has a relative import of <code>from .b import Boo</code>, it produced a similar error</p>
<p>Update</p>
<pre><code>`File "/usr/local/lib/python2.7/runpy.py", line 162 in _run_module_as_main "__main__", fname, loader, pkg_name)
File "/usr/local/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals
File "/usr/local/lib/python2.7/unittest/__main__.py", line 12, in module main(module=None)
File "/usr/local/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv)
File "/usr/local/lib/python2.7/unittest/main.py", line 149 in parseArgs self.createTests()
File "/usr/local/lib/python2.7/unittest/main.py", line 158, in createTests self.module)
File "/usr/local/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames suites = [self.loadTestsFromName(name,module) for name in names]
File "/usr/local/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName module = __import__('-'.join(parts_copy))
File "test_something.py", line 8, in module from .context import sample
</code></pre>
<p>Update</p>
<p>if I run the following command from root directory</p>
<pre><code> python -m unittest test
</code></pre>
<p>It says , "Ran 0 tests in 0.000s"</p>
<p>If, as was suggested in the comments by @cuongnv, I run this from root directory</p>
<pre><code>python -m unittest test/test_something.py
</code></pre>
<p>or this (without the file extension)</p>
<pre><code>python -m unittest test/test_something
</code></pre>
<p>It says "Import by filename is not supported"</p>
| 0 | 2016-08-24T23:58:30Z | 39,134,755 | <p>Try adding an empty <code>__init__.py</code> to <code>tests/</code>: <code>touch tests/__init__.py</code> should do it.</p>
| 2 | 2016-08-25T00:03:12Z | [
"python"
] |
how to add a package to sys path for testing | 39,134,718 | <p>This question is occasioned by instructions in the <a href="http://docs.python-guide.org/en/latest/writing/structure/" rel="nofollow">python guide</a> for adding a project to sys path to use in tests, which do not seem to work unless I am misunderstanding the instructions</p>
<p>I have a directory structure for a python project like this</p>
<pre><code>sample/a.py
sample/b.py
sample/c.py
sample/__init__.py
test/context.py
test/test_something.py
test/__init__.py
docs
</code></pre>
<p>According to <a href="http://docs.python-guide.org/en/latest/writing/structure/" rel="nofollow">the python guide</a>, I should create a test/context.py file and add this</p>
<pre><code>import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import sample
</code></pre>
<p>Then, in my <code>test/test_something.py</code> file, it says I can do this</p>
<pre><code>from .context import sample
</code></pre>
<p>The guide says "This will always work as expected".</p>
<p>but, when I <code>cd</code> into test and run</p>
<pre><code>python -m unittest test_something
</code></pre>
<p>I get an error</p>
<pre><code>ValueError: Attempted relative import in non-package
</code></pre>
<p>and the error message specifically refers to this: <code>from .context import sample</code></p>
<p>Question: How can I add my sample package to the sys path correctly? </p>
<p>When answering, can you also clarify if the solution will handle absolute imports within the sample package. For example, my sample.a imports sample.b etc. When I had my tests structured a different way, I did an absolute import of sample.a, but since it has a relative import of <code>from .b import Boo</code>, it produced a similar error</p>
<p>Update</p>
<pre><code>`File "/usr/local/lib/python2.7/runpy.py", line 162 in _run_module_as_main "__main__", fname, loader, pkg_name)
File "/usr/local/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals
File "/usr/local/lib/python2.7/unittest/__main__.py", line 12, in module main(module=None)
File "/usr/local/lib/python2.7/unittest/main.py", line 94, in __init__ self.parseArgs(argv)
File "/usr/local/lib/python2.7/unittest/main.py", line 149 in parseArgs self.createTests()
File "/usr/local/lib/python2.7/unittest/main.py", line 158, in createTests self.module)
File "/usr/local/lib/python2.7/unittest/loader.py", line 130, in loadTestsFromNames suites = [self.loadTestsFromName(name,module) for name in names]
File "/usr/local/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName module = __import__('-'.join(parts_copy))
File "test_something.py", line 8, in module from .context import sample
</code></pre>
<p>Update</p>
<p>if I run the following command from root directory</p>
<pre><code> python -m unittest test
</code></pre>
<p>It says , "Ran 0 tests in 0.000s"</p>
<p>If, as was suggested in the comments by @cuongnv, I run this from root directory</p>
<pre><code>python -m unittest test/test_something.py
</code></pre>
<p>or this (without the file extension)</p>
<pre><code>python -m unittest test/test_something
</code></pre>
<p>It says "Import by filename is not supported"</p>
| 0 | 2016-08-24T23:58:30Z | 39,134,904 | <blockquote>
<p>Question: How can I add my sample package to the sys path correctly? </p>
</blockquote>
<p>You're doing it the right way, but you missed declaring your folder to be a package. Try solution of Christian, it should work.</p>
<p>Your path is stored in <code>sys.path</code>. By doing this:</p>
<pre><code>sys.path.insert(0, os.path.abspath('..'))
</code></pre>
<p>You're telling your python to add upper folder (of current file) into your path. As <code>sys.path</code> is a list, you can using other methods of list like <code>insert</code>, <code>append</code>... </p>
<p>In your case, you're inserting your upper dir at top of the path list.</p>
<p>See:</p>
<pre><code>In [1]: import sys
In [2]: sys.path
Out[2]:
['',
'/usr/local/bin',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/usr/lib/python3.4/lib-dynload',
'/usr/local/lib/python3.4/dist-packages',
'/usr/lib/python3/dist-packages',
'/usr/local/lib/python3.4/dist-packages/IPython/extensions',
'/home/cuong/.ipython']
In [3]: sys.path.insert(0, '/tmp/foo')
In [4]: sys.path
Out[4]:
['/tmp/foo', **<-- on top**
'',
'/usr/local/bin',
'/usr/lib/python3.4',
'/usr/lib/python3.4/plat-x86_64-linux-gnu',
'/usr/lib/python3.4/lib-dynload',
'/usr/local/lib/python3.4/dist-packages',
'/usr/lib/python3/dist-packages',
'/usr/local/lib/python3.4/dist-packages/IPython/extensions',
'/home/cuong/.ipython']
</code></pre>
<p>So, from here, when you have </p>
<pre><code>import sample
</code></pre>
<p>your python will try to look in path to see if there is any <code>sample</code> package. </p>
<p>Unfortunately, it can't find <code>sample</code> as you didn't make it as a package because your forgot <code>__init__.py</code> in <code>sample</code> folder.</p>
<p>Hope my explanation would help you to understand and you can handle other situations different to this.</p>
| 1 | 2016-08-25T00:23:13Z | [
"python"
] |
Missing u-strings on Python 3.2? | 39,134,742 | <p>I have a litany of unit tests that are run on Travis CI and <em>only</em> on PY3.2 it goes belly up. How can I solve this without using six.u()?</p>
<pre><code>def test_parse_utf8(self):
s = String("foo", 12, encoding="utf8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u"hello joh\u0503n")
======================================================================
ERROR: Failure: SyntaxError (invalid syntax (test_strings.py, line 37))
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/loader.py", line 414, in loadTestsFromName
addr.filename, addr.module)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/travis/build/construct/construct/tests/test_strings.py", line 37
self.assertEqual(s.build(u"hello joh\u0503n"), b"hello joh\xd4\x83n")
^
SyntaxError: invalid syntax
</code></pre>
<hr>
<p>Trying to get this to work:</p>
<pre><code>PY3 = sys.version_info[0] == 3
def u(s): return s if PY3 else s.decode("utf-8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u("hello joh\u0503n"))
</code></pre>
<hr>
<p>Quote from <a href="https://pythonhosted.org/six/" rel="nofollow">https://pythonhosted.org/six/</a></p>
<blockquote>
<p>On Python 2, u() doesnât know what the encoding of the literal is.
Each byte is converted directly to the unicode codepoint of the same
value. Because of this, itâs only safe to use u() with strings of
ASCII data.</p>
</blockquote>
<p>But the whole point of using unicode is to not be restricted to ASCII. </p>
| 1 | 2016-08-25T00:01:29Z | 39,135,072 | <p>Could you instead do <code>from __future__ import unicode_literals</code> and not use the <code>u</code> syntax anywhere?</p>
<p><code>from __future__ import unicode_literals</code> makes string literals without a preceding <code>u</code> in earlier versions of Python act as in Python 3, that is default to unicode. So if you do <code>from __future__ import unicode_literals</code> and change all <code>u"strings"</code> to <code>"strings"</code>, your string literals will be unicode in all versions. This will not affect <code>b</code> literals.</p>
| 0 | 2016-08-25T00:49:25Z | [
"python",
"unicode",
"travis-ci",
"nose",
"six"
] |
Missing u-strings on Python 3.2? | 39,134,742 | <p>I have a litany of unit tests that are run on Travis CI and <em>only</em> on PY3.2 it goes belly up. How can I solve this without using six.u()?</p>
<pre><code>def test_parse_utf8(self):
s = String("foo", 12, encoding="utf8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u"hello joh\u0503n")
======================================================================
ERROR: Failure: SyntaxError (invalid syntax (test_strings.py, line 37))
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/loader.py", line 414, in loadTestsFromName
addr.filename, addr.module)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/travis/build/construct/construct/tests/test_strings.py", line 37
self.assertEqual(s.build(u"hello joh\u0503n"), b"hello joh\xd4\x83n")
^
SyntaxError: invalid syntax
</code></pre>
<hr>
<p>Trying to get this to work:</p>
<pre><code>PY3 = sys.version_info[0] == 3
def u(s): return s if PY3 else s.decode("utf-8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u("hello joh\u0503n"))
</code></pre>
<hr>
<p>Quote from <a href="https://pythonhosted.org/six/" rel="nofollow">https://pythonhosted.org/six/</a></p>
<blockquote>
<p>On Python 2, u() doesnât know what the encoding of the literal is.
Each byte is converted directly to the unicode codepoint of the same
value. Because of this, itâs only safe to use u() with strings of
ASCII data.</p>
</blockquote>
<p>But the whole point of using unicode is to not be restricted to ASCII. </p>
| 1 | 2016-08-25T00:01:29Z | 39,135,416 | <p>I think you're out of luck here.</p>
<p>Either use <code>six.u()</code> or drop support for Python 3.2.</p>
| 1 | 2016-08-25T01:39:24Z | [
"python",
"unicode",
"travis-ci",
"nose",
"six"
] |
Missing u-strings on Python 3.2? | 39,134,742 | <p>I have a litany of unit tests that are run on Travis CI and <em>only</em> on PY3.2 it goes belly up. How can I solve this without using six.u()?</p>
<pre><code>def test_parse_utf8(self):
s = String("foo", 12, encoding="utf8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u"hello joh\u0503n")
======================================================================
ERROR: Failure: SyntaxError (invalid syntax (test_strings.py, line 37))
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/failure.py", line 39, in runTest
raise self.exc_val.with_traceback(self.tb)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/loader.py", line 414, in loadTestsFromName
addr.filename, addr.module)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 47, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 94, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/home/travis/build/construct/construct/tests/test_strings.py", line 37
self.assertEqual(s.build(u"hello joh\u0503n"), b"hello joh\xd4\x83n")
^
SyntaxError: invalid syntax
</code></pre>
<hr>
<p>Trying to get this to work:</p>
<pre><code>PY3 = sys.version_info[0] == 3
def u(s): return s if PY3 else s.decode("utf-8")
self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u("hello joh\u0503n"))
</code></pre>
<hr>
<p>Quote from <a href="https://pythonhosted.org/six/" rel="nofollow">https://pythonhosted.org/six/</a></p>
<blockquote>
<p>On Python 2, u() doesnât know what the encoding of the literal is.
Each byte is converted directly to the unicode codepoint of the same
value. Because of this, itâs only safe to use u() with strings of
ASCII data.</p>
</blockquote>
<p>But the whole point of using unicode is to not be restricted to ASCII. </p>
| 1 | 2016-08-25T00:01:29Z | 39,145,308 | <p>I taken the implementation of <code>six.u()</code> and discarded <code>six</code>.</p>
<pre><code>import sys
PY3 = sys.version_info[0] == 3
def u(s): return s if PY3 else unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
</code></pre>
| 0 | 2016-08-25T12:27:08Z | [
"python",
"unicode",
"travis-ci",
"nose",
"six"
] |
Python matplotlib divide scatterplot into categories based on slope | 39,134,747 | <p>I have a list of x and a list of y values. I'd like to construct a scatterplot in Matplotlib and divide the dots into five categories based on their x and y coordinates, like in the image below:</p>
<p><a href="http://i.stack.imgur.com/unof7.png" rel="nofollow"><img src="http://i.stack.imgur.com/unof7.png" alt="enter image description here"></a></p>
<pre><code>angles = [0, 18, 36, 54, 72, 90]
colors = ['r','g','b','c']
x = [....]
y = [....]
</code></pre>
<p>All of the points in the divided category will be the same color. It would also be great to have a legend for the categories. I am new to Matplotlib and Python, does anyone know how I can approach this?</p>
| 0 | 2016-08-25T00:02:05Z | 39,134,988 | <p>Here's a working example which will give you a little idea to get started:</p>
<pre><code>from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
import math
import random
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
w, h = 7, 5
a = [[random.random() * w, random.random() * h] for i in range(100)]
plt.plot(*zip(*a), marker='o', color='r', ls='')
for deg in [18, 36, 54]:
r = 10
line = Line2D([0, r * math.cos(math.radians(deg))],
[0, r * math.sin(math.radians(deg))],
linewidth=1, linestyle="-", color="green")
ax.add_line(line)
ax.set_xlim(0, w)
ax.set_ylim(0, h)
plt.legend()
plt.show()
</code></pre>
| 1 | 2016-08-25T00:36:21Z | [
"python",
"matplotlib"
] |
PyQt: How to get the item at a specific position in a TreeWidget? | 39,134,775 | <p>How do I get the item at a specific position (the first, the last, or any given position) of a TreeWidget? I am interested only on items at the parent level, so that I can programmatically select an item at that position.</p>
<p>I searched for more than an hour without finding any clear example.</p>
<p>Thanks in advance!</p>
| 0 | 2016-08-25T00:06:03Z | 39,134,929 | <p>Did you actually looked in <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qtreewidget.html#itemAt" rel="nofollow">docs</a> ?, you can probably look in to itemAt or itemFromIndex</p>
| 1 | 2016-08-25T00:28:04Z | [
"python",
"pyqt"
] |
Inheritance of class attributes? | 39,134,847 | <p>Can someone provides a detail explanation why this is happening? How does Python compiler create class variables in this case?</p>
<pre><code>class A(object):
x = 1
y = x + 1
class B(A):
x = 10
>>> B.x
10
>>> B.y
2 # ---> I was expecting 11 here, why does this y still uses the A's value?
</code></pre>
| 1 | 2016-08-25T00:15:50Z | 39,134,891 | <p>It does not do that.</p>
<pre><code>>>> class A(object):
... x = 1
... y = x + 1
...
>>> class B(object):
... x = 10
...
>>> B.x
10
>>> B.y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'B' has no attribute 'y'
</code></pre>
| -1 | 2016-08-25T00:21:12Z | [
"python",
"inheritance"
] |
Inheritance of class attributes? | 39,134,847 | <p>Can someone provides a detail explanation why this is happening? How does Python compiler create class variables in this case?</p>
<pre><code>class A(object):
x = 1
y = x + 1
class B(A):
x = 10
>>> B.x
10
>>> B.y
2 # ---> I was expecting 11 here, why does this y still uses the A's value?
</code></pre>
| 1 | 2016-08-25T00:15:50Z | 39,134,892 | <p>Because class variables are evaluated at the same time the class itself is evaluated. Here the sequence of events is: <code>A</code> is defined and the values in it are set, so <code>x</code> is 1 and <code>y</code> is 2. Then <code>B</code> is defined, and the <code>x</code> entry in <code>B</code> is set to 10. Then you access <code>B.y</code>, and since there is no <code>y</code> entry in <code>B</code>, it checks its parent class. It does find a <code>y</code> entry in <code>A</code>, with a value of <code>2</code>. <code>y</code> is defined only once.</p>
<p>If you really want such a variable, you may want to define a class method.</p>
<pre><code>class A:
x = 1
@classmethod
def y(cls):
return cls.x + 1
class B(A):
x = 10
>>> B.y()
11
</code></pre>
| 5 | 2016-08-25T00:21:23Z | [
"python",
"inheritance"
] |
Inheritance of class attributes? | 39,134,847 | <p>Can someone provides a detail explanation why this is happening? How does Python compiler create class variables in this case?</p>
<pre><code>class A(object):
x = 1
y = x + 1
class B(A):
x = 10
>>> B.x
10
>>> B.y
2 # ---> I was expecting 11 here, why does this y still uses the A's value?
</code></pre>
| 1 | 2016-08-25T00:15:50Z | 39,134,902 | <p>This is because <code>y</code> is a class attribute that belongs to A, so changing the value of x in a class instance of <code>B</code> does not change the value of <code>y</code>. You can read more about that in the documentation: <a href="https://docs.python.org/2/tutorial/classes.html#class-objects" rel="nofollow">https://docs.python.org/2/tutorial/classes.html#class-objects</a></p>
| 1 | 2016-08-25T00:22:49Z | [
"python",
"inheritance"
] |
Finding neighbours for a an element of an array and making sure it has <4 of them | 39,134,888 | <p>I have an array of atomic coordinates ( a diamond lattice)
That looks like this:</p>
<pre><code> [[0.0, 0.0, 0.0],
[0.0, 0.5, 0.5],
[0.5, 0.0, 0.5],
[0.5, 0.5, 0.0],
[0.25, 0.25, 0.25],
[0.25, 0.75, 0.75],
[0.75, 0.25, 0.75],
[0.75, 0.75, 0.25]]
</code></pre>
<p>Every atom has an id.
I need to create a bond list, which is essential a neighbour list of atoms that a given atom is connected to.
All interior atoms have to have 4 neighbours (bonds). All surface atoms <strong>can't</strong> have more than 4 neighbours(bonds).</p>
<p>I know how to do it for the interior atoms:
Using kdTree which is fast and works well. </p>
<pre><code>kdtree = scipy.spatial.KDTree(Atom_xyz[:,])
Neighs = kdtree.query_pairs(RCUT=1.0)
Neighs = list(Neighs)
</code></pre>
<p>However it doesn't work for the surface atoms since it doesn't work with periodic images and I need to make sure I have no more than 4 neighbours.
I was wondering if you guys can help me with an algorithm for that.</p>
<p>Here I attach an image of my lattice, where the atoms are visualized as cyan and the bonds are the curvy white.</p>
<p>Diamond lattice where only the interior atoms are bonded:</p>
<p><a href="http://i.stack.imgur.com/vAjZ6.png" rel="nofollow"><img src="http://i.stack.imgur.com/vAjZ6.png" alt="Diamond lattice where only the interior atoms are bonded"></a></p>
| 0 | 2016-08-25T00:20:59Z | 39,141,866 | <p>I just took some four neighbors:</p>
<p><strong>Note:</strong> the interior atoms may have pathological cases where there are no four neighbors by the Voronoi diagram) </p>
<p>(I used <a href="http://docs.enthought.com/mayavi/mayavi/auto/example_chemistry.html" rel="nofollow">http://docs.enthought.com/mayavi/mayavi/auto/example_chemistry.html</a>)</p>
<pre><code>import numpy as np
import scipy.spatial as ssp
from mayavi import mlab
atoms = np.array(
[[0.0, 0.0, 0.0],
[0.0, 0.5, 0.5],
[0.5, 0.0, 0.5],
[0.5, 0.5, 0.0],
[0.25, 0.25, 0.25],
[0.25, 0.75, 0.75],
[0.75, 0.25, 0.75],
[0.75, 0.75, 0.25]])
vor = ssp.Voronoi(atoms)
mlab.figure(1, bgcolor=(0, 0, 0), size=(350, 350))
mlab.clf()
# The position of the atoms
atoms_ridge_x = atoms[vor.ridge_points, 0]
atoms_ridge_y = atoms[vor.ridge_points, 1]
atoms_ridge_z = atoms[vor.ridge_points, 2]
tot_uniq = set()
atoms_count = np.zeros(atoms.shape[0], dtype=int)
for i in range(atoms.shape[0]):
uniq = [j for j, x in enumerate(vor.ridge_points) if i in x]
uniq = [x for x in uniq if x not in tot_uniq]
tot_uniq.update(uniq)
for k in uniq:
if atoms_count[i] >= 4:
continue
mlab.plot3d(atoms_ridge_x[k, :], atoms_ridge_y[k, :], atoms_ridge_z[k, :],
tube_radius=0.05, colormap='Reds')
atoms_count[vor.ridge_points[k]] += 1
H2 = mlab.points3d(atoms[:, 0], atoms[:, 1], atoms[:, 2],
scale_factor=0.2,
resolution=20,
color=(1, 0, 0),
scale_mode='none')
mlab.show()
</code></pre>
| 0 | 2016-08-25T09:45:49Z | [
"python",
"numpy",
"scipy",
"simulation",
"kdtree"
] |
urllib2.Request 404 exception | 39,134,898 | <p>Okay so I'm having an issue with 404, if my request reaches a 404 it throws an exception error.. rather than return 0 & continue with list</p>
<p>Code is here <a href="http://pastebin.com/48tspcEc" rel="nofollow">http://pastebin.com/48tspcEc</a></p>
| 0 | 2016-08-25T00:22:29Z | 39,135,064 | <p>I think you indented correctly since python does not acquire a two spaced or four spaced indentation.
You should better post the detail of exception error in your question to analyze your problem.</p>
| 0 | 2016-08-25T00:48:55Z | [
"python",
"request",
"http-status-code-404"
] |
accuracy of float32 | 39,134,956 | <p>To reduce the filesize, I'm trying to save <code>float64</code> data to file in <code>float32</code>. The data values generally range from 1e-12 to 10. I tested the accuracy loss when converting <code>float64</code> to <code>float32</code>.</p>
<pre><code>print np.finfo('float32')
</code></pre>
<p>shows</p>
<pre><code>Machine parameters for float32
---------------------------------------------------------------
precision= 6 resolution= 1.0000000e-06
machep= -23 eps= 1.1920929e-07
negep = -24 epsneg= 5.9604645e-08
minexp= -126 tiny= 1.1754944e-38
maxexp= 128 max= 3.4028235e+38
nexp = 8 min= -max
---------------------------------------------------------------
</code></pre>
<p>Looks <code>float32</code> has a resolution of <code>1e-6</code> and the abs value is valid down to as small as <code>1.2e-38</code>.</p>
<pre><code>import numpy as np
x = 2.0*np.random.rand(100) - 1.0 # make random numbers in [-1, 1]
print('x.dtype: %s'%(x.dtype)) # outputs float64
print('number : max_error max_relative_error')
for i in xrange(-40, 1):
y = x * 10**i
print('1e%-4d: %s'%(i, np.max(np.abs(y - y.astype('f4').astype('f8')))))
</code></pre>
<p>The results are </p>
<pre><code>number: max_error max_relative_error
1e-40 : 6.915620e-46 6.915620e-06
1e-39 : 6.910361e-46 6.910361e-07
1e-38 : 6.949349e-46 6.949349e-08
1e-37 : 4.816590e-45 4.816590e-08
1e-36 : 4.303771e-44 4.303771e-08
1e-35 : 3.518621e-43 3.518621e-08
1e-34 : 5.165854e-42 5.165854e-08
1e-33 : 3.660088e-41 3.660088e-08
1e-32 : 3.660088e-40 3.660088e-08
1e-31 : 4.097193e-39 4.097193e-08
1e-30 : 4.615068e-38 4.615068e-08
1e-29 : 3.696983e-37 3.696983e-08
1e-28 : 2.999860e-36 2.999860e-08
1e-27 : 4.723454e-35 4.723454e-08
1e-26 : 3.801082e-34 3.801082e-08
1e-25 : 3.062408e-33 3.062408e-08
1e-24 : 4.876378e-32 4.876378e-08
1e-23 : 3.779378e-31 3.779378e-08
1e-22 : 3.144592e-30 3.144592e-08
1e-21 : 4.991049e-29 4.991049e-08
1e-20 : 3.949261e-28 3.949261e-08
1e-19 : 3.002761e-27 3.002761e-08
1e-18 : 5.162480e-26 5.162480e-08
1e-17 : 4.135703e-25 4.135703e-08
1e-16 : 3.282146e-24 3.282146e-08
1e-15 : 4.722129e-23 4.722129e-08
1e-14 : 3.863295e-22 3.863295e-08
1e-13 : 3.375549e-21 3.375549e-08
1e-12 : 4.011790e-20 4.011790e-08
1e-11 : 4.011790e-19 4.011790e-08
1e-10 : 3.392060e-18 3.392060e-08
1e-9 : 5.471206e-17 5.471206e-08
1e-8 : 4.072652e-16 4.072652e-08
1e-7 : 3.496987e-15 3.496987e-08
1e-6 : 5.662626e-14 5.662626e-08
1e-5 : 4.412957e-13 4.412957e-08
1e-4 : 3.482083e-12 3.482083e-08
1e-3 : 5.597344e-11 5.597344e-08
1e-2 : 4.620014e-10 4.620014e-08
1e-1 : 3.540690e-09 3.540690e-08
1e0 : 2.817751e-08 2.817751e-08
</code></pre>
<p>The relative error is at the order of <code>1e-8</code> for values above 1e-38, lower than <code>1e-6</code> proposed by <code>np.finfo</code> and the error is still acceptable even if the value if lower than the <code>tiny</code> value of <code>np.finfo</code>.</p>
<p>Looks it's safe to save my data in <code>float32</code>, but I'm curious about the test looks inconsistent with the results of <code>np.finfo</code>? </p>
| 2 | 2016-08-25T00:31:55Z | 39,135,004 | <p>Numbers that low are in the subnormal range. Basically, the exponent doesn't have enough range to get sufficiently low, so you're gradually losing significant bits as values get lower. This is called "gradual underflow".</p>
<p><a href="https://en.wikipedia.org/wiki/Denormal_number" rel="nofollow">https://en.wikipedia.org/wiki/Denormal_number</a></p>
| 4 | 2016-08-25T00:39:55Z | [
"python",
"numpy",
"floating-point",
"floating-accuracy"
] |
accuracy of float32 | 39,134,956 | <p>To reduce the filesize, I'm trying to save <code>float64</code> data to file in <code>float32</code>. The data values generally range from 1e-12 to 10. I tested the accuracy loss when converting <code>float64</code> to <code>float32</code>.</p>
<pre><code>print np.finfo('float32')
</code></pre>
<p>shows</p>
<pre><code>Machine parameters for float32
---------------------------------------------------------------
precision= 6 resolution= 1.0000000e-06
machep= -23 eps= 1.1920929e-07
negep = -24 epsneg= 5.9604645e-08
minexp= -126 tiny= 1.1754944e-38
maxexp= 128 max= 3.4028235e+38
nexp = 8 min= -max
---------------------------------------------------------------
</code></pre>
<p>Looks <code>float32</code> has a resolution of <code>1e-6</code> and the abs value is valid down to as small as <code>1.2e-38</code>.</p>
<pre><code>import numpy as np
x = 2.0*np.random.rand(100) - 1.0 # make random numbers in [-1, 1]
print('x.dtype: %s'%(x.dtype)) # outputs float64
print('number : max_error max_relative_error')
for i in xrange(-40, 1):
y = x * 10**i
print('1e%-4d: %s'%(i, np.max(np.abs(y - y.astype('f4').astype('f8')))))
</code></pre>
<p>The results are </p>
<pre><code>number: max_error max_relative_error
1e-40 : 6.915620e-46 6.915620e-06
1e-39 : 6.910361e-46 6.910361e-07
1e-38 : 6.949349e-46 6.949349e-08
1e-37 : 4.816590e-45 4.816590e-08
1e-36 : 4.303771e-44 4.303771e-08
1e-35 : 3.518621e-43 3.518621e-08
1e-34 : 5.165854e-42 5.165854e-08
1e-33 : 3.660088e-41 3.660088e-08
1e-32 : 3.660088e-40 3.660088e-08
1e-31 : 4.097193e-39 4.097193e-08
1e-30 : 4.615068e-38 4.615068e-08
1e-29 : 3.696983e-37 3.696983e-08
1e-28 : 2.999860e-36 2.999860e-08
1e-27 : 4.723454e-35 4.723454e-08
1e-26 : 3.801082e-34 3.801082e-08
1e-25 : 3.062408e-33 3.062408e-08
1e-24 : 4.876378e-32 4.876378e-08
1e-23 : 3.779378e-31 3.779378e-08
1e-22 : 3.144592e-30 3.144592e-08
1e-21 : 4.991049e-29 4.991049e-08
1e-20 : 3.949261e-28 3.949261e-08
1e-19 : 3.002761e-27 3.002761e-08
1e-18 : 5.162480e-26 5.162480e-08
1e-17 : 4.135703e-25 4.135703e-08
1e-16 : 3.282146e-24 3.282146e-08
1e-15 : 4.722129e-23 4.722129e-08
1e-14 : 3.863295e-22 3.863295e-08
1e-13 : 3.375549e-21 3.375549e-08
1e-12 : 4.011790e-20 4.011790e-08
1e-11 : 4.011790e-19 4.011790e-08
1e-10 : 3.392060e-18 3.392060e-08
1e-9 : 5.471206e-17 5.471206e-08
1e-8 : 4.072652e-16 4.072652e-08
1e-7 : 3.496987e-15 3.496987e-08
1e-6 : 5.662626e-14 5.662626e-08
1e-5 : 4.412957e-13 4.412957e-08
1e-4 : 3.482083e-12 3.482083e-08
1e-3 : 5.597344e-11 5.597344e-08
1e-2 : 4.620014e-10 4.620014e-08
1e-1 : 3.540690e-09 3.540690e-08
1e0 : 2.817751e-08 2.817751e-08
</code></pre>
<p>The relative error is at the order of <code>1e-8</code> for values above 1e-38, lower than <code>1e-6</code> proposed by <code>np.finfo</code> and the error is still acceptable even if the value if lower than the <code>tiny</code> value of <code>np.finfo</code>.</p>
<p>Looks it's safe to save my data in <code>float32</code>, but I'm curious about the test looks inconsistent with the results of <code>np.finfo</code>? </p>
| 2 | 2016-08-25T00:31:55Z | 39,155,754 | <p>Since machine floating point epsilon is 1.1920929e-07, rounding would get you relative error within half of that for normal floats: 5.9604645e-8. However, when you get smaller than 1.1754944e-38, you have denormalized numbers, which instead have an absolute error of 1.4012985e-45.</p>
| 1 | 2016-08-25T22:32:30Z | [
"python",
"numpy",
"floating-point",
"floating-accuracy"
] |
Scheduled scripts stopped logging correctly...don't understand cause | 39,135,010 | <p>I have a few python scripts that I run with Task Scheduler (Windows 10) everyday. When the scripts run I have a few print lines that I like to view in the command prompt to see some information regarding the script as it runs.</p>
<p>I actually had the scripts printing out until recently when I changed the directory path.</p>
<p>I have "<strong>Run whether user is logged on or not</strong>" chosen, along with "<strong>Run with highest privileges</strong>". I also haven chosen "<strong>Configure for: Windows 10</strong>"</p>
<p>For Program/script: <code>C:\Python27\python.exe</code></p>
<p>Add arguments: </p>
<pre><code>C:\Users\Justin\Desktop\Quant\chron_scripts\obtainPriceData.py >> log.txt
</code></pre>
<p>I previously had the script in the following directory:</p>
<pre><code>C:\Users\Justin\Desktop\Quant\obtainPriceData.py >> log.txt
</code></pre>
<p>This worked fine. It is only when I added the chron_scripts directory that nothing gets logged on the command prompt. Any suggestions would be much apperciated, and thanks for your time!</p>
| 0 | 2016-08-25T00:40:20Z | 39,135,018 | <p>Probably your log file is in other directories such as the working directory. Maybe try to specify the location of log.txt can solve your problem</p>
| 0 | 2016-08-25T00:42:58Z | [
"python",
"python-2.7",
"logging",
"scheduled-tasks",
"windows-10"
] |
TensorFlow tf.sparse_tensor_dense_matmul | 39,135,024 | <p>I run a small experiment to benchmark the tf.sparse_tensor_dense_matmul operation. Unfortunately, I am surprised by the result.</p>
<p>I am running a sparse matrix, dense vector multiplication, and vary</p>
<ul>
<li>the number of columns of the sparse matrix (decreasing)</li>
<li>the number of rows of the dense vector (decreasing)</li>
<li>the sparsity of the sparse matrix (increasing)</li>
</ul>
<p>While increasing the sparsisy for each run, I decrease the columns. This means that the number of non-zero values (nnz) stays always the same (100 per row).</p>
<p>When measuring the time needed for computing the matml operation, I would expect, that it will stay the same (since the output size nor the nnz varies).</p>
<p>What I see instead is the following:
<a href="http://i.stack.imgur.com/zlw6q.png" rel="nofollow"><img src="http://i.stack.imgur.com/zlw6q.png" alt="enter image description here"></a></p>
<p>I looked into the C++ code to see if I can spot any reasons for the result. Though, also taking the C++ code into account I would expect the same time for each run. If I understand the code right, it loops through all nnz values of the sparse matrix (<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/sparse_tensor_dense_matmul_op.cc#L239" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/sparse_tensor_dense_matmul_op.cc#L239</a>). For each nnz value it loops through all columns of the second dense matrix (in my case it is only one column since it is a vector) (<a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/sparse_tensor_dense_matmul_op.cc#L245" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/sparse_tensor_dense_matmul_op.cc#L245</a>).</p>
<p>The only point where I could imagine that the number of rows of the second matrix/vector effects the performance is <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/sparse_tensor_dense_matmul_op.cc#L246" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/kernels/sparse_tensor_dense_matmul_op.cc#L246</a> if it loops through all the rows of the second matrix/vector insight the "maybe_adjoint_b" function to get to the currently needed row. </p>
<p>[What disturbs me about the "maybe_adjoint_b" call is, that it gets called with the variable "k" passed over as the row index. Though, I thought "m" would be the row index and "k" the column index of the sparse matrix.]</p>
<p><strong>Question:</strong> Why do I get different execution times for the matmul operation, even though the nnz and the output sizes are always the same? </p>
| 2 | 2016-08-25T00:43:29Z | 39,933,514 | <p>I actually think that it is not an issue of TensorFlow but instead the 8MB input of the input vector in the first case does not fit into the L2 memory. In all the other cases the vector is <= 800kb and fits into the L2 memory.</p>
| 0 | 2016-10-08T14:23:33Z | [
"python",
"c++",
"matrix",
"tensorflow"
] |
ActiveMQ prebvents new subscribers from getting frames, once there are frames | 39,135,055 | <p>I have tried this with several libs and languages (php5|php7|Stomp extension|ZF1 Stomp| Python2.7 Stomp package).<br>
What I found out is that if there is a subscriber to a queue, and it start to get messages (frames) from the queue, any new subscriber during that time will not be getting any of the messages. </p>
<p>My question:<br>
Is there a way to create a new subscriber to a queue that currenty have messages in it + an existing subscriber, and that the new subscriber will receive those messages.<br>
I do not send the Exclusive subscriber headers.<br>
If I had two subscriber prior to getting the messages, both will participate.</p>
| 0 | 2016-08-25T00:47:09Z | 39,135,739 | <p>You are most likely running into issues with prefetching where the first client has prefetched all the messages and is churning through them while the second gets none as a result. To tackle this you should configure the clients with a small prefetch value such as 1 using the values given in the <a href="http://activemq.apache.org/stomp.html" rel="nofollow">ActiveMQ STOMP guide</a>. The client needs to add header activemq.prefetchSize:1 or the like. </p>
<p>You could also set the client subscription to use client acknowledgement mode which will allow you to control when the message is considered handled and prevent the broker from dispatching more messages. </p>
| 0 | 2016-08-25T02:19:26Z | [
"php",
"python",
"queue",
"activemq",
"stomp"
] |
Negation Marking with Regular Expressions in Python | 39,135,065 | <p>I'm struggling to implement negation marking using regex in Python, a la Christopher Potts' <a href="http://sentiment.christopherpotts.net/lingstruc.html#fig:tokenizer_accuracy_neg" rel="nofollow">sentiment analysis tutorial</a>.</p>
<p>The definition of a negation, taken from his tutorial is:</p>
<pre><code>(?:
^(?:never|no|nothing|nowhere|noone|none|not|
havent|hasnt|hadnt|cant|couldnt|shouldnt|
wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint
)$
)
|
n't
</code></pre>
<p>and the definition of clause-level punctuation is:</p>
<pre><code>^[.:;!?]$
</code></pre>
<p>The idea is to capture words between a negation and clause-level punctuation and then to modify them to indicate that they are being negated, eg:</p>
<pre><code>No one enjoys it.
</code></pre>
<p>should become something like:</p>
<pre><code>No one_NEG enjoys_NEG it_NEG.
</code></pre>
<p>Any suggestions would be appreciated.</p>
| -1 | 2016-08-25T00:48:58Z | 39,135,217 | <p>If you have a sentence as a string, as you imply, then you can't use '^' and '$' in your regexps. Use <code>\b</code> instead. Then this should work:</p>
<pre><code>def add_negation_markers(m):
return m.group(1) + re.sub(r'(?<=\w)\b', '_NEG', m.group(2))
re.sub('(' + neg_re + ')(.*)(?=' + punct_re + ')', add_negation_markers, text)
</code></pre>
<p>If you have a sentence as a list of words, as <code>$</code> and <code>^</code> marks imply, then...</p>
<pre><code>def negate(word):
if re.search(punct_re, word):
negate.should = False
elif re.search(neg_re, word):
negate.should = True
elif negate.should:
return word + '_NEG'
return word
negate.should = False
map(negate, words)
</code></pre>
| 0 | 2016-08-25T01:10:28Z | [
"python",
"regex",
"nlp"
] |
How to extract username and public key from a website using xpath? | 39,135,093 | <p>For my thesis work I am gathering data from bitcointalk.org about the users and their bitcoin public keys which they give at the end of each post they write(for donations and tips).</p>
<pre><code><td valign="top" width="16%" rowspan="2" style="overflow: hidden;" class="poster_info">
<b><a href="https://bitcointalk.org/index.php?action=profile;u=2786" title="View the profile of Pieter Wuille">Pieter Wuille</a></b>
</code></pre>
<p>I am trying to extract the username value from the above syntax using xpath and also the value of public key for the user from the signature field from the below syntax </p>
<pre><code><div class="signature sig2786">aka sipa, core dev team<br /><br />Tips and donations: 1KwDYMJMS4xq3ZEWYfdBRwYG2fHwhZsipa</div>
</code></pre>
<p>My code to extract the items is given below</p>
<pre><code>site.xpath('.//td[@class="poster_info"]/b/a/text()').extract()
site.xpath('.//div[contains(@class, "signature")]/text()').re(r'(1[1-9A-HJ- NP-Za-km-z]{26,33})')
</code></pre>
<p>The code works fine but what it does is that it extracts all the usernames and all the bitcoin keys that (the user gave at the end of the post for donation) on a page and there is no way to associate the key to a user since they are extracted separately what I want to do is extract the information in a pair so that I could omit the users who have not specified their public keys(for donation) in their post. Can anyone help me? I am kind of stuck </p>
| 0 | 2016-08-25T00:53:16Z | 39,183,196 | <p>So from what you've described in the comments you want to do is find users in the forum thread got to each of their profiles and if they have a bitcoin address in their profiles scrape the address and their usersname, right? This is the spider that pretty much does that:</p>
<pre><code> class BitcointalkSpider(scrapy.Spider):
name = "bitcointalk"
allowed_domains = ["bitcointalk.org"]
start_urls = (
'http://www.https://bitcointalk.org/index.php?topic=1474398.0/',
)
def parse(self, response):
# find profile urls
profiles = response.xpath("//a[contains(@title,'View the profile')]/@href").extract()
profiles = list(set(profiles)) # only unique values
# scrape every one of them individually
for pro in profiles:
yield scrapy.Request(pro, self.parse_profile)
def parse_profile(self, response):
bitcoin = response.xpath("//td[contains(.//text(),'Bitcoin address')]"
"/following-sibling::td/text()").extract_first()
if not bitcoin: # no bitcoin, drop user
return
item = dict()
item['bitcoin_address'] = bitcoin
item['username'] = response.xpath("//td[contains(.//text(),'Name')]"
"/following-sibling::td/text()").extract_first()
return item
</code></pre>
| 0 | 2016-08-27T16:15:30Z | [
"python",
"xpath",
"scrapy"
] |
How to extract username and public key from a website using xpath? | 39,135,093 | <p>For my thesis work I am gathering data from bitcointalk.org about the users and their bitcoin public keys which they give at the end of each post they write(for donations and tips).</p>
<pre><code><td valign="top" width="16%" rowspan="2" style="overflow: hidden;" class="poster_info">
<b><a href="https://bitcointalk.org/index.php?action=profile;u=2786" title="View the profile of Pieter Wuille">Pieter Wuille</a></b>
</code></pre>
<p>I am trying to extract the username value from the above syntax using xpath and also the value of public key for the user from the signature field from the below syntax </p>
<pre><code><div class="signature sig2786">aka sipa, core dev team<br /><br />Tips and donations: 1KwDYMJMS4xq3ZEWYfdBRwYG2fHwhZsipa</div>
</code></pre>
<p>My code to extract the items is given below</p>
<pre><code>site.xpath('.//td[@class="poster_info"]/b/a/text()').extract()
site.xpath('.//div[contains(@class, "signature")]/text()').re(r'(1[1-9A-HJ- NP-Za-km-z]{26,33})')
</code></pre>
<p>The code works fine but what it does is that it extracts all the usernames and all the bitcoin keys that (the user gave at the end of the post for donation) on a page and there is no way to associate the key to a user since they are extracted separately what I want to do is extract the information in a pair so that I could omit the users who have not specified their public keys(for donation) in their post. Can anyone help me? I am kind of stuck </p>
| 0 | 2016-08-25T00:53:16Z | 39,217,325 | <p>I think you've the idea about getting a common ancestor so that you can match each author to its public key, but I think you're missing the correct selectors, for example try this:</p>
<pre><code>posts = response.css('.windowbg, .windowbg2')
for post in posts:
author = post.css('.poster_info>b>a::text').extract_first()
bitcoinkey = post.css('.signature').re_first(r'(1[1-9A-HJ-NP-Za-km-z]{26,33})')
if author and bitcoinkey:
print author, bitcoinkey
</code></pre>
| 0 | 2016-08-30T00:59:08Z | [
"python",
"xpath",
"scrapy"
] |
cassandra no host available: | 39,135,096 | <p>I tried using the following code but gave an error: </p>
<pre><code>File "cassandra/cluster.py", line 1961,
in cassandra.cluster.Session.execute (cassandra/cluster.c:34076)
File "cassandra/cluster.py", line 3649,
in cassandra.cluster.ResponseFuture.result (cassandra/cluster.c:69755)
cassandra.cluster.NoHostAvailable:
('Unable to complete the operation against any hosts', {})
</code></pre>
<p>I am a bit new to cassandra and I am using it behind my college proxy if that comes to any help.</p>
<pre><code>from cassandra.cluster import Cluster
cluster=Cluster(['127.0.0.1'],port=9042)
session=cluster.connect('demo')
session.execute(
"""
INSERT INTO users (name, credits)
VALUES (%s, %s)
""",
("John O'Reilly", 42)
)
</code></pre>
| -1 | 2016-08-25T00:53:30Z | 39,135,526 | <p>It appears that you don't have a keyspace: <code>demo</code></p>
<p>If you're referencing a similar example to the one on the <a href="https://docs.datastax.com/en/developer/python-driver/2.7/python-driver/reference/passingParameters2CqlQueries.html" rel="nofollow">DataStax Documentation</a> page, did you already create the <code>demo</code> keyspace and the user table?</p>
<p>Based on your above error, I am assuming no.</p>
<p>CQL:</p>
<pre><code>from cassandra.cluster import Cluster
cluster=Cluster(['127.0.0.1'], port=9042)
session=cluster.connect() # Don't specify a keyspace here, since we haven't created it yet.
# Create the demo keyspace
session.execute(
"""
CREATE KEYSPACE IF NOT EXISTS demo WITH REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1
}
"""
)
# Set the active keyspace to demo
# Equivalent to: session.execute("""USE demo""")
session.set_keyspace('demo')
# Create the users table
# This creates a users table with columns: name (text) and credits (int)
session.execute(
"""
CREATE TABLE users (
name text PRIMARY KEY,
credits int
);
"""
)
# Execute your original insert
session.execute(
"""
INSERT INTO users (name, credits)
VALUES (%s, %s)
""",
("John O'Reilly", 42)
)
</code></pre>
| 1 | 2016-08-25T01:52:50Z | [
"python",
"cassandra"
] |
How to write into influxdb using line Protocol with Python | 39,135,119 | <p>I am using line protocol and Python to write into InfluxDB. Below is the code that creates DB and working fine.</p>
<pre><code> client = InfluxDBClient(host, port, user, password, dbname)
print("Creating database: " + dbname)
client.create_database(dbname)
print("Database created: " + dbname)
</code></pre>
<p>I want to write below mention sample data using Line protocol into influxDB</p>
<p>Sample lines of data of Line protocol looks like</p>
<pre><code>interface,path=address,element=link value=3
interface,path=address,element=link value=7
interface,path=address,element=link value=4
</code></pre>
<p>I am using latest version of InfluxDB which supports line protocol.</p>
<p>Any idea about how the client.write statement looks like for python client?</p>
| 0 | 2016-08-25T00:56:47Z | 39,138,651 | <p>This is how a client.write statement could look like for the sample data you provided. Also see the GitHub readme for more examples: <a href="https://github.com/influxdata/influxdb-python" rel="nofollow">Source</a></p>
<pre><code>json_body = [
{
"measurement": "interface",
"tags": {
"path": "address",
"element": "link"
},
"fields": {
"value": 3
}
}
]
client.write_points(json_body)
</code></pre>
| 1 | 2016-08-25T06:59:02Z | [
"python",
"influxdb"
] |
Don't understand cause of exception | 39,135,161 | <p>Here is my code:</p>
<pre><code>import boto3
import json
client = boto3.client('elasticbeanstalk')
code_pipeline = boto3.client('codepipeline')
def put_job_success(job, message):
print "Putting job success"
print (message)
code_pipeline.put_job_success_result(jobId=job)
def put_job_failure(job, message):
print('Putting job failure')
print(message)
code_pipeline.put_job_failure_result(jobId=job, failureDetails={'message': message, 'type': 'JobFailed'})
def get_user_params(job_data):
user_parameters = job_data['actionConfiguration']['configuration']['UserParameters']
decoded_parameters = json.loads(user_parameters)
print user_parameters
def lambda_handler(event, context):
try:
# Extract the Job ID
job_id = event['CodePipeline.job']['id']
# Extract the Job Data
job_data = event['CodePipeline.job']['data']
# Extract the params
params = get_user_params(job_data)
# Get the list of artifacts passed to the function
artifacts = job_data['inputArtifacts']
put_job_success(job_id, 'successfuly done')
except Exception as e:
# If any other exceptions which we didn't expect are raised
# then fail the job and log the exception message.
print('Function failed due to exception.')
print(e)
put_job_failure(job_id, 'Function exception: ' + str(e))
print('Function complete.')
return "Complete."
</code></pre>
<p>Getting Error:</p>
<pre class="lang-none prettyprint-override"><code>traceback (most recent call last):
File "/var/task/lambda_function.py", line 48, in lambda_handler
put_job_failure(job_id, 'Function exception: ' + str(e))
UnboundLocalError: local variable 'job_id' referenced before assignment
</code></pre>
<p>Please help!</p>
| -1 | 2016-08-25T01:02:30Z | 39,135,188 | <p>Nothing in your <code>try</code> block is guaranteed to run once you hit the <code>except</code> block. This includes the <code>job_id</code> assignment. If you want to get rid of the error, you can try:</p>
<pre><code>def lambda_handler(event, context):
job_id = None
try:
# Extract the Job ID
job_id = event['CodePipeline.job']['id']
# Extract the Job Data
job_data = event['CodePipeline.job']['data']
# Extract the params
params = get_user_params(job_data)
# Get the list of artifacts passed to the function
artifacts = job_data['inputArtifacts']
put_job_success(job_id, 'successfuly done')
except Exception as e:
# If any other exceptions which we didn't expect are raised
# then fail the job and log the exception message.
print('Function failed due to exception.')
print(e)
put_job_failure(job_id, 'Function exception: ' + str(e))
</code></pre>
| 5 | 2016-08-25T01:06:03Z | [
"python"
] |
Do Cython files break the Community Edition (Free) PyCharm? | 39,135,179 | <p>So, the free edition of PyCharm does not support Cython (unlike the paid version). What does this mean? Will it break if I have any *pyx files in my project directory, or refuse to work with those files in any way, or ...?</p>
| 1 | 2016-08-25T01:05:22Z | 39,135,238 | <p>From the <a href="https://www.jetbrains.com/help/pycharm/5.0/cython-support.html" rel="nofollow">docs</a>:</p>
<blockquote>
<p>Cython support includes:</p>
<p>Coding assistance: <br/>
Error and syntax highlighting.<br/>
Code completion for keywords, fields of structs, and attributes of extension types.<br/>
Code formatting and folding.<br/>
Ability to create line comments (â/).<br/>
Cython syntax for typed memoryviews.<br/>
Code inspections. Almost all Python code inspections work for Cython.<br/>
Refactorings.<br/>
Numerous ways to navigate through the source code, among them:<br/>
Navigating with Structure View.<br/>
Navigate | Declaration (âB).<br/>
Navigate | Implementation (â¥âB) from overridden method / subclassed class.<br/>
Advanced facilities to search through the source code, in particular, finding usages.<br/>
Compiling Cython modules:<br/>
Compilation is done using external tools. The preferred build systems (Makefile, setup.py, etc.) should be configured as external tools.<br/>
C compiler should be downloaded and installed on your computer.<br/></p>
</blockquote>
<p>The free version just gives you a text editor view of your .pyx, .pxi, and .pxd files, just like any other file it doesn't know what to do with.</p>
| 3 | 2016-08-25T01:12:55Z | [
"python",
"pycharm",
"cython"
] |
Do Cython files break the Community Edition (Free) PyCharm? | 39,135,179 | <p>So, the free edition of PyCharm does not support Cython (unlike the paid version). What does this mean? Will it break if I have any *pyx files in my project directory, or refuse to work with those files in any way, or ...?</p>
| 1 | 2016-08-25T01:05:22Z | 39,628,692 | <p>This can be sorted out rather cleanly, in three small steps, for anyone curious:</p>
<ol>
<li>Create a sample Cython project (those with writersâ block can <a href="https://github.com/thearn/simple-cython-example" rel="nofollow">start with this</a>)</li>
<li>Open this project using PyCharm® Community Editionâ¢</li>
<li>See (and report back!) what then happens to what</li>
</ol>
| 0 | 2016-09-22T01:02:22Z | [
"python",
"pycharm",
"cython"
] |
nginx uwsgi won't accept new connection while request is being processed | 39,135,183 | <p>I have a <code>Python Flask</code> app being served with <code>nginx</code> and <code>uwsgi</code>. I am serving the app on my local machine for development and when I open it in the browser, everything is fine. I make a POST request and the request comes back fine. So far so good...</p>
<p>Now this POST request is a long running request, very computationally intensive, and takes about 60 seconds to run. So I want to test if I can have multiple connections open. I make a POST request, then open the app in another browser tab, but it won't load until the POST request has been responded to.</p>
<p>I am very new to nginx and uwsgi, and it's been a tough road to even get this far, but I thought the idea was that you'd be able to more efficiently handle connections and loads out of the box, so I assume that I am making a rookie mistake here.</p>
<p><strong>How can I get this app to handle multiple connections and requests?</strong></p>
<p>Here is my <code>nginx.conf</code>:</p>
<pre><code>daemon off;
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name 127.0.0.1;
#root /app;
charset UTF-8;
access_log /var/log/nginx/t206cv.access.log;
location / {
proxy_pass http://app;
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
}
upstream app {
server app:5000;
}
}
</code></pre>
<p>Here is my <code>uwsgi.ini</code>:</p>
<pre><code>[uwsgi]
chdir = /app
module = t206cv:app
http-socket = 0.0.0.0:5000
master = True
</code></pre>
<p>And here is what happens when I launch the app:</p>
<pre><code>app_1 | [uWSGI] getting INI configuration from /etc/uwsgi.ini
app_1 | *** Starting uWSGI 2.0.13.1 (64bit) on [Thu Aug 25 00:49:37 2016] ***
app_1 | compiled with version: 4.9.2 on 24 August 2016 02:00:22
app_1 | os: Linux-4.1.19-boot2docker #1 SMP Mon Mar 7 17:44:33 UTC 2016
app_1 | nodename: b6faafc928a1
app_1 | machine: x86_64
app_1 | clock source: unix
app_1 | pcre jit disabled
app_1 | detected number of CPU cores: 1
app_1 | current working directory: /
app_1 | detected binary path: /usr/local/bin/uwsgi
app_1 | uWSGI running as root, you can use --uid/--gid/--chroot options
app_1 | *** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
app_1 | chdir() to /app
app_1 | your processes number limit is 1048576
app_1 | your memory page size is 4096 bytes
app_1 | detected max file descriptor number: 1048576
app_1 | lock engine: pthread robust mutexes
app_1 | thunder lock: disabled (you can enable it with --thunder-lock)
app_1 | uwsgi socket 0 bound to TCP address 0.0.0.0:5000 fd 3
app_1 | Python version: 2.7.12 (default, Aug 22 2016, 20:25:04) [GCC 4.9.2]
app_1 | *** Python threads support is disabled. You can enable it with --enable-threads ***
app_1 | Python main interpreter initialized at 0xe34450
app_1 | your server socket listen backlog is limited to 100 connections
app_1 | your mercy for graceful operations on workers is 60 seconds
app_1 | mapped 145536 bytes (142 KB) for 1 cores
app_1 | *** Operational MODE: single process ***
app_1 | WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0xe34450 pid: 6 (default app)
app_1 | *** uWSGI is running in multiple interpreter mode ***
app_1 | spawned uWSGI master process (pid: 6)
app_1 | spawned uWSGI worker 1 (pid: 11, cores: 1)
app_1 | [pid: 11|app: 0|req: 1/1] 172.17.0.3 () {34 vars in 605 bytes} [Thu Aug 25 00:50:06 2016] GET / => generated 2383 bytes in 16 msecs (HTTP/1.0 200) 2 headers in 81 bytes (1 switches on core 0)
app_1 | [pid: 11|app: 0|req: 2/2] 172.17.0.3 () {38 vars in 697 bytes} [Thu Aug 25 00:50:06 2016] GET /static/styles.css => generated 0 bytes in 6 msecs (HTTP/1.0 304) 4 headers in 181 bytes (0 switches on core 0)
app_1 | [pid: 11|app: 0|req: 3/3] 172.17.0.3 () {38 vars in 683 bytes} [Thu Aug 25 00:50:06 2016] GET /static/scripts.js => generated 0 bytes in 1 msecs (HTTP/1.0 304) 4 headers in 182 bytes (0 switches on core 0)
app_1 | [pid: 11|app: 0|req: 4/4] 172.17.0.3 () {34 vars in 605 bytes} [Thu Aug 25 00:51:03 2016] GET / => generated 2383 bytes in 2 msecs (HTTP/1.0 200) 2 headers in 81 bytes (1 switches on core 0)
app_1 | [pid: 11|app: 0|req: 5/5] 172.17.0.3 () {38 vars in 697 bytes} [Thu Aug 25 00:51:03 2016] GET /static/styles.css => generated 0 bytes in 2 msecs (HTTP/1.0 304) 4 headers in 181 bytes (0 switches on core 0)
app_1 | [pid: 11|app: 0|req: 6/6] 172.17.0.3 () {38 vars in 683 bytes} [Thu Aug 25 00:51:03 2016] GET /static/scripts.js => generated 0 bytes in 3 msecs (HTTP/1.0 304) 4 headers in 182 bytes (0 switches on core 0)
app_1 | [pid: 11|app: 0|req: 7/7] 172.17.0.3 () {40 vars in 683 bytes} [Thu Aug 25 00:51:06 2016] POST /search => generated 89 bytes in 81585 msecs (HTTP/1.0 200) 2 headers in 71 bytes (2 switches on core 0)
app_1 | [pid: 11|app: 0|req: 8/8] 172.17.0.3 () {32 vars in 574 bytes} [Thu Aug 25 00:52:28 2016] GET / => generated 2383 bytes in 1 msecs (HTTP/1.0 200) 2 headers in 81 bytes (1 switches on core 0)
app_1 | [pid: 11|app: 0|req: 9/9] 172.17.0.3 () {32 vars in 574 bytes} [Thu Aug 25 00:52:28 2016] GET / => generated 2383 bytes in 2 msecs (HTTP/1.0 200) 2 headers in 81 bytes (1 switches on core 0)
</code></pre>
| 0 | 2016-08-25T01:05:48Z | 39,135,421 | <p>You're only running one worker.</p>
<pre><code>spawned uWSGI worker 1 (pid: 11, cores: 1)
</code></pre>
<p>One thread/process worker can handle one request. Configure more workers in the uWSGI config.</p>
<pre><code>workers = 8
</code></pre>
<p>Use <a href="http://uwsgi-docs.readthedocs.io/en/latest/Cheaper.html" rel="nofollow">cheaper mode</a> for a simple way to scale worker processes based on demand.</p>
<pre><code>cheaper = 2
cheaper-initial = 2
workers = 16
</code></pre>
| 0 | 2016-08-25T01:40:13Z | [
"python",
"nginx",
"flask",
"uwsgi"
] |
Why os.path.dirname returns /usr/local/bin not the python script's path? | 39,135,208 | <p>For another simple test, I made this code (file name is test3.py) and I put in in /home/ckim/python/test3 directory.</p>
<pre><code>import os.path as osp
import sys
def add_path(path):
if path not in sys.path:
sys.path.insert(0, path)
this_dir = osp.dirname(__file__)
lib_path = osp.join(this_dir, 'lib')
add_path(lib_path)
from pack1.ppp import ppp
if __name__ == '__main__':
print ('starting main..')
ppp()
</code></pre>
<p>When I run the code, <code>this_dir</code> value gives me <code>/usr/local/dir</code> when I expected it to be <code>/home/ckim/python/test3</code>. What is the problem?</p>
| 0 | 2016-08-25T01:09:32Z | 39,135,371 | <p>Use <a href="https://docs.python.org/3/library/os.path.html#os.path.realpath" rel="nofollow">os.path.realpath</a> as well to make it work:</p>
<pre><code>this_dir = osp.dirname(osp.realpath(__file__))
</code></pre>
<p><code>os.getcwd()</code> might also solve your problem.</p>
| 0 | 2016-08-25T01:30:59Z | [
"python"
] |
Python - Retrieving certain indicies from an array | 39,135,210 | <p>I have an array of numbers with shape (1220,) called <code>x</code></p>
<p>I'm looking at numbers greater than 1.0, </p>
<pre><code>mask1 = [i for i in x if i>1.0 ]
</code></pre>
<p>returning</p>
<pre><code>[1.2958354, 1.0839227, 1.1919032]
</code></pre>
<p>My question now is then how am able to determine the index location of these values in my initial array <code>x</code>?</p>
<p>I've tried each individually, but an error occurs</p>
<pre><code>list(x).index(1.2958354)
ValueError: 1.2958354 is not in list
</code></pre>
| 0 | 2016-08-25T01:09:46Z | 39,135,252 | <p>Try:</p>
<pre><code>mask1 = [i for i in range(len(x)) if x[i]>1.0]
</code></pre>
| 1 | 2016-08-25T01:14:38Z | [
"python",
"arrays",
"numpy"
] |
Python - Retrieving certain indicies from an array | 39,135,210 | <p>I have an array of numbers with shape (1220,) called <code>x</code></p>
<p>I'm looking at numbers greater than 1.0, </p>
<pre><code>mask1 = [i for i in x if i>1.0 ]
</code></pre>
<p>returning</p>
<pre><code>[1.2958354, 1.0839227, 1.1919032]
</code></pre>
<p>My question now is then how am able to determine the index location of these values in my initial array <code>x</code>?</p>
<p>I've tried each individually, but an error occurs</p>
<pre><code>list(x).index(1.2958354)
ValueError: 1.2958354 is not in list
</code></pre>
| 0 | 2016-08-25T01:09:46Z | 39,135,265 | <p>You can use the <code>index</code> function on <code>x</code>, which will return the first index of each value. To get a list of all the indices from <code>mask1</code> try:</p>
<pre><code>map(x.index, mask1)
</code></pre>
| 1 | 2016-08-25T01:15:45Z | [
"python",
"arrays",
"numpy"
] |
Python - Retrieving certain indicies from an array | 39,135,210 | <p>I have an array of numbers with shape (1220,) called <code>x</code></p>
<p>I'm looking at numbers greater than 1.0, </p>
<pre><code>mask1 = [i for i in x if i>1.0 ]
</code></pre>
<p>returning</p>
<pre><code>[1.2958354, 1.0839227, 1.1919032]
</code></pre>
<p>My question now is then how am able to determine the index location of these values in my initial array <code>x</code>?</p>
<p>I've tried each individually, but an error occurs</p>
<pre><code>list(x).index(1.2958354)
ValueError: 1.2958354 is not in list
</code></pre>
| 0 | 2016-08-25T01:09:46Z | 39,135,268 | <p><code>mask_1 = [index for index, value in enumerate(x) if value > 1.0]</code></p>
| 1 | 2016-08-25T01:15:58Z | [
"python",
"arrays",
"numpy"
] |
Python - Retrieving certain indicies from an array | 39,135,210 | <p>I have an array of numbers with shape (1220,) called <code>x</code></p>
<p>I'm looking at numbers greater than 1.0, </p>
<pre><code>mask1 = [i for i in x if i>1.0 ]
</code></pre>
<p>returning</p>
<pre><code>[1.2958354, 1.0839227, 1.1919032]
</code></pre>
<p>My question now is then how am able to determine the index location of these values in my initial array <code>x</code>?</p>
<p>I've tried each individually, but an error occurs</p>
<pre><code>list(x).index(1.2958354)
ValueError: 1.2958354 is not in list
</code></pre>
| 0 | 2016-08-25T01:09:46Z | 39,135,269 | <p>Try using <code>enumerate()</code> to get the index and value together:</p>
<pre><code>mask1 = [(i,v) for i,v in enumerate(x) if v > 1.0]
</code></pre>
| 1 | 2016-08-25T01:16:00Z | [
"python",
"arrays",
"numpy"
] |
Python - Retrieving certain indicies from an array | 39,135,210 | <p>I have an array of numbers with shape (1220,) called <code>x</code></p>
<p>I'm looking at numbers greater than 1.0, </p>
<pre><code>mask1 = [i for i in x if i>1.0 ]
</code></pre>
<p>returning</p>
<pre><code>[1.2958354, 1.0839227, 1.1919032]
</code></pre>
<p>My question now is then how am able to determine the index location of these values in my initial array <code>x</code>?</p>
<p>I've tried each individually, but an error occurs</p>
<pre><code>list(x).index(1.2958354)
ValueError: 1.2958354 is not in list
</code></pre>
| 0 | 2016-08-25T01:09:46Z | 39,135,271 | <p>You can use enumerate function, for example:</p>
<pre><code>mask1 = [(i, value) for i, value in enumerate(x) if value>1.0 ]
print mask1
</code></pre>
| 1 | 2016-08-25T01:16:21Z | [
"python",
"arrays",
"numpy"
] |
Python - Retrieving certain indicies from an array | 39,135,210 | <p>I have an array of numbers with shape (1220,) called <code>x</code></p>
<p>I'm looking at numbers greater than 1.0, </p>
<pre><code>mask1 = [i for i in x if i>1.0 ]
</code></pre>
<p>returning</p>
<pre><code>[1.2958354, 1.0839227, 1.1919032]
</code></pre>
<p>My question now is then how am able to determine the index location of these values in my initial array <code>x</code>?</p>
<p>I've tried each individually, but an error occurs</p>
<pre><code>list(x).index(1.2958354)
ValueError: 1.2958354 is not in list
</code></pre>
| 0 | 2016-08-25T01:09:46Z | 39,135,345 | <p>Use enumerate to create tuple pairs of the index and the filtered value, then use zip with the * operator to unpack the variables into separate lists.</p>
<pre><code>a = np.array([0, 1, 2, 3])
idx, vals = zip(*[(i, v) for i, v in enumerate(a) if v > 1])
>>> idx
(2, 3)
>>> vals
(2, 3)
</code></pre>
| 1 | 2016-08-25T01:26:24Z | [
"python",
"arrays",
"numpy"
] |
Python - Retrieving certain indicies from an array | 39,135,210 | <p>I have an array of numbers with shape (1220,) called <code>x</code></p>
<p>I'm looking at numbers greater than 1.0, </p>
<pre><code>mask1 = [i for i in x if i>1.0 ]
</code></pre>
<p>returning</p>
<pre><code>[1.2958354, 1.0839227, 1.1919032]
</code></pre>
<p>My question now is then how am able to determine the index location of these values in my initial array <code>x</code>?</p>
<p>I've tried each individually, but an error occurs</p>
<pre><code>list(x).index(1.2958354)
ValueError: 1.2958354 is not in list
</code></pre>
| 0 | 2016-08-25T01:09:46Z | 39,135,382 | <p>You've tagged this as <code>numpy</code>, and describe a <code>shape</code> (not <code>len</code>). Which leads me to think you have a numpy array.</p>
<pre><code>In [665]: x=np.random.rand(10)
In [666]: x
Out[666]:
array([ 0.6708692 , 0.2856505 , 0.19186508, 0.59411697, 0.1188686 ,
0.54921919, 0.77402055, 0.12569494, 0.08807101, 0.11623299])
In [667]: x>.5
Out[667]: array([ True, False, False, True, False, True, True, False, False, False], dtype=bool)
In [668]: list(x).index(.6708692)
ValueError: 0.6708692 is not in list
</code></pre>
<p>The reason for the <code>ValueError</code> is that you are looking for a float, and those often don't exactly match. If the array was of ints, then such an index would work.</p>
<pre><code>In [669]: list(np.arange(10)).index(5)
Out[669]: 5
</code></pre>
<p>This reasoning applies whether <code>x</code> was an array or a list.</p>
<p><code>numpy</code> has a <code>where</code> that returns the index of boolean true values in an array</p>
<pre><code>In [670]: np.where(x>.5)
Out[670]: (array([0, 3, 5, 6], dtype=int32),)
</code></pre>
<p><code>x>.5</code> is the boolean array as shown above, and <code>[0,3,5,6]</code> the index values where this is true.</p>
<pre><code>In [671]: x[np.where(x>.5)]
Out[671]: array([ 0.6708692 , 0.59411697, 0.54921919, 0.77402055])
</code></pre>
<p>The equality test doesn't work any better</p>
<pre><code>In [672]: x[np.where(x==0.6708692)]
Out[672]: array([], dtype=float64)
</code></pre>
<p>For floats there is the concept of <code>close</code> - the difference is within some tolerance (<code>np.allclose</code> is particularly useful):</p>
<pre><code>In [679]: np.where(np.isclose(x,0.59411697))
Out[679]: (array([3], dtype=int32),)
</code></pre>
<p>For lists, one of the enumerate solutions is great, and also works with 1d arrays. But it is already an array, use the <code>where</code>.</p>
| 4 | 2016-08-25T01:34:51Z | [
"python",
"arrays",
"numpy"
] |
django rest framework : contenttype unique_together and serialization | 39,135,281 | <p>I have a little problem with django rest framework about a generic relation which is also used in a unique_together constraint.</p>
<p>I have this model :</p>
<pre><code>class VPC(models.Model):
name = models.SlugField(null=False, max_length=100)
deletable = models.BooleanField(null=False, default=True)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = (('name', 'content_type', 'object_id'))
</code></pre>
<p>It has a generic relation and a unique constraint : the name of the vpc + the generic relation(which is the owner).</p>
<p>Here is the serializer:</p>
<pre><code>class VPCSerializer(serializers.ModelSerializer):
class Meta:
model = VPC
read_only_fields = ('deletable', 'date_created', 'date_modified')
fields = ('name', 'deletable')
lookup_field = 'name'
validators = [
UniqueTogetherValidator(
queryset=VPC.objects.all(),
fields=('name', 'content_type', 'object_id')
)
]
</code></pre>
<p>In the fields I don't put the content_type and object_id as I don't want them to be displayed/set by the users.</p>
<p>But I have to put them in the UniqueTogetherValidator in order to avoid a django.db.utils.integrityerror raised error when creating a VPC with the same account/name.</p>
<p>But now when I try to create a VPC I got this error :</p>
<blockquote>
<p>{"object_id":["This field is required."],"content_type":["This field is required."]}</p>
</blockquote>
<p>So in my <strong>viewsets.ModelViewSet</strong> I tried to override <strong>perform_create()</strong>
to set the <em>object_id</em> and <em>content_type</em> but it looks like that the error raised before calling this method.</p>
<p>I also try to override <strong>get_serializer_context()</strong> to return a dictionary containing the object_id and content_type, but it doesn't work neither.</p>
<p>I spent a lot of time on this and I don't find out.
So what method should I override to be able to set the object_id and content_type in the serializer ?</p>
<p>Thanks.</p>
| 0 | 2016-08-25T01:17:45Z | 39,138,781 | <p>The serializer validation happens in the </p>
<pre><code>def create(self, request, *args, **kwargs):
</code></pre>
<p>method not in "perform_create"</p>
<p>you need to override the "create" method and fill 'content_type', 'object_id' to the request data(which will be used to initialize the serializer and validation).</p>
<p>you can do like, for example, </p>
<pre><code>def create(self, request, *args, **kwargs):
if hasattr(request.data, '_mutable'):
request.data._mutable = True
request.data['content_type'] = "your_content_type"
request.data['content_type'] = "your_object_id"
serializer = VPCSerializer(data=request.data, request=request)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
return Response here..
</code></pre>
<p>Just fill the required data before you initialize the serializer and check for validation then save using the serializer object and return the serilizer.data or any custom response you want. </p>
| 0 | 2016-08-25T07:06:12Z | [
"python",
"django",
"django-rest-framework"
] |
Float error when writing Celsius-Fahrenheit converter (Zelle) | 39,135,297 | <p>I'm currently learning Python from Zelle's book, and wrote the following Celsius to Fahrenheit converter. It works without issue:</p>
<pre><code>print("This program will convert Celsius to Fahrenheit")
c = eval(input("Input the temperature in Celsius: "))
for i in range(10):
f = c * (9/5) + 32
print(f)
</code></pre>
<p>Zelle asks to later adapt this so that every ten degrees from 0 to 100 Celsius are converted to Fahrenheit, and set on top of one another like columns. I wrote it like this:</p>
<pre><code>print("This program will do 10 temperature conversions.")
c = [0,10,20,30,40,50,60,70,80,90,100]
f = c * (9/5) + 32
for i in range(1):
print(c)
for i in range(1):
print(f)
</code></pre>
<p>I get the following errors:</p>
<p>1) If I leave it as is, the error states: "line 63, in fourthprogram
f = c * (9/5) + 32 TypeError: can't multiply sequence by non-int of type 'float'"</p>
<p>2) If I change (9/5) to another number, like 2, the error states: "line 63, in fourthprogram
f = c * 2 + 32
TypeError: can only concatenate list (not "int") to list"</p>
<p>So, there's a couple of things going on here that I can't quite figure out. The "float" error, according to other answers on Stack Overflow, often relate to variables treated as strings, but it looks like the variables are given a numerical value here. The other error, I tried rewriting the list in the options given by Zelle in Ch 2 and prior, but it's not helping.</p>
<p>How do I deal with this float error, specifically, and other more complex float errors in the future?</p>
<p>Zelle has answers up on his website, but I'd like to know why my code doesn't work as written.</p>
<p>Thank you.</p>
| 0 | 2016-08-25T01:19:39Z | 39,135,424 | <p>Your code doesn't work because you are trying to do mathematical operations on the entire list 'c'. Python requires you to access the elements before operating on them. You have two options:</p>
<p>1) Use a for loop or list comprehension to do elementwise operations on your list. For example:</p>
<pre><code>f = [x * (9/5) + 32 for x in c]
</code></pre>
<p>Will give you a list of all ten temperatures converted to fahrenheit.</p>
<p>2) If you'd like to get more advanced, you can use numpy. Numpy is a highly optimized library for doing math, and supports the vectorized operation syntax that seems natural to you. In other words, it automatically applies math operations to every element of the array, so just changing the first two lines of your code to read:</p>
<pre><code>import numpy as np
c = np.array([0,10,20,30,40,50,60,70,80,90,100])
</code></pre>
<p>will work. </p>
<p>As an aside, once you've made either of those changes, there's no need for the </p>
<pre><code>for i in range(1):
print(c)
</code></pre>
<p>loops. Just print(c), it will make your code easier to read. </p>
| 0 | 2016-08-25T01:40:25Z | [
"python"
] |
Encountering problems encoding characters | 39,135,303 | <p>I'm retrieving long lists of songs <code>ids</code> from <code>API</code>'s, and I'm appending them to a list:</p>
<pre><code>track_ids = [spotify:id:1,spotify:id:2 ...]
</code></pre>
<p>latetr on, song values are being passed to a function, in order to get corresponding song names, in this fashion:</p>
<pre><code>(...)
for i, x in enumerate(values):
if x > threshold:
track_name = sp.track(track_ids[i])['name']
xsongs.append(track_name)
print product.upper(),'-', "{} = {}".format(track_name, x), filter_name
</code></pre>
<p>But when I run the script the list of song names output is halted showing the following error:</p>
<p><code>print product.upper(),'-', "{} = {}".format(track_name, x), filter_name
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 7: ordinal not in range(128)</code></p>
<p><strong>EDIT</strong>:</p>
<p>the following line fixed it:</p>
<pre><code>xsongs.append(track_name.encode("utf-8"))
</code></pre>
| 0 | 2016-08-25T01:20:35Z | 39,135,403 | <p>You can encode every element of list. If your file system encoding is <code>utf-8</code>, you can try:</p>
<pre><code>results = [value.encode('utf-8') for value in results]
print(results)
</code></pre>
| 0 | 2016-08-25T01:38:08Z | [
"python",
"regex",
"list",
"utf-8"
] |
Encountering problems encoding characters | 39,135,303 | <p>I'm retrieving long lists of songs <code>ids</code> from <code>API</code>'s, and I'm appending them to a list:</p>
<pre><code>track_ids = [spotify:id:1,spotify:id:2 ...]
</code></pre>
<p>latetr on, song values are being passed to a function, in order to get corresponding song names, in this fashion:</p>
<pre><code>(...)
for i, x in enumerate(values):
if x > threshold:
track_name = sp.track(track_ids[i])['name']
xsongs.append(track_name)
print product.upper(),'-', "{} = {}".format(track_name, x), filter_name
</code></pre>
<p>But when I run the script the list of song names output is halted showing the following error:</p>
<p><code>print product.upper(),'-', "{} = {}".format(track_name, x), filter_name
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 7: ordinal not in range(128)</code></p>
<p><strong>EDIT</strong>:</p>
<p>the following line fixed it:</p>
<pre><code>xsongs.append(track_name.encode("utf-8"))
</code></pre>
| 0 | 2016-08-25T01:20:35Z | 39,135,638 | <p>The strings in your example are already decoded since they are Unicode strings. You can't decode a Unicode string again, so Python 2 implicitly encodes it back to a byte string using the <code>ascii</code> codec, hence the "Unicode<strong>Encode</strong>Error". The strings you have are correct, you are just seeing escape codes for the non-ASCII characters, which is the default when printing a list. Print the individual strings instead:</p>
<pre><code>results = [u'Magic Carpet Ride', u'La Grange', u'Tausendmal ber\xfchrt',
u'Funkelperlenaugen',u'Lied F\xfcr All Die Vergessenen']
for r in results:
print r
</code></pre>
<p>Output:</p>
<pre><code>Magic Carpet Ride
La Grange
Tausendmal berührt
Funkelperlenaugen
Lied Für All Die Vergessenen
</code></pre>
| 0 | 2016-08-25T02:07:28Z | [
"python",
"regex",
"list",
"utf-8"
] |
PIL.Image.save followed by PIL.Image.open doesn't work | 39,135,330 | <p>I'm using</p>
<p><code>Python 2.7.11 |Anaconda 4.0.0 (64-bit)</code> and <code>PIL.Image.VERSION = 1.1.7</code></p>
<p>I have a saved tiff image that I can correctly open and view it using:</p>
<pre><code>tiffIm = PIL.Image.open(tiffFileName)
tiffIm.show()
</code></pre>
<p>Now if I save the file this way:</p>
<pre><code>tiffIm.save(saveFileName)
</code></pre>
<p>Then I can correctly open and view it using:</p>
<pre><code>tiffImSaved = PIL.Image.open(saveFileName)
tiffImSaved.show()
</code></pre>
<p>However, if I save the file this way:</p>
<pre><code>tiffIm.save(saveFileNameCompressionNone, compression="None")
</code></pre>
<p>Then I can't correctly open and view it using:</p>
<pre><code>tiffImCompressionNone = PIL.Image.open(saveFileNameCompressionNone)
tiffImCompressionNone.show()
</code></pre>
<p>Note: when I open the image saved without specifying <code>compression="None"</code> the mode attribute is <code>F</code> (i.e. tiffImSaved.mode = 'F'). But when I save the image with specifying <code>compression="None"</code>, the mode attribute is <code>I</code> (i.e. tiffImCompressionNone.mode = 'I').</p>
<p>What is going on here?</p>
| 0 | 2016-08-25T01:24:41Z | 39,135,379 | <p>Try passing in <code>compression=None</code> rather than <code>compression="None"</code></p>
| 0 | 2016-08-25T01:33:15Z | [
"python",
"python-imaging-library",
"tiff"
] |
How do I see mail related errors in Django logs? | 39,135,353 | <p>I'm trying to figure out why mail isn't being sent from a django application I copied from a perfectly working application where the mail works. I've tried in vain to get django to spit out something related to mail in the logs, but nothing shows up. Here are my settings in settings.py:</p>
<pre><code>LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'DEBUG',
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter': 'simple'
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': '/tmp/ooto.log',
'formatter': 'verbose'
},
},
'loggers': {
'django.request': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
'django_opensso':{
'handlers' : ['file'],
'level' : 'DEBUG',
},
'timekeeper':{
'handlers' : ['file'],
'level' : 'DEBUG',
},
}
</code></pre>
<p>Can someone explain in detail or post an example of how I can get mail related errors out of django so I can troubleshoot the real problem?</p>
| 0 | 2016-08-25T01:27:37Z | 39,135,563 | <p>Neither <code>django.core.mail</code> nor <code>smtplib</code> are using Pythons logging module. There is a simple logging facility in <code>smtplib</code> that write to the console. You have to set run <code>.set_debuglevel(level)</code> on the connection instace, where level is an integer > 0.</p>
<p>This <em>should</em> have the same result:</p>
<pre><code>import smtplib
smtplib.SMTP.debuglevel = 9
</code></pre>
<p>This is a so called monkey patch. Be careful with it, it is hard to trace.</p>
| 0 | 2016-08-25T01:56:31Z | [
"python",
"django",
"email"
] |
Find average grade of 10 students, and increment students | 39,135,410 | <p>I need to ask the final grade of 10 students (<strong>while</strong>) incrementing their values:</p>
<p>So something like:</p>
<blockquote>
<p>Please enter final grade for student 1</p>
<p>Please enter final grade for student 2</p>
</blockquote>
<p>and so on... till 10</p>
<p>Then I need to get the grades they entered, and find average. </p>
<p>This is what I have so far:</p>
<pre><code>def main():
x = []
for i in range(10):
final_grades = x.append(int(input('Please enter final grade for student: ')))
##average_final_grade = final_grades / 10
##print(average_final_grade)
main()
</code></pre>
| 1 | 2016-08-25T01:38:42Z | 39,135,501 | <pre><code># list of grades
x = []
# count of students
n = 10
# fill list with grades from console input
# using pythonic generator
x = [int(input('Please enter final grade for student {}: '.format(i+1))) for i in range(n)]
# count average,
# sum is builtin way to sum values in list
# float required for python 2.x to make avg float, not int
average_final_grade = sum(x) / float(n)
print('Avg grade is {}'.format(average_final_grade))
</code></pre>
<p><a href="http://code.runnable.com/V75O7syW5IsNknuE/find-average-grade-of-10-students-and-increment-students-for-python" rel="nofollow">Online demo</a>.</p>
| 1 | 2016-08-25T01:50:06Z | [
"python",
"loops",
"python-3.x",
"for-loop"
] |
Find average grade of 10 students, and increment students | 39,135,410 | <p>I need to ask the final grade of 10 students (<strong>while</strong>) incrementing their values:</p>
<p>So something like:</p>
<blockquote>
<p>Please enter final grade for student 1</p>
<p>Please enter final grade for student 2</p>
</blockquote>
<p>and so on... till 10</p>
<p>Then I need to get the grades they entered, and find average. </p>
<p>This is what I have so far:</p>
<pre><code>def main():
x = []
for i in range(10):
final_grades = x.append(int(input('Please enter final grade for student: ')))
##average_final_grade = final_grades / 10
##print(average_final_grade)
main()
</code></pre>
| 1 | 2016-08-25T01:38:42Z | 39,135,511 | <p>First, you need to get the values, as you have already done:</p>
<pre><code>x = []
for i in range(10):
x.append(int(input('Please enter final grade for student: ')))
</code></pre>
<p>Now you need to sum the values of <code>x</code>:</p>
<pre><code>total_sum = sum(x)
</code></pre>
<p>Then, you get the average:</p>
<pre><code>average_final_grade = total_sum/len(sum)
</code></pre>
| 1 | 2016-08-25T01:50:50Z | [
"python",
"loops",
"python-3.x",
"for-loop"
] |
Find average grade of 10 students, and increment students | 39,135,410 | <p>I need to ask the final grade of 10 students (<strong>while</strong>) incrementing their values:</p>
<p>So something like:</p>
<blockquote>
<p>Please enter final grade for student 1</p>
<p>Please enter final grade for student 2</p>
</blockquote>
<p>and so on... till 10</p>
<p>Then I need to get the grades they entered, and find average. </p>
<p>This is what I have so far:</p>
<pre><code>def main():
x = []
for i in range(10):
final_grades = x.append(int(input('Please enter final grade for student: ')))
##average_final_grade = final_grades / 10
##print(average_final_grade)
main()
</code></pre>
| 1 | 2016-08-25T01:38:42Z | 39,135,677 | <pre><code> total=sum(x)
average=total/10
print(average)
</code></pre>
<h1>tack this at the bottom and it should work</h1>
| 0 | 2016-08-25T02:12:01Z | [
"python",
"loops",
"python-3.x",
"for-loop"
] |
why am I not getting a 4 in this list? | 39,135,412 | <pre><code>my_list = [9,8,7]
for k in range (3):
my_list.insert(-k,k+1)
print(my_list)
</code></pre>
<p>I am getting: <code>[1,9,8,3,2,7]</code>
I have changed the insert and tested it with different numbers and do not understand. I thought -1 would insert at the end of the list.</p>
| 0 | 2016-08-25T01:39:00Z | 39,135,448 | <p><code>-1</code> will insert into the last but one,if you want insert at the end of the list, use <code>your_list.append(val)</code></p>
| 0 | 2016-08-25T01:43:19Z | [
"python",
"python-3.x"
] |
why am I not getting a 4 in this list? | 39,135,412 | <pre><code>my_list = [9,8,7]
for k in range (3):
my_list.insert(-k,k+1)
print(my_list)
</code></pre>
<p>I am getting: <code>[1,9,8,3,2,7]</code>
I have changed the insert and tested it with different numbers and do not understand. I thought -1 would insert at the end of the list.</p>
| 0 | 2016-08-25T01:39:00Z | 39,135,464 | <p>The <code>insert(i, x)</code> function insert a new item with value x in the list before position i. my_list[-1] is the end element, so my_list.insert(-1, 2) will insert before the end element 7.</p>
<pre><code>for k in range (3): my_list.insert(-k,k+1)
my_list.insert(0,1) --> my_list = [1, 9, 8, 7]
my_list.insert(-1,2) --> my_list = [1, 9, 8, 2, 7]
my_list.insert(-2,3) --> my_list = [1, 9, 8, 3, 2, 7]
</code></pre>
| 2 | 2016-08-25T01:45:12Z | [
"python",
"python-3.x"
] |
why am I not getting a 4 in this list? | 39,135,412 | <pre><code>my_list = [9,8,7]
for k in range (3):
my_list.insert(-k,k+1)
print(my_list)
</code></pre>
<p>I am getting: <code>[1,9,8,3,2,7]</code>
I have changed the insert and tested it with different numbers and do not understand. I thought -1 would insert at the end of the list.</p>
| 0 | 2016-08-25T01:39:00Z | 39,135,466 | <p><code>4</code> is not inserted because you are doing <code>(k+1)</code> on <code>insert</code>.
And you called <code>range(3)</code>. <code>range(3)</code> returns <code>[0, 1, 2]</code>. </p>
<p>So, it never reaches till <code>4</code>. </p>
<p>And if you want to insert at the end use <code>my_list.append(k)</code> instead.</p>
| 3 | 2016-08-25T01:45:17Z | [
"python",
"python-3.x"
] |
How to flatten nested python dictionaries? | 39,135,433 | <p>I'm trying to flatten the nested dictionary:</p>
<pre><code>dict1 = {
'Bob': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 0, 6],
},
'Sarah': {
'shepherd': [1, 2, 3],
'collie': [3, 31, 4],
'poodle': [21, 5, 6],
},
'Ann': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 10, 8],
}
}
</code></pre>
<p>I'd like to display all values in lists:
[4, 6, 3, 23, 3, 45, 2, 0, 6, 1, 2, 3,..., 2, 10, 8]</p>
<p>My first idea was to do in this way:</p>
<pre><code>dict_flatted = [ i for name in names.values() for dog in dogs.values() for i in dog]
</code></pre>
<p>Though I'm getting the error. I'd be happy for tips how to handle it.</p>
| 0 | 2016-08-25T01:41:15Z | 39,135,486 | <p>You can use a simple recursive function as follows.</p>
<pre><code>def flatten(d):
res = [] # Result list
if isinstance(d, dict):
for key, val in d.items():
res.extend(flatten(val))
elif isinstance(d, list):
res = d
else:
raise TypeError("Undefined type for flatten: %s"%type(d))
return res
dict1 = {
'Bob': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 0, 6],
},
'Sarah': {
'shepherd': [1, 2, 3],
'collie': [3, 31, 4],
'poodle': [21, 5, 6],
},
'Ann': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 10, 8],
}
}
print( flatten(dict1) )
</code></pre>
| 2 | 2016-08-25T01:48:09Z | [
"python",
"dictionary"
] |
How to flatten nested python dictionaries? | 39,135,433 | <p>I'm trying to flatten the nested dictionary:</p>
<pre><code>dict1 = {
'Bob': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 0, 6],
},
'Sarah': {
'shepherd': [1, 2, 3],
'collie': [3, 31, 4],
'poodle': [21, 5, 6],
},
'Ann': {
'shepherd': [4, 6, 3],
'collie': [23, 3, 45],
'poodle': [2, 10, 8],
}
}
</code></pre>
<p>I'd like to display all values in lists:
[4, 6, 3, 23, 3, 45, 2, 0, 6, 1, 2, 3,..., 2, 10, 8]</p>
<p>My first idea was to do in this way:</p>
<pre><code>dict_flatted = [ i for name in names.values() for dog in dogs.values() for i in dog]
</code></pre>
<p>Though I'm getting the error. I'd be happy for tips how to handle it.</p>
| 0 | 2016-08-25T01:41:15Z | 39,135,549 | <p>You're trying to use variables that don't exist.</p>
<p>Use this</p>
<pre><code>dict_flatted = [ i for names in dict1.values() for dog in names.values() for i in dog]
</code></pre>
| 1 | 2016-08-25T01:55:12Z | [
"python",
"dictionary"
] |
Add value into tuple (zip() inside for loop ) in Python | 39,135,437 | <p>I need to format a list of list into a list of tuples, the desired outcome is:</p>
<pre><code>>>A = [[1, 2, 3]]
>>A.append([1, 2, 3])
>>A.append([1, 2, 3])
>>print A
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
</code></pre>
<p>And my desired output is:</p>
<pre><code>>>zip (A[0],A[1],A[2])
[(1, 1, 1), (2, 2, 2), (3, 3, 3)]
</code></pre>
<p>Now imagine that the list A is very large and I cannot do that process writing a small line of code, if I try to loop the zip() function the outcome is as follows:</p>
<pre><code>>>print zip (A[0],a)
>>[(1, (1, 1, 1)), (2, (2, 2, 2)), (3, (3, 3, 3))]
</code></pre>
<p>The nasty solution that I came up was using a recursive loop:</p>
<pre><code>>>B = zip(A[0])
>>for idx,val in enumerate(A):
for idx1,val1 in enumerate(B):
B[idx1] = val1 + (A[idx][idx1],)
</code></pre>
<p>That returns the desired result:</p>
<pre><code>[(1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3)]
</code></pre>
<p>Hence, is there a proper/cleaner/faster way to solve this problem?</p>
<p>(Because it is an embedded package of Python I cannot use Pandas nut NumPy is allowed in an early version)</p>
| 1 | 2016-08-25T01:41:53Z | 39,135,462 | <p>try <code>zip(*A)</code>, which is exactly <code>zip(A[0],A[1],...)</code></p>
<p>(that's true for any function, not just zip). <a href="https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists</a></p>
| 2 | 2016-08-25T01:45:02Z | [
"python",
"numpy"
] |
an if Statement inside an if Statement? | 39,135,470 | <pre><code>FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
</code></pre>
<p><a href="http://i.stack.imgur.com/qaqYl.png" rel="nofollow">undescribed image</a></p>
| -4 | 2016-08-25T01:45:27Z | 39,135,599 | <p>You can indent additional statements, including <code>if</code> statements inside your existing <code>if</code> block, just like you're indented the first <code>print</code> statement. It's not clear from your question what exactly you want to do, so I'll fill in some pseudo-code (which you can replace with whatever you actually want):</p>
<pre><code>FarmGround=input("Do you want to pat the animal? ")
if FarmGround==("Yes") or FarmGround==("yes"):
print("You patted the animal")
some_other_answer = input("Some other question?") # here's more code inside the first if
if some_other_answer == "Foo": # it can include another if statement, if you want it to
print("Foo!")
elif FarmGround==("No") or FarmGround==("no"):
print("You didn't patt the animal and it is triggered")
</code></pre>
| 2 | 2016-08-25T02:01:49Z | [
"python",
"variables"
] |
an if Statement inside an if Statement? | 39,135,470 | <pre><code>FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
</code></pre>
<p><a href="http://i.stack.imgur.com/qaqYl.png" rel="nofollow">undescribed image</a></p>
| -4 | 2016-08-25T01:45:27Z | 39,135,609 | <p>Indentation matters in python. To nest an if statement in another if statement, just indent it below the first with 4 spaces.</p>
<pre><code>If ( var1 == 1 ):
If ( var2 == 2 ):
print "Both statements are true."
</code></pre>
| 1 | 2016-08-25T02:03:55Z | [
"python",
"variables"
] |
an if Statement inside an if Statement? | 39,135,470 | <pre><code>FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
</code></pre>
<p><a href="http://i.stack.imgur.com/qaqYl.png" rel="nofollow">undescribed image</a></p>
| -4 | 2016-08-25T01:45:27Z | 39,135,618 | <p>Your code is quite clear. What I understand is you want to ask another question if animal is patted. </p>
<pre><code>FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround=="Yes" or FarmGround=="yes": #this is if
print("You patted the animal")
holy_field = input("Did you clear the field?")
if holy_field.lower() == "yes":
print("Do something else. Don't look at me.")
else:
print("When are you going to do it ?")
elif FarmGround== "No" or FarmGround== "no": #this is elif
print("You didn't patt the animal and it is triggered")
</code></pre>
| 2 | 2016-08-25T02:04:48Z | [
"python",
"variables"
] |
Setting Order of Columns with matplotlib bar chart | 39,135,472 | <p>I produce a bar graph with the following code: </p>
<pre><code>Temp_Counts = Counter(weatherDFConcat['TEMPBIN_CON'])
df = pd.DataFrame.from_dict(Temp_Counts, orient = 'index')
df.plot(kind = 'bar')
</code></pre>
<p>It produces the following bar chart: </p>
<p><a href="http://i.stack.imgur.com/4sWHw.png" rel="nofollow"><img src="http://i.stack.imgur.com/4sWHw.png" alt="enter image description here"></a></p>
<p>I would like to change the order the columns are listed. I've tried a few different things that aren't seeming to work. The DataFrame I am working with looks like this:</p>
<p><a href="http://i.stack.imgur.com/GBj7o.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/GBj7o.jpg" alt="enter image description here"></a></p>
<p>I am creating a barplot of the last column in the dataframe pictured. Any direction or ideas of alternate methods of creating a barplot that would allow me to change the order of the axis would be greatly appreciated. As it exists its difficult to interpret. </p>
| 2 | 2016-08-25T01:45:53Z | 39,135,625 | <p>I would suggest that you split the <code>TEMPBIN_CON</code> in two: <code>LOWER_TEMP</code> and <code>HIGHER_TEMP</code>. Then, you sort the DataFrame by these columns using:</p>
<pre><code>sorted = df.sort_values(by=['LOWER_TEMP', 'HIGHER_TEMP'])
</code></pre>
<p>and then you do the plot as you have already done:</p>
<pre><code>sorted.plot(kind='bar')
</code></pre>
| 1 | 2016-08-25T02:06:19Z | [
"python",
"pandas",
"numpy",
"matplotlib",
"bar-chart"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.