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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Why is using the Python mmap module much slower than calling POSIX mmap from C++? | 38,682,501 | <p>C++ code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <string>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/time.h>
using namespace std;
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main() {
timeval tv1, tv2, tv3, tve;
gettimeofday(&tv1, 0);
int size = 0x1000000;
int fd = open("data", O_RDWR | O_CREAT | O_TRUNC, FILE_MODE);
ftruncate(fd, size);
char *data = (char *) mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
for(int i = 0; i < size; i++) {
data[i] = 'S';
}
munmap(data, size);
close(fd);
gettimeofday(&tv2, 0);
timersub(&tv2, &tv1, &tve);
printf("Time elapsed: %ld.%06lds\n", (long int) tve.tv_sec, (long int) tve.tv_usec);
}
</code></pre>
<p>Python code:</p>
<pre class="lang-py prettyprint-override"><code>import mmap
import time
t1 = time.time()
size = 0x1000000
f = open('data/data', 'w+')
f.truncate(size)
f.close()
file = open('data/data', 'r+b')
buffer = mmap.mmap(file.fileno(), 0)
for i in xrange(size):
buffer[i] = 'S'
buffer.close()
file.close()
t2 = time.time()
print "Time elapsed: %.3fs" % (t2 - t1)
</code></pre>
<p>I think these two program are the essentially same since C++ and Python call the same system call(<code>mmap</code>).</p>
<p>But the Python version is much slower than C++'s:</p>
<pre><code>Python: Time elapsed: 1.981s
C++: Time elapsed: 0.062143s
</code></pre>
<p><strong>Could any one please explain the reason why the mmap Python of is much slower than C++?</strong></p>
<hr>
<p>Environment:</p>
<p>C++:</p>
<pre><code>$ c++ --version
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.5.0
</code></pre>
<p>Python:</p>
<pre><code>$ python --version
Python 2.7.11 :: Anaconda 4.0.0 (x86_64)
</code></pre>
| 0 | 2016-07-31T09:18:00Z | 38,682,857 | <p>To elaborate on what @Daniel said â any Python operation has more overhead (in some cases <em>way</em> more, like orders of magnitude) than the comparable amount of code implementing a solution in C++.</p>
<p>The loop filling the buffer is indeed the culprit â but also the <code>mmap</code> module itself has a lot more housekeeping to do than you might think, despite that it offers an interface whose semantics are, misleadingly, verrrry closely aligned with POSIX <code>mmap()</code>. You know how POSIX <code>mmap()</code> just tosses you a <code>void*</code> (which you just have to use <code>munmap()</code> to clean up after it, at some point)? Pythonâs <code>mmap</code> has to allocate a <code>PyObject</code> structure to babysit the <code>void*</code> â making it conform to Pythonâs buffer protocol by furnishing metadata and callbacks to the runtime, propagating and queueing reads and writes, maintaining GIL state, cleaning up its allocations no matter what errors occurâ¦</p>
<p>All of that stuff takes time and memory, too. I personally donât ever find myself using the <code>mmap</code> module, as it doesnât give you a clear-cut advantage on any I/O problem, like out-of-the-box â you can just as easily use <code>mmap</code> to make things slower as you might make them faster.</p>
<p><em>Contrastingly I often *do* find that using POSIX</em> <code>mmap()</code> <em>can be VERY advantageous when doing I/O from within a Python C/C++ extension (provided youâre minding the GIL state), precisely because coding around</em> <code>mmap()</code> <em>avoids all that Python internal-infrastructure stuff in the first place.</em></p>
| 1 | 2016-07-31T10:04:48Z | [
"python",
"c++",
"performance",
"posix",
"mmap"
] |
Weird characters printed during json key-value printing | 38,682,556 | <p>I have made a python program to get the movie/tv show information using the OMDb API <a href="http://www.omdbapi.com/" rel="nofollow">http://www.omdbapi.com/</a> </p>
<p>I am getting an error while printing the running years of the tv show. Here's a part of the code where this is happening:</p>
<pre><code>keys = ['Title', 'Year', 'imdbRating', 'Director', 'Actors', 'Genre', 'totalSeasons']
def jsonContent(self):
payload = {'t':self.title}
movie = requests.get(self.url, params = payload)
return movie.json()
def getInfo(self):
data = self.jsonContent()
for key, value in data.items():
if key in keys:
print key.encode('utf-8') + ' : ' + value.encode('utf-8')
</code></pre>
<p>For example if I search for <em>How I Met Your Mother</em>, it prints out like this:</p>
<pre><code>totalSeasons : 9
Title : How I Met Your Mother
imdbRating : 8.4
Director : N/A
Actors : Josh Radnor, Jason Segel, Cobie Smulders, Neil Patrick Harris
Year : 2005ÎÃô2014 #problem here
Genre : Comedy, Romance
</code></pre>
<p>How can I fix this?</p>
| -2 | 2016-07-31T09:24:54Z | 38,682,630 | <p>You are encoding Unicode text to UTF-8 before printing:</p>
<pre><code>print key.encode('utf-8') + ' : ' + value.encode('utf-8')
</code></pre>
<p>Your console or terminal is not configured to interpret UTF-8 however. It is being sent bytes and it is then displaying characters based on a <em>different</em> codec altogether. </p>
<p>Your <code>value</code> contains a <code>\u2013</code> or <a href="https://codepoints.net/U+2013" rel="nofollow">U+2013 EN DASH</a> character, which encodes to UTF-8 as 3 bytes <code>E2 80 93</code>, which your terminal appears to decode as Windows Codepage 437 instead:</p>
<pre><code>>>> value = u'2005\u20132014'
>>> print value
2005â2014
>>> print value.encode('utf8').decode('cp437')
2005ÎÃô2014
</code></pre>
<p>Either re-configure your console or terminal, or set the <a href="https://docs.python.org/2/using/cmdline.html#envvar-PYTHONIOENCODING" rel="nofollow"><code>PYTHONIOENCODING</code> environment variable</a> to use an error handler:</p>
<pre><code>PYTHONIOENCODING=cp437:replace
</code></pre>
<p>The <code>:replace</code> part will tell Python to encode to cp437 but to use <em>placeholders</em> for characters it can't handle. You'll get a question mark instead:</p>
<pre><code>>>> print value.encode('cp437', 'replace')
2005?2014
</code></pre>
<p>Note that I have to encode to CP437 explicitly in all these examples. <em>You don't</em> as Python has detected your configuration and will do this automatically for you. Just stick to printing Unicode directly.</p>
<p>Another alternative is to use the <a href="https://pypi.python.org/pypi/Unidecode" rel="nofollow"><code>Unicodecode</code> package</a> to replace non-ASCII characters with close approximations; it'll replace the en-dash with an ASCII dash:</p>
<pre><code>>>> from unidecode import unidecode
>>> value
u'2005\u20132014'
>>> unidecode(value)
'2005-2014'
</code></pre>
| 2 | 2016-07-31T09:33:49Z | [
"python",
"json",
"python-2.7",
"utf-8",
"character-encoding"
] |
jira-python create_issue jiraerror http 400 with a url of local address | 38,682,713 | <p>I'm new to jira-python. I am trying to automate a bit on jira management, blocked on creating issue for a long time, going along with the jira-python official documents.
I'm confused with the createmeta of create_issue() method. After trial and error, I'm blocked with a strange http 400 error followed by a url with a local address.</p>
<h2><strong>Environment:</strong></h2>
<blockquote>
<p>OS, Windows 10.</p>
<p>Spyder IDE in Anaconda(latest version with Python 3.5 installed)</p>
<p>jira-python, 1.0.7</p>
</blockquote>
<p>There are several 'projects' on the customized JIRA deployed, and I'm interested on the project-'ZXQ', in which I create an issue manually with 'Project', 'Issue Type', 'Summary', and 'Priority' required (This is my first post on stackoverflow, and I don't have permission to upload pic.).</p>
<p>Here are the code, error message, and createmeta in tidy manner.</p>
<h2><strong>Code:</strong></h2>
<pre><code>from jira import JIRA
authedjira = JIRA(server = 'http://xxx.xx.xx.xxx:48082',
basic_auth = ('username', 'password'))
issue_dict = {
'project': {'key': 'ZXQ'},
'summary': 'New issue from jira-python',
'description': 'Look into this one',
'issuetype': {'name': 'Bug'}
# 'priority' : '0-Blocked'
}
new_issue = authedjira.create_issue(fields=issue_dict)
</code></pre>
<h2><strong>msg in console:</strong></h2>
<pre><code>runfile('.../Spyder/test/tcreateissue.py', wdir='.../Spyder/test')
Traceback (most recent call last):
File "<ipython-input-15-16266e46b0c1>", line 1, in <module>
runfile('.../Spyder/test/tcreateissue.py', wdir='.../Spyder/test')
File "C:\App\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
execfile(filename, namespace)
File "C:\App\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File ".../Spyder/test/tcreateissue.py", line 21, in <module>
new_issue = authedjira.create_issue(fields=issue_dict)
File "C:\App\Anaconda3\lib\site-packages\jira\client.py", line 897, in create_issue
r = self._session.post(url, data=json.dumps(data))
File "C:\App\Anaconda3\lib\site-packages\jira\resilientsession.py", line 152, in post
return self.__verb('POST', url, **kwargs)
File "C:\App\Anaconda3\lib\site-packages\jira\resilientsession.py", line 145, in __verb
raise_on_error(response, verb=verb, **kwargs)
File "C:\App\Anaconda3\lib\site-packages\jira\resilientsession.py", line 55, in raise_on_error
r.status_code, error, r.url, request=request, response=r, **kwargs)
JIRAError: JiraError HTTP 400 url: http://xxx.xx.xx.xxx:48082/rest/api/2/issue details: C:\Users\ABSmi\AppData\Local\Temp\jiraerror-jjcv0rwp.tmp
</code></pre>
<p>Content in jiraerror-jjcv0rwp.tmp:</p>
<pre><code>response headers = {'Vary': 'User-Agent', 'Content-Encoding': 'gzip', 'X-Seraph-LoginReason': 'OK', 'X-AREQUESTID': '1024x353617x1', 'Transfer-Encoding': 'chunked', 'Date': 'Sun, 31 Jul 2016 09:04:51 GMT', 'Server': 'Apache-Coyote/1.1', 'X-ASESSIONID': 'sen5dn', 'X-Content-Type-Options': 'nosniff', 'Connection': 'close', 'X-AUSERNAME': 'zhaoya', 'X-ASEN': 'SEN-5285313', 'Content-Type': 'application/json;charset=UTF-8', 'Cache-Control': 'no-cache, no-store, no-transform'}
response text = {"errorMessages":[],"errors":{"description":"Field 'description' cannot be set. It is not on the appropriate screen, or unknown."}}
</code></pre>
<h2><strong>createmeta:</strong></h2>
<pre><code>{
"expand": "projects",
================================================================================================================================================
================================================================================================================================================
================================================================================================================================================
"projects": [
================================================================================================
================================================================================================
================================================================================================
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/project/11001",
"id": "11001",
"name": "Precheck",
"key": "PRECHECK",
"issuetypes": [
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/1",
"id": "1",
"name": "Bug",
"description": "A problem which impairs or prevents the functions of the product.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/bug.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/2",
"id": "2",
"name": "New Feature",
"description": "A new feature of the product, which has yet to be developed.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/newfeature.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/3",
"id": "3",
"name": "Task",
"description": "A task that needs to be done.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/task.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/4",
"id": "4",
"name": "Improvement",
"description": "An improvement or enhancement to an existing feature or task.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/improvement.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/5",
"id": "5",
"name": "Sub-task",
"description": "The sub-task of the issue",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/subtask_alternate.png",
"subtask": true
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10001",
"id": "10001",
"name": "\u6d4b\u8bd5",
"description": "\u6b64\u53d1\u5e03\u7c7b\u578b\u7528\u4e8e\u5728 Jira \u4e2d\u521b\u5efa Zephyr \u6d4b\u8bd5\u3002",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/com.thed.zephyr.je/images/icons/ico_zephyr_issuetype.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10100",
"id": "10100",
"name": "Epic",
"description": "Created by JIRA Agile - do not edit or delete. Issue type for a big user story that needs to be broken down.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/epic.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10200",
"id": "10200",
"name": "Ticket Template(WBSGantt)",
"description": "Ticket Template",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/template-icon.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10201",
"id": "10201",
"name": "Phase",
"description": "Project Development Phase",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/phase-icon.png",
"subtask": false
}
],
"avatarUrls": {
"24x24": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=small&pid=11001&avatarId=10011",
"16x16": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=xsmall&pid=11001&avatarId=10011",
"32x32": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=medium&pid=11001&avatarId=10011",
"48x48": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?pid=11001&avatarId=10011"
}
},
================================================================================================
================================================================================================
================================================================================================
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/project/11200",
"id": "11200",
"name": "\u4e8b\u4ef6\u7ba1\u7406",
"key": "SJGL",
"issuetypes": [
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/5",
"id": "5",
"name": "Sub-task",
"description": "The sub-task of the issue",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/subtask_alternate.png",
"subtask": true
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/2",
"id": "2",
"name": "New Feature",
"description": "A new feature of the product, which has yet to be developed.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/newfeature.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/3",
"id": "3",
"name": "Task",
"description": "A task that needs to be done.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/task.png",
"subtask": false
}
],
"avatarUrls": {
"24x24": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=small&pid=11200&avatarId=10011",
"16x16": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=xsmall&pid=11200&avatarId=10011",
"32x32": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=medium&pid=11200&avatarId=10011",
"48x48": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?pid=11200&avatarId=10011"
}
},
================================================================================================
================================================================================================
================================================================================================
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/project/10201",
"id": "10201",
"name": "\u4ea7\u54c1\u5185\u90e8\u4ea4\u6d41",
"key": "CP",
"issuetypes": [
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/1",
"id": "1",
"name": "Bug",
"description": "A problem which impairs or prevents the functions of the product.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/bug.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/2",
"id": "2",
"name": "New Feature",
"description": "A new feature of the product, which has yet to be developed.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/newfeature.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/3",
"id": "3",
"name": "Task",
"description": "A task that needs to be done.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/task.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/4",
"id": "4",
"name": "Improvement",
"description": "An improvement or enhancement to an existing feature or task.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/improvement.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/5",
"id": "5",
"name": "Sub-task",
"description": "The sub-task of the issue",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/subtask_alternate.png",
"subtask": true
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10001",
"id": "10001",
"name": "\u6d4b\u8bd5",
"description": "\u6b64\u53d1\u5e03\u7c7b\u578b\u7528\u4e8e\u5728 Jira \u4e2d\u521b\u5efa Zephyr \u6d4b\u8bd5\u3002",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/com.thed.zephyr.je/images/icons/ico_zephyr_issuetype.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10100",
"id": "10100",
"name": "Epic",
"description": "Created by JIRA Agile - do not edit or delete. Issue type for a big user story that needs to be broken down.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/epic.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10200",
"id": "10200",
"name": "Ticket Template(WBSGantt)",
"description": "Ticket Template",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/template-icon.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10201",
"id": "10201",
"name": "Phase",
"description": "Project Development Phase",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/phase-icon.png",
"subtask": false
}
],
"avatarUrls": {
"24x24": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=small&pid=10201&avatarId=10011",
"16x16": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=xsmall&pid=10201&avatarId=10011",
"32x32": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=medium&pid=10201&avatarId=10011",
"48x48": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?pid=10201&avatarId=10011"
}
},
================================================================================================
================================================================================================
================================================================================================
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/project/11009",
"id": "11009",
"name": "\u4ea7\u54c1\u8bbe\u8ba1\u9700\u6c42",
"key": "PD",
"issuetypes": [
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/1",
"id": "1",
"name": "Bug",
"description": "A problem which impairs or prevents the functions of the product.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/bug.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/2",
"id": "2",
"name": "New Feature",
"description": "A new feature of the product, which has yet to be developed.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/newfeature.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/3",
"id": "3",
"name": "Task",
"description": "A task that needs to be done.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/task.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/4",
"id": "4",
"name": "Improvement",
"description": "An improvement or enhancement to an existing feature or task.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/improvement.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/5",
"id": "5",
"name": "Sub-task",
"description": "The sub-task of the issue",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/subtask_alternate.png",
"subtask": true
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10001",
"id": "10001",
"name": "\u6d4b\u8bd5",
"description": "\u6b64\u53d1\u5e03\u7c7b\u578b\u7528\u4e8e\u5728 Jira \u4e2d\u521b\u5efa Zephyr \u6d4b\u8bd5\u3002",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/com.thed.zephyr.je/images/icons/ico_zephyr_issuetype.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10100",
"id": "10100",
"name": "Epic",
"description": "Created by JIRA Agile - do not edit or delete. Issue type for a big user story that needs to be broken down.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/epic.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10200",
"id": "10200",
"name": "Ticket Template(WBSGantt)",
"description": "Ticket Template",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/template-icon.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10201",
"id": "10201",
"name": "Phase",
"description": "Project Development Phase",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/phase-icon.png",
"subtask": false
}
],
"avatarUrls": {
"24x24": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=small&pid=11009&avatarId=10011",
"16x16": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=xsmall&pid=11009&avatarId=10011",
"32x32": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=medium&pid=11009&avatarId=10011",
"48x48": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?pid=11009&avatarId=10011"
}
},
================================================================================================
================================================================================================
================================================================================================
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/project/10005",
"id": "10005",
"name": "\u7f3a\u9677\u7ba1\u7406\u5e73\u53f0",
"key": "ZXQ",
"issuetypes": [
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/1",
"id": "1",
"name": "Bug",
"description": "A problem which impairs or prevents the functions of the product.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/bug.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/2",
"id": "2",
"name": "New Feature",
"description": "A new feature of the product, which has yet to be developed.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/newfeature.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/3",
"id": "3",
"name": "Task",
"description": "A task that needs to be done.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/task.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/4",
"id": "4",
"name": "Improvement",
"description": "An improvement or enhancement to an existing feature or task.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/improvement.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/5",
"id": "5",
"name": "Sub-task",
"description": "The sub-task of the issue",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/subtask_alternate.png",
"subtask": true
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10001",
"id": "10001",
"name": "\u6d4b\u8bd5",
"description": "\u6b64\u53d1\u5e03\u7c7b\u578b\u7528\u4e8e\u5728 Jira \u4e2d\u521b\u5efa Zephyr \u6d4b\u8bd5\u3002",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/com.thed.zephyr.je/images/icons/ico_zephyr_issuetype.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10100",
"id": "10100",
"name": "Epic",
"description": "Created by JIRA Agile - do not edit or delete. Issue type for a big user story that needs to be broken down.",
"iconUrl": "http://xxx.xx.xx.xxx:48082/images/icons/issuetypes/epic.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10200",
"id": "10200",
"name": "Ticket Template(WBSGantt)",
"description": "Ticket Template",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/template-icon.png",
"subtask": false
},
{
"self": "http://xxx.xx.xx.xxx:48082/rest/api/2/issuetype/10201",
"id": "10201",
"name": "Phase",
"description": "Project Development Phase",
"iconUrl": "http://xxx.xx.xx.xxx:48082/download/resources/jp.ricksoft.plugins.wbsgantt-for-jira:wbsgantt-resources/images/phase-icon.png",
"subtask": false
}
],
"avatarUrls": {
"24x24": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=small&pid=10005&avatarId=10011",
"16x16": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=xsmall&pid=10005&avatarId=10011",
"32x32": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?size=medium&pid=10005&avatarId=10011",
"48x48": "http://xxx.xx.xx.xxx:48082/secure/projectavatar?pid=10005&avatarId=10011"
}
}
]
}
</code></pre>
| 1 | 2016-07-31T09:46:37Z | 38,698,327 | <p>The error detail message is:</p>
<pre><code>Field 'description' cannot be set. It is not on the appropriate screen, or unknown.
</code></pre>
<p>If you go to the <em>Project Settings</em> of your project in JIRA and click on <em>Screens</em> then you can check the <em>Screen Scheme</em> that is associated with your project. The screen scheme lists which screen is used for each issue operation (create, edit, view). Your <em>Create Screen</em> does not contain the <em>description</em> field, but you do try to set it in the body of your create request. That's why you get the 400 error.</p>
<p>You have a few options:</p>
<ul>
<li>Don't specify the description field in your request body</li>
<li>Update your <em>Create Screen</em> to show the <em>description</em> field</li>
</ul>
<p>More information about how project screens, schemes etc. relate to each other is available <a href="https://confluence.atlassian.com/adminjiraserver071/project-screens-schemes-and-fields-802592517.html" rel="nofollow">here</a>.
More information about how to configure screens is available <a href="https://confluence.atlassian.com/adminjiraserver071/defining-a-screen-802592587.html" rel="nofollow">here</a>.</p>
| 0 | 2016-08-01T11:59:41Z | [
"python",
"jira",
"jira-rest-api"
] |
NLP - extract categories/tags from text | 38,682,784 | <p>Does anyone have any idea or can give me directions about how I can extract categories from an article?</p>
<p>What I have is a corpus of few thousands of articles (about sports, news, buisness etc.) I can work with.</p>
<p>For example, if theres an article about sports I would like my program to know if its soccer or basketball (or somthing else) so the output will be somthing like:</p>
<p>soccer 90% basketball 10%</p>
| 0 | 2016-07-31T09:55:43Z | 38,682,870 | <p>I guess that you can use some machine learning approaches to achieve this. What comes to my mind is using <a href="https://en.wikipedia.org/wiki/Tf%E2%80%93idf" rel="nofollow">tf-idf</a> statistic. </p>
<p>There is an online course on Coursera called "<a href="https://www.coursera.org/specializations/machine-learning" rel="nofollow">Machine Learning Foundations: A Case Study Approach</a>" which teaches how to use <code>tf-idf</code> statistic on week 4 of the course.</p>
| 0 | 2016-07-31T10:07:19Z | [
"python",
"nltk",
"gensim"
] |
NLP - extract categories/tags from text | 38,682,784 | <p>Does anyone have any idea or can give me directions about how I can extract categories from an article?</p>
<p>What I have is a corpus of few thousands of articles (about sports, news, buisness etc.) I can work with.</p>
<p>For example, if theres an article about sports I would like my program to know if its soccer or basketball (or somthing else) so the output will be somthing like:</p>
<p>soccer 90% basketball 10%</p>
| 0 | 2016-07-31T09:55:43Z | 38,683,983 | <p>As you don't have gold data for training, first you will need to create some.</p>
<p>For that, you will need to <strong>define your classes</strong> and define some <strong>rules</strong> which are obvious selection for each class,</p>
<pre><code>article_text.contains("soccer")
article_text.contains("Ronaldo")
</code></pre>
<p>and so on to make your own tagged corpus for each class. </p>
<p>It will not be 100% accurate training data but still it will be good enough for training purpose.</p>
<p>Then you can use any ML algorithm for training and testing. </p>
| 0 | 2016-07-31T12:29:54Z | [
"python",
"nltk",
"gensim"
] |
How do I cast a 2D list to a void pointer and back | 38,682,817 | <p>I'm trying to write two Cython functions to wrap external functions. The functions are the inverse of each another; one accepts a string, and returns a struct with two fields: a void pointer to a 2D array (the second dimension is always two elements: <code>[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], ⦠]</code>), and the array's length. The other accepts the same struct, and returns a string. So far, I've got the following. It compiles, but the cast to and from the nested list is definitely incorrect.</p>
<p>My <code>.pxd</code>:</p>
<pre><code>cdef extern from "header.h":
struct _FFIArray:
void* data
size_t len
cdef _FFIArray decode_polyline_ffi(char* polyline, int precision);
cdef char* encode_coordinates_ffi(_FFIArray, int precision);
cdef void drop_float_array(_FFIArray coords);
cdef void drop_cstring(char* polyline)
</code></pre>
<p>My <code>.pyx</code>:</p>
<pre><code>import numpy as np
from pypolyline_p cimport (
_FFIArray,
decode_polyline_ffi,
encode_coordinates_ffi,
drop_float_array,
drop_cstring
)
def encode_coordinates(coords, int precision):
""" coords looks like [[1.0, 2.0], [3.0, 4.0], â¦] """
cdef double[::1] ncoords = np.array(coords, dtype=np.float64)
cdef _FFIArray coords_ffi
# Wrong
coords_ffi.data = <void*>&ncoords[0]
# Wrong
coords_ffi.len = ncoords.shape[0]
cdef char* result = encode_coordinates_ffi(coords_ffi, precision)
cdef bytes polyline = result
drop_cstring(result)
return polyline
def decode_polyline(bytes polyline, int precision):
cdef char* to_send = polyline
cdef _FFIArray result = decode_polyline_ffi(to_send, precision)
# Wrong
cdef double* incoming_ptr = <double*>(result.data)
# Wrong
cdef double[::1] view = <double[:result.len:1]>incoming_ptr
coords = np.copy(view)
drop_float_array(result)
return coords
</code></pre>
| 3 | 2016-07-31T10:00:27Z | 38,683,207 | <p>I think the issue is that you're trying to use 2D arrays and 1D memoryviews</p>
<p>In the encoding function </p>
<pre><code> # the coords are a 2D, C contiguous array
cdef double[:,::1] ncoords = np.array(coords, dtype=np.float64)
# ...
coords_ffi.data = <void*>&ncoords[0,0] # take the 0,0 element
# the rest stays the same
</code></pre>
<p>In the decoding function</p>
<pre><code> # specify it as a 2D, len by 2, C contiguous array
cdef double[:,::1] view = <double[:result.len,:2:1]>incoming_ptr
# the rest stays the same
</code></pre>
<p>(It's possible that your FFI functions expect Fortran contiguous arrays. In which case the <code>::1</code> goes on the first dimension of the memoryview, and you also change <code>incoming_ptr</code>)</p>
| 3 | 2016-07-31T10:52:24Z | [
"python",
"numpy",
"cython"
] |
Can't import module in folders aside from home | 38,682,909 | <p>I was trying to install the module, tweepy, through the python3 shell on Ubuntu in a folder called dtrump in my home directory (donald trump response twitter bot), except it keeps saying "ImportError: No module named 'tweepy'". While you may think I simply did not install tweepy, I have, I even uninstalled to reinstall. The weird thing is I can import tweepy through the shell as long as I'm in the home directory and no child folders. I am running the latest version of python, pip, and ubuntu.</p>
| 0 | 2016-07-31T10:11:42Z | 38,683,825 | <p>Run the following command from a terminal:</p>
<pre><code>sudo apt-get install python3-pip
</code></pre>
<p>This should help</p>
| 0 | 2016-07-31T12:11:00Z | [
"python",
"python-3.x",
"ubuntu",
"module",
"pip"
] |
Cube root of negative real numbers | 38,682,936 | <p>I'm trying to plot a quite complex function, i.e. <code>log(x/(x-2))**Rational(1,3)</code>. I'm working only with real numbers. If I try to plot it, <code>sympy</code> only plots the <strong>x>2 part</strong> of it.</p>
<p>I found that actually complex numbers come into play and, for example,<code>root(-8,3).n()</code> gives:</p>
<blockquote>
<p>1.0+1.73205080756888i</p>
</blockquote>
<p>Which is reasonable, even though it's not what I was looking for (because I'm only interested in the real result).</p>
<p>Reading <a href="https://groups.google.com/forum/#!topic/sympy/7MgDY2AKPzA" rel="nofollow">sympy ⺠principle root</a> I found that <code>real_root(-8,3)</code> gives <code>-2</code> as expected. But I still cannot plot the <strong>x<0 part</strong> of that function; in fact it seems that <code>real_root</code> only works for integer roots, and <code>real_root(-9,3).n()</code> still gives an imaginary result, instead of <code>-(real_root(9, 3))</code> as I would expect.</p>
<p>I thought a real result existed for (-9)^(1/3) and I don't understand why <code>real_root</code> gives an imaginary result instead.</p>
<p>Is there a simple way to get a schoolbook result for the cube root of real negative numbers, like (-x)^(1/3) = - (x)^(1/3)?</p>
<p><strong>Edit</strong>:<br>
Following @Leon 's suggestion: I updated <code>sympy</code> and could actually calculate the real cube root of -9.
But still I cannot plot the function I mentioned at the beginning of the topic.</p>
<pre><code>from sympy import *
var('x')
f=real_root((log(x/(x-2))), 3)
plot(f)
</code></pre>
<p>gives an error like <code>NameError: name 'Ne' is not defined</code>.
I noticed that trying to print <code>f</code> results in</p>
<pre><code>Piecewise((1, Ne(arg(x/(x - 2)), 0)), ((-1)**(2/3), log(x/(x - 2)) < 0), (1, True))*log(x/(x - 2))**(1/3)
</code></pre>
<p>Does that <code>Ne</code> have something to do with my error?</p>
| 2 | 2016-07-31T10:15:59Z | 38,707,315 | <p>It seems SymPy's plot has a bug, so for now, you'll have to use <code>lambdify</code> and <code>matplotlib</code> to plot it manually:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
f = lambdify(x, (real_root((log(x/(x-2))), 3)), 'numpy')
vals = np.linspace(2, 10, 1000)
plt.plot(vals, f(vals))
</code></pre>
<p>This gives some warnings because the 2 value at the end point is a singularity, and also warns that if you have a complex number that the imaginary part is ignored.</p>
<p>Here is the plot<a href="http://i.stack.imgur.com/lPlHU.png" rel="nofollow"><img src="http://i.stack.imgur.com/lPlHU.png" alt="enter image description here"></a></p>
| 2 | 2016-08-01T20:12:11Z | [
"python",
"sympy",
"python-3.5"
] |
Sqlite3 & Python creating tables | 38,683,021 | <p>I'm trying to use the scrapy pipeline to store its data in a sqlite3 database here is the little part that trows a OperationalError: near "Transaction": syntax error</p>
<pre><code>def createResidentialTable(self):
self.cur.execute("""CREATE TABLE IF NOT EXISTS Residential
(Id INT PRIMARY KEY NOT NULL, Transaction TEXT, Location TEXT, Price REAL)""")
</code></pre>
<p>My debugging so far, if i remove the Transaction TEXT & Location TEXT & Price Real from the creating tables my spider runs again. So i'm assuming there is something wrong with my listing of the tables.</p>
<p>Have looked trough some code examples and the official sqlite3 documentation and they list it as followed :</p>
<h1>Create table</h1>
<pre><code>c.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
</code></pre>
<p>Any thoughts or suggestions?</p>
| 0 | 2016-07-31T10:28:21Z | 38,683,056 | <p><code>Transaction</code> is a <a href="https://www.sqlite.org/lang_keywords.html" rel="nofollow">reserved keyword</a> which you are not allowed to use as an identifier. Just use something other than <code>Transaction</code> as an identifier.</p>
| 1 | 2016-07-31T10:31:34Z | [
"python",
"sqlite",
"sqlite3"
] |
No module named pymongo - Jython | 38,683,037 | <p>I have a python script and i am executing the same through java process using Jython.</p>
<p>Database - <strong>mongodb</strong></p>
<p><strong>Pom.xml</strong></p>
<pre><code><dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
</code></pre>
<p>Java Process</p>
<pre><code>public String execute(String val) throws FileNotFoundException,
ScriptException {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = (InputStream) classLoader
.getResourceAsStream("my.py");
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(is);
PyObject someFunc = interpreter.get("myFunc");
PyObject result = someFunc.__call__(new PyString(val));
String realResult = (String) result.__tojava__(String.class);
return realResult;
}
</code></pre>
<p>When i run python script, <strong><code>my.py</code></strong>, i get below error</p>
<pre><code>File "<iostream>", line 3, in <module>
ImportError: No module named pymongo
</code></pre>
| 0 | 2016-07-31T10:30:19Z | 38,683,492 | <p>I solved by importing the module like below :-</p>
<pre><code> PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
PySystemState sys = interpreter.getSystemState();
sys.path.append(new PyString("\\python_modules\\pymongo-3.3.0-cp26-none-win_amd64.whl"));
</code></pre>
<p>I have downloaded the <strong>pymongo</strong> module from <a href="https://pypi.python.org/pypi/pymongo/#downloads" rel="nofollow">here</a>.
The above worked for me, this way we can import modules through jython.</p>
| 0 | 2016-07-31T11:29:08Z | [
"java",
"python",
"mongodb",
"jython-2.7"
] |
404 on media files - Django | 38,683,105 | <p>Last night I uploaded my project to pythonanywhere.com where I wanted to test my <strong>production</strong> settings. In one of my models I allow <strong>users to upload</strong> JPG's (Logo of a team). The uploading process works good, the file lands in my MEDIA_ROOT. The issue is that when I try to access it in my template (to display it on the page) I get a 404. My first thought is that my MEDIA_URL is not configured properly but I still don't know why. I want to say that my media folder isn't in the project - it is outside.
On <strong>development</strong> mode I see the Logo (I have the if settings.DEBUG: urlpattern += static(...) option set properly).</p>
<p>I'm using Django 1.9.7 with python 2.7
Here is my code:</p>
<p>My model:</p>
<pre><code>class Team(models.Model):
name = models.CharField(verbose_name='Name of the team', max_length=24)
logo = models.ImageField(upload_to='team_logos', verbose_name='Logo', blank=True, null=True)
def get_logo(self):
u"""Get path to logo, if there is no logo then show default."""
if self.logo:
return self.logo.url
return '/static/img/default_team_logo.jpg'
</code></pre>
<p>My Settings.py:</p>
<pre><code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media", "soccerV1", "static")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "media", "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media", "soccerV1", "media")
</code></pre>
<p>And my template where I call for the logo:</p>
<pre><code><td><img src="{{ details.get_logo }}" alt="{{ details.name }} logo" height="64px" width="64px"></td>
</code></pre>
| 2 | 2016-07-31T10:37:48Z | 38,683,329 | <p>You need to set a media files mapping in PythonAnywhere's dashboard. From their <a href="https://help.pythonanywhere.com/pages/DjangoStaticFiles/">documentation</a>:</p>
<ul>
<li>Go to the <strong>Web</strong> tab on the PythonAnywhere dashboard</li>
<li>Go to the <strong>Static Files</strong> section</li>
<li>Enter the same URL as MEDIA_URL in the <strong>url</strong> section (in your case, <code>/media/</code>)</li>
<li>Enter the path from MEDIA_ROOT into the <strong>path</strong> section (the full path, including <code>/home/username/etc</code>)</li>
</ul>
<p>Then hit <strong>Reload</strong> and your uploaded files should be served correctly.</p>
| 5 | 2016-07-31T11:08:21Z | [
"python",
"django",
"django-settings"
] |
Validating id recieved with regular expression | 38,683,217 | <p>I'm trying to get ID from URL (in django):</p>
<pre><code>url(r'^preset/(P<pk>\d+)$', views.route_preset_api.as_view()),
</code></pre>
<p>This works well as long as the input is a number. But if it isn't a number the page will return a 500 error.</p>
<p>How can I do a special case, that will take care of all non-valid inputs and will give for example </p>
<pre><code>pk=0
</code></pre>
<p>as an output?</p>
| 0 | 2016-07-31T10:54:17Z | 38,683,374 | <p>First of all your pattern is missing a required <code>?</code> which specifies a named group. It should be:</p>
<pre><code>r'^preset/(?P<pk>\d+)$'
</code></pre>
<p>which will associate the matched substring with the group name <code>pk</code>, i.e. a named group. Without the <code>?</code> the regex will literally match <code>preset/P<pk></code> followed by 1 or more digits.</p>
<p>Secondly, the regex will not match if any non-digit is present, and a 404 Not Found response will be sent. Possibly the 500 error is occurring elsewhere in your code - is there a less specific pattern that is matching?</p>
<p>To handle invalid requests you could add a second pattern that routes to the same view function, but add a default argument for the <code>pk</code> parameter. The URL pattern would be:</p>
<pre><code>url(r'^preset/[^\d]*$', views.route_preset_api.as_view()),
</code></pre>
<p>and the view function would look something like this:</p>
<pre><code>def route_preset_api(request, pk=0):
...
</code></pre>
<p>Now <code>pk</code> will default to <code>0</code> whenever a request is made that contains a non-digit character.</p>
| 0 | 2016-07-31T11:14:23Z | [
"python",
"regex",
"django"
] |
Tkinter app using sockets hangs on start | 38,683,324 | <p>I am having problems with a socket/tkinter login app. The server is on a Raspberry Pi but even with the server not on I see no reason that this should hang on startup. I have imported a module I have made which I will include.</p>
<p>Why does it hang?</p>
<p>Here is my client code - the one that hangs:</p>
<pre><code>import socket, pickle
import Tkinter as tk
import loginutility
class Server(object):
def __init__(self):
self.s = socket.socket()
self.p = 10000
self.ip = "192.168.1.120"
def addUser(self, userinfo):
puserinfo = pickle.dumps(userinfo)
self.s.connect((self.ip, self.p))
self.s.sendall("check")
self.sendall(puserinfo)
if self.s.recv(1024) == False:
self.s.sendall("add")
self.send(puserinfo)
return True
else:
return False
def userDump(self):
self.s.sendall("userdump")
return pickle.loads(self.s.recv(1024))
class Main(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
class LoginFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.pack()
self.l = loginutility.LoginBox(self)
login = tk.Button(self, text="Login", command=self.login)
login.pack()
def login(self):
u, p = self.l.values()
users = Server.userDump()
if u in users and users[u] == p:
tk.Label(self, text="Success").pack()
main = Main()
mf = LoginFrame(main)
main.mainloop()
</code></pre>
<p>The server code - wasn't on when tested:</p>
<pre><code>import loginutility as lu
import socket
import pickle
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
address = ''
port = 10000
s.bind((address, port))
s.listen(5)
users = lu.UserList("accounts")
while True:
c, clientaddress = s.accept()
c.send("You're Connected")
d = c.recv(1024)
if d == "add":
userdata = c.recv(1024)
username, password = pickle.loads(userdata)
users.adduser(username, password)
print "User {} added with password of {}.".format(username, password)
c.send("Success")
elif d == "check":
username, password = pickle.loads(c.recv(1024))
if users.checkuser(username) == False:
c.sendall(False)
else:
c.sendall(True)
elif d == "userdump":
c.send(pickle.dumps(users.dumpuser())
c.close()
</code></pre>
<p>Necessary loginutility code:</p>
<pre><code>class LoginBox:
def __init__(self, parent):
self.l1=Label(parent, text="Username:").grid()
self.ubox=Entry(parent)
self.ubox.grid()
self.l2=Label(parent, text="Password:").grid()
self.pbox=Entry(parent, show="*")
self.pbox.grid()
def values(self):
return (self.ubox.get(), self.pbox.get())
class UserList:
def __init__(self, file=None):
self.users = {}
self.file = file
if file != None:
with open(file, "rb") as f:
self.users = pickle.load(f)
def adduser(self, user, pswrd):
self.users[user] = pswrd
if file != None:
with open(self.file, "wb") as f:
pickle.dump(self.users, f)
def dumpuser(self):
return self.users
</code></pre>
<p>Any help is much appreciated!</p>
| -1 | 2016-07-31T11:07:42Z | 38,683,667 | <p>The reason it hangs is because you are mixing both <code>pack</code> and <code>grid</code> in the same parent widget. Consider the following code:</p>
<pre><code>class LoginFrame(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.pack()
self.l = loginutility.LoginBox(self)
login = tk.Button(self, text="Login", command=self.login)
login.pack()
</code></pre>
<p>In the above code, you create a frame (<code>self</code>), create a <code>LoginBox</code> that is a child of <code>self</code>, and a button that is also the child of <code>self</code>. The button uses <code>pack</code>, and <code>LoginBox.__init__</code> uses <code>grid</code>.</p>
<p>You cannot use both <code>pack</code> and <code>grid</code> on widgets that share a common parent. In this case the common parent is the instance of <code>LoginFrame</code>. </p>
| 0 | 2016-07-31T11:48:54Z | [
"python",
"sockets",
"tkinter"
] |
Python regex group search returns only the first match | 38,683,380 | <p>I need to extract the contents of the numbered list. Please check the following url: <a href="https://regex101.com/r/oS0yT5/1" rel="nofollow">https://regex101.com/r/oS0yT5/1</a></p>
<pre><code>string = @BarsAndMelody #3thingsthatmakeyousmile #1) @livingleondre #2) Leondre and Charlie #3) chocolate âºï¸ í ½í¹
please notice me í ½í¸ it's my birthdayí ½í±
</code></pre>
<p>The following code extracts only the first match:</p>
<pre><code>p = re.compile("(?<=[#\s][\d][\)\.\:][\s])(.*?)(?=[#][\d][\)\.\:][\s])")
x = p.search(string)
x.group(1)
</code></pre>
<p>The above code returns the first match: <code>@livingleondre</code> using x.group(2) returns <code>No such group error</code>.
As shown in the above given <a href="https://regex101.com/r/oS0yT5/1" rel="nofollow">url</a> how can I extract other contents of the group
Desired output: <code>@livingleondre</code> , <code>Leondre and Charlie</code></p>
| 1 | 2016-07-31T11:14:47Z | 38,683,444 | <p>You need <code>re.findall</code> to find <em>all</em> the matches, not only the first:</p>
<pre><code>string = "@BarsAndMelody #3thingsthatmakeyousmile #1) @livingleondre #2) Leondre and Charlie #3) chocolate âºï¸ í ½í¹
please notice me í ½í¸ it's my birthdayí ½í±"
p = re.findall("(?<=[#\s][\d][\)\.\:][\s])(.*?)(?=[#][\d][\)\.\:][\s])",string)
print p[0]
print p[1]
</code></pre>
<p>Also, you could simplify the regex to this:</p>
<pre><code>(?<=[#\s]\d[).:]\s)(.*?)(?=#\d[).:]\s)
</code></pre>
<p>Since there's no need to escape anything inside <code>[...]</code> and you can omit <code>[...]</code> around single characters.</p>
| 3 | 2016-07-31T11:23:12Z | [
"python",
"regex"
] |
Scrapy - 301 redirect in shell | 38,683,382 | <p>I can not find a solution to the following problem. I am using Scrapy (latest version) and am trying to debug a spider.
Using <code>scrapy shell https://jigsaw.w3.org/HTTP/300/301.html</code> -> it does not follow the redirect ( it is using a default spider to get the data). If I am running my spider it follows the 301 - but I can not debug.</p>
<p>How can you make the shell to follow the 301 to allow one to debug the final page?</p>
| 1 | 2016-07-31T11:14:58Z | 38,683,410 | <p>Scrapy uses Redirect Middleware for redirects, however it's not enabled in shell. Quick fix for this:</p>
<pre><code>scrapy shell "https://jigsaw.w3.org/HTTP/300/301.html"
fetch(response.headers['Location'])
</code></pre>
<p>Also to debug your spider you probably want to inspect the response your spider is receiving:</p>
<pre><code>from scrapy.shell import inspect_response
def parse(self, response)
inspect_response(response, self)
# the spider will stop here and open up an interactive shell during the run
</code></pre>
| 2 | 2016-07-31T11:18:36Z | [
"python",
"web-scraping",
"scrapy",
"scrapy-shell"
] |
Python - return date and time value and use it later | 38,683,386 | <p>I have the following code, but I'm not quite sure how it's going to work.</p>
<p>I'll execute the following:</p>
<pre><code>date = strftime("%Y-%m-%d %H:%M:%S")
</code></pre>
<p>and it will return exact date and time of the moment I call this. I want to use the exact output of this date and time in another function which is going to be execute 2-3 seconds later.</p>
<p>How can I pass the date variable here and not use the new current time and date?</p>
| 0 | 2016-07-31T11:15:22Z | 38,683,417 | <p>Does anything stop you from passing <code>date</code> as a parameter to your other function ? </p>
<p><a href="http://www.tutorialspoint.com/python/python_functions.htm" rel="nofollow">http://www.tutorialspoint.com/python/python_functions.htm</a></p>
<p>If you can't pass it as a parameter, and both functions are within the same object / class, you can use <code>self.date = strftime("%Y-%m-%d %H:%M:%S")</code> and on your other function use <code>self.date</code> when you need to read it.</p>
<p><a href="https://docs.python.org/3/tutorial/classes.html#class-objects" rel="nofollow">https://docs.python.org/3/tutorial/classes.html#class-objects</a></p>
<p>Finally you can simply set a global variable, but depending on your project, this may cause bugs, if for example the code is multi-threaded (like a web application).</p>
<p><a href="http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them">Using global variables in a function other than the one that created them</a></p>
| 1 | 2016-07-31T11:19:34Z | [
"python",
"python-2.7"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p>But same website(<a href="http://www.base64decode.org" rel="nofollow">base64decode</a>) can decode it, </p>
<p>Please anybody can tell me why, and how to use python3.5 decode it?</p>
<p>Thanks</p>
| 2 | 2016-07-31T11:23:01Z | 38,683,518 | <p>According to this <a href="http://stackoverflow.com/a/2942039/6495334">answer</a>, you can just add the required padding.</p>
<pre><code>code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA"
b64_string = code
b64_string += "=" * ((4 - len(b64_string) % 4) % 4)
base64.b64decode(b64_string) #'admin:202cb962ac59075b964b07152d234b70'
</code></pre>
| 0 | 2016-07-31T11:31:24Z | [
"python",
"base64"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p>But same website(<a href="http://www.base64decode.org" rel="nofollow">base64decode</a>) can decode it, </p>
<p>Please anybody can tell me why, and how to use python3.5 decode it?</p>
<p>Thanks</p>
| 2 | 2016-07-31T11:23:01Z | 38,683,522 | <p>It actually seems to just be that <code>code</code> is incorrectly <a href="https://en.wikipedia.org/wiki/Base64#Padding" rel="nofollow">padded</a> (<code>code</code> is incomplete)</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA"
base64.b64decode(code+"=")
</code></pre>
<p>returns <code>b'admin:202cb962ac59075b964b07152d234b70'</code></p>
| 0 | 2016-07-31T11:31:47Z | [
"python",
"base64"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p>But same website(<a href="http://www.base64decode.org" rel="nofollow">base64decode</a>) can decode it, </p>
<p>Please anybody can tell me why, and how to use python3.5 decode it?</p>
<p>Thanks</p>
| 2 | 2016-07-31T11:23:01Z | 38,683,523 | <p>Base64 needs a string with length multiple of 4. If the string is short, it is padded with 1 to 3 <code>=</code>.</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA="
base64.b64decode(code)
# b'admin:202cb962ac59075b964b07152d234b70'
</code></pre>
| 2 | 2016-07-31T11:31:47Z | [
"python",
"base64"
] |
How to decode base64 in python3 | 38,683,439 | <p>I have a base64 encrypt code, and I can't decode in python3.5</p>
<pre><code>import base64
code = "YWRtaW46MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA" # Unencrypt is 202cb962ac59075b964b07152d234b70
base64.b64decode(code)
</code></pre>
<p>Result:</p>
<pre><code>binascii.Error: Incorrect padding
</code></pre>
<p>But same website(<a href="http://www.base64decode.org" rel="nofollow">base64decode</a>) can decode it, </p>
<p>Please anybody can tell me why, and how to use python3.5 decode it?</p>
<p>Thanks</p>
| 2 | 2016-07-31T11:23:01Z | 38,683,654 | <p>I tried the other way around. If you know what the unencrypted value is:</p>
<pre><code>>>> import base64
>>> unencoded = b'202cb962ac59075b964b07152d234b70'
>>> encoded = base64.b64encode(unencoded)
>>> print(encoded)
b'MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA='
>>> decoded = base64.b64decode(encoded)
>>> print(decoded)
b'202cb962ac59075b964b07152d234b70'
</code></pre>
<p>Now you see the correct padding. <code>b'MjAyY2I5NjJhYzU5MDc1Yjk2NGIwNzE1MmQyMzRiNzA=</code></p>
| 0 | 2016-07-31T11:47:21Z | [
"python",
"base64"
] |
How to apply my own function along each rows and columns with NumPy | 38,683,562 | <p>I'm using NumPy to store data into matrices.
I'm struggling to make the below Python code perform better.
<code>RESULT</code> is the data store I want to put the data into.</p>
<pre><code>TMP = np.array([[1,1,0],[0,0,1],[1,0,0],[0,1,1]])
n_row, n_col = TMP.shape[0], TMP.shape[0]
RESULT = np.zeros((n_row, n_col))
def do_something(array1, array2):
intersect_num = np.bitwise_and(array1, array2).sum()
union_num = np.bitwise_or(array1, array2).sum()
try:
return intersect_num / float(union_num)
except ZeroDivisionError:
return 0
for i in range(n_row):
for j in range(n_col):
if i >= j:
continue
RESULT[i, j] = do_something(TMP[i], TMP[j])
</code></pre>
<p>I guess it would be much faster if I could use some NumPy built-in function instead of for-loops.</p>
<p>I was looking for the various questions around here, but I couldn't find the best fit for my problem.
Any suggestion? Thanks in advance!</p>
| 2 | 2016-07-31T11:36:44Z | 38,684,188 | <p><strong>Approach #1</strong></p>
<p>You could do something like this as a vectorized solution -</p>
<pre><code># Store number of rows in TMP as a paramter
N = TMP.shape[0]
# Get the indices that would be used as row indices to select rows off TMP and
# also as row,column indices for setting output array. These basically correspond
# to the iterators involved in the loopy implementation
R,C = np.triu_indices(N,1)
# Calculate intersect_num, union_num and division results across all iterations
I = np.bitwise_and(TMP[R],TMP[C]).sum(-1)
U = np.bitwise_or(TMP[R],TMP[C]).sum(-1)
vals = np.true_divide(I,U)
# Setup output array and assign vals into it
out = np.zeros((N, N))
out[R,C] = vals
</code></pre>
<p><strong>Approach #2</strong></p>
<p>For cases with <code>TMP</code> holding <code>1s</code> and <code>0s</code>, those <code>np.bitwise_and</code> and <code>np.bitwise_or</code> would be replaceable with dot-products and as such could be faster alternatives. So, with those we would have an implementation like so -</p>
<pre><code>M = TMP.shape[1]
I = TMP.dot(TMP.T)
TMP_inv = 1-TMP
U = M - TMP_inv.dot(TMP_inv.T)
out = np.triu(np.true_divide(I,U),1)
</code></pre>
| 1 | 2016-07-31T12:55:33Z | [
"python",
"python-3.x",
"numpy"
] |
Embedding Matplotlib and Slider in Tk window | 38,683,656 | <p>I am trying to embed a matplotlib window inside a tkinter GUI, but I am having trouble getting the "slider" widget to show up. In fact, the code below does show an embedded image, but the image itself is behaving like a slider, if you click on it!</p>
<p>I have tried using the ideas from this question </p>
<p><a href="http://stackoverflow.com/questions/31440167/placing-plot-on-tkinter-main-window-in-python">Placing plot on Tkinter main window in Python</a></p>
<pre><code>import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from matplotlib.widgets import Slider
import Tkinter as tk
class Embed:
def __init__(self, root):
self.root = root
self.plot = Plotting(self.root)
self.a = np.array([[1,2,3],[2,3,4],[3,4,5]])
self.b = np.array([[1,2,3],[4,5,6],[7,8,9]])
self.ctuple = (self.a,self.b)
self.cube = np.dstack(self.ctuple)
self.button = tk.Button(root, text="check", command=lambda: self.plot.plot(self.cube))
self.button.pack()
class Plotting:
def __init__(self, root):
self.root = root
def plot(self, cube, axis=2, **kwargs):
fig = Figure(figsize=(6,6))
ax = fig.add_subplot(111)
s = [slice(0,1) if i == axis else slice(None) for i in xrange(3)]
im = cube[s].squeeze()
l = ax.imshow(im, **kwargs)
canvas = FigureCanvasTkAgg(fig, self.root)
canvas.get_tk_widget().pack()
canvas.draw()
slider = Slider(ax, 'Axis %i index' % axis, 0, cube.shape[axis] - 1,
valinit=0, valfmt='%i')
def update(val):
ind = int(slider.val)
s = [slice(ind, ind + 1) if i == axis else slice(None)
for i in xrange(3)]
im = cube[s].squeeze()
l.set_data(im, **kwargs)
canvas.draw()
slider.on_changed(update)
if __name__ == '__main__':
root = tk.Tk()
app = Embed(root)
root.mainloop()
root.destroy()
</code></pre>
<p>any help is much appreciated!</p>
| 0 | 2016-07-31T11:47:41Z | 38,692,794 | <p>I don't know what your code does. I tried to change it as little as I can:</p>
<pre><code>import matplotlib
matplotlib.use('TkAgg')
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import Tkinter as Tk
import matplotlib.pyplot as plt
class Embed:
def __init__(self, root_):
self.root = root_
self.a = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
self.b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
self.c = np.array([[1, 4, 7], [4, 7, 10], [7, 10, 13]])
self.ctuple = (self.a, self.b)
self.cube = np.dstack(self.ctuple)
self.cube = np.dstack([self.cube, self.c])
self.plot = Plotting(self.root, self.cube)
self.button = Tk.Button(root, text="check", command=lambda: self.plot.plot())
self.button.pack()
class Plotting:
def __init__(self, root, cube):
self.root = root
self.fig = Figure(figsize=(6, 6))
self.ax = self.fig.add_subplot(111)
self.cube = cube
self.slider = Tk.Scale(
self.root, from_=0, to=cube.shape[2] - 1, resolution=0.01, orient=Tk.HORIZONTAL, command=self.update
)
# self.slider.on_changed(self.update)
self.slider.pack()
self.plotted = False
self.l = None
self.canvas = None
plt.show()
def plot(self, **kwargs):
self.plotted = True
s = [slice(0, 1) if i == 2 else slice(None) for i in xrange(3)]
im = self.cube[s].squeeze()
self.l = self.ax.imshow(im, **kwargs)
self.canvas = FigureCanvasTkAgg(self.fig, self.root)
self.canvas.get_tk_widget().pack()
self.canvas.draw()
def update(self, val):
ind = int(self.slider.get())
s = [slice(ind, ind + 1) if i == 2 else slice(None) for i in xrange(3)]
if self.plotted:
im = self.cube[s].squeeze()
self.l.set_data(im)
self.canvas.draw()
if __name__ == '__main__':
root = Tk.Tk()
app = Embed(root)
root.mainloop()
root.destroy()
</code></pre>
| 0 | 2016-08-01T07:04:54Z | [
"python",
"python-2.7",
"matplotlib",
"tkinter"
] |
Print Arabic words from Python to ESC/POS printer? | 38,683,686 | <p>I have an Odoo implementation, and I need to print Arabic words to an ESC/POS printer.</p>
<p>The Odoo community has already developed a Python module that translates UTF-8 text to ESC/POS Code Page. The problem is that when I print Arabic text I'm getting reversed text and disconnected letters.</p>
<p>How do I print correct Arabic word from Python to ESC/POS?</p>
<p>See the <a href="https://github.com/odoo/odoo/blob/8.0/addons/hw_escpos/escpos/escpos.py#L715" rel="nofollow"><code>Escpos.text</code></a> method from <code>escpos.py</code> for reference.</p>
| 2 | 2016-07-31T11:50:42Z | 39,425,875 | <p>As noted in the comments, it is not a trivial task display UTF-8 Arabic text correctly on an embedded device. You need to handle text direction, joining and character encoding.</p>
<p>I've had an attempt at this in the past for a <a href="https://github.com/mike42/escpos-php" rel="nofollow">PHP ESC/POS driver</a> that I maintain, and was unable to get joined Arabic characters in native ESC/POS. However, I did end up settling on <a href="https://github.com/mike42/escpos-php/blob/ba2ed8c0b78fd4aa4cc2a16eb5f81c29b0e83307/example/specific/6-arabic-epos-tep-220m.php" rel="nofollow">this workaround</a> (PHP) that printed images instead.</p>
<p>The basic steps to working around this are:</p>
<ul>
<li>Get an Arabic font, some text libraries, and an image library</li>
<li>Join ('reshape') the characters</li>
<li>Convert the UTF-8 to LTR (print) order, using the bidi text layout algorithm</li>
<li>Slap it on an image, right aligned</li>
<li>Print the image</li>
</ul>
<p>To port this to python, I lent on <a href="http://stackoverflow.com/questions/5732408/printing-bidi-text-to-an-image">this answer</a> using <a href="http://wand-py.org/" rel="nofollow">Wand</a>. The Python Image Library (PIL) was displaying diacritics as separate characters, making the output unsuitable.</p>
<p>The dependencies are listed in the comments.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Print an Arabic string to a printer.
# Based on example from escpos-php
# Dependencies-
# - pip install wand python-bidi python-escpos
# - sudo apt-get install fonts-hosny-thabit
# - download arabic_reshaper and place in arabic_reshaper/ subfolder
import arabic_reshaper
from escpos import printer
from bidi.algorithm import get_display
from wand.image import Image as wImage
from wand.drawing import Drawing as wDrawing
from wand.color import Color as wColor
# Some variables
fontPath = "/usr/share/fonts/opentype/fonts-hosny-thabit/Thabit.ttf"
textUtf8 = u"بعض اÙÙØµÙص Ù
Ù Ø¬ÙØ¬Ù ترجÙ
Ø©"
tmpImage = 'my-text.png'
printFile = "/dev/usb/lp0"
printWidth = 550
# Get the characters in order
textReshaped = arabic_reshaper.reshape(textUtf8)
textDisplay = get_display(textReshaped)
# PIL can't do this correctly, need to use 'wand'.
# Based on
# http://stackoverflow.com/questions/5732408/printing-bidi-text-to-an-image
im = wImage(width=printWidth, height=36, background=wColor('#ffffff'))
draw = wDrawing()
draw.text_alignment = 'right';
draw.text_antialias = False
draw.text_encoding = 'utf-8'
draw.text_kerning = 0.0
draw.font = fontPath
draw.font_size = 36
draw.text(printWidth, 22, textDisplay)
draw(im)
im.save(filename=tmpImage)
# Print an image with your printer library
printer = printer.File(printFile)
printer.set(align="right")
printer.image(tmpImage)
printer.cut()
</code></pre>
<p>Running the script gives you a PNG, and prints the same to a printer at "/dev/usb/lp0".</p>
<p><a href="http://i.stack.imgur.com/UvByg.png" rel="nofollow"><img src="http://i.stack.imgur.com/UvByg.png" alt="Output example"></a></p>
<p>This is a standalone <a href="https://github.com/python-escpos/python-escpos" rel="nofollow">python-escpos</a> demo, but I'm assuming that Odoo has similar commands for alignment and image output.</p>
<p><strong>Disclaimer:</strong> I don't speak or write Arabic even slightly, so I can't be sure this is correct. I'm just visually comparing the print-out to what Google translate gave me.</p>
<p><a href="http://i.stack.imgur.com/A5nU1.png" rel="nofollow"><img src="http://i.stack.imgur.com/A5nU1.png" alt="Google translate in use"></a></p>
| 0 | 2016-09-10T12:02:03Z | [
"python",
"escpos"
] |
Python Pandas: How to set Dataframe Column value as X-axis labels | 38,683,709 | <p>Say I have data in following format:</p>
<pre><code>Region Men Women
City1 10 5
City2 50 89
</code></pre>
<p>When I load it in Dataframe and plot graph, it shows index as X-axis labels instead of <code>Region</code> name. How do I get names on X-axis?</p>
<p>So far I tried:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
ax = df[['Men','Women']].plot(kind='bar', title ="Population",figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel("Areas",fontsize=12)
ax.set_ylabel("Population",fontsize=12)
plt.show()
</code></pre>
<p>Currently it shows x ticks as <code>0,1,2..</code></p>
| 3 | 2016-07-31T11:54:14Z | 38,683,832 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.bar.html" rel="nofollow">plot.bar()</a> method inherits its arguments from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">plot()</a>, which has <code>rot</code> argument:</p>
<p>from the docs:</p>
<blockquote>
<p><strong>rot</strong> : int, default None</p>
<p>Rotation for ticks (xticks for vertical,
yticks for horizontal plots)</p>
</blockquote>
<p>it also uses per default index as ticks for x axis:</p>
<blockquote>
<p><strong>use_index</strong> : boolean, default True</p>
<p>Use index as ticks for x axis</p>
</blockquote>
<pre><code>In [34]: df.plot.bar(x='Region', rot=0, title='Population', figsize=(15,10), fontsize=12)
Out[34]: <matplotlib.axes._subplots.AxesSubplot at 0xd09ff28>
</code></pre>
<p>alternatively you can set index explicitly - it might be useful for multi-level indexes (axes):</p>
<pre><code>df.set_index('Region').plot.bar(rot=0, title='Population', figsize=(15,10), fontsize=12)
</code></pre>
<p><a href="http://i.stack.imgur.com/XTKJm.png" rel="nofollow"><img src="http://i.stack.imgur.com/XTKJm.png" alt="enter image description here"></a></p>
| 2 | 2016-07-31T12:11:36Z | [
"python",
"pandas",
"matplotlib",
"dataframe"
] |
Python Pandas: How to set Dataframe Column value as X-axis labels | 38,683,709 | <p>Say I have data in following format:</p>
<pre><code>Region Men Women
City1 10 5
City2 50 89
</code></pre>
<p>When I load it in Dataframe and plot graph, it shows index as X-axis labels instead of <code>Region</code> name. How do I get names on X-axis?</p>
<p>So far I tried:</p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
ax = df[['Men','Women']].plot(kind='bar', title ="Population",figsize=(15,10),legend=True, fontsize=12)
ax.set_xlabel("Areas",fontsize=12)
ax.set_ylabel("Population",fontsize=12)
plt.show()
</code></pre>
<p>Currently it shows x ticks as <code>0,1,2..</code></p>
| 3 | 2016-07-31T11:54:14Z | 38,683,877 | <p>Since you're using pandas, it looks like you can pass the tick labels right to the DataFrame's <code>plot()</code> method. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html" rel="nofollow">(docs)</a>. (e.g. <code>df.plot(..., xticks=<your labels>)</code>)</p>
<p>Additionally, since pandas uses matplotlib, you can control the labels that way.</p>
<p>For example with <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xticks" rel="nofollow"><code>plt.xticks()</code></a> <a href="http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html" rel="nofollow">(example)</a> or <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_xticklabels" rel="nofollow"><code>ax.set_xticklabels()</code></a> </p>
<p>Regarding the rotation, the last two methods allow you to pass a rotation argument along with the labels. So something like:</p>
<pre><code>ax.set_xticklabels(<your labels>, rotation=0)
</code></pre>
<p>should force them to lay horizontally.</p>
| 2 | 2016-07-31T12:16:01Z | [
"python",
"pandas",
"matplotlib",
"dataframe"
] |
Django's Model.save() modifies undesired columns | 38,683,838 | <p>Recently I've found that Django ORM's <code>Model.save()</code> executes an SQL to update 'ALL' columns by default, even if nothing has been modified.
This really concerns me, because any changes I made has a chance to be set back to the original value by some other <code>Model.save()</code> process.</p>
<p>For example, I have a model <code>Order</code>. And there are two concurrent processes (P1, P2) working on it. First of all, P1 selects a row:</p>
<pre><code># P1
order = Order.objects.get(pk=10000)
</code></pre>
<p>Then, P2 selects the same row and updates the <code>status</code> column: (the following statements can be wrapped in a transaction, or even a SERIALIZABLE one, but this can not solve the issue.)</p>
<pre><code># P2
order = Order.objects.get(pk=10000)
if order.status == UNPAID:
order.status = PAID # update the `status` column
order.save()
</code></pre>
<p>After that, P1 updates some other trivial column:</p>
<pre><code># P1
order.xxx = xxx # update some other trivial column
order.save() # This would set the `status` back to UNPAID !!!
</code></pre>
<p><code>order.status</code> would be set back to <code>UNPAID</code>, and that is NOT what I want.</p>
<p>I know I can use <code>save(update_fields=...)</code>, <code>select_for_update()</code>, <code>filter(...).update(...)</code>, SERIALIZABLE transaction, or explicit locking on P1 to prevent this issue.
But the thing is: It's ridiculous to use them on all <code>Model.save()</code> statements in the whole project. Furthermore, even if I do in my project code, there's some other code doing this (Django Admin, ModelForm...).</p>
<p>Should I rewrite <code>Model.save()</code> to update only those modified fields?</p>
<p>(It seems like a severe problem to me. Or have I taken something wrong?)</p>
| 2 | 2016-07-31T12:12:09Z | 38,684,417 | <p>As other folks said in comments, you have classic type of <a href="http://stackoverflow.com/questions/34510/what-is-a-race-condition">race condition</a>. There are some ways of dealing this in Django. You've already mention some of this, but they can't be considered safety in my experience. I highly suggest you to watch <a href="https://www.youtube.com/watch?v=e2ikLB1Ka3Q" rel="nofollow">this video</a> called <code>Immutable Django</code> and start digging in this direction.</p>
<p>Basically you can add some kind of <code>version</code> column in your model and increment it in every save and compare to existing one. If new version is same or less then already saved one - you trying to save unactual entry.</p>
| 0 | 2016-07-31T13:24:14Z | [
"python",
"sql",
"django"
] |
Django's Model.save() modifies undesired columns | 38,683,838 | <p>Recently I've found that Django ORM's <code>Model.save()</code> executes an SQL to update 'ALL' columns by default, even if nothing has been modified.
This really concerns me, because any changes I made has a chance to be set back to the original value by some other <code>Model.save()</code> process.</p>
<p>For example, I have a model <code>Order</code>. And there are two concurrent processes (P1, P2) working on it. First of all, P1 selects a row:</p>
<pre><code># P1
order = Order.objects.get(pk=10000)
</code></pre>
<p>Then, P2 selects the same row and updates the <code>status</code> column: (the following statements can be wrapped in a transaction, or even a SERIALIZABLE one, but this can not solve the issue.)</p>
<pre><code># P2
order = Order.objects.get(pk=10000)
if order.status == UNPAID:
order.status = PAID # update the `status` column
order.save()
</code></pre>
<p>After that, P1 updates some other trivial column:</p>
<pre><code># P1
order.xxx = xxx # update some other trivial column
order.save() # This would set the `status` back to UNPAID !!!
</code></pre>
<p><code>order.status</code> would be set back to <code>UNPAID</code>, and that is NOT what I want.</p>
<p>I know I can use <code>save(update_fields=...)</code>, <code>select_for_update()</code>, <code>filter(...).update(...)</code>, SERIALIZABLE transaction, or explicit locking on P1 to prevent this issue.
But the thing is: It's ridiculous to use them on all <code>Model.save()</code> statements in the whole project. Furthermore, even if I do in my project code, there's some other code doing this (Django Admin, ModelForm...).</p>
<p>Should I rewrite <code>Model.save()</code> to update only those modified fields?</p>
<p>(It seems like a severe problem to me. Or have I taken something wrong?)</p>
| 2 | 2016-07-31T12:12:09Z | 38,759,882 | <p>You only need one column for a similar race condition to happen:</p>
<pre><code># Process 1
account = Account.objects.get(pk=1)
account.balance += 1000
# Process 2
account = Account.objects.get(pk=1)
account.balance -= 10
account.save()
# Process 1
account.save()
</code></pre>
<p>Now the balance deduction from process 2 is lost. You <em>must</em> use <code>select_for_update</code> to ensure your writes are consistent. Even if you only save the "dirty" fields, and make that the default, this will still happen.</p>
| 0 | 2016-08-04T06:23:59Z | [
"python",
"sql",
"django"
] |
How to define (string+int+...) URL Pattern RegEx Django | 38,683,848 | <p>my url :
<code>http://127.0.0.1:8000/avatar/Z0FBQUFBQlhuZWI3ejVzTU10TUwyY0twMFJqZHM5MU1LajdEVnJfSzVWN3RXcUFya00wZjdLOUZmbjBzUG5ZSldibkNXeEtMQ1dsZnE4WXlRd0lNLXllRXhNbS1CUWdFSnc9PQ==</code> </p>
<p>url pattern : <code>url(r'^avatar/(?P<avaID>\w+)$', ReportsController.UserImage),</code></p>
<p>"w+" this means just string or "d+" this means just digit but
i need in url with all character in url pattern django how?</p>
| 0 | 2016-07-31T12:13:10Z | 38,683,888 | <p>Then match every character using <code>.</code>:</p>
<pre><code> url(r'^avatar/(?P<avaID>.+)$', ReportsController.UserImage)
</code></pre>
| 1 | 2016-07-31T12:17:22Z | [
"python",
"django",
"python-2.7"
] |
PyInstaller exe only works when run from cmd | 38,683,881 | <p>I'm trying to pack a python tool I wrote into an exe file for use on Windows 10. As far as I know, the exe is built correctly. It loads and everything works if I run it from the command line. </p>
<p>However, if I try to run the tool from Explorer (double-clicking the icon), I get a "Failed to execute script" error. I've tried building it using the --debug switch, hoping that I could quickly catch any output before cmd closes, but it's just too fast. </p>
<p>The line I use to build the tool is:</p>
<pre><code>pyinstaller.exe --onefile --debug --console --icon=C:\Users\Ross\Desktop\gtt\assets\icon.ico --hidden-import xlrd gtt.py
</code></pre>
<p>It worked perfectly before I began using the reportlab modules: </p>
<pre><code>from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.pagesizes import letter, portrait
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer
</code></pre>
<p>The command line gives absolutely no output regarding errors when I run it using the debug switch:
<a href="http://i.stack.imgur.com/Yr1OQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/Yr1OQ.png" alt="Screenshot showing tool running in cmd"></a></p>
<p>I've tried the following and nothing has worked.</p>
<ul>
<li>--noupx</li>
<li>--onedir</li>
<li>--onefile</li>
</ul>
<p>To sum it up, why would a PyInstaller exe file work when run from the command line, but not from the Windows GUI?</p>
<p><strong>EDIT: The issue seems to be with PyQt4. I went back to a commit where I switch from tkinter to Qt and the issue is still there. The previous build, with tkinter, loads fine from the GUI.</strong></p>
| 0 | 2016-07-31T12:16:43Z | 38,684,586 | <p>I figured it out! </p>
<p>I had to convert the gui.ui file into a package.</p>
<ol>
<li>I created the package "gui," containing an empty __init__.py</li>
<li>I ran <code>pyuic4 gui.ui -o gui.py</code>to convert the gui.ui code into Python</li>
<li>I moved both gui.ui and gui.py files into the gui directory</li>
<li>In my main program code, I imported the module: <code>from gui.gui import *</code></li>
</ol>
<p>Hope that helps anyone else!</p>
| 0 | 2016-07-31T13:45:37Z | [
"python",
"windows",
"pyinstaller"
] |
find the negative couple in matrix using pandas | 38,684,026 | <p>I have got a covariance matrix using <code>dataframe.cov()</code> in pandas, now i want to find all the most negative couple(eg. <code>v1</code> and <code>v3</code> is the most negative couple in the matrix because matrix[<code>v1</code>, <code>v3</code>] is minimum, and then <code>v1</code> and <code>v3</code> is excluded in the next selection phase) in a ascending order, i want to find all the couple with such character.</p>
<p>here is my matrix:</p>
<pre><code> V1 V2 V3 V4 V5
V1 471.189543 404.059694 -59.847099 415.214121 -571.672083
V2 404.059694 4768.251838 3740.331544 557.050042 1750.542728
V3 -59.847099 3740.331544 6563.713527 -782.229345 3378.108799
V4 415.214121 557.050042 -782.229345 1949.914430 -582.306412
V5 -571.672083 1750.542728 3378.108799 -582.306412 3355.819315
</code></pre>
| 2 | 2016-07-31T12:35:48Z | 38,684,337 | <pre><code>import numpy as np
import pandas as pd
df = pd.DataFrame({'V1': [471.18954309999998, 404.05969449999998, -59.847098750000001, 415.21412069999997, -571.67208340000002], 'V2': [404.05969449999998, 4768.2518380000001, 3740.3315439999997, 557.05004150000002, 1750.5427280000001], 'V3': [-59.847098750000001, 3740.3315439999997, 6563.7135269999999, -782.22934510000005, 3378.1087990000001], 'V4': [415.21412069999997, 557.05004150000002, -782.22934510000005, 1949.91443, -582.30641220000007], 'V5': [-571.67208340000002, 1750.5427280000001, 3378.1087990000001, -582.30641220000007, 3355.8193149999997]}, index=['V1', 'V2', 'V3', 'V4', 'V5'])
result = df.stack()
result.name = 'cov'
result = result.reset_index()
result = result.loc[result['level_0'] < result['level_1']]
result = result.sort_values(by='cov')
print(result)
</code></pre>
<p>yields</p>
<pre><code> level_0 level_1 cov
13 V3 V4 -782.229345
19 V4 V5 -582.306412
4 V1 V5 -571.672083
2 V1 V3 -59.847099
1 V1 V2 404.059694
3 V1 V4 415.214121
8 V2 V4 557.050042
9 V2 V5 1750.542728
14 V3 V5 3378.108799
7 V2 V3 3740.331544
</code></pre>
<p>The rows are sorted by covariance in ascending order.</p>
| 2 | 2016-07-31T13:12:45Z | [
"python",
"pandas",
"dataframe",
"covariance"
] |
find the negative couple in matrix using pandas | 38,684,026 | <p>I have got a covariance matrix using <code>dataframe.cov()</code> in pandas, now i want to find all the most negative couple(eg. <code>v1</code> and <code>v3</code> is the most negative couple in the matrix because matrix[<code>v1</code>, <code>v3</code>] is minimum, and then <code>v1</code> and <code>v3</code> is excluded in the next selection phase) in a ascending order, i want to find all the couple with such character.</p>
<p>here is my matrix:</p>
<pre><code> V1 V2 V3 V4 V5
V1 471.189543 404.059694 -59.847099 415.214121 -571.672083
V2 404.059694 4768.251838 3740.331544 557.050042 1750.542728
V3 -59.847099 3740.331544 6563.713527 -782.229345 3378.108799
V4 415.214121 557.050042 -782.229345 1949.914430 -582.306412
V5 -571.672083 1750.542728 3378.108799 -582.306412 3355.819315
</code></pre>
| 2 | 2016-07-31T12:35:48Z | 38,684,983 | <p>consider the dataframe <code>df</code></p>
<pre><code>import numpy as np
import pandas as pd
rows = pd.Index(['V1', 'V2', 'V3', 'V4', 'V5'], name='rows')
cols = pd.Index(['V1', 'V2', 'V3', 'V4', 'V5'], name='cols')
df = pd.DataFrame(
[[ 471.189543, 404.059694, -59.847099, 415.214121, -571.672083,],
[ 404.059694, 4768.251838, 3740.331544, 557.050042, 1750.542728,],
[ -59.847099, 3740.331544, 6563.713527, -782.229345, 3378.108799,],
[ 415.214121, 557.050042, -782.229345, 1949.91443, -582.306412,],
[ -571.672083, 1750.542728, 3378.108799, -582.306412, 3355.819315,]],
rows, cols
)
</code></pre>
<hr>
<h3>Use <code>numpy</code> to find solution more efficiently</h3>
<p>Find the row and col of the minimum value.</p>
<pre><code>pos = df.values.argmin()
rpos = rows[pos // len(cols)]
cpos = cols[pos % len(rows)]
print rpos, cpos, df.loc[rpos, cpos]
V3 V4 -782.229345
</code></pre>
<hr>
<p>Sort the entire dataframe</p>
<pre><code>ti = np.triu_indices(len(rows), 1, len(cols))
argsorted = df.values[ti[0], ti[1]].argsort()
tups = zip(rows[ti[0][argsorted]], cols[ti[1][argsorted]])
df.stack().loc[tups].rename('cov').reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/DCoaC.png" rel="nofollow"><img src="http://i.stack.imgur.com/DCoaC.png" alt="enter image description here"></a></p>
| 1 | 2016-07-31T14:28:29Z | [
"python",
"pandas",
"dataframe",
"covariance"
] |
Django: Umlaut problems in admin page | 38,684,050 | <p>I went through the django tutorial <a href="https://docs.djangoproject.com/en/1.9/intro/tutorial01/" rel="nofollow">https://docs.djangoproject.com/en/1.9/intro/tutorial01/</a>, created a couple of models. Some of the models have German labels with umlauts:</p>
<p><a href="http://i.stack.imgur.com/2PCc6.png" rel="nofollow"><img src="http://i.stack.imgur.com/2PCc6.png" alt="Model with umlaut"></a></p>
<p>When I try to link this item to another item in the UI (or even when I try to edit the item itself in order to replace the umlaut by a ascii-7-bit character) I'm getting </p>
<pre>'ascii' codec can't encode character u'\xfc' in position 1: ordinal not in range(128)</pre>
<p><a href="http://i.stack.imgur.com/VQVLc.png" rel="nofollow"><img src="http://i.stack.imgur.com/VQVLc.png" alt="enter image description here"></a></p>
<p>I didn't edit one single code line so this can hardly be my mistake.... What needs to be done to make this work with sth else than English? I thought this was supporting utf-8 out of the box...</p>
<p>Thanks.</p>
| 0 | 2016-07-31T12:39:02Z | 38,684,224 | <p>Let's say you have a simple model with title attribute. You have to encode that title to <code>utf-8</code>, something like this should work.</p>
<pre><code>class MyModel(models.Model):
title = models.CharField(max_length=255)
def __str__(self):
return self.title.encode('UTF-8')
def __repr__(self)
return self.title.encode('UTF-8')
</code></pre>
| 1 | 2016-07-31T12:59:30Z | [
"python",
"django"
] |
Saving Auto-Incrementing line number in Inline field Django | 38,684,096 | <p>I have the following model as an inline field in another model:</p>
<pre><code>class route_ordering(models.Model):
route_id = models.ForeignKey(route, on_delete=models.CASCADE)
activity_id = models.ForeignKey(activity, on_delete=models.CASCADE)
day = models.IntegerField()
order = models.IntegerField()
</code></pre>
<p>And in the admin.py:</p>
<pre><code>class RouteAdmin(admin.ModelAdmin):
inlines = (RouteOrderingInline,)
</code></pre>
<p>I would like to make "order" self-incrementing from one, so it will be auto filled when I go to the Django admin panel (in the first line order=1 , then order-2 etc.)</p>
<p>I know you can use Default to set an autofilled value, but I want it to increment by itself.</p>
<p>How can I do this?</p>
| 0 | 2016-07-31T12:45:23Z | 38,684,167 | <p>I can't guarantee this will work, and I'm not able to test out right now, but I think you can pass in a generator to your default value arg.</p>
<pre><code>define increment():
return range(1, 1000)
</code></pre>
<p>And wherever your passing in a default just call <code>next(increment())</code></p>
<p>Sorry I can't provide a more detailed example, I'm writing this on my phone XD, but I think that should work.</p>
| 0 | 2016-07-31T12:52:55Z | [
"python",
"django",
"postgresql",
"django-models"
] |
Python - using list() and manipulating lists | 38,684,165 | <p>I seem to have a problem with my list generating script. I'm trying to convert a string into a list of string-lists, in order to use it in a specific fonction. </p>
<p>For exemple I want to convert the string
<code>'abc'</code> to a : <code>[['a'],['b'],['c']]</code>.
so the script i wrote was:</p>
<pre><code>s='some string'
t=[[0]]*len(s)
for i in range(len(s)):
t[i][0] = list(s)[i]
return t
</code></pre>
<p>the problem is that this returns <code>[['g'],['g'],..,['g']]</code> instead of <code>[['s'],['o'],..,['g'])</code>.</p>
<p>I found another way to achieve that, but i can't seem to find the problem of this script.
So,if anyone could help me, i would really appreciate it. Thanks in advance.</p>
| 2 | 2016-07-31T12:52:50Z | 38,684,193 | <p>This is a classic mistake: <code>[[0]]*n</code> creates a list of <code>n</code> references to a unique object <code>[0]</code>. Use this instead to create a list of <code>n</code> different objects all equal to <code>[0]</code>: <code>[[0] for i in range(n)]</code>. This way, you can then change the value of each of them without affecting the others.</p>
| 3 | 2016-07-31T12:56:08Z | [
"python",
"list"
] |
Python - using list() and manipulating lists | 38,684,165 | <p>I seem to have a problem with my list generating script. I'm trying to convert a string into a list of string-lists, in order to use it in a specific fonction. </p>
<p>For exemple I want to convert the string
<code>'abc'</code> to a : <code>[['a'],['b'],['c']]</code>.
so the script i wrote was:</p>
<pre><code>s='some string'
t=[[0]]*len(s)
for i in range(len(s)):
t[i][0] = list(s)[i]
return t
</code></pre>
<p>the problem is that this returns <code>[['g'],['g'],..,['g']]</code> instead of <code>[['s'],['o'],..,['g'])</code>.</p>
<p>I found another way to achieve that, but i can't seem to find the problem of this script.
So,if anyone could help me, i would really appreciate it. Thanks in advance.</p>
| 2 | 2016-07-31T12:52:50Z | 38,684,195 | <p><code>[[0]] * len(s)</code> doesn't do what you think it does, see this example: <a class='doc-link' href="http://stackoverflow.com/documentation/python/3553/common-pitfalls/12259/list-multiplication-and-common-references#t=201607311255286287854">List multiplication and common references</a></p>
<p>Also consider this better approach:</p>
<pre><code>s = 'abc'
li = [[ch] for ch in s]
print(li)
>> [['a'], ['b'], ['c']]
</code></pre>
| 5 | 2016-07-31T12:56:20Z | [
"python",
"list"
] |
Getting strings in a entry widget and printing some response through a label | 38,684,271 | <p>So i saw many videos and questions and stuff but i'm still stuck on how i can respond to strings in an entry widget.so far all the tuts and videos seem to show how to handle numbers and not string,To be more specific i want to make a Tkinter Gui box that has an entry widget and when i type 'hey',it should respond/answer "hey" in/through a label,now the answering part is the one i know,i just don't know how to manipulate strings and not numbers in entry widgets.
Thanks,sorry for being a noob</p>
| 0 | 2016-07-31T13:06:05Z | 38,684,331 | <p>You can use a <code>StringVar</code> to get/set the string value of an Entry widget:</p>
<pre><code>import tkinter as tk
master = tk.Tk()
val = tk.StringVar()
entry = tk.Entry(master, textvariable=val)
entry.pack()
val.set("some value")
the_string = val.get()
print(the_string)
# some value
</code></pre>
| 1 | 2016-07-31T13:12:15Z | [
"python",
"user-interface",
"tkinter",
"python-3.4"
] |
What's the purpose of a password in symmetric cryptography? | 38,684,333 | <p>I found the Python package to encrypt some data and see <a href="https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet" rel="nofollow">this</a> in python Cryptography:</p>
<blockquote>
<p>It is possible to use passwords with Fernet(symmetric key). To do this, you need to run the password through a key derivation function such as PBKDF2HMAC, bcrypt or scrypt.</p>
</blockquote>
<p>But, it turns out that a password works in the same way as a key(use password/key to en/decrypt). So why bother to use password instead of key itself?</p>
<p>I mean why not just use key itself:</p>
<pre><code>from cryptography.fernet import Fernet
key = Fernet.generate_key()
token = Fernet(key).encrypt(b"my deep dark secret")
Fernet(key).decrypt(token)
</code></pre>
| 0 | 2016-07-31T13:12:25Z | 38,684,378 | <p>A password is something that can be remembered by a person whereas a key is usually not remembered, because it is long (at least 128 bit or Hex-encoded in 32 characters) and is supposed to be really random (indistinguishable from random noise). If you want to encrypt something with a key, but this key cannot be transmitted by asymmetric cryptography and instead should be given over the phone or should never be written anywhere, then you can't simply generate a random key and use that. You need have a password/passphrase in place to derive the key from.</p>
<p>Example 1: </p>
<p>A personal password safe like KeePass needs a key for encryption/decryption. A user will not be able to simply remember that key, therefore we have a much shorter password, which can be remembered. Now, the security lies in the fact that a <em>slow</em> key derivation function is used to derive a key from the password, so an attacker still has trouble brute-forcing the key even though it depends on a much shorter password.</p>
<p>Example 2: </p>
<p>You compress a document and use the encryption of the compression software. Now you can send the container via e-mail, but you can't send the password along with it. So, you call the person you've sent the e-mail to and tell them the password. A password is much easier to transmit than a long and random key in this way.</p>
| 6 | 2016-07-31T13:19:50Z | [
"python",
"security",
"cryptography",
"passwords",
"symmetric-key"
] |
BeautifulSoup won't remove i element | 38,684,392 | <p>I am learning how to parse and manipulate <code>html</code> using <code>beautiful soup</code> like so:</p>
<pre><code>from lxml.html import parse
import urllib2
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
url = 'some-url-here'
req = urllib2.Request(url, headers={'User-Agent' : "Magic Browser"})
parsed = urllib2.urlopen( req )
soup = BeautifulSoup(parsed)
for elem in soup.findAll(['script', 'style', 'i']):
elem.extract()
for main_body in soup.findAll("div", {"role" : "main"}):
print main_body.getText(separator=u' ')
</code></pre>
<p>The result contains <code><i></code> tags and I can't figure out how to remove them. How can this be accomplished and why is the only tag not to be removed by the above code?</p>
| 1 | 2016-07-31T13:21:23Z | 38,684,510 | <p>The issue is actually the fact you are using the deprecated <em>Beautifulsoup3</em>, install <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><em>bs4</em></a> and everything will work fine:</p>
<pre><code>In [10]: import urllib2
In [11]: from bs4 import BeautifulSoup # bs4
In [12]: url = 'https://www.gwr.com/'
In [13]: req = urllib2.Request(url, headers={'User-Agent': "Magic Browser"})
In [14]: parsed = urllib2.urlopen(req)
In [15]: soup = BeautifulSoup(parsed,"html.parser")
In [16]: tags = soup.find_all(['script','style','i'])
In [17]: print(len(tags))
25
In [18]: for elem in tags:
....: elem.extract()
....:
In [19]: assert len(soup.find_all(['script','style','i'])) == 0
In [20]:
</code></pre>
| 1 | 2016-07-31T13:36:29Z | [
"python",
"beautifulsoup",
"web-crawler"
] |
Autocompletion with Jedi-vim gives Error | 38,684,578 | <pre><code>-- Omni completion (^O^N^P) Pattern not found
</code></pre>
<p>This is the error that I am getting when I look into the :messages in Vim.</p>
<pre><code>Please install Jedi if you want to use jedi-vim.
The error was: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder^@ Referenced fro
m: /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so^@ Expected in: flat namespace^@ in /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework
/Versions/2.7/lib/python2.7/lib-dynload/_io.so
Press ENTER or type command to continue
</code></pre>
<p>But I already have Jedi installed using pip</p>
<pre><code>$ pip freeze
jedi==0.9.0
vboxapi==1.0
</code></pre>
<p>I'm trying to run <code>:python import jedi;</code> from vim and it gives the following error:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/jedi/__init__.py", line 41, in <module>
from jedi.api import Script, Interpreter, NotFoundError, set_debug_function
File "/usr/local/lib/python2.7/site-packages/jedi/api/__init__.py", line 16, in <module>
from jedi.parser import Parser, load_grammar
File "/usr/local/lib/python2.7/site-packages/jedi/parser/__init__.py", line 22, in <module>
from jedi.parser import tokenize
File "/usr/local/lib/python2.7/site-packages/jedi/parser/tokenize.py", line 16, in <module>
from io import StringIO
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/io.py", line 51, in <module>
import _io
ImportError: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder
Referenced from: /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
Expected in: flat namespace
in /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
</code></pre>
<p>Python from my command-line shows the following version</p>
<pre><code>>>> import sys
>>> sys.version
'2.7.12 (default, Jun 29 2016, 14:05:02) \n[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)]'
>>>
</code></pre>
<p>But from Vim if the run the following command</p>
<pre><code>:python import sys; print sys.version
</code></pre>
<p>It outputs </p>
<pre><code>2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)]
</code></pre>
<p>Now how do I update the python that vim is using? / What exactly is happening here and what do I do to solve it?</p>
| 0 | 2016-07-31T13:45:04Z | 38,684,786 | <p>I installed jedi-vim with pathogen, and it now works.</p>
<pre><code>pip install --user jedi
cd ~/.vim/bundle/
git clone https://github.com/davidhalter/jedi-vim.git
</code></pre>
<p>You can also run <strong>this</strong>:</p>
<pre><code>sudo apt-get install vim-python-jedi
</code></pre>
<p>This should help</p>
| 1 | 2016-07-31T14:06:34Z | [
"python",
"vim",
"vim-plugin",
"jedi-vim"
] |
Autocompletion with Jedi-vim gives Error | 38,684,578 | <pre><code>-- Omni completion (^O^N^P) Pattern not found
</code></pre>
<p>This is the error that I am getting when I look into the :messages in Vim.</p>
<pre><code>Please install Jedi if you want to use jedi-vim.
The error was: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder^@ Referenced fro
m: /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so^@ Expected in: flat namespace^@ in /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework
/Versions/2.7/lib/python2.7/lib-dynload/_io.so
Press ENTER or type command to continue
</code></pre>
<p>But I already have Jedi installed using pip</p>
<pre><code>$ pip freeze
jedi==0.9.0
vboxapi==1.0
</code></pre>
<p>I'm trying to run <code>:python import jedi;</code> from vim and it gives the following error:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/jedi/__init__.py", line 41, in <module>
from jedi.api import Script, Interpreter, NotFoundError, set_debug_function
File "/usr/local/lib/python2.7/site-packages/jedi/api/__init__.py", line 16, in <module>
from jedi.parser import Parser, load_grammar
File "/usr/local/lib/python2.7/site-packages/jedi/parser/__init__.py", line 22, in <module>
from jedi.parser import tokenize
File "/usr/local/lib/python2.7/site-packages/jedi/parser/tokenize.py", line 16, in <module>
from io import StringIO
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/io.py", line 51, in <module>
import _io
ImportError: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder
Referenced from: /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
Expected in: flat namespace
in /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
</code></pre>
<p>Python from my command-line shows the following version</p>
<pre><code>>>> import sys
>>> sys.version
'2.7.12 (default, Jun 29 2016, 14:05:02) \n[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)]'
>>>
</code></pre>
<p>But from Vim if the run the following command</p>
<pre><code>:python import sys; print sys.version
</code></pre>
<p>It outputs </p>
<pre><code>2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)]
</code></pre>
<p>Now how do I update the python that vim is using? / What exactly is happening here and what do I do to solve it?</p>
| 0 | 2016-07-31T13:45:04Z | 38,686,061 | <p>This has happened because of the 2 versions python installed on the Mac.
One that came by default resided in /usr/bin directory and was 2.7.10 version. One that I installed using brew was in the /usr/local/bin directory and was 2.7.12 version. </p>
<p>Vim was using the 2.7.10 version but looking for packages in the folders where brew installed packages.
So I did a brew uninstall python and everything is working fine.</p>
<p>(But I lost pip and all the packages installed through pip. I should've been more careful)</p>
| 1 | 2016-07-31T16:25:22Z | [
"python",
"vim",
"vim-plugin",
"jedi-vim"
] |
Autocompletion with Jedi-vim gives Error | 38,684,578 | <pre><code>-- Omni completion (^O^N^P) Pattern not found
</code></pre>
<p>This is the error that I am getting when I look into the :messages in Vim.</p>
<pre><code>Please install Jedi if you want to use jedi-vim.
The error was: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder^@ Referenced fro
m: /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so^@ Expected in: flat namespace^@ in /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework
/Versions/2.7/lib/python2.7/lib-dynload/_io.so
Press ENTER or type command to continue
</code></pre>
<p>But I already have Jedi installed using pip</p>
<pre><code>$ pip freeze
jedi==0.9.0
vboxapi==1.0
</code></pre>
<p>I'm trying to run <code>:python import jedi;</code> from vim and it gives the following error:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/jedi/__init__.py", line 41, in <module>
from jedi.api import Script, Interpreter, NotFoundError, set_debug_function
File "/usr/local/lib/python2.7/site-packages/jedi/api/__init__.py", line 16, in <module>
from jedi.parser import Parser, load_grammar
File "/usr/local/lib/python2.7/site-packages/jedi/parser/__init__.py", line 22, in <module>
from jedi.parser import tokenize
File "/usr/local/lib/python2.7/site-packages/jedi/parser/tokenize.py", line 16, in <module>
from io import StringIO
File "/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/io.py", line 51, in <module>
import _io
ImportError: dlopen(/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so, 2): Symbol not found: __PyCodecInfo_GetIncrementalDecoder
Referenced from: /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
Expected in: flat namespace
in /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/_io.so
</code></pre>
<p>Python from my command-line shows the following version</p>
<pre><code>>>> import sys
>>> sys.version
'2.7.12 (default, Jun 29 2016, 14:05:02) \n[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)]'
>>>
</code></pre>
<p>But from Vim if the run the following command</p>
<pre><code>:python import sys; print sys.version
</code></pre>
<p>It outputs </p>
<pre><code>2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)]
</code></pre>
<p>Now how do I update the python that vim is using? / What exactly is happening here and what do I do to solve it?</p>
| 0 | 2016-07-31T13:45:04Z | 39,723,279 | <p>uninstall was not a solution in my case, vim complained at the very beginning, that is not finding python support
I did the following:</p>
<pre><code>cd /usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/
mv _io.so _io.so.orig
cp /usr/lib/python2.7/lib-dynload/_io.so ./
</code></pre>
<p>( I've built vim8 from source - from github.com/vim/vim.git )</p>
<pre><code>./configure --enable-pythoninterp --with-python-config-dir=/usr/lib/python2.7/config/
make
sudo make install)
</code></pre>
| 0 | 2016-09-27T11:17:52Z | [
"python",
"vim",
"vim-plugin",
"jedi-vim"
] |
Bring all values in an array closer together | 38,684,614 | <p>I need to do is "crush" the values in l1 by some percentage so they are closer together such that perhaps if an array l1 were ...</p>
<pre><code>l1 =[10,20,30,40,50,60,70,80,90,100]
</code></pre>
<p>Then l2 <em>could be...</em> </p>
<pre><code>l2 = [12.5, 25.0, 37.5, 50.0, 62.5, 45.0, 52.5, 60.0, 67.5, 75.0]
</code></pre>
<p>That can be done on a simple script such as...</p>
<pre><code>for i in l1:
if i <= 50:
i = (i*1.25)
l2.append(i)
print(i)
elif i >= 50:
i = (i*0.75)
l2.append(i)
print (l2)
</code></pre>
<p>So that's to indicate I need to bring all the items closer together - ideally by some percentile (printed). The problem occurs when you have a list like this...</p>
<pre><code>l1 =[4,2,3,4,3,6,4,8.6,10,7,12,4,14,15,26,14,15,16,10]
</code></pre>
<p>What I need to then do is bring all the items together discretely (so by some percentage) but in a loop. I need to "condense" or "crush" the values of the array, reduce the range between each number from smallest to biggest and biggest to smallest (closer to the median). I can't just divide by the whole list since the ranges remain the same.</p>
<p>I thought one way to approach this (what I'm working on now) would be to (a) find the median of l1, (b) start from the smallest and biggest item in l1, increase that item by 10% of it's value or decrease it by 10% of its value (in the case of the biggest item), then work to the second smallest and biggest items in the same loop (to avoid the script going over the same 'smaller variable' twice). </p>
<p>This would mean listing the values from biggest to smallest whilst maintaining their positions in the array (which are important), then searching through that list and making the changes for each corresponding value to the array l1. </p>
<p>For the attention of the proposed solution... One iteration of... </p>
<pre><code>import statistics
a = [4, 3, 3, 4, 5, 1, 31, 321]
input_scope = 1.1
def scouter (input_list, scope):
mean = statistics.mean(input_list)
searchpositions = []
for x, i in enumerate(input_list):
print (x, i)
if i == max(input_list) or i == min(input_list):
searchpositions.append(x)
for i in searchpositions:
input_list[i] = [(input_list[i] - mean) / scope + mean]
return (input_list)
print(scouter((a), input_scope))
</code></pre>
<p>Gives me what I need, sort of...</p>
<pre><code>[4, 3, 3, 4, 5, [5.13636363636364], 31, [296.0454545454545]]
</code></pre>
<p>Output is lists in lists! Is there an easy way to eliminate this by re-writing the function?</p>
| -3 | 2016-07-31T13:48:47Z | 38,684,860 | <p>Why not find the lowest number in your list and divide the whole list by that number? Or even any number that you want. </p>
<pre><code>num = percentage/100 # gets you a decimal
l2 = [x*num for x in l1]
</code></pre>
<p>Use <code>min()</code> to find the lowest number of the list if you want to go that way.</p>
| 0 | 2016-07-31T14:12:50Z | [
"python",
"arrays",
"algorithm",
"sorting"
] |
Bring all values in an array closer together | 38,684,614 | <p>I need to do is "crush" the values in l1 by some percentage so they are closer together such that perhaps if an array l1 were ...</p>
<pre><code>l1 =[10,20,30,40,50,60,70,80,90,100]
</code></pre>
<p>Then l2 <em>could be...</em> </p>
<pre><code>l2 = [12.5, 25.0, 37.5, 50.0, 62.5, 45.0, 52.5, 60.0, 67.5, 75.0]
</code></pre>
<p>That can be done on a simple script such as...</p>
<pre><code>for i in l1:
if i <= 50:
i = (i*1.25)
l2.append(i)
print(i)
elif i >= 50:
i = (i*0.75)
l2.append(i)
print (l2)
</code></pre>
<p>So that's to indicate I need to bring all the items closer together - ideally by some percentile (printed). The problem occurs when you have a list like this...</p>
<pre><code>l1 =[4,2,3,4,3,6,4,8.6,10,7,12,4,14,15,26,14,15,16,10]
</code></pre>
<p>What I need to then do is bring all the items together discretely (so by some percentage) but in a loop. I need to "condense" or "crush" the values of the array, reduce the range between each number from smallest to biggest and biggest to smallest (closer to the median). I can't just divide by the whole list since the ranges remain the same.</p>
<p>I thought one way to approach this (what I'm working on now) would be to (a) find the median of l1, (b) start from the smallest and biggest item in l1, increase that item by 10% of it's value or decrease it by 10% of its value (in the case of the biggest item), then work to the second smallest and biggest items in the same loop (to avoid the script going over the same 'smaller variable' twice). </p>
<p>This would mean listing the values from biggest to smallest whilst maintaining their positions in the array (which are important), then searching through that list and making the changes for each corresponding value to the array l1. </p>
<p>For the attention of the proposed solution... One iteration of... </p>
<pre><code>import statistics
a = [4, 3, 3, 4, 5, 1, 31, 321]
input_scope = 1.1
def scouter (input_list, scope):
mean = statistics.mean(input_list)
searchpositions = []
for x, i in enumerate(input_list):
print (x, i)
if i == max(input_list) or i == min(input_list):
searchpositions.append(x)
for i in searchpositions:
input_list[i] = [(input_list[i] - mean) / scope + mean]
return (input_list)
print(scouter((a), input_scope))
</code></pre>
<p>Gives me what I need, sort of...</p>
<pre><code>[4, 3, 3, 4, 5, [5.13636363636364], 31, [296.0454545454545]]
</code></pre>
<p>Output is lists in lists! Is there an easy way to eliminate this by re-writing the function?</p>
| -3 | 2016-07-31T13:48:47Z | 38,685,211 | <p>Just scale towards the median?</p>
<pre><code>>>> l1 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
>>> import statistics
>>> median = statistics.median(l1)
>>> [(x - median) / 10 + median for x in l1]
[50.5, 51.5, 52.5, 53.5, 54.5, 55.5, 56.5, 57.5, 58.5, 59.5]
</code></pre>
| 2 | 2016-07-31T14:55:49Z | [
"python",
"arrays",
"algorithm",
"sorting"
] |
How to change the arrow head style in matplotlib annotate? | 38,684,619 | <p>I want to change the head of an arrow in an annotation (<code>matplotlib</code>), but it doesn't work when used together with other properties, like <code>shrink</code>. It seems to change the type of object created, by looking at the parameters set.</p>
<hr>
<p><strong>Example</strong></p>
<p>The following code shows two types of annotation arrows. </p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
xx = np.linspace(0,8)
yy = np.sin(xx)
fig, ax = plt.subplots(1,1, figsize=(8,5))
ax.plot(xx,yy)
ax.set_ylim([-2,2])
ax.annotate( 'local\nmax', xy=(np.pi/2, 1), xytext=(1,1.5), ha='center', \
arrowprops={'shrink':0.05})
ax.annotate( 'local\nmin', xy=(np.pi*3/2, -1), xytext=(5,0), ha='center', \
arrowprops={'arrowstyle':'->'})
</code></pre>
<p><a href="http://i.stack.imgur.com/Qh7T1.png" rel="nofollow"><img src="http://i.stack.imgur.com/Qh7T1.png" alt="enter image description here"></a></p>
<hr>
<p><strong>Problem</strong></p>
<p>I tried to set the arrow type together with the other properties in the first annotation like this:</p>
<pre><code>ax.annotate( 'other\nmax', xy=(np.pi*5/2, 1), xytext=(7,1.5), ha='center', \
arrowprops={'arrowstyle':'->', 'shrink':0.05})
</code></pre>
<p>However, that line throws an error:</p>
<pre><code>AttributeError: Unknown property shrink
</code></pre>
<hr>
<p><strong>Why does it not work?</strong></p>
<p><strong>How do I change the arrow head style of an annotation?</strong></p>
<p><a href="http://stackoverflow.com/questions/36148773/how-to-change-the-head-size-of-the-double-head-annotate-in-matplotlib">Related question</a></p>
<hr>
<p>I am using:</p>
<p>python: 3.4.3 + numpy: 1.11.0 + matplotlib: 1.5.1</p>
| 3 | 2016-07-31T13:49:19Z | 38,684,804 | <p>From the <a href="http://matplotlib.org/api/text_api.html#matplotlib.text.Annotation" rel="nofollow">matplotlib documentation</a>, "if the dictionary has a key arrowstyle, a FancyArrowPatch instance is created with the given dictionary and is drawn. Otherwise, a YAArrow patch instance is created and drawn."</p>
<p>As you can see in the same link, <code>shrink</code> is a valid key for <code>YAArrow</code> but not for <code>FancyArrowPatch</code>.</p>
| 1 | 2016-07-31T14:08:04Z | [
"python",
"numpy",
"matplotlib"
] |
Porting python hash digest to node js | 38,684,647 | <p>I'm trying to port a Python script to Node and I've become stuck on SHA1 hashes.</p>
<p>The following Python code:</p>
<pre><code>import hashlib
user = 'test'
ret = hashlib.sha1(user.encode('utf-8')).digest()
print(ret);
</code></pre>
<p>Prints out:</p>
<pre><code>b'\xa9J\x8f\xe5\xcc\xb1\x9b\xa6\x1cL\x08s\xd3\x91\xe9\x87\x98/\xbb\xd3'
</code></pre>
<p>I need a SHA1 hash in this format in Node. This Javascript:</p>
<pre><code>var crypto = require('crypto');
var generator = crypto.createHash('sha1');
generator.update(new Buffer('test'));
console.log(generator.digest('binary'));
</code></pre>
<p>prints</p>
<pre><code>©JåñsÃé/»Ã
</code></pre>
<p>How can I get Node to produce the output in the same style as Python does? It's clearly not binary or hex, what format is the python output in?</p>
| 1 | 2016-07-31T13:52:39Z | 38,684,790 | <p>Both results are the same already. The string representation of bytes (the stuff you see on the console) differs in JavaScript and Python though. To prove that they're identical, convert both to an integer list:</p>
<pre><code>> var crypto = require('crypto');
> var generator = crypto.createHash('sha1');
> generator.update(new Buffer('test'));
> var digest = generator.digest('binary');
> var lst = [];
> for (let i = 0;i < digest.length;i++) st.push(digest.charCodeAt(i));
> console.log(JSON.stringify(lst));
[169,74,143,229,204,177,155,166,28,76,8,115,211,145,233,135,152,47,187,211]
</code></pre>
<p>Same result in python:</p>
<pre><code>>>> import hashlib, base64
>>> ret = hashlib.sha1('test'.encode('utf-8')).digest()
>>> print(list(ret))
[169, 74, 143, 229, 204, 177, 155, 166, 28, 76, 8, 115, 211, 145, 233, 135, 152, 47, 187, 211]
</code></pre>
<p>You can use <a href="https://docs.python.org/dev/library/hashlib.html#hashlib.hash.hexdigest" rel="nofollow"><code>hexdigest</code></a>/<a href="https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding" rel="nofollow"><code>digest('hex')</code></a> to get a hexadecimal string (<code>'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3'</code>), which may be easier to handle.</p>
<p>But there's nothing wrong with the bytes; again, it's just the string representation that's different. For instance, if you write both bytes to a file, then both files will be totally identical.</p>
| 2 | 2016-07-31T14:06:44Z | [
"python",
"node.js",
"sha1"
] |
Customize Keras' loss function in a way that the y_true will depend on y_pred | 38,684,768 | <p>I'm working on a multi-label classifier. I have many output labels [1, 0, 0, 1...] where 1 indicates that the input belongs to that label and 0 means otherwise. </p>
<p>In my case the loss function that I use is based on MSE. I want to change the loss function in a way that when the output label is -1 than it will change to the predicted probability of this label. </p>
<p>Check the attached images to best understand what I mean:
The scenario is - when the output label is -1 I want the MSE to be equal to zero:</p>
<p>This is the scenario:
<a href="http://i.stack.imgur.com/uyTVb.png" rel="nofollow"><img src="http://i.stack.imgur.com/uyTVb.png" alt="enter image description here"></a></p>
<p>And in such case I want it to change to:</p>
<p><a href="http://i.stack.imgur.com/lwcbE.png" rel="nofollow"><img src="http://i.stack.imgur.com/lwcbE.png" alt="enter image description here"></a></p>
<p>In such case the MSE of the second label (the middle output) will be zero (this is a special case where I don't want the classifier to learn about this label).</p>
<p>It feels like this is a needed method and I don't really believe that I'm the first to think about it so firstly I wanted to know if there's a name for such way of training Neural Net and second I would like to know how can I do it.</p>
<p>I understand that I need to change some stuff in the loss function but I'm really newbie to Theano and not sure about how to look there for a specific value and how to change the content of the tensor.</p>
| 3 | 2016-07-31T14:05:04Z | 38,738,401 | <p>I believe this is what you looking for.</p>
<pre><code>import theano
from keras import backend as K
from keras.layers import Dense
from keras.models import Sequential
def customized_loss(y_true, y_pred):
loss = K.switch(K.equal(y_true, -1), 0, K.square(y_true-y_pred))
return K.sum(loss)
if __name__ == '__main__':
model = Sequential([ Dense(3, input_shape=(4,)) ])
model.compile(loss=customized_loss, optimizer='sgd')
import numpy as np
x = np.random.random((1, 4))
y = np.array([[1,-1,0]])
output = model.predict(x)
print output
# [[ 0.47242549 -0.45106074 0.13912249]]
print model.evaluate(x, y) # keras's loss
# 0.297689884901
print (output[0, 0]-1)**2 + 0 +(output[0, 2]-0)**2 # double-check
# 0.297689929093
</code></pre>
| 1 | 2016-08-03T08:31:41Z | [
"python",
"classification",
"theano",
"keras"
] |
Redirect Embedded Python IO to a console created with AllocConsole Win32 application | 38,684,857 | <p>i know that there is similar question but my efforts to resolve this problem were not successful. I want to redirect Python interpreter I/O, but i have only succeeded to redirect stdout. I have still problem with stdin and stderr. Based on <a href="http://stackoverflow.com/questions/1698439/redirect-embedded-python-io-to-a-console-created-with-allocconsole">Redirect Embedded Python IO to a console created with AllocConsole</a> i have done this:</p>
<pre><code>PyObject* sys = PyImport_ImportModule("sys");
PyObject* pystdout = PyFile_FromString("CONOUT$", "wt");
if (-1 == PyObject_SetAttrString(sys, "stdout", pystdout)) {
/* raise errors and wail very loud */
}
PyObject* pystdin = PyFile_FromString("CONIN$", "rb");
if (-1 == PyObject_SetAttrString(sys, "stdin", pystdin)) {
/* raise errors and wail very loud */
}
//cout << "no error" << endl;
Py_DECREF(sys);
Py_DECREF(pystdout);
Py_DECREF(pystdin);
</code></pre>
<p>and i have simple script for testing purposes:</p>
<pre><code>print 'Hello'
guess = int(raw_input('Take a guess: '))
print quess
</code></pre>
<p>When my script is executed only first print is show on console. Second and third commands are not shown at all. So, instead of output:</p>
<pre><code>Hello
Take a guess: "my guess"
"my guess"
</code></pre>
<p>i have only</p>
<pre><code>Hello
</code></pre>
<p>I would appreciate any help and it needs to be solved using Python C API.
Thanks.</p>
| 0 | 2016-07-31T14:12:22Z | 38,783,629 | <p>i have found solution by changing few things and using Python 3.x instead of 2.x. Now everything works fine if we modify script a bit in accordance to Python 3.x standard. </p>
<pre><code>PyObject* sys = PyImport_ImportModule("sys");
if (sys == NULL)
{
/*show error*/
}
PyObject* io = PyImport_ImportModule("io");
PyObject* pystdout = PyObject_CallMethod(io, "open", "ss", "CONOUT$", "w");
if (pystdout == NULL)
{
/*show error*/
}
if (-1 == PyObject_SetAttrString(sys, "stdout", pystdout))
{
/*show error*/
}
PyObject* pystdin = PyObject_CallMethod(io, "open", "ss", "CONIN$", "r");
if (pystdin == NULL)
{
/*show error*/
}
if (-1 == PyObject_SetAttrString(sys, "stdin", pystdin))
{
/*show error*/
}
PyObject* pystderr = PyObject_CallMethod(io, "open", "ss", "CONOUT$", "w");
if (pystderr == NULL)
{
/*show error*/
}
if (-1 == PyObject_SetAttrString(sys, "stderr", pystderr))
{
/*show error*/
}
Py_DECREF(io);
Py_DECREF(sys);
Py_DECREF(pystdout);
Py_DECREF(pystdin);
</code></pre>
| 0 | 2016-08-05T07:33:00Z | [
"python",
"redirect",
"python-c-api",
"python-c-extension"
] |
What is Python replacement for PHP's error_get_last() function? | 38,684,921 | <p>I need to implement an <code>atexit</code> Python function that would get the last error object and check for it's type. If the type of python error corresponds to PHP's <code>E_ERROR</code> I should save the error's output to a file. </p>
<p>The PHP code I'm porting looks like so:</p>
<pre><code>register_shutdown_function( "fatal_handler" );
function fatal_handler() {
$error = error_get_last();
if ($error != null && $error['type'] === E_ERROR)
echo "recordFatalError: {$error['message']}\n";
}
</code></pre>
<p>My code snap are as follows:</p>
<pre><code>def fatal_handler():
# How to get last error object?
atexit.register(fatal_handler)
</code></pre>
<p>I would be glad if somebody explained me how can I get the necessary functionality with python.</p>
| 3 | 2016-07-31T14:19:16Z | 38,684,978 | <p>I would use <a href="https://docs.python.org/3/library/sys.html#sys.last_value" rel="nofollow"><code>sys.last_value</code></a> for this:</p>
<pre><code>import atexit
import sys
def fatal_handler():
try:
e = sys.last_value
except AttributeError: # no exception prior to execution of fatal_handler
return
atexit.register(fatal_handler)
</code></pre>
<p>You may choose to use <code>getattr(sys, 'last_value', None)</code> in place of the <a href="http://stackoverflow.com/q/11360858/2301450">EAFP approach</a> above. It returns <code>None</code> if <code>sys.last_value</code> isn't available.</p>
<p>Alternatively, if there's just one function you want to run only when the interpreter shutdown is caused by an exception, you could use <a href="https://docs.python.org/3/library/sys.html#sys.excepthook" rel="nofollow"><code>sys.excepthook</code></a>:</p>
<pre><code>import sys
def fatal_handler(type, value, traceback):
e = value
sys.excepthook = fatal_handler
</code></pre>
| 2 | 2016-07-31T14:27:41Z | [
"php",
"python",
"exception-handling",
"port"
] |
What is Python replacement for PHP's error_get_last() function? | 38,684,921 | <p>I need to implement an <code>atexit</code> Python function that would get the last error object and check for it's type. If the type of python error corresponds to PHP's <code>E_ERROR</code> I should save the error's output to a file. </p>
<p>The PHP code I'm porting looks like so:</p>
<pre><code>register_shutdown_function( "fatal_handler" );
function fatal_handler() {
$error = error_get_last();
if ($error != null && $error['type'] === E_ERROR)
echo "recordFatalError: {$error['message']}\n";
}
</code></pre>
<p>My code snap are as follows:</p>
<pre><code>def fatal_handler():
# How to get last error object?
atexit.register(fatal_handler)
</code></pre>
<p>I would be glad if somebody explained me how can I get the necessary functionality with python.</p>
| 3 | 2016-07-31T14:19:16Z | 38,685,146 | <p>When an exception is raised and uncaught, the interpreter calls <a href="https://docs.python.org/3/library/sys.html#sys.excepthook" rel="nofollow">sys.excepthook</a> with info about the exception. The default function prints out a given traceback and exception to sys.stderr. You can replace this function with a function which save this data. Later you can use this data in your atexit handler:</p>
<pre><code>import atexit
import sys
class LastException:
value = None
type = None
trackback = None
@staticmethod
def excepthook(type,value,trackback):
LastException.type = type
LastException.value = value
LastException.trackback = trackback
@staticmethod
def register():
sys.excepthook = LastException.excepthook
def fatal_handler():
print('{0} {1}'.format( LastException.type, LastException.value))
LastException.register()
atexit.register(fatal_handler)
raise BaseException("I am an error")
# should print: <class 'BaseException'> I am an error
</code></pre>
| 1 | 2016-07-31T14:48:39Z | [
"php",
"python",
"exception-handling",
"port"
] |
How does django static exactly work | 38,684,976 | <p>I have always used PHP and finally decided to get out of that cave and explore other scripting languages like django.</p>
<p>I am still wrapping my head around project structure in django and can't seem to figure out how to include css, js, and other so called static files.</p>
<p>I have read up on the django wiki and I know I am supposed to use static to reference these files. But in order to do so I need to define my static directory in <code>settings.py</code>.</p>
<p>I have noticed that when I call static <code>{% 'filename.extension' %}</code> it appends the file to the static directory defined in <code>settings.py</code>. But if I am understanding this right that is all it does. The issue is then I have some html code that is trying to get a file from <code>localhost:8000/static/directory/filename.extension</code> But since python handles urls differently the html code will not get any file from such url and thus my css won't be loaded.</p>
<p>My <code>settings.py</code></p>
<p>My file structure:</p>
<pre><code>PassWard >
PassWard >
__pycache__ >
wardvault >
__pucache__ >
... (pycache stuff) ...
templates >
imports.html
menu.html
wardvault >
base.html
passwords.html
migrations >
... (migration stuff) ...
__init__.py
admin.py
admin.pyc
apps.py
models.py
models.pyc
tests.py
views.py
views.pyc
__init__.py
static >
font_awesome >
... (lots of font related files) ...
js >
jquery.min.js
imports.html
menu.css
menu.html
menu.js
reset.css
db.splite3
manage.py
</code></pre>
<p>My <code>settings.py</code> looks like:</p>
<pre><code>"""
Django settings for PassWard project.
Generated by 'django-admin startproject' using Django 1.9.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 't+*07vdh&h^c*2ito-9_ywo^mcxps1o$e@^gb$%6vy7m5vr_^3'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'PassWard.wardvault',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'PassWard.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'PassWard.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
</code></pre>
<p>I am trying to load the static files into <code>passwords.html</code> inside <code>wardvault</code>.</p>
<p>My html snippit that is trying to access static files looks like this:</p>
<pre><code><link rel="stylesheet" type="text/css" href="{% static '/static/menu.css' %}"/>
</code></pre>
<p>And the result of <code>{% static '/static/menu.css' %}</code> when I just put it alone is <code>/static/menu.css</code>.</p>
<p>My question is when I use <code>static</code> does it just append what is defined in <code>settings.py</code> to the arguments? If so when the <code>STATIC_URL</code> is set to <code>/static/</code> does that first slash mean starting from the project root dir or the system root dir? Also i'm I using it correctly? or is there something I am missing?</p>
<p>Feel free to point out bad practices with the structure of the project. I am still trying to wrap my head around everything.</p>
| 1 | 2016-07-31T14:27:26Z | 38,685,037 | <p>When you use the <code>static</code> tag in your template:</p>
<pre><code><link rel="stylesheet" type="text/css" href="{% static '/static/menu.css' %}"/>
</code></pre>
<p>It will just be expanded by replacing the <code>{% static</code> part, with the <code>STATIC_URL</code> value. So that tag becomes:</p>
<pre><code><link rel="stylesheet" type="text/css" href="/static/static/menu.css" />
</code></pre>
<p>You see, there are 2 <code>/static/</code> now there. And given that it starts with a slash, it will be looked on at the root of your application. Now, given your directory structure, your tag should really be just: <code>{% static 'menu.css' %}</code></p>
<p>Now coming to how to serve the file? There are 2 options:</p>
<ol>
<li><p>When you're running development server, you can let the django's static app serve the file. <a href="https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-static-files-during-development" rel="nofollow">Django - serving static files during development</a></p></li>
<li><p>In production server, you can let nginx, or apache, serve the static files. Check <a href="https://docs.djangoproject.com/en/1.9/howto/static-files/#deployment" rel="nofollow">Django staticfiles "deployment" section</a></p></li>
</ol>
<p>Another important settings related to static apps is <code>STATIC_ROOT</code>. It's the path which is intended to store all your static assets. And that is where <code>python manage.py collectstatic</code> command will collect the static files. So, ideally the <code>STATIC_URL</code> location in your nginx or apache should be aliased to that directory.</p>
| 1 | 2016-07-31T14:34:30Z | [
"python",
"django",
"static"
] |
How metaclass ( __call__) working in this case? | 38,685,013 | <pre><code>import inspect
class meta(type):
def __new__(cls, t_name, bases, argdict):
print "inside meta __new__"
return super(meta, cls).__new__(cls, t_name, bases, argdict)
def __init__(self, t_name, bases, argdict):
print "inside __init__ of meta"
def __call__(cls, *args, **kwargs):
print "*************************"
print "inside __call__ of meta"
print cls, args, kwargs #--> cls is A
# How cls is passed as __call__ does not take cls param? through super/how? Why super requires cls?
inst = super(meta, cls).__call__(*args, **kwargs) # why no cls to call? how super works here
#inst = type.__call__(cls, *args, **kwargs) # this works well
print inst, "instance inside meta"
print "*************************"
return inst
class A(object):
__metaclass__ = meta # this line triggers metaclass
def __new__(cls, *args, **kwargs):
print "inside A __new__"
print cls, args, kwargs # we get cls here as A
inst = super(A, cls).__new__(cls, *args, **kwargs)
print inst, "instance inside A"
return inst
def __init__(self, *args, **kwargs):
print "inside A __init___"
self.attr = args[0]
def __call__(self, *args, **kwargs):
print "inside A __call__ "
print self, args, kwargs
a = A("simple arg") # this is type(A).__call__(A, ... ) == meta.__call__(A, ...)
print a
a("param") # type(a).__call__(a), ...
print type(A)
</code></pre>
<p><code>OUTPUT</code></p>
<pre><code>inside meta __new__
inside __init__ of meta
*************************
inside __call__ of meta
<class '__main__.A'> ('simple arg',) {}
inside A __new__
<class '__main__.A'> ('simple arg',) {}
<__main__.A object at 0x7ff0010f2c10> instance inside A
inside A __init___
<__main__.A object at 0x7ff0010f2c10> instance inside meta
*************************
<__main__.A object at 0x7ff0010f2c10>
inside A __call__
<__main__.A object at 0x7ff0010f2c10> ('param',) {}
<class '__main__.meta'>
<type 'type'>
True
</code></pre>
<p>I have some questions embedded inside code [not putting here as it will make question more longer]</p>
| 0 | 2016-07-31T14:31:38Z | 38,685,383 | <p>The first argument of a method is the instance. An instance of a metaclass is a class, which is why we name the argument <code>cls</code>.</p>
<p><code>super()</code> needs the instance so that it can follow MRO properly. Its methods are already bound to an appropriate instance and so don't need the instance to be passed explicitly.</p>
| 0 | 2016-07-31T15:14:09Z | [
"python",
"call",
"super",
"metaclass"
] |
How can I re-run my program in python | 38,685,021 | <p>I would like to know how can I re-run this program. After succeful process I want to offer an opportunity to use this program again without closing and re-opeing.
How can I do it?
After run this code it just open window of python and instantly close it.</p>
<pre><code>def sifra():
retezec = input("Zadejte slovo: ")
print("Zadali jste slovo: ",retezec)
zprava = 0
posun = int(input("Zadejte ÄÃslo o kolik se má Å¡ifra posouvat: "))
for znak in retezec:
i = ord(znak)
i = i + posun
if (i > ord(z)):
i = i - 26
znak = chr(i)
zprava = zprava + znak
print("Zašfrovaná zpráva: ", zprava)
znovu = input("Znovu? A/N")
if(znovu == "A" or "A"):
sifra()
elif(znovu == "N" or "n"):
sys.exit(0)
else:
pass
</code></pre>
<p>This code work... After open, it shows window when I can enter word and then it does caesar cipher as it should but I dont have a chance to see the result because it close so fast. </p>
<pre><code>retezec = input("Zadejte slovo: ")
print("Zadali jste slovo: ",retezec)
zprava = 0
posun = int(input("Zadejte ÄÃslo o kolik se má Å¡ifra posouvat: "))
for znak in retezec:
i = ord(znak)
i = i + posun
if (i > ord(z)):
i = i - 26
znak = chr(i)
zprava = zprava + znak
print("Zašfrovaná zpráva: ", zprava)
</code></pre>
<p>So how can I make this code re-useable?</p>
<p>Edit: when I run it in cmd it say: NameError: name ´z´ is not defined</p>
| -1 | 2016-07-31T14:32:35Z | 38,685,419 | <p>Perhaps all you need is for your program window to stay open until you can inspect the result. But your question is about continuing to run the program after it reaches the end, so here is the answer to that:</p>
<ol>
<li><p>Open a Windows command window ("CMD prompt").</p></li>
<li><p>Run your program by explicitly calling the python interpreter, and add the <code>-i</code> flag:</p>
<pre><code>C:\> python -i program.py
</code></pre></li>
<li><p>After the program runs and reaches the end of the script, you'll get an interactive prompt with access to all your variables. You can now do whatever you want with the environment, e.g., rerun <code>sifra()</code>.</p></li>
</ol>
<p>An alternative: Open your program with IDLE, python's default editor, and run it in the interpreter window. The effect will be the same.</p>
| 0 | 2016-07-31T15:18:54Z | [
"python",
"caesar-cipher"
] |
How can I re-run my program in python | 38,685,021 | <p>I would like to know how can I re-run this program. After succeful process I want to offer an opportunity to use this program again without closing and re-opeing.
How can I do it?
After run this code it just open window of python and instantly close it.</p>
<pre><code>def sifra():
retezec = input("Zadejte slovo: ")
print("Zadali jste slovo: ",retezec)
zprava = 0
posun = int(input("Zadejte ÄÃslo o kolik se má Å¡ifra posouvat: "))
for znak in retezec:
i = ord(znak)
i = i + posun
if (i > ord(z)):
i = i - 26
znak = chr(i)
zprava = zprava + znak
print("Zašfrovaná zpráva: ", zprava)
znovu = input("Znovu? A/N")
if(znovu == "A" or "A"):
sifra()
elif(znovu == "N" or "n"):
sys.exit(0)
else:
pass
</code></pre>
<p>This code work... After open, it shows window when I can enter word and then it does caesar cipher as it should but I dont have a chance to see the result because it close so fast. </p>
<pre><code>retezec = input("Zadejte slovo: ")
print("Zadali jste slovo: ",retezec)
zprava = 0
posun = int(input("Zadejte ÄÃslo o kolik se má Å¡ifra posouvat: "))
for znak in retezec:
i = ord(znak)
i = i + posun
if (i > ord(z)):
i = i - 26
znak = chr(i)
zprava = zprava + znak
print("Zašfrovaná zpráva: ", zprava)
</code></pre>
<p>So how can I make this code re-useable?</p>
<p>Edit: when I run it in cmd it say: NameError: name ´z´ is not defined</p>
| -1 | 2016-07-31T14:32:35Z | 38,687,833 | <p>Problem was in type of variable zprava..it should be zprava = "" not zprava = 0
and in missing quotation marks in if (i > ord(z)): --> if (i > ord("z")):</p>
<p>But one thing that is still not working is ending program..Why sys.exit() does not work?</p>
| 0 | 2016-07-31T19:49:34Z | [
"python",
"caesar-cipher"
] |
Search JSON returned from API by value in Python | 38,685,098 | <p>I'm accessing an API using Python 2.7.12 which gives a JSON response. The JSON looks something like this:</p>
<pre><code>{
"Header": {
"GeneratedAt": "2016-07-31T13:42:33",
"PeriodA": {
"startDate": "20160718",
"type": "WEEKLY",
"endDate": "20160724"
}
},
"Data": [
{
"Metrics": [
{
"name": "Sales",
"values": {
"A": "823456.32",
"B": ""
},
"id": "TL_TOTAL_SALES"
},
{
"name": "Orders",
"values": {
"A": "1230",
"B": ""
},
"id": "TL_TOTAL_ORDERS"
},
],
"label": "Commerce Metrics"
},
]
}
</code></pre>
<p>I'm parsing the JSON as a string using Python and then I need to search the JSON string and extract the values of a particular metric, so in this case I want the values of the metric "Sales".</p>
<p>My code so far:</p>
<pre><code>import json, requests
url = "https://something.com/blah-blah-blah/"
r = requests.get(url)
data = json.loads(r.text)
print json.dumps(data, indent=4)
</code></pre>
<p>What I want to go on to do is store the value "A" from "Sales" in a variable called totalSales but need to know the best practices on querying and extracting individual data values from a JSON response like this, this is a very stripped down version of what actually gets returned from the API.</p>
| 1 | 2016-07-31T14:43:07Z | 38,685,133 | <p><code>json.loads</code> gives you a regular Python nested dictionary, so something like this should work (assuming the Data entry you want is always the first one):</p>
<pre><code>for metric in data['Data'][0]['Metrics']:
if metric['name'] == "Sales":
totalSales = metric['values']['A']
</code></pre>
<p>Note that, because JSON's syntax for objects happens to match Python's syntax for dictionaries, you can just paste it into a Python prompt if you want to experiment.</p>
| 2 | 2016-07-31T14:47:31Z | [
"python",
"json"
] |
Search JSON returned from API by value in Python | 38,685,098 | <p>I'm accessing an API using Python 2.7.12 which gives a JSON response. The JSON looks something like this:</p>
<pre><code>{
"Header": {
"GeneratedAt": "2016-07-31T13:42:33",
"PeriodA": {
"startDate": "20160718",
"type": "WEEKLY",
"endDate": "20160724"
}
},
"Data": [
{
"Metrics": [
{
"name": "Sales",
"values": {
"A": "823456.32",
"B": ""
},
"id": "TL_TOTAL_SALES"
},
{
"name": "Orders",
"values": {
"A": "1230",
"B": ""
},
"id": "TL_TOTAL_ORDERS"
},
],
"label": "Commerce Metrics"
},
]
}
</code></pre>
<p>I'm parsing the JSON as a string using Python and then I need to search the JSON string and extract the values of a particular metric, so in this case I want the values of the metric "Sales".</p>
<p>My code so far:</p>
<pre><code>import json, requests
url = "https://something.com/blah-blah-blah/"
r = requests.get(url)
data = json.loads(r.text)
print json.dumps(data, indent=4)
</code></pre>
<p>What I want to go on to do is store the value "A" from "Sales" in a variable called totalSales but need to know the best practices on querying and extracting individual data values from a JSON response like this, this is a very stripped down version of what actually gets returned from the API.</p>
| 1 | 2016-07-31T14:43:07Z | 38,685,147 | <p>Presuming the order is always the same you just access by key, you also don't need to use json.loads as requests can handle that for you:</p>
<pre><code>js = requests.get(url).json()
total_sales = js["Data"][0]['Metrics'][0]["values"]["A"]
print(total_sales)
</code></pre>
<p>If the order can be different, just iterate until you find the dict then break:</p>
<pre><code>js = requests.get(url).json()
for dct in js["Data"][0]['Metrics']:
if dct.get("name") == "Sales":
total_sales = dct["values"]["A"]
break
</code></pre>
| 3 | 2016-07-31T14:48:42Z | [
"python",
"json"
] |
Python Input Validation for both alphabets and numeric in one input | 38,685,121 | <p>How do i do an input validation for NRIC numbers where there are both numbers and alphabets?
Example of NRIC number: S9738275G, S8937231H, S7402343B
ic=input('Enter NRIC Number: ')</p>
| 2 | 2016-07-31T14:45:37Z | 38,685,139 | <p>This can be done in a lot of different ways. Depending on the scale of your application, you might want something simpler or more complex.</p>
<p>If you want something rock solid, you can use a library such as <a href="https://github.com/kolypto/py-good" rel="nofollow">Pygood</a> for that.</p>
<p>If you're looking for something in the middle, you can also use regex, see here <a href="http://stackoverflow.com/questions/8022530/python-check-for-valid-email-address">an example</a>.</p>
<p>If you want to keep it as simple as possible, you can do a simple validation like so:</p>
<pre><code>str = "B123"
if str[0].isalpha() and not str[1:].isalpha():
# is valid
</code></pre>
| 0 | 2016-07-31T14:48:05Z | [
"python"
] |
Python Input Validation for both alphabets and numeric in one input | 38,685,121 | <p>How do i do an input validation for NRIC numbers where there are both numbers and alphabets?
Example of NRIC number: S9738275G, S8937231H, S7402343B
ic=input('Enter NRIC Number: ')</p>
| 2 | 2016-07-31T14:45:37Z | 38,685,297 | <p>Try this</p>
<pre class="lang-py prettyprint-override"><code>string = 'S9738275G';
if string.isalnum():
print('It\'s alphanumeric string')
else:
print('It\'s not an alphanumeric string')
</code></pre>
| 0 | 2016-07-31T15:04:52Z | [
"python"
] |
Python Input Validation for both alphabets and numeric in one input | 38,685,121 | <p>How do i do an input validation for NRIC numbers where there are both numbers and alphabets?
Example of NRIC number: S9738275G, S8937231H, S7402343B
ic=input('Enter NRIC Number: ')</p>
| 2 | 2016-07-31T14:45:37Z | 38,685,509 | <p>For your use case this should be enough:</p>
<pre><code>>>> a = 'A12345678B'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
...
True
>>> a = 'A12345678'
>>> if a[0].isalpha() and a[-1].isalpha() and a[1:-1].isdigit(): print True
...
>>>
</code></pre>
<p>[0] first character, [-1] last character, [1:-1] second character to last but one character</p>
<p>Edit: Looking at PM 2Ring's comment, the NRIC number has a specific structure and specific method of creating the check digit/character, so I'd follow the code given in the link provided. Assuming that your NRIC number is the same obviously, as you didn't specify what it was.<br>
Intriguingly: "The algorithm to calculate the checksum of the NRIC is not publicly available" Wikipedia</p>
| 1 | 2016-07-31T15:27:54Z | [
"python"
] |
How to use index in a while loop which finds the next occurrence each time | 38,685,432 | <p>I want to find the index of a letter in one string and then replace the letter in the same index but in another string, both strings are members of the dictionary. </p>
<p>however if there is more than one occurrence of the charStr (the single character) in the string it will only give the index of the first occurrence. How do I make it so that the loop would then give the index of the next occurrence of the character instead of just the first occurrence each time the loop runs?</p>
<p>Sorry if this doesnt make sense, Its a bit complicated to explain lol, thanks in advance for any help!</p>
| 2 | 2016-07-31T15:20:00Z | 38,685,447 | <p>The <code>index()</code> method takes a second argument that specifies the position at which you start searching.</p>
<pre><code>'abcbd'.index('b') # 1
'abcbd'.index('b', 1) # 1
'abcbd'.index('b', 2) # 3
'abcbd'.index('b', 3) # 3
</code></pre>
<p>So at each iteration, you can use <code>pos = x('secWord').index(charStr, pos+1)</code>. However, if the substring is not in the string, it will raise a ValueError:</p>
<pre><code>'abcbd'.index('b', 4) # ValueError: substring not found
</code></pre>
<p>For example:</p>
<pre><code>astr = 'abcdbfrgbzb'
charStr = 'b'
occ = astr.count(charStr)
pos = -1
for _ in range(occ):
pos = astr.index(charStr, pos+1)
print pos
# 1, 4, 8, 10
</code></pre>
<p>In your case:</p>
<pre><code>def updateGame (x, charStr) :
occ = x('secWord').count(charStr)
pos = -1
for _ in range(occ):
pos = x('secWord').index(charStr, pos+1)
x('curGuess')[pos] = charStr
</code></pre>
| 4 | 2016-07-31T15:21:17Z | [
"python",
"string",
"python-3.x",
"indexing"
] |
How to correctly capture generator output in a list comprehension? | 38,685,441 | <p>I'm having some confusion with regards to a generator that I am using to create a sum of squares in python. Essentially I am iterating over vectors stored in a dictionary and finding the SS with another target vector.</p>
<p>I'm trying to code more pythonically by using list comprehension and generators but am struggling to understand how this is meant to work. The function that 'generates' just returns a string</p>
<pre><code><generator object distance.<locals>.operation at 0x00000181748E2048>
</code></pre>
<p>Which is obviously wrong. Any advice would be appreciated. Ideally want to output the result of the SS operation but also interested in how I am misunderstanding this.</p>
<pre><code>import math
v = [2,-2,1,3]
dv = {'a1':[0,1,3,5], 'a2':[2,5,6,7], 'a3':[1,-2,-3,2], 'a4':[2,2,1,1],
'a5':[3,2,1,-1]}
def distance(v, dv):
def operation(orig, nbr):
yield [sum(math.sqrt(orig - nbr) for orig, nbr in zip(orig, nbr))]
for k in sorted(dv):
l = dv[k]
list = operation(v,l)
print(list)
distance(v, dv)
</code></pre>
| 1 | 2016-07-31T15:20:43Z | 38,685,454 | <p>You want to use <code>list(operation(v, l))</code>. Generators are yielded as a generator object and so you have to explicitly convert them to a list using <code>list()</code>.</p>
<p>Explained with examples <a href="http://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html#returning-iterable-objects-instead-of-lists" rel="nofollow">here</a>.</p>
| 2 | 2016-07-31T15:21:50Z | [
"python",
"generator"
] |
How to correctly capture generator output in a list comprehension? | 38,685,441 | <p>I'm having some confusion with regards to a generator that I am using to create a sum of squares in python. Essentially I am iterating over vectors stored in a dictionary and finding the SS with another target vector.</p>
<p>I'm trying to code more pythonically by using list comprehension and generators but am struggling to understand how this is meant to work. The function that 'generates' just returns a string</p>
<pre><code><generator object distance.<locals>.operation at 0x00000181748E2048>
</code></pre>
<p>Which is obviously wrong. Any advice would be appreciated. Ideally want to output the result of the SS operation but also interested in how I am misunderstanding this.</p>
<pre><code>import math
v = [2,-2,1,3]
dv = {'a1':[0,1,3,5], 'a2':[2,5,6,7], 'a3':[1,-2,-3,2], 'a4':[2,2,1,1],
'a5':[3,2,1,-1]}
def distance(v, dv):
def operation(orig, nbr):
yield [sum(math.sqrt(orig - nbr) for orig, nbr in zip(orig, nbr))]
for k in sorted(dv):
l = dv[k]
list = operation(v,l)
print(list)
distance(v, dv)
</code></pre>
| 1 | 2016-07-31T15:20:43Z | 38,685,553 | <p>You're using generators wrong way. That <code>yield</code> will anyways only be executed once (provided you convert the return value to a list). And it's result in not even used in a generator expression.</p>
<p>You can change that code to something like this:</p>
<pre><code>def operation(orig, nbr):
for orig, nbr in zip(orig, nbr):
yield math.sqrt(abs(orig - nbr))
for k in sorted(dv):
l = dv[k]
value = sum(operation(v,l))
print(value)
</code></pre>
<p>Now, this is using the generator function properly. Everytime the <code>sum()</code> function needs the next value, the <code>for</code> loop inside <code>operation()</code> function will be executed <code>1 step</code>, and it will yield the next <code>sqrt</code> value, until it is exhausted.</p>
| 3 | 2016-07-31T15:33:01Z | [
"python",
"generator"
] |
How to correctly capture generator output in a list comprehension? | 38,685,441 | <p>I'm having some confusion with regards to a generator that I am using to create a sum of squares in python. Essentially I am iterating over vectors stored in a dictionary and finding the SS with another target vector.</p>
<p>I'm trying to code more pythonically by using list comprehension and generators but am struggling to understand how this is meant to work. The function that 'generates' just returns a string</p>
<pre><code><generator object distance.<locals>.operation at 0x00000181748E2048>
</code></pre>
<p>Which is obviously wrong. Any advice would be appreciated. Ideally want to output the result of the SS operation but also interested in how I am misunderstanding this.</p>
<pre><code>import math
v = [2,-2,1,3]
dv = {'a1':[0,1,3,5], 'a2':[2,5,6,7], 'a3':[1,-2,-3,2], 'a4':[2,2,1,1],
'a5':[3,2,1,-1]}
def distance(v, dv):
def operation(orig, nbr):
yield [sum(math.sqrt(orig - nbr) for orig, nbr in zip(orig, nbr))]
for k in sorted(dv):
l = dv[k]
list = operation(v,l)
print(list)
distance(v, dv)
</code></pre>
| 1 | 2016-07-31T15:20:43Z | 38,685,556 | <p>You don't need <code>yield</code> as you are returning a list. The below <code>sum</code> function in <code>operation</code> is actually a <a href="https://www.python.org/dev/peps/pep-0289/" rel="nofollow">generator expression</a> than accomplishes the same thing.</p>
<p>Thus, <code>sum([x ** 0.5 for x in some_list])</code> becomes <code>sum(x for x in some_list)</code> using a generator expression which uses less memory.</p>
<pre><code>def distance(v, dv):
def operation(orig, nbr):
return sum(abs(orig - nbr) ** 0.5 for orig, nbr in zip(orig, nbr))
return [operation(v, dv[l]) for l in sorted(dv)]
>>> distance(v, dv)
[5.974691494688162, 6.8818192885643805, 4.0, 3.414213562373095, 5.0]
</code></pre>
| 2 | 2016-07-31T15:33:22Z | [
"python",
"generator"
] |
Properly creating a mouse event with Kivy | 38,685,626 | <p>I am trying to create a program that will control the mouse on on my Kivy application. What is the proper way to create a provider and send it the locations I want to move and click at?</p>
| 1 | 2016-07-31T15:40:56Z | 38,687,691 | <p>Take a look at the recorder module, it can both record events and also replay them</p>
<p>Here is a small example: (change RECORD to False to watch the replay after recording ... )</p>
<pre><code>import kivy
from kivy.uix.button import Button
from kivy.app import App
from kivy.input.recorder import Recorder
rec = Recorder(filename='myrecorder.kvi',
record_attrs=['is_touch', 'sx', 'sy', 'angle', 'pressure'],
record_profile_mask=['pos', 'angle', 'pressure'])
def funky(b):
print("Hello!!!")
if RECORD:
rec.record = False
else:
rec.play = False
exit(0)
class MyApp(App):
def build(self):
if RECORD:
rec.record = True
else:
rec.play = True
return Button(text="hello", on_release=funky)
if __name__ == '__main__':
RECORD = True # False for replay
MyApp().run()
</code></pre>
<p>Now you can see the file myrecorder.kvi:</p>
<pre><code>#RECORDER1.0
(1.1087048053741455, 'begin', 1, {'profile': ['pos'], 'sx': 0.65875, 'is_touch': True, 'sy': 0.51})
(1.1346497535705566, 'update', 1, {'profile': ['pos'], 'sx': 0.66, 'is_touch': True, 'sy': 0.51})
(1.1994667053222656, 'end', 1, {'profile': ['pos'], 'sx': 0.66, 'is_touch': True, 'sy': 0.51})
</code></pre>
<p>You can use the Recorder class in many other ways, see the docs:
<a href="https://kivy.org/docs/api-kivy.input.recorder.html" rel="nofollow">https://kivy.org/docs/api-kivy.input.recorder.html</a></p>
<p>You can wrap the recorder in a function to make a small helper:</p>
<pre><code>#not tested
def click(x, y):
with open("clicker.kvi", 'w') as f:
f.write("""\#RECORDER1.0
(0.1087048053741455, 'begin', 1, {{'profile': ['pos'], 'sx': {x}, 'is_touch': True, 'sy': {y}}})
(0.1346497535705566, 'update', 1, {{'profile': ['pos'], 'sx': {x}, 'is_touch': True, 'sy': {y}}})
(0.1994667053222656, 'end', 1, {{'profile': ['pos'], 'sx': {x}, 'is_touch': True, 'sy': {y}}})""".format(x=x, y=y))
rec = Recorder(filename='clicker.kvi',
record_attrs=['is_touch', 'sx', 'sy', 'angle', 'pressure'],
record_profile_mask=['pos', 'angle', 'pressure'])
rec.play = True
#should call rec.play = False somewhere?
</code></pre>
| 1 | 2016-07-31T19:31:50Z | [
"python",
"mouseevent",
"kivy",
"modeling"
] |
insert timestamp to json response in python | 38,685,654 | <p>I am trying to insert timestamp to the json curl get request and publish to pubnub and failing to serialize to right format</p>
<pre><code>#!/usr/bin/python
import requests
import json
import sys
import datetime
from pubnub import Pubnub
now = datetime.datetime.now()
pubnub = Pubnub(
publish_key = "key",
subscribe_key = "my_key")
channel = "my_channel"
payload = {'Postman-Token': 'sometoken', 'title': "pythontest"}
message = requests.get("http://localhost:8080/", data=json.dumps(payload))
</code></pre>
<p><code>print.message.text</code> gives <code>{"code":"200","message":"Success","itemCount":0,"items":[]}</code></p>
<p>I would like to add time stamp to the above message and would like the result to be like this: <code>{"code":"200","message":"Success",date:"2016-07-31 15:26"}</code></p>
<pre><code>print now.strftime("%Y-%m-%d %H:%M")
timestamp=str(now.strftime("%Y-%m-%d %H:%M"))
print message.text,now.strftime("%Y-%m-%d %H:%M")
Hello = str(message.text)
pubnub.publish(
channel = channel,
message = (Hello,timestamp))
</code></pre>
<p>But, when I publish it to pubnub, the result looks like this. </p>
<pre><code>[u'{"code":"200","message":"Success","itemCount":0,"items":[]}', u'2016-07-31 15:26']
</code></pre>
<p>Please help</p>
| 0 | 2016-07-31T15:44:43Z | 38,685,752 | <p>You get this result because you are sending a tuple containing a dictionary and the timestamp, so obviously it will return the tuple as the response. Try to inserting the timestamp in the message you will send. </p>
<p>See if the below works:</p>
<pre><code>message = json.loads(requests.get("http://localhost:8080/", data=json.dumps(payload)))
message["date"] = timestamp
</code></pre>
<p>It seems to fit for what you want.</p>
| 0 | 2016-07-31T15:53:28Z | [
"python",
"json",
"pubnub"
] |
quicksort code in Python | 38,685,665 | <p>I am trying to code quicksort in Python but wasn't able to correct the errors? How do I fix all these errors? Is there anything wrong with the logic?</p>
<pre><code>Traceback (most recent call last):
line 35, in module
line 5, in quicksort
line 3, in quicksort
line 30, in partition
IndexError: list index out of range
</code></pre>
<p>Here is my code:</p>
<pre><code>def quicksort(a, beg, end):
if beg < end:
split = partition(a, beg, end)
quicksort(a, beg, split-1)
quicksort(a, split+1, end)
def partition(a, beg, end):
left = beg
right = end
pivot = left
done = True
while done:
while a[pivot] <= a[right] and pivot != right:
right = right - 1
if pivot == right:
done = False
elif a[pivot] > a[right] :
temp = a[right]
a[right] = a[pivot]
a[pivot] = a[temp]
pivot = right
while a[pivot] >= a[left] and pivot != left:
left = left + 1
if pivot == left:
done = False
elif a[pivot] < a[left] :
temp = a[left]
a[left] = a[pivot]
a[pivot] = a[temp]
pivot = left
return pivot
a = [4, 5, 7, 3, 6, 22, 45, 82]
quicksort(a, 0, len(a)-1)
print(a)
</code></pre>
| 0 | 2016-07-31T15:45:53Z | 38,686,686 | <pre><code> elif a[pivot] > a[right] :
temp = a[right]
a[right] = a[pivot]
a[pivot] = a[temp]
pivot = right
</code></pre>
<p>Notice you set <code>a[pivot]</code> to <code>a[temp]</code>. You need to set it to <code>temp</code>.</p>
<p>and here:</p>
<pre><code> elif a[pivot] < a[left] :
temp = a[left]
a[left] = a[pivot]
# a[pivot] = a[temp]
a[pivot] = temp
pivot = left
</code></pre>
<p>Even better, use tuple unpacking -- you don't need temp:</p>
<pre><code> elif a[pivot] > a[right] :
a[pivot], a[right] = a[right], a[pivot]
"""
temp = a[right]
a[right] = a[pivot]
a[pivot] = a[temp]
"""
</code></pre>
| 0 | 2016-07-31T17:34:05Z | [
"python",
"quicksort"
] |
A surprise with 1**math.nan and 0j**math.nan | 38,685,737 | <p>I'm surprised that </p>
<pre><code>>>> import math
>>> 1**math.nan
1.0
</code></pre>
<p>And while we are at it, also that</p>
<pre><code>>>> 0j**math.nan
0j
</code></pre>
<p>I didn't find any other examples. Is there a reason or some logic I've missed that makes this the right choice? Or is this a slip? </p>
<p>I was expecting <code>nan</code>. As for every other number except <code>1</code> or <code>0j</code>.</p>
<p><strong>Edit 1:</strong> Thanks to jedwards's comment below I have a reference. But I still don't understand why. Why was this decided as the standard? Also, couldn't find reference to <code>0j**mat.nan</code>...</p>
<p><strong>Edit 2:</strong> So following the answers below and some other stuff, the logic may be this one: Any calculation involving <code>nan</code> should return <code>nan</code> unless the calculation is always returning the same answer regardless of arguments. In such cases, the fact that we have <code>nan</code> as an argument should not affect the result and we should still get the fixed answer.</p>
<p>This certainly explains <code>1**math.nan</code> and <code>math.nan**0</code>. This also explains why <code>0**math.nan</code> gives <code>nan</code> and not <code>0</code> (since <code>0**n</code> is <code>0</code> for all but when <code>n=0</code> where it results with <code>1</code>), and might be stretched to cover why <code>math.nan*0</code> is <code>nan</code> if we agree that the argument need not be finite.</p>
<p>But if this is the logic behind the scene, then <code>0j**math.nan</code> should have been <code>nan</code>, since <code>0j**n</code> is <code>0</code> for all <code>n</code>'s except <code>n=0</code> where <code>0j**0</code> is <code>1</code>. So... does <code>0j**math.nan</code> have different reasoning? or is it a problem in implementation?</p>
| 12 | 2016-07-31T15:52:36Z | 38,687,984 | <p>Quoting this <a href="http://stackoverflow.com/questions/17863619/why-does-nan0-1">question</a> which in turns quotes IEEE 754 (see <a href="https://en.wikipedia.org/wiki/NaN#Function_definition" rel="nofollow">Wikipedia</a>),</p>
<blockquote>
<p>The 2008 version of the IEEE 754 standard says that pow(1,qNaN) and pow(qNaN,0) should both return 1 since they return 1 whatever else is used instead of quiet NaN.</p>
</blockquote>
<p>For details see page 56 of <a href="http://www.csee.umbc.edu/~tsimo1/CMSC455/IEEE-754-2008.pdf" rel="nofollow">IEEE 754 2008</a>:</p>
<blockquote>
<p>pow(x, ±0) is 1 for any x (even a zero, quiet NaN, or infinity)</p>
<p>pow(±0, y) is ±â and signals the divideByZero exception for y an odd</p>
</blockquote>
<p>Thus, the reasoning seems to be that no matter what number k is in the exponent, <code>1^k = 1</code>, <code>1^Nan</code> should also be 1. Why that reasoning is reasonable (I'm sure it is) I'll need to dig further.</p>
<p>Personally, I think this makes sense - <code>Nan</code> doesn't really exist in math, it's just that our floating point representation can't handle it (or, Nan is "the computation is too much, this is some number but not sure which"). Thus, <code>1^Nan</code> could be 1 to an arbitrary power (not 1 to something that is not a number), but since the answer will always be 1, it can only help if we define <code>1^Nan</code> to be 1.</p>
| 6 | 2016-07-31T20:08:33Z | [
"python",
"floating-point",
null,
"ieee-754"
] |
Print dataframe after grouping H2o python | 38,685,750 | <p><strong>Data:</strong> "<a href="https://github.com/estimate/pandas-exercises/blob/master/baby-names2.csv" rel="nofollow">https://github.com/estimate/pandas-exercises/blob/master/baby-names2.csv</a>"<br>
In pandas:<br></p>
<pre><code>df=pd.read_csv("baby-names2.csv")
df_group=df.groupby("year")
print df_group.head()
</code></pre>
<p>It prints the dataframe grouped by year.<br>
<strong>How do I do the same thing in H2o Python ?</strong><br>
In H2o:<br></p>
<pre><code>df=h2o.upload_file("baby-names2.csv")
df_group=df.group_by("year")
print df_group.head() ==> gives Error
</code></pre>
<p>Expected output: <br>
<a href="http://i.imgur.com/VTbMX9w.png" rel="nofollow">http://i.imgur.com/VTbMX9w.png</a></p>
| 0 | 2016-07-31T15:53:27Z | 38,689,601 | <p>To get an h2o frame after you've used <code>groupby()</code>, use <code>.get_frame()</code> which returns the result of the group-by. For example, if you wanted to get the count for each year you could do:</p>
<pre><code>df=h2o.import_file("baby-names2.csv")
df_group=df.group_by("year").count()
df_group.get_frame()
</code></pre>
<p><a href="http://i.stack.imgur.com/H3iCX.png" rel="nofollow">which prints the year and count columns</a>.</p>
| 0 | 2016-08-01T00:37:42Z | [
"python",
"pandas",
"h2o"
] |
import logging.handlers breaks my program. Why? | 38,685,895 | <p>While debugging a problem I have simplified the program in question to just few lines, but I still do not understand what's wrong. Could you please help?</p>
<pre><code>import logging
def setup():
logging.warning("start")
import logging.handlers
setup()
</code></pre>
<p>The code above produces an exception:</p>
<blockquote>
<p>logging.warning("start")</p>
<p>UnboundLocalError: local variable 'logging' referenced before assignment</p>
</blockquote>
<p>and pylint complains:</p>
<blockquote>
<p>W: 5, 4: Redefining name 'logging' from outer scope (line 1)
(redefined-outer-name)</p>
</blockquote>
<p>This modification seems to help, but I do not know why:</p>
<pre><code>import logging.handlers as lh
</code></pre>
<p>Please note that the exception is thrown BEFORE the second import statement is executed. I'm confused.</p>
| 0 | 2016-07-31T16:06:49Z | 38,685,946 | <p>The <code>logging.warning</code> function will try to reference the variable from local scope first in <code>setup()</code> function, which is from <code>import logging.handlers</code>, and it finds it to be declared after the line you're using it.</p>
<p>Try changing it to:</p>
<pre><code>import logging
def setup():
global logging
logging.warning("start")
import logging.handlers
setup()
</code></pre>
| 2 | 2016-07-31T16:11:30Z | [
"python",
"python-import"
] |
import logging.handlers breaks my program. Why? | 38,685,895 | <p>While debugging a problem I have simplified the program in question to just few lines, but I still do not understand what's wrong. Could you please help?</p>
<pre><code>import logging
def setup():
logging.warning("start")
import logging.handlers
setup()
</code></pre>
<p>The code above produces an exception:</p>
<blockquote>
<p>logging.warning("start")</p>
<p>UnboundLocalError: local variable 'logging' referenced before assignment</p>
</blockquote>
<p>and pylint complains:</p>
<blockquote>
<p>W: 5, 4: Redefining name 'logging' from outer scope (line 1)
(redefined-outer-name)</p>
</blockquote>
<p>This modification seems to help, but I do not know why:</p>
<pre><code>import logging.handlers as lh
</code></pre>
<p>Please note that the exception is thrown BEFORE the second import statement is executed. I'm confused.</p>
| 0 | 2016-07-31T16:06:49Z | 38,686,010 | <p>You can see the problem if you disassemble the bytecode for that function:</p>
<pre>
>>> dis.dis(setup)
2 0 LOAD_FAST 0 (logging)
3 LOAD_ATTR 0 (warning)
6 LOAD_CONST 1 ('start')
9 CALL_FUNCTION 1 (1 positional, 0 keyword pair)
12 POP_TOP
3 13 LOAD_CONST 2 (0)
16 LOAD_CONST 0 (None)
19 IMPORT_NAME 1 (logging.handlers)
<b>22 STORE_FAST 0 (logging)</b>
25 LOAD_CONST 0 (None)
28 RETURN_VALUE
</pre>
<p>Note how the code imports the name <code>logging.handlers</code> and then <strong>assigns</strong> the module object to the name <code>logging</code>.</p>
<p>So basically it's like if your function were:</p>
<pre><code>def setup():
logging.warning('start')
logging = __import__('logging.handlers')
</code></pre>
<p>Or, removing the import mechanism:</p>
<pre><code>x = 0
def setup():
# inside this function *all* x refer to the same object
print(x)
x = 1
</code></pre>
<p>Remember that a name in a given scope can only refer to one object. By having an assignment the compiler interprets <code>logging</code> as a <em>local</em> variable <strong>for the whole scope, which is the complete function body</strong> and thus the call to <code>warning</code> yields an <code>UnboundLocalError</code> because the assignment to <code>logging</code> is done afterwards.</p>
<p>You should either move the import as the first statement in the function or just move it in the global scope (which is the preferred way of doing it).</p>
<hr>
<p>If you want to force the compiler to refer to the global variable you have to tell him so by adding a <code>global logging</code>/<code>global x</code> statement. In that case no local variable will be created but the global one will be used.</p>
| 2 | 2016-07-31T16:19:11Z | [
"python",
"python-import"
] |
How to create a non-blocking function? | 38,686,084 | <p>I am new to tornado.</p>
<p>It's exciting about the part of Coroutines.</p>
<p>So i try to convert a blocking function into a non-blocking at first.</p>
<pre><code>@tornado.concurrent.return_future
def calculate(callback):
start_time = time.time()
res = urllib2.urlopen("https://www.google.com/")
print time.time()-start_time
callback(res)
class MainHandler(tornado.web.RequestHandler):
@tornado.gen.coroutine
def get(self):
start_time = time.time()
res = yield [calculate(), calculate()]
print time.time()-start_time
</code></pre>
<p>But i got:</p>
<pre><code>1.41436505318
1.38487792015
2.80179595947
</code></pre>
<p>It's I/O bound, so i guess the total time spent should be approximate to the longer one time spent(1.41436505318).
But it seems to be blocking.</p>
<p>So i am wondering what's going wrong?How can i convert a blocking function into a non-blocking function?</p>
| 1 | 2016-07-31T16:27:29Z | 38,687,632 | <p><code>return_future</code> doesn't make a function non-blocking; it takes a non-blocking function that uses callbacks and makes it coroutine-friendly. </p>
<p>The only way to make a blocking function non-blocking without making deep changes to it is to run it in another thread or process, as with a <code>ThreadPoolExecutor</code>.</p>
| 2 | 2016-07-31T19:24:08Z | [
"python",
"tornado"
] |
Trouble clicking web element with python, selenium, and pyvirtualdisplay | 38,686,182 | <p>I have a simple web crawler that logs into Twitter, goes the the following page, then grabs information from all my followers (if they are muted, etc) by clicking on the gear icon. The problem is that click functionality has stopped working on my new computer.</p>
<p>Also, I am using the Firefox() web driver.</p>
<p>Here is the code that I am using (You will need to add your own credentials for Twitter to get it working): <a href="https://gist.github.com/anonymous/4c64054d01af77ae2c5c2b39a2165d80" rel="nofollow">https://gist.github.com/anonymous/4c64054d01af77ae2c5c2b39a2165d80</a></p>
<p>This code works perfectly fine on one machine, but fails to click a dom element on another. Here are some specs that might offer insight.</p>
<pre><code>::GOOD BOX::
pip packages
- selenium 2.47.3
- pyvirtualdisplay 0.1.5
python 2.7
firefox 41.0
lib32z-dev 1:1.2.8.dfsg-1ubuntu1
python-lxml 3.3.3-1ubuntu0.1
python-dev 2.7.5-5ubuntu3
build-essential 11.6ubuntu6
-------------------------
::BAD BOX::
pip packages
- selenium 2.53.6
- pyvirtualdisplay 0.2
python 2.7
firefox-mozilla-build 47.0.1-0ubuntu1 (not sure why I need this, the other box doesn't seem to have it. But things break if I remove it)
firefox 47.0.1
python-dev 2.7.11-1
libxml2-dev 2.9.3+dfsg1-1ubuntu0.1
libxslt-dev (1.1.28-2.1)
build-essential 12.1ubuntu2
</code></pre>
<p>When I run this code on the "bad box" and do not catch the exceptions, I get the following:</p>
<pre><code>selenium.common.exceptions.WebDriverException: Message: Element is not clickable at point (464, 1). Other element would receive the click: <div class="container"></div>
</code></pre>
| 2 | 2016-07-31T16:39:02Z | 38,686,717 | <p>It could be due to a window too small where the targeted element ends up hidden under another one. Try to set the original size:</p>
<pre><code>driver.set_window_size(1920, 1200)
</code></pre>
<p>You could also try to change the scroll behaviour if your element ends up hidden under the top banner:</p>
<pre><code>DesiredCapabilities.FIREFOX["elementScrollBehavior"] = 1 #scroll bottom instead of top
driver = webdriver.Firefox()
</code></pre>
| 2 | 2016-07-31T17:36:57Z | [
"python",
"python-2.7",
"selenium",
"firefox",
"pyvirtualdisplay"
] |
Search for an Xpath returning results outside an element with a specified attribute in scrapy | 38,686,206 | <p>I'm using the scrapy shell to grab all of the links in the subcategories section of this site: <a href="https://www.dmoz.org/Computers/Programming/Languages/Python/" rel="nofollow">https://www.dmoz.org/Computers/Programming/Languages/Python/</a>. </p>
<p>There's probably a more efficient Xpath, but the one I came up was:</p>
<pre><code>//div[@id="subcategories-div"]/section/div/div/a/@href
</code></pre>
<p>As far as I can tell from the page source, there is only one <code>div</code> element with a <code>[@id="subcategories-div"]</code> attribute, so from there I narrow down until I find the link's <code>href</code>. This works when I search for this Xpath in Chrome.</p>
<p>But when I run</p>
<p><code>response.xpath('//div[@id="subcategories-div"]/section/div/div/a/@href').extract()</code> </p>
<p>in scrapy, it gives me back the links I'm looking for, but then for some reason, it also returns links from <code>//*[@id="doc"]/section[8]/div/div[2]/a</code></p>
<p>Why is this happening, since nowhere in this path is there a <code>div</code> element with a <code>[@id="subcategories-div"]</code> attribute?</p>
| 0 | 2016-07-31T16:41:13Z | 38,686,352 | <p>I cant seem to find any id with the name doc in the page You are trying to scrape, You might haven't set a starting response.xpath. do you get the same result if You should to change, so like: </p>
<pre><code>response.xpath('//*div[@id="subcategories-div"]/section/div/div/a/@href').extract()
</code></pre>
| 0 | 2016-07-31T16:56:00Z | [
"python",
"html",
"xpath",
"scrapy"
] |
How to calculate how many different ways I can order a list in python | 38,686,269 | <p>I'm a little confused on how to do this, and I know it probably requires a bit of probability knowledge too (which I'm lacking).</p>
<p>How can I calculate how many ways, and also get all the possibilities, of how many ways I can order a list?</p>
<p>For example if I have <code>lst = ["a", "a", "a", "a", "b", "b", "b"]</code>, how many ways can I order this/how can I get all the possible combinations? I've been looking through <code>itertools</code> but haven't found something for it.</p>
| 3 | 2016-07-31T16:47:28Z | 38,686,314 | <p>You can use <code>permutations()</code> to get the all permutations, and <code>set()</code> in order to remove the duplicate items:</p>
<pre><code>>>> from itertools import permutations
>>> set(permutations(lst))
{('b', 'a', 'b', 'a', 'a', 'a', 'b'), ('b', 'a', 'a', 'b', 'a', 'a', 'b'), ('b', 'a', 'a', 'b', 'b', 'a', 'a'), ('a', 'a', 'b', 'b', 'a', 'a', 'b'), ('a', 'a', 'b', 'a', 'b', 'b', 'a'), ('b', 'b', 'a', 'b', 'a', 'a', 'a'), ('b', 'a', 'a', 'a', 'b', 'a', 'b'), ('b', 'a', 'b', 'a', 'b', 'a', 'a'), ('b', 'b', 'a', 'a', 'b', 'a', 'a'), ('b', 'b', 'b', 'a', 'a', 'a', 'a'), ('a', 'a', 'a', 'b', 'a', 'b', 'b'), ('a', 'a', 'b', 'b', 'b', 'a', 'a'), ('a', 'a', 'a', 'b', 'b', 'b', 'a'), ('a', 'b', 'b', 'a', 'a', 'b', 'a'), ('b', 'a', 'b', 'b', 'a', 'a', 'a'), ('a', 'b', 'b', 'b', 'a', 'a', 'a'), ('a', 'b', 'a', 'a', 'a', 'b', 'b'), ('a', 'b', 'a', 'b', 'a', 'b', 'a'), ('a', 'b', 'b', 'a', 'a', 'a', 'b'), ('a', 'b', 'b', 'a', 'b', 'a', 'a'), ('a', 'a', 'b', 'a', 'b', 'a', 'b'), ('a', 'b', 'a', 'b', 'b', 'a', 'a'), ('b', 'b', 'a', 'a', 'a', 'b', 'a'), ('a', 'a', 'b', 'a', 'a', 'b', 'b'), ('a', 'a', 'a', 'a', 'b', 'b', 'b'), ('b', 'a', 'b', 'a', 'a', 'b', 'a'), ('b', 'b', 'a', 'a', 'a', 'a', 'b'), ('a', 'b', 'a', 'a', 'b', 'b', 'a'), ('b', 'a', 'a', 'b', 'a', 'b', 'a'), ('a', 'a', 'a', 'b', 'b', 'a', 'b'), ('a', 'b', 'a', 'a', 'b', 'a', 'b'), ('a', 'a', 'b', 'b', 'a', 'b', 'a'), ('a', 'b', 'a', 'b', 'a', 'a', 'b'), ('b', 'a', 'a', 'a', 'a', 'b', 'b'), ('b', 'a', 'a', 'a', 'b', 'b', 'a')}
>>>
</code></pre>
<p>Note that his approach is not an optimized way, since it calculates all the permutations first, although it returns an iterator and doesn't store all of them in memory but still it's not the best way it's just good if you are dealing with non-large data sets.</p>
<p>If you want to use an optimized way you can customize the <code>permutations</code>'s equivalent function which <a href="https://docs.python.org/3.4/library/itertools.html#itertools.permutations" rel="nofollow">has mentioned in documentation</a>.</p>
| 6 | 2016-07-31T16:51:58Z | [
"python",
"probability"
] |
How to calculate how many different ways I can order a list in python | 38,686,269 | <p>I'm a little confused on how to do this, and I know it probably requires a bit of probability knowledge too (which I'm lacking).</p>
<p>How can I calculate how many ways, and also get all the possibilities, of how many ways I can order a list?</p>
<p>For example if I have <code>lst = ["a", "a", "a", "a", "b", "b", "b"]</code>, how many ways can I order this/how can I get all the possible combinations? I've been looking through <code>itertools</code> but haven't found something for it.</p>
| 3 | 2016-07-31T16:47:28Z | 38,693,715 | <p>As Kasramvd mentions, using <code>itertools.permutations</code> is <em>not</em> an efficient way to generate permutations of a list that contains repeated elements. Your sample data has 7 elements, so <code>itertools.permutations</code> generates 7! = 5040 permutations, but there are only 35 = <a href="https://en.wikipedia.org/wiki/Binomial_coefficient" rel="nofollow">7 choose 3</a> unique permutations.</p>
<p>Fortunately, there's an ancient permutation algorithm, due to the 14th century Indian mathematician Narayana Pandita, which produces permutations in lexicographic order that handles repeated elements gracefully. Here's a description (derived from the <a href="https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order" rel="nofollow">Wikipedia</a> article) showing how this algorithm generates the next permutation from the current one.</p>
<ol>
<li>Find the largest index j such that a[j] < a[j + 1]. If no such index exists,
the permutation is the last permutation.</li>
<li>Find the largest index k greater than j such that a[j] < a[k].</li>
<li>Swap the value of a[j] with that of a[k].</li>
<li>Reverse the sequence from a[j + 1] up to and including the final element a[n].</li>
</ol>
<p>Here's a generator function that implements that algorithm. In order to get all the permutations the input list <em>must</em> be sorted lexicographically in ascending order.</p>
<pre><code>def lexico_permute(a):
a = list(a)
yield a
n = len(a) - 1
while True:
for j in range(n-1, -1, -1):
if a[j] < a[j + 1]:
break
else:
return
v = a[j]
for k in range(n, j, -1):
if v < a[k]:
break
a[j], a[k] = a[k], a[j]
a[j+1:] = a[j+1:][::-1]
yield a
# Test
lst = ["a", "a", "a", "a", "b", "b", "b"]
for i, u in enumerate(lexico_permute(lst), 1):
print(i, u)
</code></pre>
<p><strong>output</strong></p>
<pre><code>1 ['a', 'a', 'a', 'a', 'b', 'b', 'b']
2 ['a', 'a', 'a', 'b', 'a', 'b', 'b']
3 ['a', 'a', 'a', 'b', 'b', 'a', 'b']
4 ['a', 'a', 'a', 'b', 'b', 'b', 'a']
5 ['a', 'a', 'b', 'a', 'a', 'b', 'b']
6 ['a', 'a', 'b', 'a', 'b', 'a', 'b']
7 ['a', 'a', 'b', 'a', 'b', 'b', 'a']
8 ['a', 'a', 'b', 'b', 'a', 'a', 'b']
9 ['a', 'a', 'b', 'b', 'a', 'b', 'a']
10 ['a', 'a', 'b', 'b', 'b', 'a', 'a']
11 ['a', 'b', 'a', 'a', 'a', 'b', 'b']
12 ['a', 'b', 'a', 'a', 'b', 'a', 'b']
13 ['a', 'b', 'a', 'a', 'b', 'b', 'a']
14 ['a', 'b', 'a', 'b', 'a', 'a', 'b']
15 ['a', 'b', 'a', 'b', 'a', 'b', 'a']
16 ['a', 'b', 'a', 'b', 'b', 'a', 'a']
17 ['a', 'b', 'b', 'a', 'a', 'a', 'b']
18 ['a', 'b', 'b', 'a', 'a', 'b', 'a']
19 ['a', 'b', 'b', 'a', 'b', 'a', 'a']
20 ['a', 'b', 'b', 'b', 'a', 'a', 'a']
21 ['b', 'a', 'a', 'a', 'a', 'b', 'b']
22 ['b', 'a', 'a', 'a', 'b', 'a', 'b']
23 ['b', 'a', 'a', 'a', 'b', 'b', 'a']
24 ['b', 'a', 'a', 'b', 'a', 'a', 'b']
25 ['b', 'a', 'a', 'b', 'a', 'b', 'a']
26 ['b', 'a', 'a', 'b', 'b', 'a', 'a']
27 ['b', 'a', 'b', 'a', 'a', 'a', 'b']
28 ['b', 'a', 'b', 'a', 'a', 'b', 'a']
29 ['b', 'a', 'b', 'a', 'b', 'a', 'a']
30 ['b', 'a', 'b', 'b', 'a', 'a', 'a']
31 ['b', 'b', 'a', 'a', 'a', 'a', 'b']
32 ['b', 'b', 'a', 'a', 'a', 'b', 'a']
33 ['b', 'b', 'a', 'a', 'b', 'a', 'a']
34 ['b', 'b', 'a', 'b', 'a', 'a', 'a']
35 ['b', 'b', 'b', 'a', 'a', 'a', 'a']
</code></pre>
<p>FWIW, this code is about 8 times faster than using <code>set(permutations(lst))</code> for the list given in the question; for larger input lists the time savings can be much greater.</p>
<p><hr>
<code>lexico_permute</code> initially makes a new list from the input sequence (which can also be a tuple, string, etc). It then yields that new list, advances it in-place to the next permutation, and yields the same list again. Etc. So if you simply append its output to an empty list you end up with a list of lists that just consists of multiple references to the same list. This is generally not very useful. :)</p>
<p>The simple way to fix that is to append a copy of the list yielded by <code>lexico_permute</code>, eg </p>
<pre><code>all_perms = []
for u in lexico_permute(lst):
all_perms.append(u[:])
</code></pre>
<p>or as a list comprehension:</p>
<pre><code>all_perms = [u[:] for u in lexico_permute(lst)]
</code></pre>
<p>Alternatively, change the two yield statements in <code>lexico_permute</code> to</p>
<pre><code>yield a[:]
</code></pre>
<p>And then you can do</p>
<pre><code>all_perms = list(lexico_permute(lst))
</code></pre>
| 5 | 2016-08-01T08:00:46Z | [
"python",
"probability"
] |
How to calculate how many different ways I can order a list in python | 38,686,269 | <p>I'm a little confused on how to do this, and I know it probably requires a bit of probability knowledge too (which I'm lacking).</p>
<p>How can I calculate how many ways, and also get all the possibilities, of how many ways I can order a list?</p>
<p>For example if I have <code>lst = ["a", "a", "a", "a", "b", "b", "b"]</code>, how many ways can I order this/how can I get all the possible combinations? I've been looking through <code>itertools</code> but haven't found something for it.</p>
| 3 | 2016-07-31T16:47:28Z | 38,731,083 | <p>It sounds like you are simply trying to calculate the number of distinguishable permutations, not generate them.</p>
<p>If you have n<sub>1</sub> indistinguishable elements of one kind, n<sub>2</sub> indistinguishable elements of another kind, up to n<sub>k</sub> elements of the last kind, then the formula for number of indistinguishable permutations of your set is:</p>
<p><a href="http://i.stack.imgur.com/jSJE4.gif" rel="nofollow"><img src="http://i.stack.imgur.com/jSJE4.gif" alt="enter image description here"></a></p>
<p>To calculate this in Python we can do:</p>
<pre><code>from collections import Counter
from math import factorial
from functools import reduce
import operator
def unique_permutations(lst):
c = Counter(lst)
return factorial(len(lst)) // reduce(operator.mul, map(factorial, c.values()))
</code></pre>
<p>And here is the output:</p>
<pre><code>>>> unique_permutations(["a", "a", "a", "a", "b", "b", "b"])
35
</code></pre>
| 0 | 2016-08-02T21:50:43Z | [
"python",
"probability"
] |
How to define a callable function whenever the value of any element in the list gets changed? | 38,686,344 | <p>I know this question is kind of simple and silly but I got stymied of searching the internet. Consider we have a 2-dimensional list in Python which represents a game board of hex and its elements would be changed by some function (like playing stone at some cell in the game board).</p>
<p>What I am looking for is a tool in Python that could define a function to be called whenever the value of any element in the array gets changed.
I already found the function <code>trace</code> in tkinter which calls a function when <code>StringVar</code>,<code>DoubleVar</code> and so on get changed.</p>
<p>I was wondering if a similar one could be found for simple lists or even numpy lists.</p>
| 1 | 2016-07-31T16:55:20Z | 38,686,541 | <p>Your requirements:</p>
<ul>
<li><p>2-dimensinal list in python which represents a game board of hex </p></li>
<li><p>and its elements would be changed by some function (like playing stone at some cell in the game board). </p></li>
<li><p>a function to be called whenever the value of any element in the array gets changed.</p></li>
</ul>
<p>The straight forward way to implement this is to define a class representing the <code>board</code> and actions. It will contain the 2d list (could be <code>numpy</code> array, but that may not be necessary).</p>
<p>It would also define methods that change the list, and perform the recording/callback. </p>
<pre><code>class Board():
def __init__(...)
self.list2d=[] # 2d nested list
def record_play(...):
<action when a cell is changed>
def play(...):
<change self.list2d>
self.record_play(...)
</code></pre>
<p>As long a the <code>Board</code> object controls all the changes, you don't need a more generic tracking tool, or even a subclass of list or array (though those are possible). Just make sure you call the tracking function each time you call the change function.</p>
<p>If you were doing this across different classes and kinds of objects it could be worth while constructing something more abstract. But for a one-off case, just do the obvious.</p>
| 1 | 2016-07-31T17:18:40Z | [
"python",
"list",
"numpy"
] |
How to set a variable's subproperty? | 38,686,377 | <p>I am a newbie to Python. I got some Python sample code from a software vendor who extended their software API with boost.python so we can call them in Python. I am confused with some of the segments, such as:</p>
<pre class="lang-py prettyprint-override"><code>settings = zoo.AddAnimalSettings(carni_bird_list)
settings.Name = 'birds'
settings.Type = settings.Type.enum.Bird
settings.water_min = 1, units.Litre
settings.food_min = 10, units.Gram
</code></pre>
<p>All the variable names are replaced to be these funny things anyway, just for explanation of the general idea. </p>
<p>So here the problem is in the 3rd line. How can we set the variable <code>settings.Type</code> with its sub property <code>settings.Type.enum.Bird</code>, where <code>enum.Bird</code> I suppose is some kind of enum of different kind of animals, which is a sub-property of <code>settings.Type</code>?</p>
<p>I tried doing some test to add one line following the above 5 lines to see if <code>enum.Bird</code> is still there:</p>
<pre><code>settings.Type = settings.Type.enum.Bird
</code></pre>
<p>and it works ok.
So for this instance <code>settings</code>, it's sub property <code>Type</code> is not overwritten by its sub property of <code>enum.Bird</code>, it still knows <code>enum.Bird</code> is its sub-property. </p>
<p>Can you advise if I need to implement this line in Python, how can I do that?</p>
<p>I suppose it would be a quite interesting knowledge for people learning Python, so I raised this question here for discussing. I am trying to think in a C++ way, but I didn't figure it out.</p>
| 1 | 2016-07-31T16:58:34Z | 38,686,564 | <p>I don't really see what's the issue. Consider an <code>Enum</code> defined in python:</p>
<pre><code>import enum
class Type(enum.Enum):
Bird = 0
Cat = 1
</code></pre>
<p>The <code>Type.Bird</code> and <code>Type.Cat</code> are <strong>instances</strong> of the <code>Type</code> class:</p>
<pre><code>>>> Type.Bird
<Type.Bird: 0>
>>> Type.Cat
<Type.Cat: 1>
</code></pre>
<p>As such they have access to their own class, which is <code>Type</code>:</p>
<pre><code>>>> Type.Bird.__class__
<enum 'Type'>
</code></pre>
<p>Now you can just add a <code>property</code> to the <code>Type</code> class and obtain that behaviour:</p>
<pre><code>class Type(enum.Enum):
Bird = 0
Cat = 1
@property
def enum(self):
return self.__class__
</code></pre>
<p>and now you have:</p>
<pre><code>>>> Type.Bird
<Type.Bird: 0>
>>> Type.Bird.enum
<enum 'Type'>
>>> Type.Bird.enum.Bird
<Type.Bird: 0>
>>> Type.Bird.enum.Cat
<Type.Cat: 1>
</code></pre>
<hr>
<p>Note that while the above allows you to write <code>Bird.enum</code> doesn't allow you to access as in <code>Type.enum</code> because this would return the <code>property</code> object.</p>
<p>To obtain the exact behaviour you see in that code you could:</p>
<ul>
<li><p>Set the <code>settings.Type</code> attribute to be an instance of <code>Type</code> (possibly an <code>Invalid</code> one) and be done:</p>
<pre><code>def AddAnimalSettings(*args)
settings = MyClass(*args)
settings.Type = Type.Bird
return settings
</code></pre></li>
<li><p>Replace the use of <code>property</code> with a custom made descriptor that will handle the access via the class too. In this case read <a href="https://docs.python.org/3/howto/descriptor.html#properties" rel="nofollow">the documentation about <code>property</code></a> which also provides its python code equivalent. The case you have to change is <code>__get__</code> when <code>obj is None</code>:</p>
<pre><code>class MyProperty(object):
# omissis
def __get__(self, obj, objtype=None):
if obj is None:
return objtype # <-- changed this line
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
</code></pre>
<p>Use this as:</p>
<pre><code>class Type(enum.Enum):
Bird = 0
Cat = 1
@MyProperty
def enum(self):
return self.__class__
</code></pre>
<p>And now you have:</p>
<pre><code>>>> Type.enum
<enum 'Type'>
</code></pre>
<p>so that <code>Type.enum.Bird</code> works.</p></li>
</ul>
| 2 | 2016-07-31T17:20:59Z | [
"python"
] |
Smooth line with spline and datetime objects doesn't work | 38,686,415 | <p>I have been trying to make a plot smoother, like it is done <a href="http://stackoverflow.com/questions/5283649/plot-smooth-line-with-pyplot">here</a>, but my Xs are datetime objects that are not compatible with linspace..</p>
<p>I convert the Xs to matplotlib dates:</p>
<pre><code>Xnew = matplotlib.dates.date2num(X)
X_smooth = np.linspace(Xnew.min(), Xnew.max(), 10)
Y_smooth = spline(Xnew, Y, X_smooth)
</code></pre>
<p>But then I get an empty plot, as my Y_smooth is </p>
<p><code>[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]</code></p>
<p>for some unknown reason.</p>
<p>How can I make this work ?</p>
<p><b>EDIT</b></p>
<p>Here's what I get when I print the variables, i see nothing abnormal :</p>
<pre><code>X : [datetime.date(2016, 7, 31), datetime.date(2016, 7, 30), datetime.date(2016, 7, 29)]
X new: [ 736176. 736175. 736174.]
X new max: 736176.0
X new min: 736174.0
XSMOOTH [ 736174. 736174.22222222 736174.44444444 736174.66666667
736174.88888889 736175.11111111 736175.33333333 736175.55555556
736175.77777778 736176. ]
Y [711.74, 730.0, 698.0]
YSMOOTH [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
</code></pre>
| 0 | 2016-07-31T17:04:56Z | 38,687,139 | <p>Your <code>X</code> values are reversed, <code>scipy.interpolate.spline</code> requires the independent variable to be monotonically increasing, and this method is deprecated - use <code>interp1d</code> instead (see below).</p>
<pre><code>>>> from scipy.interpolate import spline
>>> import numpy as np
>>> X = [736176.0, 736175.0, 736174.0] # <-- your original X is decreasing
>>> Y = [711.74, 730.0, 698.0]
>>> Xsmooth = np.linspace(736174.0, 736176.0, 10)
>>> spline(X, Y, Xsmooth)
array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
</code></pre>
<p>reverse <code>X</code> and <code>Y</code> first and it works</p>
<pre><code>>>> spline(
... list(reversed(X)), # <-- reverse order of X so also
... list(reversed(Y)), # <-- reverse order of Y to match
... Xsmooth
... )
array([ 698. , 262.18297973, 159.33767533, 293.62017489,
569.18656683, 890.19293934, 1160.79538066, 1285.149979 ,
1167.41282274, 711.74 ])
</code></pre>
<p>Note that many spline interpolation methods require <code>X</code> to be monotonically increasing:</p>
<ul>
<li><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.UnivariateSpline.html" rel="nofollow"><code>UnivariateSpline</code></a></li>
</ul>
<blockquote>
<p><code>x</code> : <em>(N,) array_like</em> - 1-D array of independent input data. Must be increasing.</p>
</blockquote>
<ul>
<li><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.InterpolatedUnivariateSpline.html" rel="nofollow"><code>InterpolatedUnivariateSpline</code></a></li>
</ul>
<blockquote>
<p><code>x</code> : <em>(N,) array_like</em> - Input dimension of data points â must be increasing</p>
</blockquote>
<p>The default order of <code>scipy.interpolate.spline</code> is cubic. Because there are only 3 data points there are large differences between a cubic spline (<code>order=3</code>) and a quadratic spline (<code>order=2</code>). The plot below shows the difference between different order splines; note: 100 points were used to <em>smooth</em> the fitted curve <em>more</em>.</p>
<p><a href="http://i.stack.imgur.com/m4DCw.png" rel="nofollow"><img src="http://i.stack.imgur.com/m4DCw.png" alt="scipy.interpolate.spline"></a></p>
<p>The documentation for <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.spline.html" rel="nofollow"><code>scipy.interpolate.spline</code></a>is vague and suggests it may not be supported. For example, it is not listed on the <a href="http://docs.scipy.org/doc/scipy/reference/interpolate.html" rel="nofollow"><code>scipy.interpolate</code> main page</a> or on the <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html" rel="nofollow">interploation tutorial</a>. The <a href="https://github.com/scipy/scipy/blob/v0.18.0/scipy/interpolate/interpolate.py#L2989-L3012" rel="nofollow">source for <code>spline</code></a> shows that it actually calls <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.spleval.html#scipy.interpolate.spleval" rel="nofollow"><code>spleval</code></a> and <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.splmake.html#scipy.interpolate.splmake" rel="nofollow"><code>splmake</code></a> which are listed under <a href="http://docs.scipy.org/doc/scipy/reference/interpolate.html#additional-tools" rel="nofollow">Additional Tools</a> as:</p>
<blockquote>
<p>Functions existing for backward compatibility (<strong>should not be used in new code</strong>).</p>
</blockquote>
<p>I would follow <a href="http://stackoverflow.com/users/2308683/cricket-007">cricket_007</a>'s suggestion and use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d" rel="nofollow"><code>interp1d</code></a>. It is the currently suggested method, it is very well documented with <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html#d-interpolation-interp1d" rel="nofollow">detailed examples in both the tutorial</a> and API, and it allows the independent variable to be unsorted (any order) by default (see <code>assume_sorted</code> argument in API).</p>
<pre><code>>>> from scipy.interpolate import interp1d
>>> f = interp1d(X, Y, kind='quadratic')
>>> f(Xsmooth)
array([ 711.74 , 720.14123457, 726.06049383, 729.49777778,
730.45308642, 728.92641975, 724.91777778, 718.4271605 ,
709.4545679 , 698. ])
</code></pre>
<p>Also it will raise an error if the data is rank deficient.</p>
<pre><code>>>> f = interp1d(X, Y, kind='cubic')
</code></pre>
<blockquote>
<p>ValueError: x and y arrays must have at least 4 entries</p>
</blockquote>
| 1 | 2016-07-31T18:27:37Z | [
"python",
"datetime",
"matplotlib",
"scipy",
"interpolation"
] |
Having both a method and a function which do the same thing? | 38,686,437 | <p>Is there a convention on how to have both a method and a function that do the same thing (or whether to do this at all)?</p>
<p>Consider, for example,</p>
<pre><code>from random import choice
from collections import Counter
class MyDie:
def __init__(self, smallest, largest, how_many_rolls):
self.min = smallest
self.max = largest
self.number_of_rolls = how_many_rolls
def __call__(self):
return choice( range(self.min, self.max+1) )
def count_values(self):
return Counter([self() for n in range(self.number_of_rolls)])
def count_values(randoms_func, number_of_values):
return Counter([randoms_func() for n in range(number_of_values)])
</code></pre>
<p>where <code>count_values</code> is both a method and a function.</p>
<p>I think it's nice to have the method because the result "belongs to" the MyDie object. Also, the method can pull attributes from the <code>MyDie</code> object without having to pass them to <code>count_values</code>. On the other hand, it's nice to have the function in order to operate on functions other than <code>MyDie</code>, like</p>
<pre><code>count_values(lambda: choice([3,5]) + choice([7,9]), 7)
</code></pre>
<p>Is it best to do this as above (where the code is repeated; assume the function is a longer piece of code, not just one line) or replace the <code>count_values</code> method with</p>
<pre><code>def count_values(self):
return count_values(self, number_of_rolls)
</code></pre>
<p>or just get rid of the method all together and just have a function? Or maybe something else?</p>
| 0 | 2016-07-31T17:07:11Z | 38,686,864 | <p>Here is an alternative that still allows you to encapsulate the logic in <code>MyDie</code>. Create a class method in <code>MyDie</code> </p>
<pre><code>@staticmethod
def count_specified_values(random_func, number_of_values):
return Counter([randoms_func() for n in range(number_of_values)])
</code></pre>
<p>You also could add additional formal parameters to the constructor with default values that you could override to achieve the same functionality. </p>
| 0 | 2016-07-31T17:54:50Z | [
"python",
"function",
"methods"
] |
Cant understand why i am getting a keyerror in my django python app | 38,686,475 | <p>I know that a key error is raised when a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary. But my key is there. It's telling me that the 'embed' key is the problem</p>
<p>heres my code</p>
<pre><code> def scrape_and_store_vlad():
url_two = 'http://www.example.net'
html = requests.get(url_two, headers=headers)
soup = BeautifulSoup(html.text, 'html5lib')
titles = soup.find_all('div', {'class': 'entry-pos-1'})
def make_soup(url):
the_comments_page = requests.get(url, headers=headers)
soupdata = BeautifulSoup(the_comments_page.text, 'html5lib')
comment = soupdata.find('div', {'class': 'article-body'})
para = comment.find_all('p')
kids = [child.text for child in para]
blu = str(kids).strip('[]')
return blu
name = 'vlad'
entries = [{'href': url_two + div.a.get('href'),
'src': url_two + div.a.img.get('data-original'),
'text': div.find('p', 'entry-title').text,
'comments': make_soup(url_two + div.a.get('href')).replace("\\", ""),
'name': name,
'url': url_two + div.a.get('href')
} for div in titles][:6]
# scraping from vlad part two
titles_two = soup.find_all('div', {'class': 'entry-pos-2'})
entries_two = [{'href': url_two + div.a.get('href'),
'src': url_two + div.a.img.get('data-original'),
'text': div.find('p', 'entry-title').text,
'comments': make_soup(url_two + div.a.get('href')).replace("\\", ""),
'name': name,
'url': url_two + div.a.get('href'),
'embed': url_two + div.a.get('href'),
} for div in titles_two][:6]
merged_vlad_entries = entries + entries_two
return merged_vlad_entries
def panties():
from lxml import html
pan_url = 'http://www.example.net'
shtml = requests.get(pan_url, headers=headers)
soup = BeautifulSoup(shtml.text, 'html5lib')
video_row = soup.find_all('div', {'class': 'video'})
name = 'pan videos'
def youtube_link(url):
youtube_page = requests.get(url, headers=headers)
soupdata = BeautifulSoup(youtube_page.text, 'html5lib')
video_row = soupdata.find_all('script', {'type': 'text/javascript'})
entries = [{'text': str(div),
} for div in video_row]
tubby = str(entries[4])
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tubby)
return urls
def embed(url):
new_embed = url.replace("watch?v=", "embed/")
return new_embed
entries = [{'href': div.a.get('href'),
'src': youtube_link(div.a.get('href'))[1],
'text': div.h4.text,
'comments': div.h4.text,
'name': name,
'url': div.a.get('href'),
'embed': embed(youtube_link(div.a.get('href'))[0]),
} for div in video_row][:3]
return entries
def save_the_scrapes():
from_world_star = scrape_and_store_world()
from_vlad_tv = scrape_and_store_vlad()
from_pan = panties()
mergence = from_world_star + from_vlad_tv + from_pan
random.shuffle(mergence)
for entry in mergence:
post = Post()
post.title = entry['text']
title = post.title
if not Post.objects.filter(title=title):
post.title = entry['text']
post.name = entry['name']
post.url = entry['url']
post.body = entry['comments']
post.image_url = entry['src']
post.video_path = entry['embed']
post.status = 'draft'
post.save()
return mergence
</code></pre>
<p>before I added the embed key everything worked fine. If anyone can spot my error please let me know where I went wrong. Thanks.</p>
| -1 | 2016-07-31T17:12:10Z | 38,686,601 | <p>The key is clearly not there, otherwise you would not get a <code>KeyError</code>.</p>
<p>You do not set the key in your <code>scrape_and_store_vlad</code> method.</p>
<pre><code>def scrape_and_store_vlad():
...
entries = [{'href': url_two + div.a.get('href'),
'src': url_two + div.a.img.get('data-original'),
'text': div.find('p', 'entry-title').text,
'comments': make_soup(url_two + div.a.get('href')).replace("\\", ""),
'name': name,
'url': url_two + div.a.get('href')
} for div in titles][:6]
</code></pre>
| 1 | 2016-07-31T17:24:00Z | [
"python",
"django",
"dictionary",
"keyerror"
] |
Where is python folder? Python install problems | 38,686,493 | <p>I have installed Python 3.5.2 on my windows 8 computer, I tried in cmd <code>python --version</code> and it gave me that stupid error: </p>
<p>"python is not recognized as an internal or external command..."</p>
<p>I also have no files named python on my computer anywhere. I used the search feature on file explorer and I've search manually. I even looked through the hidden files. I have tried to install Python 3 times and the same thing keeps happening. Any help appreciated.</p>
| 0 | 2016-07-31T17:14:33Z | 38,686,576 | <p>You may try to use <code>which python</code> to find out the location of python in your computer. If it doesn't work and you cannot find where is the your installed directory, you may need to reinstall and make sure you remember the installation directory and add it as a environment variable in windows system.</p>
| 0 | 2016-07-31T17:21:23Z | [
"python",
"install"
] |
Where is python folder? Python install problems | 38,686,493 | <p>I have installed Python 3.5.2 on my windows 8 computer, I tried in cmd <code>python --version</code> and it gave me that stupid error: </p>
<p>"python is not recognized as an internal or external command..."</p>
<p>I also have no files named python on my computer anywhere. I used the search feature on file explorer and I've search manually. I even looked through the hidden files. I have tried to install Python 3 times and the same thing keeps happening. Any help appreciated.</p>
| 0 | 2016-07-31T17:14:33Z | 38,686,608 | <p>In Windows 8 for Python 3.* I believe it is:
C:\Users\<em>yourusername</em>\AppData\Local\Programs\Python\</p>
<p>To use that from the Windows command line you will need to add it to your path. </p>
<p>Control Panel -> Advanced System Settings -> Environment Variables -> System Variables -> Path</p>
<p>Add in the Python path at the end after a semi-colon, do not delete the others.</p>
| 1 | 2016-07-31T17:24:24Z | [
"python",
"install"
] |
Where is python folder? Python install problems | 38,686,493 | <p>I have installed Python 3.5.2 on my windows 8 computer, I tried in cmd <code>python --version</code> and it gave me that stupid error: </p>
<p>"python is not recognized as an internal or external command..."</p>
<p>I also have no files named python on my computer anywhere. I used the search feature on file explorer and I've search manually. I even looked through the hidden files. I have tried to install Python 3 times and the same thing keeps happening. Any help appreciated.</p>
| 0 | 2016-07-31T17:14:33Z | 38,687,374 | <p>I was probably same problem with python launcher.</p>
<p>In registry by <strong>regedit</strong> change
<code>HKEY_CLASSES_ROOT\Python.File\shell\open\command</code> from <code>"C:\some\path\to\python" "%1" %*</code> to <code>"C:\Windows\py.exe" "%1" %*</code>.</p>
<p>And first line of script shoud be:</p>
<pre><code>#! python3
</code></pre>
<p>Now it shoud work properly and run in cmd just by <code>scriptname</code>, not <code>scriptname.py</code>, and not <code>py scripname.py</code>.</p>
<p>You can write directly to egigoka@gmail.com if you need something about this.</p>
<p>P.S. Sorry for bad English</p>
| 0 | 2016-07-31T18:54:45Z | [
"python",
"install"
] |
How to properly display image in Python? | 38,686,610 | <p>I found this code:</p>
<pre><code>from PIL import Image, ImageTk
import tkinter as tk
root = tk.Tk()
img = Image.open(r"Sample.jpg")
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()
tk_img = ImageTk.PhotoImage(img)
canvas.create_image(250, 250, image=tk_img)
root.mainloop()
</code></pre>
<p>It displays any picture in 500x500px resolution. I tried to change it and display it in its original size:</p>
<pre><code>from PIL import Image, ImageTk
import tkinter as tk
root = tk.Tk()
img = Image.open(r"D:/1.jpg")
canvas = tk.Canvas(root, width=img.width, height=img.height)
canvas.pack()
tk_img = ImageTk.PhotoImage(img)
canvas.create_image(img.width/2, img.height/2, image=tk_img)
root.mainloop()
</code></pre>
<p>But something went wrong and the picture with a size of 604x604px shows in a window with a size of 602x602px, but the window size is correct.
<a href="http://i.stack.imgur.com/I0YCx.png" rel="nofollow">Take a look</a> <a href="http://i.stack.imgur.com/h2NJj.jpg" rel="nofollow">(full image)</a>.
What am I doing wrong?</p>
<p>P.S. Sorry for bad English.</p>
| 1 | 2016-07-31T17:24:32Z | 38,728,999 | <p>Well, no, your first example still cuts off by a few pixels. All top level windows will have padding around their absolute borders to prevent other elements from 'bleeding' into the borders and looking unprofessional.</p>
<p>You are still being given a canvas of 604 pixels by 604 pixels, but the root window itself is asserting its padding. I could not find any way of removing this top level padding, and it may very well appear differently in other operating systems. A work-around could be to request a canvas size that is slightly larger than the image you would like to display.</p>
<p>Another issue, if you're aiming for precision, would be the line...</p>
<pre><code>canvas.create_image(img.width/2, img.height/2, image=tk_img)
</code></pre>
<p>Which could create off-by-one errors if your width or height is an odd number. You can anchor images to the north-west corner and place them at the co-ordinates <code>(0, 0)</code> like such:</p>
<pre><code>canvas.create_image(0, 0, anchor=tk.NW, image=tk_img)
</code></pre>
| 0 | 2016-08-02T19:31:28Z | [
"python",
"python-3.x",
"tkinter",
"python-imaging-library"
] |
Combining files into multiIndex dataframe in python and finally export to txt | 38,686,713 | <p>I have a couple of files that all have the same first column (<code>X</code>), and the same column names (<code>X</code>, <code>B</code>, <code>C</code>), but the second and third column are different values.</p>
<pre><code>X | B | C
-----------
a 0 2
b 4 9
...
z 3 0
</code></pre>
<p>I want to combine all these tables into one big dataframe, but with the addition that each part is accessible through its own index, for instance based on the filename. E.g. <code>df['f1']['B']</code> would be <code>[0, 4..., 3]</code>. The end result would look like this.</p>
<pre><code> | f1 | f1 | f2 | f2
X | B | C | B | C
-----------------------
a 0 2 3 2
b 4 9 1 2
...
z 3 0 9 8
</code></pre>
<p>This is the code I have so far</p>
<pre><code>import pandas as pd
import numpy as np
import regex as re
dir = 'directory'
path = os.path.abspath(os.path.join(os.getcwd(), dir))
# List all files in folder
filenames = [name for name in os.listdir(path) if re.match(".*\.txt$", name)]
r_coln = re.compile(r"\.txt$")
frames = []
for i in range(len(filenames)):
filename = filenames[i]
coln = r_coln.sub("", filename)
if (i == 0):
# Subtract the first column which is identical for all frames
first_frame = pd.read_csv(os.path.join(path, filename), usecols=[0], sep="\t", names=[''], header=None)
frames.append(first_frame)
# Get frame with a new header
frames.append(pd.read_csv(os.path.join(path, filename), usecols=[1, 2], sep="\t", names=[coln, ''], header=None))
# Combine all frames
df = pd.concat(frames, axis=1)
</code></pre>
<p>This works in that the resulting dataframe does indeed look like the example I posted above with the exception that I only have one 'top' heading per file. Using <code>names=[coln, coln]</code> instead of <code>names=[coln, '']</code> caused one of the two columns to get dropped (and I do not know why). However, it isn't multi-indexed. In other words, I cannot access <code>df['f1']['B']</code> because it returns the error <code>KeyError: 'B'</code>. I am looking for a way to make this possible. Either by transforming the resulting <code>df</code> after the read-in loop, or by changing something inside the loop.</p>
<p>Finally, I'd also like to export this dataframe to a tab-separated text file.</p>
| 0 | 2016-07-31T17:36:42Z | 38,687,408 | <p>Edit - Adding a one-liner, credits to @ptrj.</p>
<pre><code>df = pd.concat([df1.set_index('X'),df2.set_index('X')],axis=1,keys = ['F1','F2'])
In []: df
Out[]:
F1 F2
B C B C
X
a 0 2 0 4
b 4 9 8 18
z 3 0 6 0
</code></pre>
<hr>
<p>Alternative Solution : </p>
<p>You can define a MultiIndex from arrays.</p>
<p>Let's start with two sample DataFrame.</p>
<pre><code>df1 = pd.DataFrame({'B': {0: 0, 1: 4, 2: 3},
'C': {0: 2, 1: 9, 2: 0},
'X': {0: 'a', 1: 'b', 2: 'z'}})
df2 = pd.DataFrame({'B': {0: 0, 1: 8, 2: 6},
'C': {0: 4, 1: 18, 2: 0},
'X': {0: 'a', 1: 'b', 2: 'z'}})
# Merge the DataFrames
merged = df1.merge(df2,on='X').set_index('X')
# Create a MultiIndex
arrays = [['F1','F1','F2','F2'], ['B','C','B','C']]
columns = pd.MultiIndex.from_arrays(arrays, names=['level1', 'level2'])
# Create your DataFrame
df = pd.DataFrame(data=merged.as_matrix(),
columns=columns,
index = df1['X'])
</code></pre>
<p><code>df</code> now looks like :</p>
<pre><code>level1 F1 F2
level2 B C B C
X
a 0 2 0 4
b 4 9 8 18
z 3 0 6 0
</code></pre>
<p>Now, you can index it using <code>df['F1']</code> </p>
<pre><code>level2 B C
X
a 0 2
b 4 9
z 3 0
</code></pre>
<p>Or, <code>df['F1']['B']</code>, which gives you :</p>
<pre><code>0 0
1 4
2 3
</code></pre>
<hr>
<p>Edit : @Bram Vanroy <a href="http://pastebin.com/7L7VCzxm" rel="nofollow">extended this solution</a> to work with multiple DataFrames.</p>
| 0 | 2016-07-31T18:58:44Z | [
"python",
"pandas",
"multi-index"
] |
Frequency diagram with matplotlib | 38,686,716 | <p>I am trying to automate a frequency diagram with matplotlib in Python in order to count occurences, instead of having to manually plot in Excel. However, I am not able to make an similar as possible diagram as I have done in Excel. Is this possible with Matplotlib?</p>
<p>In Excel:</p>
<p><a href="http://i.stack.imgur.com/saGxL.png" rel="nofollow"><img src="http://i.stack.imgur.com/saGxL.png" alt="enter image description here"></a></p>
<p>Code:</p>
<pre><code>#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
from numpy import *
import os
import sys
import csv
from random import randint
x = [6,0,0,26,0,0,0,0,5,0,7,0,12,12,0,0,0,3,0,5,5,0,10,4,3,5,1,0,2,0,0,1,0,8,0,3,7,1,0,0,0,1,1,0,0,0,0,0,7,16,0,0,0,5]
plt.hist(x)
plt.title("Frequency diagram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
</code></pre>
<p>Result (The readability is not as good compared to Excel, how can I make it as similar as the excel graph):</p>
<p><a href="http://i.stack.imgur.com/ZBcty.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZBcty.png" alt="enter image description here"></a></p>
| 0 | 2016-07-31T17:36:50Z | 38,686,854 | <p>Matplotlib does support styling. You may prefer the ggplot style:</p>
<pre><code>plt.style.use('ggplot')
</code></pre>
<p>There are many other premade styles, or you can create your own:
<a href="http://matplotlib.org/users/style_sheets.html" rel="nofollow">http://matplotlib.org/users/style_sheets.html</a></p>
| 0 | 2016-07-31T17:52:49Z | [
"python",
"excel",
"matplotlib"
] |
Frequency diagram with matplotlib | 38,686,716 | <p>I am trying to automate a frequency diagram with matplotlib in Python in order to count occurences, instead of having to manually plot in Excel. However, I am not able to make an similar as possible diagram as I have done in Excel. Is this possible with Matplotlib?</p>
<p>In Excel:</p>
<p><a href="http://i.stack.imgur.com/saGxL.png" rel="nofollow"><img src="http://i.stack.imgur.com/saGxL.png" alt="enter image description here"></a></p>
<p>Code:</p>
<pre><code>#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
from numpy import *
import os
import sys
import csv
from random import randint
x = [6,0,0,26,0,0,0,0,5,0,7,0,12,12,0,0,0,3,0,5,5,0,10,4,3,5,1,0,2,0,0,1,0,8,0,3,7,1,0,0,0,1,1,0,0,0,0,0,7,16,0,0,0,5]
plt.hist(x)
plt.title("Frequency diagram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
</code></pre>
<p>Result (The readability is not as good compared to Excel, how can I make it as similar as the excel graph):</p>
<p><a href="http://i.stack.imgur.com/ZBcty.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZBcty.png" alt="enter image description here"></a></p>
| 0 | 2016-07-31T17:36:50Z | 38,687,017 | <pre><code>import numpy as np
import matplotlib.pyplot as plt
def make_hist(ax, x, bins=None, binlabels=None, width=0.85, extra_x=1, extra_y=4,
text_offset=0.3, title=r"Frequency diagram",
xlabel="Values", ylabel="Frequency"):
if bins is None:
xmax = max(x)+extra_x
bins = range(xmax+1)
if binlabels is None:
if np.issubdtype(np.asarray(x).dtype, np.integer):
binlabels = [str(bins[i]) if bins[i+1]-bins[i] == 1 else
'{}-{}'.format(bins[i], bins[i+1]-1)
for i in range(len(bins)-1)]
else:
binlabels = [str(bins[i]) if bins[i+1]-bins[i] == 1 else
'{}-{}'.format(*bins[i:i+2])
for i in range(len(bins)-1)]
if bins[-1] == np.inf:
binlabels[-1] = '{}+'.format(bins[-2])
n, bins = np.histogram(x, bins=bins)
patches = ax.bar(range(len(n)), n, align='center', width=width)
ymax = max(n)+extra_y
ax.set_xticks(range(len(binlabels)))
ax.set_xticklabels(binlabels)
ax.set_title(title)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_ylim(0, ymax)
ax.grid(True, axis='y')
# http://stackoverflow.com/a/28720127/190597 (peeol)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
# http://stackoverflow.com/a/11417222/190597 (gcalmettes)
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
autolabel(patches, text_offset)
def autolabel(rects, shift=0.3):
"""
http://matplotlib.org/1.2.1/examples/pylab_examples/barchart_demo.html
"""
# attach some text labels
for rect in rects:
height = rect.get_height()
if height > 0:
plt.text(rect.get_x()+rect.get_width()/2., height+shift, '%d'%int(height),
ha='center', va='bottom')
x = [6,0,0,26,0,0,0,0,5,0,7,0,12,12,0,0,0,3,0,5,5,0,10,4,3,5,1,0,2,0,0,1,0,8,0,
3,7,1,0,0,0,1,1,0,0,0,0,0,7,16,0,0,0,5,41]
fig, ax = plt.subplots(figsize=(14,5))
# make_hist(ax, x)
# make_hist(ax, [1,1,1,0,0,0], extra_y=1, text_offset=0.1)
make_hist(ax, x, bins=list(range(10))+list(range(10,41,5))+[np.inf], extra_y=6)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/s4O59.png" rel="nofollow"><img src="http://i.stack.imgur.com/s4O59.png" alt="enter image description here"></a></p>
<p><code>make_hist</code> attempts to identify if all the values in <code>x</code> are integers. If so, it uses integer-based bin labels. For example, the bin label <code>10-14</code> represents the range <code>[10, 14]</code> (inclusive). </p>
<p>If, on the other hand, <code>x</code> contains floats, then <code>make_hist</code> will use half-open float-based bin labels. For example, <code>10-15</code> would represent the half-open range <code>[10, 15)</code>.</p>
| 2 | 2016-07-31T18:13:19Z | [
"python",
"excel",
"matplotlib"
] |
Extending Python: process numpy arrays | 38,686,765 | <p>I wrote an extension for Python 3 in C++</p>
<p>My module is capable of handling arrays like <code>[1.0, 0.0, 0.0]</code>.
I want to add support for numpy arrays as well.</p>
<p>I process arrays with the following code:</p>
<pre><code>PyObject * MyFunction(PyObject * self, PyObject * args) {
PyObject * list;
if (!PyArg_ParseTuple(args, "O!:MyFunction", PyList_Type, &list)) {
return 0;
}
int count = (int)PyList_Size(list);
for (int i = 0; i < count; ++i) {
double value = PyFloat_AsDouble(PyList_GET_ITEM(list, i));
// ...
}
}
</code></pre>
<p>I want a function that can iterate through this: <code>np.array([2,3,1,0])</code></p>
<p><strong>TL;DR:</strong></p>
<p>Numpy equivalent for:</p>
<ul>
<li><code>PyList_Type</code></li>
<li><code>PyList_Size</code></li>
<li><code>PyList_GET_ITEM</code> or <code>PyList_GetItem</code></li>
</ul>
| 2 | 2016-07-31T17:42:23Z | 39,477,955 | <p>First of all there is no <code>numpy</code> equivalent for:</p>
<ul>
<li>PyList_Type</li>
<li>PyList_Size</li>
<li>PyList_GET_ITEM or PyList_GetItem</li>
</ul>
<p>The <code>numpy.array</code> implements the <a href="https://docs.python.org/3/c-api/buffer.html" rel="nofollow">buffer interface</a>, so one can write:</p>
<pre><code>const char * data;
int size;
PyArg_ParseTuple(args, "y#:MyFunction", &data, &size);
</code></pre>
<p>The <code>numpy.array([1.0, 0.0, 0.0])</code> uses <code>double</code> precision:</p>
<pre><code>double * array = (double *)data;
int length = size / sizeof(double);
</code></pre>
<p><strong>The full example:</strong></p>
<ul>
<li><p><strong>C++</strong></p>
<pre><code>PyObject * MyFunction(PyObject * self, PyObject * args) {
const char * data;
int size;
if (!PyArg_ParseTuple(args, "y#:MyFunction", &data, &size)) {
return 0;
}
double * content = (double *)data;
int length = size / sizeof(double);
for (int i = 0; i < length; ++i) {
double value = content[i];
// ...
}
Py_RETURN_NONE;
}
</code></pre></li>
<li><p><strong>Python</strong></p>
<pre><code>MyFunction(numpy.array([1.0, 2.0, 3.0]))
</code></pre></li>
</ul>
| 0 | 2016-09-13T19:50:41Z | [
"python",
"c++",
"arrays",
"python-3.x",
"numpy"
] |
JRE_HOME not found on pip jnius installation | 38,686,809 | <p>Trying to install <code>jnius</code> from pip (it is a requirement to <code>pip install sikuli</code>). </p>
<p>This is the error I get when I am trying to install:</p>
<p><a href="http://i.stack.imgur.com/iSgvF.png" rel="nofollow"><img src="http://i.stack.imgur.com/iSgvF.png" alt="enter image description here"></a></p>
<p>Are the variables correctly defined?</p>
<p><a href="http://i.stack.imgur.com/1li7F.png" rel="nofollow"><img src="http://i.stack.imgur.com/1li7F.png" alt="enter image description here"></a></p>
<p>Does anyone understand why it keeps saying that it can't find <code>JRE_HOME</code>?</p>
<p><strong>Edit:</strong> My path variable is:</p>
<p><a href="http://i.stack.imgur.com/In09r.png" rel="nofollow"><img src="http://i.stack.imgur.com/In09r.png" alt="enter image description here"></a></p>
| 1 | 2016-07-31T17:47:37Z | 38,686,897 | <p>The setup.py contains:</p>
<pre><code>jdk_home = environ.get('JDK_HOME')
if not jdk_home:
jdk_home = subprocess.Popen('readlink -f /usr/bin/javac | sed "s:bin/javac::"',
shell=True, stdout=subprocess.PIPE).communicate()[0].strip()
if not jdk_home:
raise Exception('Unable to determine JDK_HOME')
jre_home = environ.get('JRE_HOME')
if not jre_home:
jre_home = subprocess.Popen('readlink -f /usr/bin/java | sed "s:bin/java::"',
shell=True, stdout=subprocess.PIPE).communicate()[0].strip()
if not jre_home:
raise Exception('Unable to determine JRE_HOME')
</code></pre>
<p>Somehow you pass the first error check <code>Unable to determine JDK_HOME</code>
start a new cmd window and try again.</p>
<p>Write a small code where you test these:</p>
<pre><code>import os
print os.environ.get('JDK_HOME')
print os.environ.get('JRE_HOME')
</code></pre>
<p>They are not case sensitive I tested it.</p>
<p><strong>EDIT:</strong> Check the environment variables:</p>
<pre><code>import json, os
print json.dumps(dict(os.environ), indent = 2)
</code></pre>
| 1 | 2016-07-31T17:59:34Z | [
"python",
"sikuli",
"pyjnius"
] |
Deserialize file from multipart post request in Flask | 38,686,826 | <p>In my HTML I have the following code:</p>
<pre><code><form action="editprojects" method="post" enctype="multipart/form-data">
<input type="file" name="pdf"/><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</code></pre>
<p>Now in my Flask I have the endpoint:</p>
<pre><code>@app.route('/editprojects',methods=['GET','POST'])
def editProjects():
pdf = request.files['pdf']
with open('mypdf.pdf', 'wb') as f:
f.write(pdf)
</code></pre>
<p>All files seem to be corrupted and ~ 52 bytes, so there must be some content. I've tried converting to <code>String</code>, trying <code>w</code> and <code>wb</code>, I've also seen errors like <code>must be convertible to a buffer not FileStorage</code>.</p>
<p>Any ideas? Thanks.</p>
| 1 | 2016-07-31T17:49:24Z | 38,698,181 | <p>As @IsmailRBOUH mentioned, this fixed my problem:</p>
<pre><code>pdf.save(path, filename) // path is optional
</code></pre>
<p>This is because <code>request.files</code> gives a file instead of a string or bytes, therefore you can just save the file.</p>
| 0 | 2016-08-01T11:52:42Z | [
"python",
"html",
"file",
"flask"
] |
python basic show and return values | 38,686,830 | <p>I'm using python to input data to my script </p>
<p>then trying to return it back
on demand to show the results</p>
<p>I tried to write it as simple as possible since it's only practicing and trying to get the hang of python</p>
<p>here's how my script looks like</p>
<pre><code>#!/usr/python
## imports #####
##################
import os
import sys
## functions
##################
# GET INSERT DATA
def getdata():
clientname = raw_input(" *** Enter Client Name > ")
phone = raw_input(" *** Enter Client Phone > ")
location = raw_input(" *** Enter Client Location > ")
email = raw_input(" *** Enter Client email > ")
website = raw_input(" *** Enter Client Website > ")
return clientname, phone, location, email, website
# VIEW DATA
def showdata():
print "==================="
print ""
print clientname
print ""
print phone
print ""
print location
print ""
print email
print ""
print website
print ""
print "==================="
# CLEAR
def clear():
os.system("clear") #linux
os.system("cls") #windows
# SHOW INSTRUCTIONS
def welcome():
clear()
while True:
choice = raw_input(" Select Option > ")
# INSERT DATA
if choice == "1":
getdata()
# VIEW DATA
elif choice == "2":
showdata()
else:
print "Invalid Selection.. "
print "Terminating... "
#exit()
welcome()
</code></pre>
<p>what am i doing wrong ? what am i missing? </p>
| -3 | 2016-07-31T17:49:39Z | 38,686,851 | <p>You're absolutely misusing globals. Please go back and read a good Python tutorial, for example from python.org.</p>
<p>Python is a programming language that allows you to define <em>functions</em>, i.e. things that <em>return</em> values. You should definitely use that, instead of <code>global</code>izing your input. I don't know where you've learned that â every Python ressource that I'd know of will first introduce how to deal properly with functions and their return values before even <em>mentioning</em> <code>global</code>.</p>
| 1 | 2016-07-31T17:52:36Z | [
"python"
] |
python basic show and return values | 38,686,830 | <p>I'm using python to input data to my script </p>
<p>then trying to return it back
on demand to show the results</p>
<p>I tried to write it as simple as possible since it's only practicing and trying to get the hang of python</p>
<p>here's how my script looks like</p>
<pre><code>#!/usr/python
## imports #####
##################
import os
import sys
## functions
##################
# GET INSERT DATA
def getdata():
clientname = raw_input(" *** Enter Client Name > ")
phone = raw_input(" *** Enter Client Phone > ")
location = raw_input(" *** Enter Client Location > ")
email = raw_input(" *** Enter Client email > ")
website = raw_input(" *** Enter Client Website > ")
return clientname, phone, location, email, website
# VIEW DATA
def showdata():
print "==================="
print ""
print clientname
print ""
print phone
print ""
print location
print ""
print email
print ""
print website
print ""
print "==================="
# CLEAR
def clear():
os.system("clear") #linux
os.system("cls") #windows
# SHOW INSTRUCTIONS
def welcome():
clear()
while True:
choice = raw_input(" Select Option > ")
# INSERT DATA
if choice == "1":
getdata()
# VIEW DATA
elif choice == "2":
showdata()
else:
print "Invalid Selection.. "
print "Terminating... "
#exit()
welcome()
</code></pre>
<p>what am i doing wrong ? what am i missing? </p>
| -3 | 2016-07-31T17:49:39Z | 38,686,943 | <p>Your <code>getdata()</code> function returns five values. That means when you call it, you can get five values out.</p>
<pre><code>clientname, phone, location, email, website = getdata()
</code></pre>
<p>Then you can pass those into <code>showdata()</code> as arguments, if you change the function definition to say:</p>
<pre><code>def showdata(clientname, phone, location, email, website):
</code></pre>
<p>and call it with:</p>
<pre><code>showdata(clientname, phone, location, email, website)
</code></pre>
<p>But of course, that will fail if the user tries to show the data before they have input the data.</p>
| 1 | 2016-07-31T18:04:33Z | [
"python"
] |
Django admin: Custom ordering | 38,686,887 | <p>I have version field for a model, a string field. I defined my Django admin ordering by that field ("-version"). <br>
The problem is python's version comparison doesn't work when it comes to strings. For example:<br></p>
<pre><code>vers=['5.10.0.','5.9.0','5.8.0']
vers[0]>vers[1]
>>False
</code></pre>
<p>Should be <b>true</b>. <br><br>
How do I write custom ordering without changing the models?<br>
I saw <a href="http://stackoverflow.com/questions/2168475/django-admin-how-to-sort-by-one-of-the-custom-list-display-fields-that-has-no-d">this question</a>, but it works only for aggregation functions.
<br><br>
Note: I need solution for <b>ordering</b>, not <b>list_filter</b>, which I already have an answer <a href="http://stackoverflow.com/questions/2168475/django-admin-how-to-sort-by-one-of-the-custom-list-display-fields-that-has-no-d">here</a>. I changed the lookup as follows:
<br></p>
<pre><code>def lookups(self, request, model_admin):
qs = model_admin.queryset(request)
vers = qs.values_list('version', flat=True).distinct().order_by('-version')
s_vers = [tuple([int(x) for x in n.split('.')]) for n in vers]
s_vers = sorted(s_vers, reverse=True)
ns_vers = ['.'.join(map(str, x)) for x in s_vers]
ret_vers = []
for v in ns_vers:
ret_vers.append((v, v))
return ret_vers
</code></pre>
| 0 | 2016-07-31T17:58:05Z | 38,692,085 | <p>Here is how I solved this:</p>
<pre><code>class MyModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
qs = super(MyModelAdmin, self).get_queryset(request)
qs = qs.extra(select={'nversion': "string_to_array(version, '.')::bigint[]"}).order_by('-nversion')
return qs
def vers(self, obj):
return obj.nversion
ordering = ('-nversion',)
</code></pre>
| 1 | 2016-08-01T06:17:11Z | [
"python",
"django",
"django-admin",
"django-filter"
] |
Pandas - Unpack column of lists of varying lengths of tuples | 38,686,918 | <p>I would like to take a Pandas Dataframe named <code>df</code> which has an ID column and a lists column of lists that have variable number of tuples, all the tuples have the same length. Looks like this:</p>
<pre><code>ID list
1 [(0,1,2,3),(1,2,3,4),(2,3,4,NaN)]
2 [(Nan,1,2,3),(9,2,3,4)]
3 [(Nan,1,2,3),(9,2,3,4),(A,b,9,c),($,*,k,0)]
</code></pre>
<p>And I would like to unpack each list into columns 'A','B','C','D' representing the fixed positions in each tuple.</p>
<p>The result should look like:</p>
<pre><code>ID A B C D
1 0 1 2 3
1 1 2 3 4
1 2 3 4 NaN
2 NaN 1 2 3
2 9 2 3 4
3 NaN 1 2 3
3 9 2 3 4
3 A b 9 c
3 $ * k 0
</code></pre>
<p>I have tried <code>df.apply(pd.Series(list)</code> but fails as the <code>len</code> of the list elements is different on different rows. Somehow need to unpack to columns and transpose by ID?</p>
| 3 | 2016-07-31T18:02:05Z | 38,687,037 | <pre><code>In [38]: (df.groupby('ID')['list']
.apply(lambda x: pd.DataFrame(x.iloc[0], columns=['A', 'B', 'C', 'D']))
.reset_index())
Out[38]:
ID level_1 A B C D
0 1 0 0 1 2 3
1 1 1 1 2 3 4
2 1 2 2 3 4 NaN
3 2 0 NaN 1 2 3
4 2 1 9 2 3 4
5 3 0 NaN 1 2 3
6 3 1 9 2 3 4
7 3 2 A b 9 c
8 3 3 $ * k 0
</code></pre>
| 3 | 2016-07-31T18:15:52Z | [
"python",
"pandas",
"group-by",
"iterable-unpacking"
] |
Inserting unicode into MySQL database from python script | 38,686,924 | <p>I am trying to retrieve the text, longitude, and latitude from a tweepy StreamListener and then store the data in my SQL database. I am able to store the coordinates fine, but for some reason the unicode is not working.
For the SQL I have: </p>
<pre><code>mysql> CREATE TABLE tweets (tweet nvarchar(140), lat float(10,6) not null, lng float(10,6) not null) engine=myisam;
</code></pre>
<p>For my python script I have (not including the main()):</p>
<pre><code>import mysql.connector
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
from authenticator import Authenticator
import json
#connecting to mysql database
conn = mysql.connector.connect(user='root', password='arlenyu123',host='localhost',database='twitter')
mycursor = conn.cursor()
class MyStreamListener(StreamListener):
def on_status(self, status):
if status.coordinates is not None:
#for some reason the status text isn't being fed into the database properly... not sure why.
mycursor.execute('INSERT INTO tweets (tweet, lat, lng) VALUES ({},{},{})'.
format(status.text, status.coordinates['coordinates'][0], status.coordinates['coordinates'][1]))
return True
def on_error(self, status_code):
if status_code == 403:
print("The request is understood, but it has been refused or access is not allowed. Limit is maybe reached")
return False
</code></pre>
<p>Please note that I am a beginner so any advice is appreciated.</p>
| 0 | 2016-07-31T18:02:37Z | 38,687,034 | <p>You should <em>never</em> use string interpolation to create SQL commands. Use the parameter substitution that is provided by the SQL connector.</p>
<pre><code> mycursor.execute('INSERT INTO tweets (tweet, lat, lng) VALUES (%s,%s,%s)',
(status.text, status.coordinates['coordinates'][0], status.coordinates['coordinates'][1]))
</code></pre>
| 0 | 2016-07-31T18:15:18Z | [
"python",
"mysql",
"tweepy"
] |
Write multiple Dataframes to same PDF file using matplotlib | 38,686,926 | <p>I'm stuck at a point where I have to write multiple pandas dataframe's to a PDF file.The function accepts dataframe as input.</p>
<p>However, I'm able to write to PDF for the first time but all the subsequent calls are overriding the existing data, leaving with only one dataframe in the PDF by the end.</p>
<p>Please find the python function below :</p>
<pre><code>def fn_print_pdf(df):
pp = PdfPages('Sample.pdf')
total_rows, total_cols = df.shape;
rows_per_page = 30; # Number of rows per page
rows_printed = 0
page_number = 1;
while (total_rows >0):
fig=plt.figure(figsize=(8.5, 11))
plt.gca().axis('off')
matplotlib_tab = pd.tools.plotting.table(plt.gca(),df.iloc[rows_printed:rows_printed+rows_per_page],
loc='upper center', colWidths=[0.15]*total_cols)
#Tabular styling
table_props=matplotlib_tab.properties()
table_cells=table_props['child_artists']
for cell in table_cells:
cell.set_height(0.024)
cell.set_fontsize(12)
# Header,Footer and Page Number
fig.text(4.25/8.5, 10.5/11., "Sample", ha='center', fontsize=12)
fig.text(4.25/8.5, 0.5/11., 'P'+str(page_number), ha='center', fontsize=12)
pp.savefig()
plt.close()
#Update variables
rows_printed += rows_per_page;
total_rows -= rows_per_page;
page_number+=1;
pp.close()
</code></pre>
<p>And I'm calling this function as ::</p>
<pre><code>raw_data = {
'subject_id': ['1', '2', '3', '4', '5'],
'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'],
'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']}
df_a = pd.DataFrame(raw_data, columns=['subject_id', 'first_name', 'last_name'])
fn_print_pdf(df_a)
raw_data = {
'subject_id': ['4', '5', '6', '7', '8'],
'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'],
'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan']}
df_b = pd.DataFrame(raw_data, columns=['subject_id', 'first_name', 'last_name'])
fn_print_pdf(df_b)
</code></pre>
<p>PDF file is available at
<a href="https://drive.google.com/open?id=0B7NgTayxCMOTR28wdjNDbzJFWUk" rel="nofollow">SamplePDF</a>
.As you can see only the data from second dataframe is saved ultimately.Is there a way to append to the same Sample.pdf in the second pass and so on while still preserving the former data?</p>
| 0 | 2016-07-31T18:02:42Z | 38,687,054 | <p>Your PDF's are being overwritten, because you're creating a new PDF document every time you call <code>fn_print_pdf()</code>. You can try keep your <code>PdfPages</code> instance open between function calls, and make a call to <code>pp.close()</code> only after all your plots are written. For reference see <a href="http://stackoverflow.com/a/27419170/3915498">this answer</a>.</p>
<p>Another option is to write the PDF's to a different file, and use pyPDF to merge them, see <a href="http://stackoverflow.com/a/38128675/3915498">this answer</a>.</p>
<p>Edit : Here is some working code for the first approach.</p>
<p>Your function is modified to : </p>
<pre><code>def fn_print_pdf(df,pp):
total_rows, total_cols = df.shape;
rows_per_page = 30; # Number of rows per page
rows_printed = 0
page_number = 1;
while (total_rows >0):
fig=plt.figure(figsize=(8.5, 11))
plt.gca().axis('off')
matplotlib_tab = pd.tools.plotting.table(plt.gca(),df.iloc[rows_printed:rows_printed+rows_per_page],
loc='upper center', colWidths=[0.15]*total_cols)
#Tabular styling
table_props=matplotlib_tab.properties()
table_cells=table_props['child_artists']
for cell in table_cells:
cell.set_height(0.024)
cell.set_fontsize(12)
# Header,Footer and Page Number
fig.text(4.25/8.5, 10.5/11., "Sample", ha='center', fontsize=12)
fig.text(4.25/8.5, 0.5/11., 'P'+str(page_number), ha='center', fontsize=12)
pp.savefig()
plt.close()
#Update variables
rows_printed += rows_per_page;
total_rows -= rows_per_page;
page_number+=1;
</code></pre>
<p>Call your function with:</p>
<pre><code>pp = PdfPages('Sample.pdf')
fn_print_pdf(df_a,pp)
fn_print_pdf(df_b,pp)
pp.close()
</code></pre>
| 1 | 2016-07-31T18:17:50Z | [
"python",
"pdf",
"pandas",
"matplotlib"
] |
Postgresql: migrating local database to the PythonAnywhere database | 38,686,955 | <p>I've followed the Djangogirls tutorial and usually the tutorial calls for you to create a database on <code>pythonanywhere</code>. This usually works without a hitch when using <code>sqlite3</code> however this time I'm using <code>postgresql</code> and I got the below error when I ran the <code>migrate</code> command in the console:</p>
<pre><code>conn = _connect(dsn, connection_factory=connection_factory, async=async)
django.db.utils.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql
</code></pre>
<p>What does this mean exactly?</p>
<p>using <code>python 3.5.1</code>
<code>django 1.9.8</code>
<code>postgresql 9.4</code></p>
<p>Thanks</p>
<p>Ok after reading around some more, this is my problem in a nutshell. </p>
<p>I have postgresql running locally. I then deployed the wbapp onto pythonanywhere. Whilst there I tried to create the database by running migrate which resulted in the above error. </p>
<p>Since then i realised that I had to setup postgresql to run on pythonanywhere. I followed the instructions and did that, but what I don't understand is do I now have to create the database from scratch? And if that is the case what happens to all my tables etc. from my local database?</p>
| 2 | 2016-07-31T18:05:43Z | 38,687,181 | <p>According to their <a href="https://help.pythonanywhere.com/pages/Postgres/" rel="nofollow">help page</a> you need to upgrade to a paid account to be able to use postgres.</p>
| 2 | 2016-07-31T18:32:40Z | [
"python",
"django",
"postgresql",
"pythonanywhere"
] |
Postgresql: migrating local database to the PythonAnywhere database | 38,686,955 | <p>I've followed the Djangogirls tutorial and usually the tutorial calls for you to create a database on <code>pythonanywhere</code>. This usually works without a hitch when using <code>sqlite3</code> however this time I'm using <code>postgresql</code> and I got the below error when I ran the <code>migrate</code> command in the console:</p>
<pre><code>conn = _connect(dsn, connection_factory=connection_factory, async=async)
django.db.utils.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql
</code></pre>
<p>What does this mean exactly?</p>
<p>using <code>python 3.5.1</code>
<code>django 1.9.8</code>
<code>postgresql 9.4</code></p>
<p>Thanks</p>
<p>Ok after reading around some more, this is my problem in a nutshell. </p>
<p>I have postgresql running locally. I then deployed the wbapp onto pythonanywhere. Whilst there I tried to create the database by running migrate which resulted in the above error. </p>
<p>Since then i realised that I had to setup postgresql to run on pythonanywhere. I followed the instructions and did that, but what I don't understand is do I now have to create the database from scratch? And if that is the case what happens to all my tables etc. from my local database?</p>
| 2 | 2016-07-31T18:05:43Z | 38,704,048 | <p>To clarify, you should not be trying to connect to your local postgres. Instead, you should setup postgres on pythonanywhere, and make sure that your django settings.py is pointing the database address and port to the pythonanywhere database. Which is not local to the console/webapp server that you are running your code on. Instead, go to the pythonanywhere database tab and look at the address/port that is given to you.</p>
| 2 | 2016-08-01T16:46:14Z | [
"python",
"django",
"postgresql",
"pythonanywhere"
] |
Python 3 from CMD | 38,687,032 | <p>I am attempting to run this .PY file from Command Prompt:</p>
<pre><code># Merge two .BSG files
# Starting block and world position are taken from the first file
# Example: "bsgmerge input.bsg output.bsg merged.bsg"
import io, sys
one = open(sys.argv[1]).readlines()
two = open(sys.argv[2]).readlines()
for n in [1,3,5,7,9,11,17,19,21,23]:
one[n] = one[n][:-1]+"|"+two[n].partition("|")[2]
open(sys.argv[3],"w").write("".join(one))
</code></pre>
<p>It is a program that takes a creation from the game Beseige and merges it with another saved creation so that opening the merged file results in both creations being present. If you want more details, you can read up on that <a href="https://www.reddit.com/r/Besiege/comments/3spaus/math_is_awesome_a_parametrically_generated_3d/" rel="nofollow">here</a>.</p>
<p>I am having trouble figuring out how to call this program from the command line. At first I thought the problem was me having Python 2 (it requires Python 3), so I uninstalled 2 and installed 3. This did not help.</p>
<p>What I am doing is entering the "python" command to pull up the Python environment within CMD, then entering the command to call the program based on the third comment in the file ("bsgmerge input.bsg output.bsg merged.bsg").</p>
<p>I tried using full file paths or simply changing to the correct directory before typing the "python" command and using only the file names, but so far I've had no luck.</p>
<p>When I am in the correct directory, then enter the Python environment, typing the command "bsgmerge 1.bsg 2.bsg M.bsg" (my existing files to be merged are 1.bsg and 2.bsg), this error occurs:</p>
<pre><code>File "<stdin>", line 1
bsgmerge 1.bsg 2.bsg M.bsg
^
SyntaxError: invalid syntax
</code></pre>
<p>I took a Python course (which is why I used to have Python 2 on my machine) last fall, so I noticed that there is no "def" defining a function in the above code, which is something I've never encountered, so I'm thinking that is the root of my problems.</p>
<p>Thanks in advance for the help.</p>
| -2 | 2016-07-31T18:15:00Z | 38,687,170 | <p>I was probably same problem with python launcher.</p>
<p>If you use Linux, first line shoud be: </p>
<pre><code>#! /path/to/your/python/3
</code></pre>
<p>In Windows it some more complicated: </p>
<p>In registry by <strong>regedit</strong> change
<code>HKEY_CLASSES_ROOT\Python.File\shell\open\command</code> from <code>"C:\Python27\python.exe" "%1" %*</code> to <code>"C:\Windows\py.exe" "%1" %*</code>.</p>
<p>And first line of script shoud be:</p>
<pre><code>#! python3
</code></pre>
<p>Now it shoud work properly.</p>
| 0 | 2016-07-31T18:31:57Z | [
"python",
"python-3.x",
"cmd"
] |
NLTK issue in deriving sql query using fcfg | 38,687,056 | <p>I'm using NLTK to get sql query from english text using feature based cfg. I followed this link <a href="http://www.nltk.org/book/ch10.html" rel="nofollow">http://www.nltk.org/book/ch10.html</a>. I can run the example stated where fcfg is stored in the sql0.fcfg file.</p>
<p>After that I tried to modify it for my own use where I added a following new set of rules:</p>
<pre><code>% start S
## Added by me
S[SEM=(?whadvp + ?sq)] -> WHADVP[SEM=?whadvp] SQ[SEM=?sq]
WHADVP[SEM=(?wrb + ?jj)] -> WRB[SEM=?wrb] JJ[SEM=?jj]
SQ[SEM=(?vbp + ?np + ?vp)] -> VBP[SEM=?vbp] NP[SEM=?np] VP[SEM=?vp]
NP[SEM=(?np + ?pp)] -> NP[SEM=?np] PP[SEM=?pp]
NP[SEM=(?np)] -> JJS[SEM=?jjs]
VP[SEM=(?vbz + ?advp)] -> VBZ[SEM=?vbz] ADVP[SEM=?advp]
PP[SEM=(?in + ?np)] -> IN[SEM=?in] NP[SEM=?np]
NP[SEM=(?prp + ?nn)] -> PRP$[SEM=?prp] NN[SEM=?nn]
ADVP[SEM=(?rb)] -> RB[SEM=?rb]
WRB[SEM='SELECT average(calldurationinsexonds) FROM Task'] -> 'How'
JJ[SEM=''] -> 'long'
VBP[SEM=''] -> 'do'
JJS[SEM=''] -> 'most'
IN[SEM=''] -> 'of'
PRP$[SEM=''] -> 'our'
NN[SEM=''] -> 'phone'
VBZ[SEM=''] -> 'calls'
JJ[SEM=''] -> 'last'
## Default example
S[SEM=(?np + WHERE + ?vp)] -> NP[SEM=?np] VP[SEM=?vp]
VP[SEM=(?v + ?pp)] -> IV[SEM=?v] PP[SEM=?pp]
VP[SEM=(?v + ?ap)] -> IV[SEM=?v] AP[SEM=?ap]
NP[SEM=(?det + ?n)] -> Det[SEM=?det] N[SEM=?n]
PP[SEM=(?p + ?np)] -> P[SEM=?p] NP[SEM=?np]
AP[SEM=?pp] -> A[SEM=?a] PP[SEM=?pp]
NP[SEM='Country="greece"'] -> 'Greece'
NP[SEM='Country="china"'] -> 'China'
Det[SEM='SELECT'] -> 'Which' | 'What'
N[SEM='City FROM city_table'] -> 'cities'
IV[SEM=''] -> 'are'
A[SEM=''] -> 'located'
P[SEM=''] -> 'in'
</code></pre>
<p>After saving the file, when I execute following commands I run into errors</p>
<pre><code>cp = load_parser('grammars/book_grammars/sql0.fcfg')
query = 'How long do most of our phone calls last'
trees = list(cp.parse(query.split()))
</code></pre>
<p>Error:</p>
<blockquote>
<p>Traceback (most recent call last): File "", line 1, in
File "C:\Python27\lib\site-packages\nltk\parse\chart.py",
line 1350, in parse
chart = self.chart_parse(tokens) File "C:\Python27\lib\site-packages\nltk\parse\chart.py", line 1309, in
chart_parse
self._grammar.check_coverage(tokens) File "C:\Python27\lib\site-packages\nltk\grammar.py", line 631, in
check_coverage
"input words: %r." % missing) ValueError: Grammar does not cover some of the input words: u"'How', 'long', 'do', 'most', 'of', 'our',
'phone', 'calls', 'last'".</p>
</blockquote>
<p>I don't know if there is a mistake in my added grammar or some other issue. Any help or suggestion would be great.</p>
| 0 | 2016-07-31T18:18:10Z | 38,713,635 | <p>The issue was that I was modifying the \grammars\book_grammars\sql0.fcfg. When I saved it as separate file and loaded grammar from there, the problem got solved.</p>
<p>Don't know why it happened, but it resolved the issue.</p>
| 0 | 2016-08-02T06:55:29Z | [
"python",
"parsing",
"nlp",
"nltk",
"information-extraction"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.