title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
using newaxis in Python | 39,157,426 | <pre><code>A = np.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10,11,12]])
B = A[:, np.newaxis]
print(B)
print(B.shape)
</code></pre>
<p>the output is</p>
<pre><code>[[[ 1 2 3]]
[[ 4 5 6]]
[[ 7 8 9]]
[[10 11 12]]]
(4L, 1L, 3L)
</code></pre>
<p>I have two questions:</p>
<ol>
<li>Why are there extra brackets outside brackets, for example, <code>[[ 1 2 3]]</code>, so why it is not <code>[ 1 2 3]</code>? </li>
<li>what does <code>1L</code> mean? It looks like to me that <code>B</code> is a 4X3 matrix, so why is it not <code>(4L, 3L)</code>?</li>
</ol>
| 0 | 2016-08-26T02:22:59Z | 39,157,603 | <p>The "extra" bracket and the 1L are there for the same reason: your use of <code>np.newaxis</code> inserted a new dimension of extent 1 into the array shapeâin other words, you transformed a two-dimensional 4x3 array into a three-dimensional 4x1x3 array. </p>
<p>Each of the 4 "rows" of <code>B</code>contains a two-dimensional 1x3 array, such as</p>
<pre><code>[[4,5,6]]
</code></pre>
<p>whereas each corresponding row of <code>A</code> was just a one-dimensional array of length 3:</p>
<pre><code>[4,5,6]
</code></pre>
<p>Hence the extra brackets. </p>
| 0 | 2016-08-26T02:49:24Z | [
"python",
"arrays",
"numpy",
"matrix"
] |
How to set empty value to DateField in django model? | 39,157,455 | <p>What am I doing wrong here? I need to set empty value to doing_field. </p>
<pre><code>def delete_todo_today(request):
if request.is_ajax() and request.POST and request.user.is_authenticated:
thingtodo = ThingToDo.objects.filter(author = request.user, thing = request.POST.get('item'))
thingtodo.doing_date = None
thingtodo.save()
data = {'message': "%s 's doing_date deleted" % request.POST.get('item')}
return HttpResponse(json.dumps(data), content_type='application/json')
else:
raise Http404
</code></pre>
| 0 | 2016-08-26T02:27:36Z | 39,157,721 | <p>by default <code>models.DateField.empty_strings_allowed</code> is set to <code>False</code>,
<a href="https://docs.djangoproject.com/en/1.10/_modules/django/db/models/fields/#DateField" rel="nofollow">https://docs.djangoproject.com/en/1.10/_modules/django/db/models/fields/#DateField</a></p>
<p>try defining <code>ThingToDo.doing_date</code> with <code>options['blank'] = True</code> something like <code>doing_date = models.DateField(**options)</code></p>
| 0 | 2016-08-26T03:06:44Z | [
"python",
"django"
] |
How to set empty value to DateField in django model? | 39,157,455 | <p>What am I doing wrong here? I need to set empty value to doing_field. </p>
<pre><code>def delete_todo_today(request):
if request.is_ajax() and request.POST and request.user.is_authenticated:
thingtodo = ThingToDo.objects.filter(author = request.user, thing = request.POST.get('item'))
thingtodo.doing_date = None
thingtodo.save()
data = {'message': "%s 's doing_date deleted" % request.POST.get('item')}
return HttpResponse(json.dumps(data), content_type='application/json')
else:
raise Http404
</code></pre>
| 0 | 2016-08-26T02:27:36Z | 39,157,795 | <p>You are using <code>.filter()</code> to get the objects for <code>thingtodo</code>. This will return a QuerySet or simply said a list of objects. You can not set an attribute on multiple objects directly. </p>
<p>If you wat to retrieve one object only, use <code>get()</code> instead of <code>.filter()</code>. This will raise an exception when there it more or less than one object matching.</p>
<p>If you want to update multiple objects, use the <code>update()</code> method of the QuerySet:</p>
<pre><code>thingtodo.update(doing_date=None)
</code></pre>
<p>Also make use that you model allows <code>Null</code> for the attribute.</p>
| 2 | 2016-08-26T03:17:40Z | [
"python",
"django"
] |
Simplest example for streaming audio with Alexa | 39,157,599 | <p>I'm trying to get the new streaming audio API going. Is the following response valid? I'm getting a "there was a problem with the skill" error when I test it on my device. </p>
<p>Here is the code for my AWS-lambda function:</p>
<pre><code>def lambda_handler(event, context):
return {
"response": {
"directives": [
{
"type": "AudioPlayer.Play",
"playBehavior": "REPLACE_ALL",
"audioItem": {
"stream": {
"token": "12345",
"url": "http://emit-media-production.s3.amazonaws.com/pbs/the-afterglow/2016/08/24/1700/201608241700_the-afterglow_64.m4a",
"offsetInMilliseconds": 0
}
}
}
],
"shouldEndSession": True
}
}
</code></pre>
| 7 | 2016-08-26T02:49:19Z | 39,283,692 | <p>The following code worked for me:</p>
<pre><code>def lambda_handler(event, context):
return {
"response": {
"directives": [
{
"type": "AudioPlayer.Play",
"playBehavior": "REPLACE_ALL",
"audioItem": {
"stream": {
"token": "12345",
"url": "https://emit-media-production.s3.amazonaws.com/pbs/the-afterglow/2016/08/24/1700/201608241700_the-afterglow_64.m4a",
"offsetInMilliseconds": 0
}
}
}
],
"shouldEndSession": True
}
}
]
</code></pre>
<p>The only difference is that the URL is https rather than http.</p>
<p>Don't be put off if it doesn't work in the skill simulator. That hasn't been upgraded yet to work with streaming audio. You won't even see your directives there. But it should work when used with your device.</p>
| 7 | 2016-09-02T03:03:11Z | [
"python",
"aws-lambda",
"alexa-skills-kit"
] |
Sorting based on max length and max sum | 39,157,890 | <p>Can you please help me figure this out</p>
<pre><code>q = [[12, 13, 14], [8, 9, 10,11], [2, 3, 4], [5, 6, 7]]
</code></pre>
<p>suppose I've a list like q, How do I sort the based on </p>
<ol>
<li>Max length of sublists and </li>
<li>Max sum of the sublists</li>
</ol>
<p>The output should be:</p>
<pre><code>q = [[8,9,10,11],[12,13,14][5,6,7],[1,2,3]]
</code></pre>
| 1 | 2016-08-26T03:31:21Z | 39,157,907 | <p>Supply your criteria in a lambda function for the <code>key</code>:</p>
<pre><code>sorted(q, key=lambda sub: (len(sub), sum(sub)), reverse=True)
>>> [[8, 9, 10, 11], [12, 13, 14], [5, 6, 7], [2, 3, 4]]
</code></pre>
<p>The <code>lambda</code> function will take every sub-list <code>x</code> and sort it based on it's <code>len</code>, in cases where the result of <code>len</code> is not sufficient in making a decision, the <code>sum</code> of their contents is used to break the tie.</p>
| 5 | 2016-08-26T03:34:27Z | [
"python",
"list",
"sorting"
] |
Sorting based on max length and max sum | 39,157,890 | <p>Can you please help me figure this out</p>
<pre><code>q = [[12, 13, 14], [8, 9, 10,11], [2, 3, 4], [5, 6, 7]]
</code></pre>
<p>suppose I've a list like q, How do I sort the based on </p>
<ol>
<li>Max length of sublists and </li>
<li>Max sum of the sublists</li>
</ol>
<p>The output should be:</p>
<pre><code>q = [[8,9,10,11],[12,13,14][5,6,7],[1,2,3]]
</code></pre>
| 1 | 2016-08-26T03:31:21Z | 39,157,940 | <p>Try:</p>
<pre><code>sorted(q, lambda a,b: len(b)-len(a) or sum(b)-sum(a))
</code></pre>
| 3 | 2016-08-26T03:39:50Z | [
"python",
"list",
"sorting"
] |
Python retrieving value from URL | 39,157,895 | <p>I'm trying to write a python script that checks money.rediff.com for a particular stock price and prints it. I know that this can be done easily with their API, but I want to learn how urllib2 works, so I'm trying to do this the old fashioned way. But, I'm stuck on how to use the urllib. Many tutorials online asked me to the "Inspect element" of the value I need to return and split the string to get it. But, all the examples in the videos have the values with easily to split HTML Tags, but mine has it in something like this:</p>
<pre><code><div class="f16">
<span id="ltpid" class="bold" style="color: rgb(0, 0, 0); background: rgb(255, 255, 255);">6.66</span> &nbsp;
<span id="change" class="green">+0.50</span> &nbsp;
<span id="ChangePercent" style="color: rgb(130, 130, 130); font-weight: normal;">+8.12%</span>
</div>
</code></pre>
<p>I only need the "6.66" in Line2 out. How do I go about doing this? I'm very very new to Urllib2 and Python. All help will be greatly appreciated. Thanks in advance.</p>
| 5 | 2016-08-26T03:32:27Z | 39,157,965 | <p>You can certainly do this with just <code>urllib2</code> and perhaps a regular expression, but I'd encourage you to use better tools, namely <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code></a> and <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>Beautiful Soup</code></a>.</p>
<p>Here's a complete program to fetch a quote for "Tata Motors Ltd.":</p>
<pre><code>from bs4 import BeautifulSoup
import requests
html = requests.get('http://money.rediff.com/companies/Tata-Motors-Ltd/10510008').content
soup = BeautifulSoup(html, 'html.parser')
quote = float(soup.find(id='ltpid').get_text())
print(quote)
</code></pre>
<p><strong>EDIT</strong></p>
<p>Here's a Python 2 version just using <code>urllib2</code> and <code>re</code>:</p>
<pre><code>import re
import urllib2
html = urllib2.urlopen('http://money.rediff.com/companies/Tata-Motors-Ltd/10510008').read()
quote = float(re.search('<span id="ltpid"[^>]*>([^<]*)', html).group(1))
print quote
</code></pre>
| 2 | 2016-08-26T03:43:28Z | [
"python",
"html",
"urllib2"
] |
Python retrieving value from URL | 39,157,895 | <p>I'm trying to write a python script that checks money.rediff.com for a particular stock price and prints it. I know that this can be done easily with their API, but I want to learn how urllib2 works, so I'm trying to do this the old fashioned way. But, I'm stuck on how to use the urllib. Many tutorials online asked me to the "Inspect element" of the value I need to return and split the string to get it. But, all the examples in the videos have the values with easily to split HTML Tags, but mine has it in something like this:</p>
<pre><code><div class="f16">
<span id="ltpid" class="bold" style="color: rgb(0, 0, 0); background: rgb(255, 255, 255);">6.66</span> &nbsp;
<span id="change" class="green">+0.50</span> &nbsp;
<span id="ChangePercent" style="color: rgb(130, 130, 130); font-weight: normal;">+8.12%</span>
</div>
</code></pre>
<p>I only need the "6.66" in Line2 out. How do I go about doing this? I'm very very new to Urllib2 and Python. All help will be greatly appreciated. Thanks in advance.</p>
| 5 | 2016-08-26T03:32:27Z | 39,157,966 | <p>BeautifulSoup is good for html parsing</p>
<pre><code>from bs4 import BeautifulSoup
##Use your urllib code to get the source code of the page
source = (Your get code here)
soup = BeautifulSoup(source)
##This assumes the id 'ltpid' is the one you are looking for all the time
span = soup.find('span', id="ltpid")
float(span.text) #will return 6.66
</code></pre>
| 1 | 2016-08-26T03:44:10Z | [
"python",
"html",
"urllib2"
] |
Python retrieving value from URL | 39,157,895 | <p>I'm trying to write a python script that checks money.rediff.com for a particular stock price and prints it. I know that this can be done easily with their API, but I want to learn how urllib2 works, so I'm trying to do this the old fashioned way. But, I'm stuck on how to use the urllib. Many tutorials online asked me to the "Inspect element" of the value I need to return and split the string to get it. But, all the examples in the videos have the values with easily to split HTML Tags, but mine has it in something like this:</p>
<pre><code><div class="f16">
<span id="ltpid" class="bold" style="color: rgb(0, 0, 0); background: rgb(255, 255, 255);">6.66</span> &nbsp;
<span id="change" class="green">+0.50</span> &nbsp;
<span id="ChangePercent" style="color: rgb(130, 130, 130); font-weight: normal;">+8.12%</span>
</div>
</code></pre>
<p>I only need the "6.66" in Line2 out. How do I go about doing this? I'm very very new to Urllib2 and Python. All help will be greatly appreciated. Thanks in advance.</p>
| 5 | 2016-08-26T03:32:27Z | 39,196,267 | <p>Use BeautifulSoup instead of regex to parse HTML. </p>
| 1 | 2016-08-28T22:11:27Z | [
"python",
"html",
"urllib2"
] |
Install pyhdf error: hdf.h: No such file or directory | 39,157,914 | <p>I want to install <code>pyhdf</code> to read hdf4 files in python on ubuntu, and I downloaded from <a href="https://sourceforge.net/projects/pysclint/files/pyhdf/" rel="nofollow">https://sourceforge.net/projects/pysclint/files/pyhdf/</a>,<code>pyhdf-0.8.3.tar.gz</code>, but when I run <code>python setup.py install</code> on ubuntu, it shows </p>
<pre><code>running install
running bdist_egg
running egg_info
running build_src
build_src
building extension "pyhdf._hdfext" sources
build_src: building npy-pkg config files
writing pyhdf.egg-info/PKG-INFO
writing top-level names to pyhdf.egg-info/top_level.txt
writing dependency_links to pyhdf.egg-info/dependency_links.txt
reading manifest file 'pyhdf.egg-info/SOURCES.txt'
writing manifest file 'pyhdf.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
running build_ext
customize UnixCCompiler
customize UnixCCompiler using build_ext
building 'pyhdf._hdfext' extension
compiling C sources
C compiler: x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC
compile options: '-I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c'
x86_64-linux-gnu-gcc: pyhdf/hdfext_wrap.c
pyhdf/hdfext_wrap.c: In function âSWIG_Python_AddErrorMsgâ:
pyhdf/hdfext_wrap.c:859:5: error: format not a string literal and no format arguments [-Werror=format-security]
PyErr_Format(PyExc_RuntimeError, mesg);
^
pyhdf/hdfext_wrap.c: At top level:
pyhdf/hdfext_wrap.c:3048:17: fatal error: hdf.h: No such file or directory
cc1: some warnings being treated as errors
compilation terminated.
pyhdf/hdfext_wrap.c: In function âSWIG_Python_AddErrorMsgâ:
pyhdf/hdfext_wrap.c:859:5: error: format not a string literal and no format arguments [-Werror=format-security]
PyErr_Format(PyExc_RuntimeError, mesg);
^
pyhdf/hdfext_wrap.c: At top level:
pyhdf/hdfext_wrap.c:3048:17: fatal error: hdf.h: No such file or directory
cc1: some warnings being treated as errors
compilation terminated.
error: Command "x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c pyhdf/hdfext_wrap.c -o build/temp.linux-x86_64-2.7/pyhdf/hdfext_wrap.o" failed with exit status 1
</code></pre>
<p>How to fix it?</p>
| 0 | 2016-08-26T03:35:17Z | 39,200,807 | <p>Well finally I am answering my own question now...For people who want to install python-hdf4 on ubuntu.</p>
<p>Firstly you need to install the hdf4 and then the python-hdf4.</p>
<p>Hdf4 could be downloaded from <a href="https://www.hdfgroup.org/products/hdf4/" rel="nofollow">https://www.hdfgroup.org/products/hdf4/</a>, and then <code>unzip</code> the file using <code>tar xvf ...</code>, <code>cd</code> to the file and <code>/.configure</code>, if you do not need fortran then do <code>./configure --disable-fortran</code>, and it shoule be configured, and then <code>make</code>, <code>make check</code>, <code>make install</code> step by step, HDF4 should be installed succesfully.</p>
<p>And the next thing is simple, download python-hdf4 from <a href="https://pypi.python.org/pypi/python-hdf4" rel="nofollow">https://pypi.python.org/pypi/python-hdf4</a> and then cd to the file, <code>python setup.py install</code>, done!</p>
| 0 | 2016-08-29T07:34:38Z | [
"python",
"pyhdf"
] |
confused about random_state in decision tree of scikit learn | 39,158,003 | <p>Confused about <code>random_state</code> parameter, not sure why decision tree training needs some randomness. My thoughts, (1) is it related to random forest? (2) is it related to split training testing data set? If so, why not use training testing split method directly (<a href="http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.train_test_split.html</a>)?</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html</a></p>
<pre><code>>>> from sklearn.datasets import load_iris
>>> from sklearn.cross_validation import cross_val_score
>>> from sklearn.tree import DecisionTreeClassifier
>>> clf = DecisionTreeClassifier(random_state=0)
>>> iris = load_iris()
>>> cross_val_score(clf, iris.data, iris.target, cv=10)
...
...
array([ 1. , 0.93..., 0.86..., 0.93..., 0.93...,
0.93..., 0.93..., 1. , 0.93..., 1. ])
</code></pre>
<p>regards,
Lin</p>
| 1 | 2016-08-26T03:48:43Z | 39,158,831 | <p>This is explained in <a href="http://scikit-learn.org/stable/modules/tree.html#tree" rel="nofollow">the documentation</a></p>
<blockquote>
<p>The problem of learning an optimal decision tree is known to be NP-complete under several aspects of optimality and even for simple concepts. Consequently, practical decision-tree learning algorithms are based on heuristic algorithms such as the greedy algorithm where locally optimal decisions are made at each node. Such algorithms cannot guarantee to return the globally optimal decision tree. This can be mitigated by training multiple trees in an ensemble learner, where the features and samples are randomly sampled with replacement.</p>
</blockquote>
<p>So, basically, a sub-optimal greedy algorithm is repeated a number of times using random selections of features and samples (a similar technique used in random forests). The <code>random_state</code> parameter allows controlling these random choices.</p>
<p>The <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html" rel="nofollow">interface documentation</a> specifically states:</p>
<blockquote>
<p>If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random.</p>
</blockquote>
<p>So, the random algorithm will be used in any case. Passing any value (whether a specific int, e.g., 0, or a <code>RandomState</code> instance), will not change that. The only rationale for passing in an int value (0 or otherwise) is to make the outcome consistent across calls: if you call this with <code>random_state=0</code> (or any other value), then each and every time, you'll get the same result.</p>
| 1 | 2016-08-26T05:26:06Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"decision-tree"
] |
How to add corresponding elements of 2 multidimensional matrices in python? | 39,158,062 | <p>I have 2 multidimensional arrays , both of size 128X640X5. 5 is the number of channels for the matrices. I wish to add the respective channel values of both the matrices for every point in the matrices. For eg if we have A and B as 2 matrices, I wish to do an operation something like this:
A(x,y,0)+B(x,y,0) =A(x,y,0). This should add the 0th channel values of points x and y in both A and B and then store it back in A. Similiary I wish to do it for other 4 channels also. Any idea on how to do this in python? I am using numpy array of python and basically working on image manipulation problem.</p>
| 0 | 2016-08-26T03:58:26Z | 39,158,367 | <p>In order to add each corresponding point of a <code>ndarray</code> in numpy you can use numpy's add function (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html" rel="nofollow">numpy.add</a>).</p>
<p>It will add up each corresponding point of two ndarrays which have the <strong>same</strong> shape. If the arrays do not have the same shape, it will <code>broadcast</code> (change their shape) so that they can be added together.</p>
<p>In your case, you would simply write:</p>
<pre><code>import numpy as np
C = np.add(A, B)
</code></pre>
<p><strong>Source:</strong><br>
<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html</a></p>
| 0 | 2016-08-26T04:35:24Z | [
"python",
"numpy",
"image-processing"
] |
Python eve - POST a list media files with curl command failed with 422 error | 39,158,068 | <p>I use python-eve to build my RESTful API, I set a endpoint 'risks' in settings.py, like so:</p>
<pre><code>risks = {
'schema': {
'description': {
'type': 'string',
'required': True,
},
'pic': {
'type': 'list',
'schema': {
'type': 'media',
}
},
}
}
</code></pre>
<p>I try curl command to POST two jpg files to 'pic' field like so:</p>
<pre><code>curl -F "description=something" -F "pic=@test1.jpg,test2.jpg" http://127.0.0.1:8080/risks
</code></pre>
<p>but get 422 error like this:</p>
<pre><code>{"_status": "ERR", "_issues": {"pic": "must be of list type"}, "_error": {"message": "Insertion failure: 1 document(s) contain(s) error(s)", "code": 422}}%
</code></pre>
<p>what can I do, I tried just one media(not list type),It's no problem,why?
Can someone help me?</p>
| 0 | 2016-08-26T03:58:52Z | 39,218,316 | <p>When you access the <code>risks</code> endpoint you need to supply the right datatypes in order for the resource endpoint to work. It complains about the pic you send because that is still a string and not a list.</p>
<p>You can make your life a bit easier by using <code>requests</code></p>
<pre><code>import requests
url = 'http://127.0.0.1:8080/risks'
data = {description : 'something', 'pic' : ['a','b','c','d']}
r = requests.post(url, json=data)
</code></pre>
| 0 | 2016-08-30T03:25:13Z | [
"python",
"list",
"curl",
"media",
"eve"
] |
Python eve - POST a list media files with curl command failed with 422 error | 39,158,068 | <p>I use python-eve to build my RESTful API, I set a endpoint 'risks' in settings.py, like so:</p>
<pre><code>risks = {
'schema': {
'description': {
'type': 'string',
'required': True,
},
'pic': {
'type': 'list',
'schema': {
'type': 'media',
}
},
}
}
</code></pre>
<p>I try curl command to POST two jpg files to 'pic' field like so:</p>
<pre><code>curl -F "description=something" -F "pic=@test1.jpg,test2.jpg" http://127.0.0.1:8080/risks
</code></pre>
<p>but get 422 error like this:</p>
<pre><code>{"_status": "ERR", "_issues": {"pic": "must be of list type"}, "_error": {"message": "Insertion failure: 1 document(s) contain(s) error(s)", "code": 422}}%
</code></pre>
<p>what can I do, I tried just one media(not list type),It's no problem,why?
Can someone help me?</p>
| 0 | 2016-08-26T03:58:52Z | 39,518,331 | <blockquote>
<p>@Mike Tung</p>
<p>...</p>
<p>You can make your life a bit easier by using requests</p>
<p>...</p>
</blockquote>
<p><strong>How do you pass files to the requests <code>json</code> kwarg ? As file handles ? Or Strings ?</strong></p>
<p>When I try this,</p>
<pre><code>import requests
url = 'http://localhost:5000/tests'
data = {
'icons': [
open('/home/test/git-projects/test.com/backend/fixtures/media/test1.jpg').read(), # If I pass the handle, it fails as well.
open('/home/test/git-projects/test.com/backend/fixtures/media/test2.jpg').read()
]
}
r = requests.post(url, json=data)
/home/test/venvs/test/bin/python2.7 /home/test/git-projects/test.com/backend/__main__.py
/home/test/venvs/test/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.pymongo is deprecated, use flask_pymongo instead.
.format(x=modname), ExtDeprecationWarning
/home/test/venvs/test/local/lib/python2.7/site-packages/flask/exthook.py:71: ExtDeprecationWarning: Importing flask.ext.sentinel is deprecated, use flask_sentinel instead.
.format(x=modname), ExtDeprecationWarning
Traceback (most recent call last):
File "/home/test/git-projects/test.com/backend/__main__.py", line 43, in <module>
r = requests.post(url, json=data)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/requests/api.py", line 109, in post
return request('post', url, data=data, json=json, **kwargs)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/requests/api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/requests/sessions.py", line 451, in request
prep = self.prepare_request(req)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/requests/sessions.py", line 382, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "/home/test/venvs/test/local/lib/python2.7/site-packages/requests/models.py", line 307, in prepare
self.prepare_body(data, files, json)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/requests/models.py", line 428, in prepare_body
body = json_dumps(json)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/simplejson/__init__.py", line 380, in dumps
return _default_encoder.encode(obj)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/simplejson/encoder.py", line 275, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/test/venvs/test/local/lib/python2.7/site-packages/simplejson/encoder.py", line 357, in iterencode
return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte
Process finished with exit code 1
</code></pre>
| 0 | 2016-09-15T18:48:52Z | [
"python",
"list",
"curl",
"media",
"eve"
] |
Select dropdown in AngularJS application from Python Selenium | 39,158,148 | <p>I wanted to test page in <code>Python</code> <code>Selenium</code>, which uses <code>AngularJS</code>. It contains a select option and I have tried a number of options to select it but it fails.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="xtzpp001" ng-model="..." ng-options="...." ng-change="changeView()">
<option value class>select</option>
<option value="200" selected="selected">Student 1</option>
<option value="201">Student 2</option>
<option value="202">Student 3</option>
</select></code></pre>
</div>
</div>
</p>
<p>As I said, I tried---</p>
<pre><code>driver.find_element_by_xpath('//select[@id="xtzpp001"]/option[contains(text(), "Student 2")]').click()
</code></pre>
<p>then</p>
<pre><code>from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('xtzpp001'))
for i in select.options:
.......etc etc
</code></pre>
<p>I used explicit waits also.</p>
<p>I came to know that pytractor can help me in this situation (not being actively developed though), but I am unable to find any documentation regarding select option using pytractor.</p>
<p>Is there any other way to achieve this?? or pytractor equivalent? </p>
<p>Or can I use protractor(or any javascript framework) to continue in testing in <code>Javascript</code> from this stage and integrate/callback the results in <code>Python</code>??</p>
| 0 | 2016-08-26T04:09:18Z | 39,158,523 | <p>Use the Select class from selenium.webdriver.support.ui. Pass the select webelement to the constructor. Use selectByVisibleText. Refer to the answer by @alecxe in the post - <a href="http://stackoverflow.com/questions/7867537/selenium-python-drop-down-menu-option-value">Selenium - Python - drop-down menu option value</a></p>
| 0 | 2016-08-26T04:56:47Z | [
"python",
"selenium",
"protractor"
] |
Select dropdown in AngularJS application from Python Selenium | 39,158,148 | <p>I wanted to test page in <code>Python</code> <code>Selenium</code>, which uses <code>AngularJS</code>. It contains a select option and I have tried a number of options to select it but it fails.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="xtzpp001" ng-model="..." ng-options="...." ng-change="changeView()">
<option value class>select</option>
<option value="200" selected="selected">Student 1</option>
<option value="201">Student 2</option>
<option value="202">Student 3</option>
</select></code></pre>
</div>
</div>
</p>
<p>As I said, I tried---</p>
<pre><code>driver.find_element_by_xpath('//select[@id="xtzpp001"]/option[contains(text(), "Student 2")]').click()
</code></pre>
<p>then</p>
<pre><code>from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('xtzpp001'))
for i in select.options:
.......etc etc
</code></pre>
<p>I used explicit waits also.</p>
<p>I came to know that pytractor can help me in this situation (not being actively developed though), but I am unable to find any documentation regarding select option using pytractor.</p>
<p>Is there any other way to achieve this?? or pytractor equivalent? </p>
<p>Or can I use protractor(or any javascript framework) to continue in testing in <code>Javascript</code> from this stage and integrate/callback the results in <code>Python</code>??</p>
| 0 | 2016-08-26T04:09:18Z | 39,179,288 | <p>If you have tried all the possible attempt but never got success, you should try using <code>execute_script()</code> as below :-</p>
<pre><code>element = driver.find_element_by_id("xtzpp001")
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", element, "Student 2");
</code></pre>
| 0 | 2016-08-27T08:54:58Z | [
"python",
"selenium",
"protractor"
] |
Select dropdown in AngularJS application from Python Selenium | 39,158,148 | <p>I wanted to test page in <code>Python</code> <code>Selenium</code>, which uses <code>AngularJS</code>. It contains a select option and I have tried a number of options to select it but it fails.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="xtzpp001" ng-model="..." ng-options="...." ng-change="changeView()">
<option value class>select</option>
<option value="200" selected="selected">Student 1</option>
<option value="201">Student 2</option>
<option value="202">Student 3</option>
</select></code></pre>
</div>
</div>
</p>
<p>As I said, I tried---</p>
<pre><code>driver.find_element_by_xpath('//select[@id="xtzpp001"]/option[contains(text(), "Student 2")]').click()
</code></pre>
<p>then</p>
<pre><code>from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('xtzpp001'))
for i in select.options:
.......etc etc
</code></pre>
<p>I used explicit waits also.</p>
<p>I came to know that pytractor can help me in this situation (not being actively developed though), but I am unable to find any documentation regarding select option using pytractor.</p>
<p>Is there any other way to achieve this?? or pytractor equivalent? </p>
<p>Or can I use protractor(or any javascript framework) to continue in testing in <code>Javascript</code> from this stage and integrate/callback the results in <code>Python</code>??</p>
| 0 | 2016-08-26T04:09:18Z | 39,193,018 | <p>you can also use Actions to click the menu item, here is an example:</p>
<pre><code>menu = driver.find_element_by_css_selector(".nav")
hidden_submenu = driver.find_element_by_css_selector(".nav #submenu1")
ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()
</code></pre>
| 0 | 2016-08-28T15:46:49Z | [
"python",
"selenium",
"protractor"
] |
GraphLab Create Launcher installation error | 39,158,156 | <p>Why problem creating the "gl-env" ?
I have tried reinstalling it also... but nothing help me out. </p>
<pre><code>CIO_TEST: <not set>
CONDA_DEFAULT_ENV: <not set>
CONDA_ENVS_PATH: <not set>
PATH: C:\Users\Himanshu\Anaconda2\Library\bin;C:\Users\Himanshu\Anaconda2;C:\Users\Himanshu\Anaconda2\Scripts;C:\Users\Himanshu\Anaconda2;C:\Users\Himanshu\Anaconda2\Scripts;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd;C:\Program Files (x86)\GtkSharp\2.12\bin;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Users\Himanshu\AppData\Local\Programs\Python\Python35-32\Scripts\;C:\Users\Himanshu\AppData\Local\Programs\Python\Python35-32\;C:\Program Files\Java\jdk1.8.0_91\bin;C:\Users\Himanshu\AppData\Local\Microsoft\WindowsApps;
PYTHONHOME: <not set>
PYTHONPATH: <not set>
WARNING: could not import _license.show_info
# try:
# $ conda install -n root _license
===================
There was a problem creating the "gl-env" conda environment. Restart GraphLab Create Launcher.
Process completed with exit code -1
</code></pre>
| 4 | 2016-08-26T04:10:58Z | 39,297,359 | <p>Having the same problem. Read elsewhere it is because the PATH variable is too long. I deleted everything possible from the PATH variable and that is not the solution.</p>
| 0 | 2016-09-02T16:52:21Z | [
"python",
"windows",
"git",
"anaconda",
"graphlab"
] |
Exception: Acess Violation in client C# | 39,158,157 | <p>I am trying to learn C# through trials and errors. I have a server in Python, and the client in C#.</p>
<p>The client is supposed to get data from the server, save it to disk ((which it doesn't)), then continue using that data to communicate until the user decides to exit it.</p>
<p>Unfortunately, it has been raising an Exception Access Violation for quite some time, and provides no helpful information as to why.</p>
<p>Code: </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Scripting.Hosting;
using System.Threading;
using Rage;
using System.Net.Sockets;
using System.IO;
[assembly: Rage.Attributes.Plugin("LSPDFROnlineClient", Description = "LSPDFR Online Client. Used to connect to LSPDFR Online.", Author = "Thecheater887")]
namespace LSPDFROnlineClient
{
public class EntryPoint
{
private static int IsDead;
public static void Main()
{
IsDead = 0;
Thread mt = new Thread(new ThreadStart(Run));
mt.Start();
while (true)
{
if (IsDead == 1)
{
break;
}
GameFiber.Yield();
}
return;
}
public static void Run()
{
File.WriteAllText("C:/ProgramData/dbg.log","1");
try
{
Byte[] header;
Byte[] packet;
Byte[] data;
Byte[] kad;
Byte[] td;
int paylen;
String rd;
String nd;
String msgid;
File.WriteAllText("C:/ProgramData/dbg.log", "2");
TcpClient connector = new TcpClient();
connector.Connect("127.0.0.1", 5773);
NetworkStream conn = connector.GetStream();
try {
File.WriteAllText("C:/ProgramData/dbg.log", "3");
FileStream savedat = File.OpenRead("C:/Users/Public/Documents/save.dat");
BinaryReader savdat = new BinaryReader(savedat);
nd = savdat.ReadString();
savdat.Close();
if (nd.Length == 16)
{
} else {
File.WriteAllText("C:/ProgramData/save.dat", "user000000000000");
nd = "user000000000000";
}
}
catch
{
File.WriteAllText("C:/ProgramData/save.dat", "user000000000000");
nd = "user000000000000";
}
File.WriteAllText("C:/ProgramData/dbg.log", "4");
data = new Byte[26];
data = Encoding.ASCII.GetBytes("clogr00000" + nd);
conn.Write(data, 0, data.Length);
while (true)
{
try
{
// Get header of packet
header = new Byte[26];
Int32 rcvhead = conn.Read(header, 0, header.Length);
String hd = Encoding.ASCII.GetString(header, 0, rcvhead);
//Deal with it 8-)
msgid = hd.Substring(0, 5);
paylen = Convert.ToInt32(hd.Substring(5, 5));
string servkey = hd.Substring(10, 16);
}
catch
{
continue;
}
File.WriteAllText("C:/ProgramData/dbg.log", "5");
try
{
//Receive packet data
if (paylen > 0)
{
packet = new Byte[paylen];
Int32 newdata = conn.Read(packet, 0, packet.Length);
rd = Encoding.ASCII.GetString(packet, 0, newdata);
}
else
{
rd = null;
}
File.WriteAllText("C:/ProgramData/dbg.log", "6");
if (msgid == "ConOK")
{
File.WriteAllText("C:/ProgramData/dbg.log", "7");
string userid = rd.Substring(0, 16);
Game.DisplayHelp(rd.Substring(16, (rd.Length - 16)));
File.WriteAllText("C:/ProgramData/save.dat", userid);
File.WriteAllText("C:/ProgramData/dbg.log", "8");
}
else if (msgid == "savdt")
{
File.WriteAllText("C:/ProgramData/dbg.log", "9");
string[] tnd = rd.Split(',');
var nud = new List<string>();
nud.Add("Player1");
nud.AddRange(tnd);
File.WriteAllText("C:/ProgramData/dbg.log", "A");
string name = nud[0];
string streetname = nud[1];
int money = Convert.ToInt32(nud[2]);
int bounty = Convert.ToInt32(nud[3]);
int playerrep = Convert.ToInt32(nud[4]);
File.WriteAllText("C:/ProgramData/dbg.log", "B");
int rep = Convert.ToInt32(nud[5]);
string pclass = nud[6];
bool canbecop = Convert.ToBoolean(nud[7]);
int rank = Convert.ToInt32(nud[8]);
int stars = Convert.ToInt32(nud[9]);
int cites = Convert.ToInt32(nud[10]);
File.WriteAllText("C:/ProgramData/dbg.log", "C");
int citesgiven = Convert.ToInt32(nud[11]);
int citesdismissed = Convert.ToInt32(nud[12]);
int arrestsmade = Convert.ToInt32(nud[13]);
int arrested = Convert.ToInt32(nud[14]);
int convictionsmade = Convert.ToInt32(nud[15]);
int convitced = Convert.ToInt32(nud[16]);
string warrant = nud[17];
File.WriteAllText("C:/ProgramData/dbg.log", "D");
int prisontimeremaining = Convert.ToInt32(nud[18]);
int copskilled = Convert.ToInt32(nud[19]);
int crimskilled = Convert.ToInt32(nud[20]);
int civskilled = Convert.ToInt32(nud[21]);
int bountyclaimed = Convert.ToInt32(nud[22]);
int overflowprep = Convert.ToInt32(nud[23]);
string title = nud[24];
bool banned = Convert.ToBoolean(nud[25]);
bool vip = Convert.ToBoolean(nud[26]);
int viprank = Convert.ToInt32(nud[27]);
File.WriteAllText("C:/ProgramData/dbg.log", "E");
var v3 = new Vector3();
float posx = Convert.ToSingle(nud[29]);
float posy = Convert.ToSingle(nud[30]);
float posz = Convert.ToSingle(nud[31]);
v3.X = posx;
v3.Y = posy;
v3.Z = posz;
File.WriteAllText("C:/ProgramData/dbg.log", "EE");
int rot = Convert.ToInt32(nud[32]);
File.WriteAllText("C:/ProgramData/dbg.log", "FF");
World.TeleportLocalPlayer(v3, false);
File.WriteAllText("C:/ProgramData/dbg.log", "F");
string custommessage = nud[28];
if (custommessage == "null")
{
} else {
Game.DisplayNotification(custommessage);
}
}
else if (msgid == "isalv")
{
kad = new Byte[26];
kad = Encoding.ASCII.GetBytes("yesil00000" + nd);
conn.Write(kad, 0, kad.Length);
}
else if (msgid == "pospk")
{
}
else
{
Game.DisplayNotification("Unknown packet recieved! ID: " + msgid);
}
//send end client turn
td = new Byte[26];
td = Encoding.ASCII.GetBytes("endmt00000" + nd);
conn.Write(td, 0,td.Length);
File.WriteAllText("C:/ProgramData/dbg.log", "0");
//
}
catch (Exception e)
{
Game.DisplayHelp(Convert.ToString(e));
Game.DisplayNotification("LSPDFR Online has crashed. Try reloading it maybe..?");
}
}
} catch (Exception e) {
Game.DisplayHelp(Convert.ToString(e));
Game.DisplayNotification("Connection interrupted! Reconnecting....");
IsDead = 1;
return;
}
}
}
}
</code></pre>
<p>The protocol goes as such;</p>
<pre><code>Client -> Server: LoginRequest
Server -> Client: LoginOkay
Client -> Server: EndTurnMessage
Server -> Client: SaveDataMessage
Client -> Server: EndTurnMessage
Server -> Client: PositionUpdatePacket
Client -> Server: EndTurnMessage
</code></pre>
<p>Then continue routine, however, the server only receives one of these <code>EndTurnMessage</code> packets, which means it is choking on the save data portion, right?</p>
<p>Possibly, but that was working at an earlier time without flaw, and hasn't been modified since.</p>
<p>It is a class file, so it can't be debugged, and I've been tearing my hair out as to what is causing it.</p>
<p>Yes, it is crap-code, and needs rewritten at some point, I am aware, but I'd like it to work before I rewrite it entirely.</p>
<p>TL;DR: Why is this code raising an Access Violation? It's around the <code>savdt</code> sector or after.</p>
<p><strong>UPDATE:</strong> I fixed the issue posted in the first answer, however, that didn't do much, so, as posted in both the answer and comments, it's rather difficult to debug with a program, so I'll try the old fashioned route of logging info every so many lines of code. I'll keep this updated.</p>
<p><strong>UPDATE 2:</strong> I have figured out from the log debugging, that the line causing the error is <code>World.TeleportLocalPlayer(v3, false);</code>. Unfortunatley, <code>World</code> can't be inherited, and the documentation claims that <code>Vector3</code> requires you to set it's internal values using get and set. I saw that on MSDN previously, but have no clue about how to search it, and there is nor <code>get</code> or <code>set</code> methods available within that <code>Vector3</code> object.</p>
| -1 | 2016-08-26T04:11:21Z | 39,158,696 | <p>You might have a stream that remained open, which prevents a new one to be created. If the msgid is "ConOK" you are creating a new instance without closing it after the write operation is done.</p>
<pre><code>if (msgid == "ConOK"){
string userid = rd.Substring(0, 16);
Game.DisplayHelp(rd.Substring(16, (rd.Length - 16)));
FileStream savedat = File.OpenWrite(("C:/ProgramData/save.dat"));
BinaryWriter savdat = new BinaryWriter(savedat);
savdat.Write(userid);
// Close file stream here
}
</code></pre>
<p>But that's just a first guess. You can help us and yourself by making use of the debugger. The fact that your code is contained by a "class file" is no problem but a requirement. </p>
<p>Hava a look at this article for more information about debugging in the world of C#:
<a href="http://www.dotnetperls.com/debugging" rel="nofollow">http://www.dotnetperls.com/debugging</a></p>
| 1 | 2016-08-26T05:12:12Z | [
"c#",
"python",
"networking",
"visual-studio-2015"
] |
Exception: Acess Violation in client C# | 39,158,157 | <p>I am trying to learn C# through trials and errors. I have a server in Python, and the client in C#.</p>
<p>The client is supposed to get data from the server, save it to disk ((which it doesn't)), then continue using that data to communicate until the user decides to exit it.</p>
<p>Unfortunately, it has been raising an Exception Access Violation for quite some time, and provides no helpful information as to why.</p>
<p>Code: </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Scripting.Hosting;
using System.Threading;
using Rage;
using System.Net.Sockets;
using System.IO;
[assembly: Rage.Attributes.Plugin("LSPDFROnlineClient", Description = "LSPDFR Online Client. Used to connect to LSPDFR Online.", Author = "Thecheater887")]
namespace LSPDFROnlineClient
{
public class EntryPoint
{
private static int IsDead;
public static void Main()
{
IsDead = 0;
Thread mt = new Thread(new ThreadStart(Run));
mt.Start();
while (true)
{
if (IsDead == 1)
{
break;
}
GameFiber.Yield();
}
return;
}
public static void Run()
{
File.WriteAllText("C:/ProgramData/dbg.log","1");
try
{
Byte[] header;
Byte[] packet;
Byte[] data;
Byte[] kad;
Byte[] td;
int paylen;
String rd;
String nd;
String msgid;
File.WriteAllText("C:/ProgramData/dbg.log", "2");
TcpClient connector = new TcpClient();
connector.Connect("127.0.0.1", 5773);
NetworkStream conn = connector.GetStream();
try {
File.WriteAllText("C:/ProgramData/dbg.log", "3");
FileStream savedat = File.OpenRead("C:/Users/Public/Documents/save.dat");
BinaryReader savdat = new BinaryReader(savedat);
nd = savdat.ReadString();
savdat.Close();
if (nd.Length == 16)
{
} else {
File.WriteAllText("C:/ProgramData/save.dat", "user000000000000");
nd = "user000000000000";
}
}
catch
{
File.WriteAllText("C:/ProgramData/save.dat", "user000000000000");
nd = "user000000000000";
}
File.WriteAllText("C:/ProgramData/dbg.log", "4");
data = new Byte[26];
data = Encoding.ASCII.GetBytes("clogr00000" + nd);
conn.Write(data, 0, data.Length);
while (true)
{
try
{
// Get header of packet
header = new Byte[26];
Int32 rcvhead = conn.Read(header, 0, header.Length);
String hd = Encoding.ASCII.GetString(header, 0, rcvhead);
//Deal with it 8-)
msgid = hd.Substring(0, 5);
paylen = Convert.ToInt32(hd.Substring(5, 5));
string servkey = hd.Substring(10, 16);
}
catch
{
continue;
}
File.WriteAllText("C:/ProgramData/dbg.log", "5");
try
{
//Receive packet data
if (paylen > 0)
{
packet = new Byte[paylen];
Int32 newdata = conn.Read(packet, 0, packet.Length);
rd = Encoding.ASCII.GetString(packet, 0, newdata);
}
else
{
rd = null;
}
File.WriteAllText("C:/ProgramData/dbg.log", "6");
if (msgid == "ConOK")
{
File.WriteAllText("C:/ProgramData/dbg.log", "7");
string userid = rd.Substring(0, 16);
Game.DisplayHelp(rd.Substring(16, (rd.Length - 16)));
File.WriteAllText("C:/ProgramData/save.dat", userid);
File.WriteAllText("C:/ProgramData/dbg.log", "8");
}
else if (msgid == "savdt")
{
File.WriteAllText("C:/ProgramData/dbg.log", "9");
string[] tnd = rd.Split(',');
var nud = new List<string>();
nud.Add("Player1");
nud.AddRange(tnd);
File.WriteAllText("C:/ProgramData/dbg.log", "A");
string name = nud[0];
string streetname = nud[1];
int money = Convert.ToInt32(nud[2]);
int bounty = Convert.ToInt32(nud[3]);
int playerrep = Convert.ToInt32(nud[4]);
File.WriteAllText("C:/ProgramData/dbg.log", "B");
int rep = Convert.ToInt32(nud[5]);
string pclass = nud[6];
bool canbecop = Convert.ToBoolean(nud[7]);
int rank = Convert.ToInt32(nud[8]);
int stars = Convert.ToInt32(nud[9]);
int cites = Convert.ToInt32(nud[10]);
File.WriteAllText("C:/ProgramData/dbg.log", "C");
int citesgiven = Convert.ToInt32(nud[11]);
int citesdismissed = Convert.ToInt32(nud[12]);
int arrestsmade = Convert.ToInt32(nud[13]);
int arrested = Convert.ToInt32(nud[14]);
int convictionsmade = Convert.ToInt32(nud[15]);
int convitced = Convert.ToInt32(nud[16]);
string warrant = nud[17];
File.WriteAllText("C:/ProgramData/dbg.log", "D");
int prisontimeremaining = Convert.ToInt32(nud[18]);
int copskilled = Convert.ToInt32(nud[19]);
int crimskilled = Convert.ToInt32(nud[20]);
int civskilled = Convert.ToInt32(nud[21]);
int bountyclaimed = Convert.ToInt32(nud[22]);
int overflowprep = Convert.ToInt32(nud[23]);
string title = nud[24];
bool banned = Convert.ToBoolean(nud[25]);
bool vip = Convert.ToBoolean(nud[26]);
int viprank = Convert.ToInt32(nud[27]);
File.WriteAllText("C:/ProgramData/dbg.log", "E");
var v3 = new Vector3();
float posx = Convert.ToSingle(nud[29]);
float posy = Convert.ToSingle(nud[30]);
float posz = Convert.ToSingle(nud[31]);
v3.X = posx;
v3.Y = posy;
v3.Z = posz;
File.WriteAllText("C:/ProgramData/dbg.log", "EE");
int rot = Convert.ToInt32(nud[32]);
File.WriteAllText("C:/ProgramData/dbg.log", "FF");
World.TeleportLocalPlayer(v3, false);
File.WriteAllText("C:/ProgramData/dbg.log", "F");
string custommessage = nud[28];
if (custommessage == "null")
{
} else {
Game.DisplayNotification(custommessage);
}
}
else if (msgid == "isalv")
{
kad = new Byte[26];
kad = Encoding.ASCII.GetBytes("yesil00000" + nd);
conn.Write(kad, 0, kad.Length);
}
else if (msgid == "pospk")
{
}
else
{
Game.DisplayNotification("Unknown packet recieved! ID: " + msgid);
}
//send end client turn
td = new Byte[26];
td = Encoding.ASCII.GetBytes("endmt00000" + nd);
conn.Write(td, 0,td.Length);
File.WriteAllText("C:/ProgramData/dbg.log", "0");
//
}
catch (Exception e)
{
Game.DisplayHelp(Convert.ToString(e));
Game.DisplayNotification("LSPDFR Online has crashed. Try reloading it maybe..?");
}
}
} catch (Exception e) {
Game.DisplayHelp(Convert.ToString(e));
Game.DisplayNotification("Connection interrupted! Reconnecting....");
IsDead = 1;
return;
}
}
}
}
</code></pre>
<p>The protocol goes as such;</p>
<pre><code>Client -> Server: LoginRequest
Server -> Client: LoginOkay
Client -> Server: EndTurnMessage
Server -> Client: SaveDataMessage
Client -> Server: EndTurnMessage
Server -> Client: PositionUpdatePacket
Client -> Server: EndTurnMessage
</code></pre>
<p>Then continue routine, however, the server only receives one of these <code>EndTurnMessage</code> packets, which means it is choking on the save data portion, right?</p>
<p>Possibly, but that was working at an earlier time without flaw, and hasn't been modified since.</p>
<p>It is a class file, so it can't be debugged, and I've been tearing my hair out as to what is causing it.</p>
<p>Yes, it is crap-code, and needs rewritten at some point, I am aware, but I'd like it to work before I rewrite it entirely.</p>
<p>TL;DR: Why is this code raising an Access Violation? It's around the <code>savdt</code> sector or after.</p>
<p><strong>UPDATE:</strong> I fixed the issue posted in the first answer, however, that didn't do much, so, as posted in both the answer and comments, it's rather difficult to debug with a program, so I'll try the old fashioned route of logging info every so many lines of code. I'll keep this updated.</p>
<p><strong>UPDATE 2:</strong> I have figured out from the log debugging, that the line causing the error is <code>World.TeleportLocalPlayer(v3, false);</code>. Unfortunatley, <code>World</code> can't be inherited, and the documentation claims that <code>Vector3</code> requires you to set it's internal values using get and set. I saw that on MSDN previously, but have no clue about how to search it, and there is nor <code>get</code> or <code>set</code> methods available within that <code>Vector3</code> object.</p>
| -1 | 2016-08-26T04:11:21Z | 39,163,165 | <p>At a first glance, you can have different class of bugs. Disregarding the logic flows and intended behaviour of the program, let's start with basic debugging.</p>
<ul>
<li><p>at this step, don't use threads and fibers, from Main just call Run</p></li>
<li><p>there isn't strong input validation</p></li>
<li><p>use a lot more of try catch, isolating small pieces of code</p></li>
<li><p>in the catch, print ex.Message and ex.StackTrace</p></li>
<li><p>read carefully the docs about the methods you call and their possible exceptions</p></li>
<li><p>it is weird you write a file inside a exception (catch)</p></li>
<li><p>possible race conditions on global variables?
inside Run to set IsDead use Interlocked.Increment
<a href="https://msdn.microsoft.com/en-us/library/dd78zt0c(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/dd78zt0c(v=vs.110).aspx</a></p></li>
</ul>
<p>...</p>
<ul>
<li>remove the unused ( I think like Microsoft.Scripting.Hosting ), it only confuse-a-cat</li>
</ul>
| 1 | 2016-08-26T09:37:52Z | [
"c#",
"python",
"networking",
"visual-studio-2015"
] |
Comparing Dates in SQLLite | 39,158,180 | <p>Hello Im currently doing a small project in python and sqllite and I have a csv that has been imported into a database with values under table name : Members.</p>
<p>Each member has a "Date Joined" field in the format m/dd/yy. Some example formats are below:</p>
<p><strong>I cant change the values in the csv because when I turn this assignment in they're going to use a document with the same format as below</strong></p>
<h2>Date Joined</h2>
<p>5/1/98
6/4/97
7/1/99<br>
8/1/99<br>
8/3/99<br>
11/20/99<br>
2/2/00<br>
1/2/99<br>
2/3/99</p>
<p>One of the questions Im asked is:</p>
<p>to retrieve all member information that have joined after 1999-07-01 (yyyy-mm-dd) and are from VA (can ignore the VA part) </p>
<p>My query to do this something like this started off as</p>
<pre><code>SELECT * FROM Members WHERE "Date Joined" >= "1999-07-01" AND "State"="VA";
</code></pre>
<p>But my problem is that Im having trouble converting the date (Im guessing its stored as a string in the database) so it can be compared with "1999-07-01".</p>
| 2 | 2016-08-26T04:13:33Z | 39,158,610 | <p>You can try the following query:</p>
<pre><code>SELECT *
FROM yourTable
WHERE CAST(SUBSTR(SUBSTR(join_date, INSTR(join_date, '/') + 1), INSTR(SUBSTR(join_date, INSTR(join_date, '/') + 1), '/') + 1) AS INTEGER) <= 16 OR
(
CAST(SUBSTR(SUBSTR(join_date, INSTR(join_date, '/') + 1), INSTR(SUBSTR(join_date, INSTR(join_date, '/') + 1), '/') + 1) AS INTEGER) >= 99 AND
CAST(SUBSTR(join_date, 1, INSTR(join_date, '/') - 1) AS INTEGER) >= 7
)
</code></pre>
<p><strong>Explanation:</strong></p>
<p>Apologies for such an ugly query, but then again the date data you are working with is also very ugly. The logic of the query is that is will select all records where the year is <code>16</code> or less, <em>or</em> if the year be <code>99</code> or greater <em>and</em> the month be <code>7</code> or greater.</p>
<p>The trick here is to carefully use SQLite's string manipulation functions to extract the pieces we want. To extract the month, use:</p>
<pre><code>SUBSTR(join_date, 1, INSTR(join_date, '/') - 1)
</code></pre>
<p>This will extract everything from the date column up to, but not including, the first forward slash. To extract the day and year is a bit more work, because <code>INSTR</code> picks up the first matching character. In this case, we can substring the date to remove everything up and including the first forward slash. So the day and year can be extracted using:</p>
<pre><code>SUBSTR(sub, 1, INSRT(sub, '/') - 1) -- day
SUBSTR(sub, INSTR(sub, '/') + 1) -- year
</code></pre>
<p>where <code>sub</code> is obtained as <code>SUBSTR(join_date, INSTR(join_date, '/') + 1)</code>.</p>
| 0 | 2016-08-26T05:04:56Z | [
"python",
"sql",
"database",
"sqlite"
] |
Python Multithreading basics confusion | 39,158,275 | <p>I have the below code:</p>
<pre><code>import time
from threading import Thread
def fun1():
time.sleep(5)
def fun2():
time.sleep(5)
def fun3():
time.sleep(5)
def fun4():
time.sleep(5)
if __name__ == '__main__':
t1 = Thread(target=fun1, args=())
t2 = Thread(target=fun2, args=())
t3 = Thread(target=fun3, args=())
t4 = Thread(target=fun4, args=())
t1.start()
t2.start()
t3.start()
t4.start()
start = time.clock()
t1.join()
t2.join()
t3.join()
t4.join()
end = time.clock()
print("Time Taken = ",end-start)
</code></pre>
<p>Que1: <strong>At a time only one thread will be serviced</strong>, meaning if the control is with thread t1,rest other threads will be waiting. Once the context switch takes place to thread t2,rest all other threads(t1,t3 and t4) will be waiting.
Is that the correct understanding?</p>
<p>Que2:If my understanding of Que1 is true, the total time(start - end) should be twenty seconds(as good as running in sequential manner rather than threaded manner)...but it is somewhat close to 5 seconds....why?At the end of the day,the threads are getting executed in sequence(though, not in entirety) one by one
Please explain in laymen terms.Where is my understanding incorrect?</p>
<p>Que3:What if i do the same thing using multiprocessing?How will the execution differ? </p>
<p>Que4:Let's say(assume) fun1() has the code that does a 1000 repeat count ping to Router 1 and takes a time of 1 min.
Similary, fun2() does a 1000 repeat count ping to Router 2 and takes a time of 1 min.
Similary, fun3() does a 1000 repeat count ping to Router 3 and takes a time of 1 min.</p>
<p>If i do this sequentially, total expected time is 3 min for(ping to R1,then ping to R2 and then ping to R3)
But when i did this using threading,the total execution time was almost close to 1 min. Why ? I am unable to understand.</p>
| 1 | 2016-08-26T04:24:58Z | 39,158,320 | <p>Blocking calls in Python (<code>sleep</code>, waiting on I/O or locks) release the GIL, allowing other threads to run while they are blocked, so all four threads can <code>sleep</code> in parallel, that's why you're seeing a five second delay. If you want to see the effects of GIL contention, have the thread function do something CPU bound, e.g.</p>
<pre><code>def fun():
for _ in xrange(1000000000):
pass
</code></pre>
<p><code>multiprocessing</code> won't change a thing for the <code>sleep</code> case, since you're not GIL bound, but it would improve the wall clock time of the CPU bound case if you have more than one core to run on.</p>
| 3 | 2016-08-26T04:29:51Z | [
"python",
"multithreading",
"multiprocessing",
"python-2.x",
"gil"
] |
Python Multithreading basics confusion | 39,158,275 | <p>I have the below code:</p>
<pre><code>import time
from threading import Thread
def fun1():
time.sleep(5)
def fun2():
time.sleep(5)
def fun3():
time.sleep(5)
def fun4():
time.sleep(5)
if __name__ == '__main__':
t1 = Thread(target=fun1, args=())
t2 = Thread(target=fun2, args=())
t3 = Thread(target=fun3, args=())
t4 = Thread(target=fun4, args=())
t1.start()
t2.start()
t3.start()
t4.start()
start = time.clock()
t1.join()
t2.join()
t3.join()
t4.join()
end = time.clock()
print("Time Taken = ",end-start)
</code></pre>
<p>Que1: <strong>At a time only one thread will be serviced</strong>, meaning if the control is with thread t1,rest other threads will be waiting. Once the context switch takes place to thread t2,rest all other threads(t1,t3 and t4) will be waiting.
Is that the correct understanding?</p>
<p>Que2:If my understanding of Que1 is true, the total time(start - end) should be twenty seconds(as good as running in sequential manner rather than threaded manner)...but it is somewhat close to 5 seconds....why?At the end of the day,the threads are getting executed in sequence(though, not in entirety) one by one
Please explain in laymen terms.Where is my understanding incorrect?</p>
<p>Que3:What if i do the same thing using multiprocessing?How will the execution differ? </p>
<p>Que4:Let's say(assume) fun1() has the code that does a 1000 repeat count ping to Router 1 and takes a time of 1 min.
Similary, fun2() does a 1000 repeat count ping to Router 2 and takes a time of 1 min.
Similary, fun3() does a 1000 repeat count ping to Router 3 and takes a time of 1 min.</p>
<p>If i do this sequentially, total expected time is 3 min for(ping to R1,then ping to R2 and then ping to R3)
But when i did this using threading,the total execution time was almost close to 1 min. Why ? I am unable to understand.</p>
| 1 | 2016-08-26T04:24:58Z | 39,158,326 | <p>Q1: Yes</p>
<p>Q2: If the threads each did something that took 5 seconds of processing time, then you would expect the total time to be 20 seconds. But each thread is just sleeping for 5 seconds, so each thread releases the <code>GIL</code>, and thus allows other threads to run "in parallel" (only conceptually), as it waits for the sleep timeout.</p>
<p>Q3: Multiprocessing, unlike <code>threads</code>, creates child processes which can each run on different processors concurrently (actually parallel). But even if these <code>sleeps</code> each run on separate processors, they will still collectively finish in about 5 seconds. If they run on the same processor the OS's time-sharing mechanism will, in a manner similar to Python's threading mechanism, also ensure they complete in about 5 minutes. </p>
<p>Q4: It's the same concept as with <code>sleep</code>. Each <code>ping</code> is not CPU-intensive and thus its thread rarely has possession of the GIL. This allows all three <code>ping</code> threads to conceptually run in parallel.</p>
| 2 | 2016-08-26T04:31:12Z | [
"python",
"multithreading",
"multiprocessing",
"python-2.x",
"gil"
] |
Python Multithreading basics confusion | 39,158,275 | <p>I have the below code:</p>
<pre><code>import time
from threading import Thread
def fun1():
time.sleep(5)
def fun2():
time.sleep(5)
def fun3():
time.sleep(5)
def fun4():
time.sleep(5)
if __name__ == '__main__':
t1 = Thread(target=fun1, args=())
t2 = Thread(target=fun2, args=())
t3 = Thread(target=fun3, args=())
t4 = Thread(target=fun4, args=())
t1.start()
t2.start()
t3.start()
t4.start()
start = time.clock()
t1.join()
t2.join()
t3.join()
t4.join()
end = time.clock()
print("Time Taken = ",end-start)
</code></pre>
<p>Que1: <strong>At a time only one thread will be serviced</strong>, meaning if the control is with thread t1,rest other threads will be waiting. Once the context switch takes place to thread t2,rest all other threads(t1,t3 and t4) will be waiting.
Is that the correct understanding?</p>
<p>Que2:If my understanding of Que1 is true, the total time(start - end) should be twenty seconds(as good as running in sequential manner rather than threaded manner)...but it is somewhat close to 5 seconds....why?At the end of the day,the threads are getting executed in sequence(though, not in entirety) one by one
Please explain in laymen terms.Where is my understanding incorrect?</p>
<p>Que3:What if i do the same thing using multiprocessing?How will the execution differ? </p>
<p>Que4:Let's say(assume) fun1() has the code that does a 1000 repeat count ping to Router 1 and takes a time of 1 min.
Similary, fun2() does a 1000 repeat count ping to Router 2 and takes a time of 1 min.
Similary, fun3() does a 1000 repeat count ping to Router 3 and takes a time of 1 min.</p>
<p>If i do this sequentially, total expected time is 3 min for(ping to R1,then ping to R2 and then ping to R3)
But when i did this using threading,the total execution time was almost close to 1 min. Why ? I am unable to understand.</p>
| 1 | 2016-08-26T04:24:58Z | 39,158,496 | <p>For multithreading environment in python. We have two very different kind of taks:</p>
<ul>
<li>CPU bound: like adding number, running for loop ... any activities that consume CPU. This kind of task hold GIL so it prevent other thread running.</li>
<li>not CPU bound (may be waiting for IO activities from outside resource like network ...):sleep system call does not use CPU so it's in this kind. this kind releases GIL while it waits for IO, sleep timeout .. so other thread can take lock and running.
That is why your program take around 5 seconds because all of your threads can run in parallel.</li>
</ul>
| 1 | 2016-08-26T04:53:17Z | [
"python",
"multithreading",
"multiprocessing",
"python-2.x",
"gil"
] |
Reshaping a numpy array (matrix) where elements appear in order | 39,158,300 | <p>I have a numpy array with the following shape:</p>
<pre><code>shape -> data
5x3 -> [[
12 10 33
9 88 41
13 39 27
1 4 7
65 78 13
]]
</code></pre>
<p>I need the numpy array to look like this though:</p>
<pre><code>shape -> data
5x3 -> [[
12 41 4
10 13 7
33 39 65
9 27 78
88 1 13
]]
</code></pre>
<p>Essentially, given a numpy array X, I want to create a new array, Y with the same shape as X that takes all the values (left -> right) in each column of X and then puts those values in the same order, but by row.</p>
<p>I have a feeling this might be a simple or easy thing to do with reshape, but I haven't been able to find out if its doable.</p>
| 0 | 2016-08-26T04:27:19Z | 39,158,373 | <p>It's a simple enough procedure. We just need to perform two phases, a reshape and a transpose:</p>
<pre><code>Y = X.reshape(X.shape[::-1]).T
</code></pre>
| 1 | 2016-08-26T04:36:18Z | [
"python",
"arrays",
"numpy"
] |
Why does using .latest() on an empty Django queryset return...nothing? | 39,158,325 | <p>Here's some code that builds a queryset, and prints the output at each step (for debugging):</p>
<pre><code>qs = self.get_queryset(True)
print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>]
qs = qs.get_user(user)
print(qs) # []
qs = qs.completed()
print(qs) # []
qs = qs.latest('time_completed')
print(qs) # <-- What happened? Why is this blank?
print(qs is None) # False <-- huh??
print("nothing") if not qs else print("something") # <-- blank?!?! how?!
print(type(qs)) #
</code></pre>
<p>The last operation <code>qs.latest('time_completed')</code> prints blank, the type is blank, the if statement is ignored. What's going on here?</p>
<p>An example where the result is NOT an empty queryset works fine (note all items are a single user, just coincidence):</p>
<pre><code>qs = self.get_queryset(True)
print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>]
qs = qs.get_user(user)
print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>]
qs = qs.completed()
print(qs) # [<MyModel: obj_1>, <MyModel: obj_2>, <MyModel: obj_2>, <MyModel: obj_3>]
qs = qs.latest('time_completed')
print(qs) # obj_1
print("nothing") if not qs else print("something") # something
print(type(qs)) # <class 'my_app.models.MyModel'>
</code></pre>
| 0 | 2016-08-26T04:30:57Z | 39,162,440 | <p><a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#latest" rel="nofollow">From the documentation</a>:</p>
<blockquote>
<p>Like get(), earliest() and latest() raise DoesNotExist if there is no object with the given parameters.</p>
</blockquote>
<p><code>qs.latest('field')</code> should raise <code>Model.DoesNotExist</code> exception whenever <code>qs</code> is an empty queryset. </p>
<pre><code>In [2]: Entity.objects.none().latest('creation_date')
---------------------------------------------------------------------------
DoesNotExist Traceback (most recent call last)
</code></pre>
<p>Check the exception is not swallowed in your view/method.</p>
| 2 | 2016-08-26T09:03:48Z | [
"python",
"django",
"django-queryset"
] |
How to convert the following Matlab loop into Python? | 39,158,384 | <p>I have been working on translating Matlab code into Python and came across a loop that I'm having some difficulty converting as I'm fairly new to both the languages.</p>
<pre><code>if fdp >=2
degreeTwoVector=[];
counter =1;
for i = 1:numVariables
for j = 1:numVariables
degreeTwoVector(counter,:) = [i j 0];
counter = counter +1;
end
end
sortedDegreeTwoVector = sort(degreeTwoVector,2);
degreeTwoVector = unique(sortedDegreeTwoVector, 'rows');
combinationVector = [combinationVector; degreeTwoVector];
end
</code></pre>
<p>Here's what I could come up with while converting it to python(incomplete):</p>
<pre><code>if fdp >= 2:
degreeTwoVector = np.array([])
counter = 1
for i in range(1, numVariables+1):
for j in range(1, numVariables+1):
degreeTwoVector(counter, :) = np.array([i, j, 0])
counter = counter + 1
break
sortedDegreeTwoVector = degreeTwoVector[np.argsort(degreeTwoVector[:, 1])]
</code></pre>
<p>I certainly know there are some mistakes in it. So I'd be grateful if you could help me complete the conversion and correct any mistakes. Thanks in advance!</p>
| 2 | 2016-08-26T04:37:43Z | 39,158,704 | <p>You are not too far off:
You do not need a <code>break</code> statement, it is causing a precocious, well, break to the loop (at the first iteration).
So here you go:
</p>
<pre><code>numVariables = np.shape(X)[0] # number of rows in X which is given
if fdp >= 2:
degreeTwoVector = np.zeros((numVariables, 3)) # you need to initialize the shape
counter = 0 # first index is 0
for i in range(numVariables):
for j in range(numVariables):
degreeTwoVector[counter, :] = np.array([i, j, 0])
counter = counter + 1 # counter += 1 is more pythonic
sortedDegreeTwoVector = np.sort(degreeTwoVector, axis=1);
degreeTwoVector = np.vstack({tuple(row) for row in sortedDegreeTwoVector})
combinationVector = np.vstack((combinationVector, degreeTwoVector))
</code></pre>
<p><strong>EDIT</strong>: added equivalent of code outside the loop in the original question.</p>
<p>Apart from the fact that i don't see where you defined <code>combinationVector</code>, everything should be okay.</p>
| 3 | 2016-08-26T05:13:06Z | [
"python",
"matlab",
"python-2.7"
] |
How to create mask for outer pixels when using skimage.transform.rotate | 39,158,420 | <p>skimage rotate function create "outer" pixels, no matter how this pixels extrapolated (wrap, mirror, constant, etc) - they are fake, and can affect statistical analysis of image. How can I get mask of this pixels to ignore them in analysis?
<a href="http://i.stack.imgur.com/xzg5n.png" rel="nofollow"><img src="http://i.stack.imgur.com/xzg5n.png" alt="How to create such mask"></a></p>
| 2 | 2016-08-26T04:43:39Z | 39,160,945 | <pre><code>mask_val = 2
rotated = skimage.transform.rotate(img, 15, resize=True, cval=mask_val,
preserve_range=False)
mask = rotated == mask_val
</code></pre>
<p>Idea: pick a value for the mask which doesn't appear in the image, then obtain mask by checking for equality with this value. Works well when image pixels are normalized floats. <code>rotate</code> above transforms image pixels to normalized floats internally thanks to <code>preserve_range=False</code> (this is default value, I specified it just to make point that without it this wouldn't work). </p>
| 1 | 2016-08-26T07:41:18Z | [
"python",
"skimage"
] |
socket progamming : tcp_client "gai" error | 39,158,573 | <p>I'm setting up a simple client socket (my server socket works well). But I'm stuck by a lil bug. here's my code and here's the error. Cant find this errorr nowhere on the web.</p>
<pre><code>from socket import *
import sys
host=socket.gethostname()
#host=127.0.0.1
serverPort= 12345
clientSocket =socket(AF_INET,SOCK_STREAM)
clientSocket.connect((127.0.0.1,serverPort))
msg= raw_input("Input text here:")
clientSocket.send(msg)
modmsg= clientSocket.recv(1024)
print "from server", modmsg
clientSocket.close()
</code></pre>
<p>the error:</p>
<pre><code>Traceback (most recent call last):
File "tcp_client.py", line 5, in <module>
clientSocket.connect((serverName,serverPort))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.gaierror: [Errno -5] No address associated with hostname
</code></pre>
| 0 | 2016-08-26T05:01:35Z | 39,158,700 | <p>Your code is incorrect here (did you post the real code you ran?):</p>
<ol>
<li>host cannot be empty</li>
<li><code>connect</code> takes 1 argument and it's a tuple</li>
<li>if you do <code>from socket import *</code>, you cannot do <code>socket.socket</code></li>
</ol>
<p>fixed:</p>
<pre><code>import socket
import sys
host=socket.gethostname()
serverPort= 12345
clientSocket = socket.socket(AF_INET,SOCK_STREAM)
clientSocket.connect((host,serverPort))
msg= raw_input("Input text here:")
clientSocket.send(msg)
modmsg= clientSocket.recv(1024)
print "from server", modmsg
clientSocket.close()
</code></pre>
<p>now I get proper timeout when I run this code (I don't have the client) instead of your error.</p>
| 0 | 2016-08-26T05:12:51Z | [
"python",
"serversocket",
"tcpsocket"
] |
Can you have multiple read/writes to SQLite database simultaneously? | 39,158,621 | <p>I am using Python with SQLite currently and wondering if it is safe to have multiple threads reading and writing to the database simultaneously. Does SQLite handle data coming in as a queue or have sort of mechanism that will stop the data from getting corrupt?</p>
| 1 | 2016-08-26T05:05:33Z | 39,158,655 | <p>SQLite has a number of robust locking mechanisms to ensure the data doesn't get corrupted, but the problem with that is if you have a number of threads reading and writing to it simultaneously you'll suffer pretty badly in terms of performance as they all trip over the others. It's not intended to be used this way, even if it does work.</p>
<p>You probably want to look at using a shared database server of some sort if this is your intended usage pattern. They have much better support for concurrent operations.</p>
| 1 | 2016-08-26T05:08:54Z | [
"python",
"multithreading",
"sqlite"
] |
Can you have multiple read/writes to SQLite database simultaneously? | 39,158,621 | <p>I am using Python with SQLite currently and wondering if it is safe to have multiple threads reading and writing to the database simultaneously. Does SQLite handle data coming in as a queue or have sort of mechanism that will stop the data from getting corrupt?</p>
| 1 | 2016-08-26T05:05:33Z | 39,163,285 | <p>This is my issue too. SQLite using some kind of locking mechanism which prevent you doing concurrency operation on a DB. But here is a trick which i use when my db are small. You can select all your tables data into memory and operate on it and then update the original table.</p>
<p>As i said this is just a trick and it does not always solve the problem.</p>
<p>I advise to create your trick.</p>
| 2 | 2016-08-26T09:43:14Z | [
"python",
"multithreading",
"sqlite"
] |
I am simply trying to write a python script that will change the filename in a directory of files | 39,158,636 | <p>I am trying to create a script in python 2.7 that will rename all the files in a directory. Below is the code I have so far. The first function removes any numbers in the file name. The second function is supposed to rename the new file name. I get the following error when the second function runs:</p>
<blockquote>
<p>[Error 183] Cannot create a file when that file already exists</p>
</blockquote>
<p>I know this is because I am not looping through the files and adding an incrementing number to the new filename, so the script changes the name of the first file, and then tries to change the name of the second file to the same name as the first, producing the error. </p>
<p>Can someone help me create a loop that adds an incrementing number to each filename in the directory?</p>
<p>I tried adding:</p>
<pre><code>if file_name == filename:
file_name = file_name + 1
</code></pre>
<p>in the while loop, but that obviously doesn't work because I cant concatenate an integer with a string.</p>
<pre><code>import os
def replace_num():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for file_name in file_list:
print("Old Name - " + file_name)
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
replace_num()
def rename_files():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for new_name in file_list:
print("New Name - " + new_name)
try:
os.rename(new_name, "iPhone")
except Exception, e:
print e
rename_files()
</code></pre>
| 4 | 2016-08-26T05:07:08Z | 39,158,669 | <p>instead of doing:</p>
<pre><code>if file_name == filename:
file_name = file_name + 1
</code></pre>
<p>do something like this:</p>
<pre><code>counter = 0
for file_name in file_container:
if file_name == file_name: # this will always be True - so it's unnecessary
file_name = "{0}_{1}".format(file_name, counter)
counter += 1
</code></pre>
| 4 | 2016-08-26T05:10:10Z | [
"python",
"python-2.7",
"loops",
"increment"
] |
Using HTML, CSS, JS with Python to make desktop application? | 39,158,663 | <p>I recently made a program. It's developed using Node.JS and Electron to make it a desktop application. Unfortunately, Electron is quite big in base file size and I'd like to reduce the file size. I've looked at my app files before adding electron and it's around 38mb. When adding electron it's roughly over 100mb more than the original. </p>
<p>I've been looking into converting the program to Python to hopefully reduce the size of it. Though I only know the basics of Python such as how to declare variables and functions. I've seen stuff like Tkinter and stuff, but would I be able to use HTML, CSS, JS to make the UI of the program and use Python as the back bone(i.e. using materailizecss framework for the ui).</p>
<p>If so, how could I do this? Also, to make it clear, I don't want a web app, I'm looking for a desktop application.</p>
| -1 | 2016-08-26T05:09:29Z | 39,163,137 | <p>YES. You can use QT standard library but if you persist on writing UI yourself there is an HTMLpy Library which can find here <a href="http://amol-mandhane.github.io/htmlPy/" rel="nofollow">HTMLPY</a></p>
<p>htmlPy is a wrapper around PySide's QtWebKit library. It helps with creating beautiful GUIs using HTML5, CSS3 and Javascript for standalone Python applications.</p>
<p>go through it and you will find interesting things</p>
| 1 | 2016-08-26T09:36:21Z | [
"javascript",
"python",
"html",
"css"
] |
How to select column and rows in pandas without column or row names? | 39,158,699 | <p>I have a pandas dataframe(df) like this</p>
<pre><code> Close Close Close Close Close
Date
2000-01-03 00:00:00 NaN NaN NaN NaN -0.033944
2000-01-04 00:00:00 NaN NaN NaN NaN 0.0351366
2000-01-05 00:00:00 -0.033944 NaN NaN NaN -0.0172414
2000-01-06 00:00:00 0.0351366 -0.033944 NaN NaN -0.00438596
2000-01-07 00:00:00 -0.0172414 0.0351366 -0.033944 NaN 0.0396476
</code></pre>
<p>in <code>R</code> If I want to select fifth column</p>
<pre><code>five=df[,5]
</code></pre>
<p>and without 5th column</p>
<pre><code>rest=df[,-5]
</code></pre>
<p>How can I do similar operations with pandas dataframe</p>
<p>I tried this in pandas</p>
<pre><code>five=df.ix[,5]
</code></pre>
<p>but its giving this error</p>
<pre><code> File "", line 1
df.ix[,5]
^
SyntaxError: invalid syntax
</code></pre>
| 1 | 2016-08-26T05:12:49Z | 39,158,738 | <p>If you want the fifth column:</p>
<pre><code>df.ix[:,4]
</code></pre>
<p>Stick the colon in there to take all the rows for that column.</p>
<p>To exclude a fifth column you could try:</p>
<pre><code>df.ix[:, (x for x in range(0, len(df.columns)) if x != 4)]
</code></pre>
| 1 | 2016-08-26T05:16:56Z | [
"python",
"pandas"
] |
How to select column and rows in pandas without column or row names? | 39,158,699 | <p>I have a pandas dataframe(df) like this</p>
<pre><code> Close Close Close Close Close
Date
2000-01-03 00:00:00 NaN NaN NaN NaN -0.033944
2000-01-04 00:00:00 NaN NaN NaN NaN 0.0351366
2000-01-05 00:00:00 -0.033944 NaN NaN NaN -0.0172414
2000-01-06 00:00:00 0.0351366 -0.033944 NaN NaN -0.00438596
2000-01-07 00:00:00 -0.0172414 0.0351366 -0.033944 NaN 0.0396476
</code></pre>
<p>in <code>R</code> If I want to select fifth column</p>
<pre><code>five=df[,5]
</code></pre>
<p>and without 5th column</p>
<pre><code>rest=df[,-5]
</code></pre>
<p>How can I do similar operations with pandas dataframe</p>
<p>I tried this in pandas</p>
<pre><code>five=df.ix[,5]
</code></pre>
<p>but its giving this error</p>
<pre><code> File "", line 1
df.ix[,5]
^
SyntaxError: invalid syntax
</code></pre>
| 1 | 2016-08-26T05:12:49Z | 39,158,821 | <p>To select filter column by index:</p>
<pre><code>In [19]: df
Out[19]:
Date Close Close.1 Close.2 Close.3 Close.4
0 2000-01-0300:00:00 NaN NaN NaN NaN -0.033944
1 2000-01-0400:00:00 NaN NaN NaN NaN 0.035137
2 2000-01-0500:00:00 -0.033944 NaN NaN NaN -0.017241
3 2000-01-0600:00:00 0.035137 -0.033944 NaN NaN -0.004386
4 2000-01-0700:00:00 -0.017241 0.035137 -0.033944 NaN 0.039648
In [20]: df.ix[:, 5]
Out[20]:
0 -0.033944
1 0.035137
2 -0.017241
3 -0.004386
4 0.039648
Name: Close.4, dtype: float64
In [21]: df.icol(5)
/usr/bin/ipython:1: FutureWarning: icol(i) is deprecated. Please use .iloc[:,i]
#!/usr/bin/python2
Out[21]:
0 -0.033944
1 0.035137
2 -0.017241
3 -0.004386
4 0.039648
Name: Close.4, dtype: float64
In [22]: df.iloc[:, 5]
Out[22]:
0 -0.033944
1 0.035137
2 -0.017241
3 -0.004386
4 0.039648
Name: Close.4, dtype: float64
</code></pre>
<p>To select all columns except index:</p>
<pre><code>In [29]: df[[df.columns[i] for i in range(len(df.columns)) if i != 5]]
Out[29]:
Date Close Close.1 Close.2 Close.3
0 2000-01-0300:00:00 NaN NaN NaN NaN
1 2000-01-0400:00:00 NaN NaN NaN NaN
2 2000-01-0500:00:00 -0.033944 NaN NaN NaN
3 2000-01-0600:00:00 0.035137 -0.033944 NaN NaN
4 2000-01-0700:00:00 -0.017241 0.035137 -0.033944 NaN
</code></pre>
| 1 | 2016-08-26T05:24:48Z | [
"python",
"pandas"
] |
How to select column and rows in pandas without column or row names? | 39,158,699 | <p>I have a pandas dataframe(df) like this</p>
<pre><code> Close Close Close Close Close
Date
2000-01-03 00:00:00 NaN NaN NaN NaN -0.033944
2000-01-04 00:00:00 NaN NaN NaN NaN 0.0351366
2000-01-05 00:00:00 -0.033944 NaN NaN NaN -0.0172414
2000-01-06 00:00:00 0.0351366 -0.033944 NaN NaN -0.00438596
2000-01-07 00:00:00 -0.0172414 0.0351366 -0.033944 NaN 0.0396476
</code></pre>
<p>in <code>R</code> If I want to select fifth column</p>
<pre><code>five=df[,5]
</code></pre>
<p>and without 5th column</p>
<pre><code>rest=df[,-5]
</code></pre>
<p>How can I do similar operations with pandas dataframe</p>
<p>I tried this in pandas</p>
<pre><code>five=df.ix[,5]
</code></pre>
<p>but its giving this error</p>
<pre><code> File "", line 1
df.ix[,5]
^
SyntaxError: invalid syntax
</code></pre>
| 1 | 2016-08-26T05:12:49Z | 39,160,661 | <p>Use <code>iloc</code>. It is explicitly a position based indexer. <code>ix</code> can be both and will get confused if an index is integer based.</p>
<pre><code>df.iloc[:, [4]]
</code></pre>
<p><a href="http://i.stack.imgur.com/dfnha.png" rel="nofollow"><img src="http://i.stack.imgur.com/dfnha.png" alt="enter image description here"></a></p>
<p>For all but the fifth column</p>
<pre><code>slc = list(range(df.shape[1]))
slc.remove(4)
df.iloc[:, slc]
</code></pre>
<p><a href="http://i.stack.imgur.com/1vHub.png" rel="nofollow"><img src="http://i.stack.imgur.com/1vHub.png" alt="enter image description here"></a></p>
<p>or equivalently</p>
<pre><code>df.iloc[:, [i for i in range(df.shape[1]) if i != 4]]
</code></pre>
| 2 | 2016-08-26T07:26:05Z | [
"python",
"pandas"
] |
List conversion - inplace | 39,158,754 | <p>I am trying to convert ['1','2','3','4'] to [1,2,3,4]
I want to make this conversion inplace. Is it possible to do it? If not, what is the optimal solution.</p>
| 3 | 2016-08-26T05:18:40Z | 39,158,850 | <p>This should be pretty much in-place?</p>
<pre><code>In [31]: l = ['1','2','3','4']
In [32]: for i in range(len(l)):
....: l[i] = int(l[i])
....:
In [33]: l
Out[33]: [1, 2, 3, 4]
</code></pre>
<p>Or, you could do it by using <code>enumerate</code> which takes an iterable (like a <code>list</code>) and returns an <code>index</code> and the corresponding value from the beginning till the end:</p>
<pre><code>In [84]: l = ['1','2','3','4']
In [85]: for idx, val in enumerate(l):
....: l[idx] = int(val)
....:
In [86]: l
Out[86]: [1, 2, 3, 4]
</code></pre>
| 0 | 2016-08-26T05:29:05Z | [
"python",
"arrays",
"list",
"in-place"
] |
List conversion - inplace | 39,158,754 | <p>I am trying to convert ['1','2','3','4'] to [1,2,3,4]
I want to make this conversion inplace. Is it possible to do it? If not, what is the optimal solution.</p>
| 3 | 2016-08-26T05:18:40Z | 39,158,927 | <p>As long as the whole array fits in memory, you should just be able to step through it, replacing each item as you go:</p>
<pre><code># bigarray is ['1','2','3','4',...];
# loop through bigarray using index i
for i in range(len(bigarray)):
# coerce bigarray[i] to int in place
bigarray[i] = int(bigarray[i])
# bigarray is [1,2,3,4,...];
</code></pre>
<p>good luck!</p>
| 0 | 2016-08-26T05:33:46Z | [
"python",
"arrays",
"list",
"in-place"
] |
List conversion - inplace | 39,158,754 | <p>I am trying to convert ['1','2','3','4'] to [1,2,3,4]
I want to make this conversion inplace. Is it possible to do it? If not, what is the optimal solution.</p>
| 3 | 2016-08-26T05:18:40Z | 39,159,317 | <p>you can do it with list comprehension like this:</p>
<pre><code>l = [int(item) for item in l]
</code></pre>
| 1 | 2016-08-26T06:04:03Z | [
"python",
"arrays",
"list",
"in-place"
] |
List conversion - inplace | 39,158,754 | <p>I am trying to convert ['1','2','3','4'] to [1,2,3,4]
I want to make this conversion inplace. Is it possible to do it? If not, what is the optimal solution.</p>
| 3 | 2016-08-26T05:18:40Z | 39,161,253 | <p>I think it is better to use <a href="https://docs.python.org/3/library/functions.html?highlight=map#map" rel="nofollow"><code>map</code></a> for this kind of tasks. Which creates iterator, what means it is more memory efficient.</p>
<pre><code>l = list(map(int, l))
# here I convert it to list, but usually you would just iterate over it
# so you can just do
for item in map(int, l):
...
</code></pre>
| 2 | 2016-08-26T07:59:19Z | [
"python",
"arrays",
"list",
"in-place"
] |
Python adaptfilt-echo canceller example with two .wav files | 39,158,762 | <p>this code isa modification from the example of adaptfilt2.0 echo canceller</p>
<pre><code> u(n) ------->->------+----------->->-----------
| |
+-----------------+ +------------------+
+->-| Adaptive filter | | John's Room |
| +-----------------+ +------------------+
| | -y(n) |
| | d(n) |
e(n) ---+---<-<------+-----------<-<----------+----<-<---- v(n)
</code></pre>
<p>i need to read two wave audio files audio1.wav like emily's signal and audio2.wav like john's signal, the thing is that the code only use audio1.wav and dont read audio2.wav in the process, so when the code run only use the audio1.wav for u(n) and v(n) and not assigns audio2.wav to the variable v(n).</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import adaptfilt as adf
import pyaudio
import wave
np.seterr(all='raise')
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(2),
channels = 1,
rate = 44100,
input = True,
output = True,
# stream_callback =callback
)
#Read U
wf1 = wave.open("audio1.wav", 'r')
data= wf1.readframes(1024)
u = np.fromstring(data, np.int16)
u = np.float64(u)
#read V
wf2= wave.open("audio2.wav", 'r')
data2= wf2.readframes(1024)
v= np.fromstring(data2, np.int16)
v = np.float64(u)
#both signals
d = u+v
# Apply adaptive filter
M = 100 # Number of filter taps in adaptive filter
step = 0.1 # Step size
y, e, w = adf.nlms(u, d, M, step, returnCoeffs=True)
plt.figure()
plt.title('Em u(n)')
plt.plot(u)
plt.grid()
plt.xlabel('Samples')
plt.figure()
plt.title('john v(n)')
plt.plot(v)
plt.grid()
plt.xlabel('Samples')
plt.show()
</code></pre>
<p>the images shows my problem </p>
<p><a href="http://i.stack.imgur.com/LcBqP.png" rel="nofollow">Emily</a></p>
<p><a href="http://i.stack.imgur.com/kF5Vs.png" rel="nofollow">John's signal</a></p>
<p>What is wrong on the code that doesnt make me use both signals?</p>
| 0 | 2016-08-26T05:19:27Z | 39,158,878 | <p>It looks like you have a "copy and paste" error. After reading <code>audio2.wav</code>, this line</p>
<pre><code>v = np.float64(u)
</code></pre>
<p>should be </p>
<pre><code>v = np.float64(v)
</code></pre>
<p>(Now that you see it is a trivial mistake, feel free to delete your question!)</p>
<hr>
<p>P.S. Using <code>np.float64</code> works, but the idiomatic way to do this with numpy is:</p>
<pre><code>v = v.astype(np.float64)
</code></pre>
| 0 | 2016-08-26T05:30:45Z | [
"python",
"numpy",
"audio",
"wave",
"pyaudio"
] |
Iterating through a list and using ltems of other lists | 39,158,795 | <pre><code>l = ['hello','hi']
a=[1,2,3,4]
b=[4,5,6,7]
for i in l:
func(x=a[index],y=b[index])
</code></pre>
<p>Now when I'm iterating through l , in the first iteration i want to use first a[0]and b[0] for a function and then use a[1] and b[1] for the same function</p>
<p>And in the second iteration of l,i want to use first a[2]and b[2] for the function and then use a[3] and b[3] for the same function.</p>
<p>Any recommendations would be appreciated.</p>
| 1 | 2016-08-26T05:22:47Z | 39,158,858 | <pre><code>>>> l = ['hello','hi']
>>> a=[1,2,3,4]
>>> b=[4,5,6,7]
>>> for i, val in enumerate(l):
... print '---iteration', i
... print 'l:', val
... print 'a:', a[2*i], ', b:', b[2*i]
... print 'a:', a[2*i+1], ' b:', b[2*i+1]
...
---iteration 0
l: hello
a: 1 , b: 4
a: 2 b: 5
---iteration 1
l: hi
a: 3 , b: 6
a: 4 b: 7
</code></pre>
| 2 | 2016-08-26T05:29:53Z | [
"python",
"python-2.7"
] |
Iterating through a list and using ltems of other lists | 39,158,795 | <pre><code>l = ['hello','hi']
a=[1,2,3,4]
b=[4,5,6,7]
for i in l:
func(x=a[index],y=b[index])
</code></pre>
<p>Now when I'm iterating through l , in the first iteration i want to use first a[0]and b[0] for a function and then use a[1] and b[1] for the same function</p>
<p>And in the second iteration of l,i want to use first a[2]and b[2] for the function and then use a[3] and b[3] for the same function.</p>
<p>Any recommendations would be appreciated.</p>
| 1 | 2016-08-26T05:22:47Z | 39,177,025 | <p>You can use the index method to find the index of the element of the list you are iterating through. Using that index you can find the element from the list you want to pass to the function.</p>
<pre><code>l = ['hello','hi']
a=[1,2,3,4]
b=[4,5,6,7]
def demo(x, y):
print x, y
for i in l:
print i
idx = 2*(l.index(i))
demo(x=a[idx],y=b[idx])
demo(x=a[idx+1],y=b[idx+1])
</code></pre>
<p>Instead of calculating the index for <code>a</code> and <code>b</code> inside the call to <code>demo()</code>, I prefer to calculate it before hand. Because, each calculation has complexity of <code>O(1)</code>, and if I am doing the same inside the call to <code>demo</code> (i.e. if I'm doing <code>demo(x=a[2*(l.index(i))],y=b[2*(l.index(i))])</code>) , then I am ending up calculating the index twice which results a complexity of <code>O(2)</code>. In the same way I am accessing the list <code>l</code> twice, which also adds overhead to complexity calculation. Therefore, calculating the index beforehand, accesses the list <code>l</code> once and reduces the complexity by 2 times for each call to <code>demo</code> thus by 4 times.</p>
| 0 | 2016-08-27T02:57:02Z | [
"python",
"python-2.7"
] |
Python Regex and group function | 39,158,859 | <p>Hi trying to separate each of the expressions from the colon. So want to obtain 'ss_vv', 'kk' and 'pp'. But the two print expressions below give me 'v' and 'k', so getting parts only of each string. Can anyone see what wrong here? </p>
<pre><code>m0 = re.compile(r'([a-z]|_)+:([a-z]|_)+:([a-z]|_)+')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)
</code></pre>
| 0 | 2016-08-26T05:29:53Z | 39,158,945 | <pre><code>In [52]: m0 = re.compile(r'([a-z|_]+):([a-z|_]+):([a-z|_]+)')
In [53]: m1 = m0.search('ss_vv:kk:pp')
In [54]: print m1.group(1)
ss_vv
In [55]: print m1.group(2)
kk
In [56]: print m1.group(3)
pp
</code></pre>
<p>What my regex does:</p>
<pre><code>([a-z|_]+):([a-z|_]+):([a-z|_]+)
</code></pre>
<p><img src="https://www.debuggex.com/i/GLOmQniLEruFOdRF.png" alt="Regular expression visualization"></p>
<p><a href="https://www.debuggex.com/r/GLOmQniLEruFOdRF" rel="nofollow">Debuggex Demo</a></p>
<p>What your regex does:</p>
<pre><code>([a-z]|_)+:([a-z]|_)+:([a-z]|_)+
</code></pre>
<p><img src="https://www.debuggex.com/i/RMei9CVdMLW4aEkE.png" alt="Regular expression visualization"></p>
<p><a href="https://www.debuggex.com/r/RMei9CVdMLW4aEkE" rel="nofollow">Debuggex Demo</a></p>
| 4 | 2016-08-26T05:35:41Z | [
"python",
"regex"
] |
Python Regex and group function | 39,158,859 | <p>Hi trying to separate each of the expressions from the colon. So want to obtain 'ss_vv', 'kk' and 'pp'. But the two print expressions below give me 'v' and 'k', so getting parts only of each string. Can anyone see what wrong here? </p>
<pre><code>m0 = re.compile(r'([a-z]|_)+:([a-z]|_)+:([a-z]|_)+')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)
</code></pre>
| 0 | 2016-08-26T05:29:53Z | 39,158,948 | <p>No need to use regex for your case. You can just split on basis of ':' and get required output..</p>
<pre><code>>>> a = 'ss_vv:kk:pp'
>>> b_list = a.split(':')
>>> b_list
['ss_vv', 'kk', 'pp']
>>>
</code></pre>
| 1 | 2016-08-26T05:35:55Z | [
"python",
"regex"
] |
Python Regex and group function | 39,158,859 | <p>Hi trying to separate each of the expressions from the colon. So want to obtain 'ss_vv', 'kk' and 'pp'. But the two print expressions below give me 'v' and 'k', so getting parts only of each string. Can anyone see what wrong here? </p>
<pre><code>m0 = re.compile(r'([a-z]|_)+:([a-z]|_)+:([a-z]|_)+')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)
</code></pre>
| 0 | 2016-08-26T05:29:53Z | 39,159,009 | <p>What are the other rules for the regular expression? based on your question, this regex would do:</p>
<pre><code>m0 = re.compile(r'(.*):(.*):(.*)')
m1 = m0.search('ss_vv:kk:pp')
print m1.group(1)
print m1.group(2)
</code></pre>
<p><strong>UPDATE:</strong>
as mentioned by @Jan in the comments, for efficient and better use of regex, you can modify it as </p>
<pre><code>regex = r'([^:]+):([^:]+):([^:]+)'
m0 = re.compile(regex)
</code></pre>
<p>output:</p>
<pre><code>ss_vv
kk
</code></pre>
<p>or by just splitting the string:</p>
<pre><code>string = 'ss_vv:kk:pp'
parts = string.split(':')
print parts
outputs: ['ss_vv', 'kk', 'pp']
</code></pre>
| 2 | 2016-08-26T05:40:57Z | [
"python",
"regex"
] |
Extract data from an HTML tag which has specific attributes | 39,158,931 | <pre><code><tr bgcolor="#FFFFFF">
<td class="tablecontent" scope="row" rowspan="1">
<a href="http://netprofile-us2/netprofile/npIndex.do?cpyKey=80823">ZURICH AMERICAN INSURANCE COMPANY</a>
</td>
<td class="tablecontent" scope="row" rowspan="1">
FARMERS GROUP INC (14523)
</td>
<td class="tablecontent" scope="row">
znaf
</td>
<td class="tablecontent" scope="row">
anhm
</td>
</tr>
</code></pre>
<p>I have an HTML document which contains multiple <code>tr</code> tags. I want to extract the <code>href</code> link from the first <code>td</code> and data from third <code>td</code> tag onwards under every <code>tr</code> tag. How can this be achieved?</p>
| -1 | 2016-08-26T05:34:08Z | 39,164,693 | <p>You can use css selector <code>nth-of-type</code> to navigate through the <code>td</code>s</p>
<p>Here's a sample"</p>
<pre><code>soup = BeautifulSoup(html, 'html.parser')
a = soup.select('td:nth-of-type(1) a')[0]
href = a['href']
td = soup.select("td:nth-of-type(3)")[0]
text = td.get_text(strip=True)
</code></pre>
| 0 | 2016-08-26T10:58:06Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
Extract data from an HTML tag which has specific attributes | 39,158,931 | <pre><code><tr bgcolor="#FFFFFF">
<td class="tablecontent" scope="row" rowspan="1">
<a href="http://netprofile-us2/netprofile/npIndex.do?cpyKey=80823">ZURICH AMERICAN INSURANCE COMPANY</a>
</td>
<td class="tablecontent" scope="row" rowspan="1">
FARMERS GROUP INC (14523)
</td>
<td class="tablecontent" scope="row">
znaf
</td>
<td class="tablecontent" scope="row">
anhm
</td>
</tr>
</code></pre>
<p>I have an HTML document which contains multiple <code>tr</code> tags. I want to extract the <code>href</code> link from the first <code>td</code> and data from third <code>td</code> tag onwards under every <code>tr</code> tag. How can this be achieved?</p>
| -1 | 2016-08-26T05:34:08Z | 39,168,372 | <p>You can find all <code>tr</code> elements, iterate over them, then do the context-specific searches for the inner <code>td</code> elements and get the first and the third:</p>
<pre><code>for tr in soup.find_all('tr'):
cells = tr.find_all('td')
if len(cells) < 3:
continue # safety pillow
link = cells[0].a['href'] # assuming every first td has an "a" element
data = cells[2].get_text()
print(link, data)
</code></pre>
<p>As a side note and depending what you are trying to accomplish in the HTML parsing, I usually find <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="nofollow"><code>pandas.read_html()</code></a> a great and convenient way to parse HTML tables into <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow">dataframes</a> and work with the dataframes after, which are quite convenient data structures to work with.</p>
| 1 | 2016-08-26T14:13:16Z | [
"python",
"python-2.7",
"beautifulsoup"
] |
How to get a single value from gae ndb query? | 39,158,983 | <p>I'm using Google App Engine with ndb backend and I want to get a single value ex: <code>int</code> from the ndb entity, after any query I get the whole entity with a projection, in my case I have a Transactions entity and I want to sum the amount properties.</p>
<p>What I'm using now is list comprehension on the query result like:</p>
<pre><code>query = ndb.gql("select amount from Transactions").fetch()
result = sum([x.amount for x in query])
</code></pre>
<p>Is there any way to make ndb query returns a list of amounts only, so, I can sum the query result directly like:</p>
<pre><code>query = ndb.gql("select amount from Transactions").fetch()
result = sum(query)
</code></pre>
<p>Thanks in advance</p>
| 0 | 2016-08-26T05:39:00Z | 39,163,351 | <p>There is no direct way to get list of values from projection fetch (I suppose you are looking for ndb analog of django orm Transactions.query().all().values()), you may do as follows:</p>
<pre><code>result = sum([x.amount for x in Transactions.query().fetch(
projection=[Transactions.amount,])])
</code></pre>
<p><a href="https://cloud.google.com/appengine/docs/python/ndb/projectionqueries" rel="nofollow">https://cloud.google.com/appengine/docs/python/ndb/projectionqueries</a></p>
| 1 | 2016-08-26T09:46:43Z | [
"python",
"google-app-engine",
"app-engine-ndb",
"gql",
"gqlquery"
] |
How to implement SNMP in python? | 39,159,059 | <p>I am now currently working with SNMP. The package I used is pysnmp but I do not know how to implement snmp in python. The problem is, given an ip address, it should give the details of that device using snmp. Could anyone suggest me how to do it?</p>
| -5 | 2016-08-26T05:44:47Z | 39,170,725 | <p>If I was in your shoes, I'd read briefly on the <a href="http://pysnmp.sourceforge.net/docs/tutorial.html" rel="nofollow">subject</a> e.g. how SNMP is designed and how it is typically used. Then I'd try to use ready-made <a href="http://pysnmp.sourceforge.net/examples/hlapi/asyncore/sync/manager/cmdgen/walking-operations.html" rel="nofollow">code snippets</a> in hope that they fulfill your immediate need.</p>
<p>Once you progress in getting better understanding of the technology and being able asking more concrete questions, SO community might welcome you! ;-)</p>
| 0 | 2016-08-26T16:22:23Z | [
"python",
"ip",
"snmp",
"pysnmp"
] |
Is there a direct way to ignore parts of a python datetime object? | 39,159,092 | <p>I'm trying to compare two datetime objects, but ignoring the year. For example, given</p>
<pre><code>a = datetime.datetime(2015,07,04,01,01,01)
b = datetime.datetime(2016,07,04,01,01,01)
</code></pre>
<p>I want a == b to return True by ignoring the year. To do a comparison like this, I imagine I could just create new datetime objects with the same year like:</p>
<pre><code>c = datetime.datetime(2014,a.month,a.day,a.hour,a.minute,a.second)
d = datetime.datetime(2014,b.month,b.day,b.hour,b.minute,b.second)
</code></pre>
<p>However, this doesn't seem very pythonic. Is there a more direct method to do a comparison like what I'm asking?</p>
<p>I'm using python 3.4.</p>
| 3 | 2016-08-26T05:47:26Z | 39,159,198 | <pre><code>(a.month, a.day, a.hour, a.minute, a.second ==
b.month, b.day, b.hour, b.minute, b.second)
</code></pre>
<p>A less explicit method is to compare the corresponding elements in the time tuples:</p>
<pre><code>a.timetuple()[1:6] == b.timetuple()[1:6]
</code></pre>
| 8 | 2016-08-26T05:56:26Z | [
"python",
"datetime"
] |
Is there a direct way to ignore parts of a python datetime object? | 39,159,092 | <p>I'm trying to compare two datetime objects, but ignoring the year. For example, given</p>
<pre><code>a = datetime.datetime(2015,07,04,01,01,01)
b = datetime.datetime(2016,07,04,01,01,01)
</code></pre>
<p>I want a == b to return True by ignoring the year. To do a comparison like this, I imagine I could just create new datetime objects with the same year like:</p>
<pre><code>c = datetime.datetime(2014,a.month,a.day,a.hour,a.minute,a.second)
d = datetime.datetime(2014,b.month,b.day,b.hour,b.minute,b.second)
</code></pre>
<p>However, this doesn't seem very pythonic. Is there a more direct method to do a comparison like what I'm asking?</p>
<p>I'm using python 3.4.</p>
| 3 | 2016-08-26T05:47:26Z | 39,159,319 | <pre><code>def cmp(a,b):
return (a > b) - (a < b)
d1=(2015,7,4,1,1,1)
d2=(2016,7,4,1,1,1)
cmp(list(d1)[1:],list(d2)[1:])
</code></pre>
<p>Returns 0 - they are the same, i.e. 0 differences</p>
<pre><code>d1=(2015,7,4,1,1,1)
d2=(2015,2,4,1,1,1)
cmp(list(d1)[1:], list(d2)[1:])
</code></pre>
<p>returns -1, there is a difference.</p>
| 1 | 2016-08-26T06:04:13Z | [
"python",
"datetime"
] |
Is there a direct way to ignore parts of a python datetime object? | 39,159,092 | <p>I'm trying to compare two datetime objects, but ignoring the year. For example, given</p>
<pre><code>a = datetime.datetime(2015,07,04,01,01,01)
b = datetime.datetime(2016,07,04,01,01,01)
</code></pre>
<p>I want a == b to return True by ignoring the year. To do a comparison like this, I imagine I could just create new datetime objects with the same year like:</p>
<pre><code>c = datetime.datetime(2014,a.month,a.day,a.hour,a.minute,a.second)
d = datetime.datetime(2014,b.month,b.day,b.hour,b.minute,b.second)
</code></pre>
<p>However, this doesn't seem very pythonic. Is there a more direct method to do a comparison like what I'm asking?</p>
<p>I'm using python 3.4.</p>
| 3 | 2016-08-26T05:47:26Z | 39,159,366 | <p>You can also consider comparing formatted date strings consisting of the fields you wish to include in the comparison. This allows you to be somewhat explicit while using shortened versions of the fields (as opposed to accessing <code>a.year</code>, <code>a.month</code>, etc.).</p>
<pre><code>from datetime import datetime
date_string = '%m %d %H %M %S'
a = datetime(2015, 7, 4, 1, 1, 1)
b = datetime(2016, 7, 4, 1, 1, 1)
print(a.strftime(date_string) == b.strftime(date_string)) # True
</code></pre>
| 3 | 2016-08-26T06:07:10Z | [
"python",
"datetime"
] |
Is there a direct way to ignore parts of a python datetime object? | 39,159,092 | <p>I'm trying to compare two datetime objects, but ignoring the year. For example, given</p>
<pre><code>a = datetime.datetime(2015,07,04,01,01,01)
b = datetime.datetime(2016,07,04,01,01,01)
</code></pre>
<p>I want a == b to return True by ignoring the year. To do a comparison like this, I imagine I could just create new datetime objects with the same year like:</p>
<pre><code>c = datetime.datetime(2014,a.month,a.day,a.hour,a.minute,a.second)
d = datetime.datetime(2014,b.month,b.day,b.hour,b.minute,b.second)
</code></pre>
<p>However, this doesn't seem very pythonic. Is there a more direct method to do a comparison like what I'm asking?</p>
<p>I'm using python 3.4.</p>
| 3 | 2016-08-26T05:47:26Z | 39,159,367 | <p>Try:</p>
<pre><code>a.replace(year=1,microsecond=0) == b.replace(year=1,microsecond=0)
</code></pre>
| 5 | 2016-08-26T06:07:14Z | [
"python",
"datetime"
] |
Is there a direct way to ignore parts of a python datetime object? | 39,159,092 | <p>I'm trying to compare two datetime objects, but ignoring the year. For example, given</p>
<pre><code>a = datetime.datetime(2015,07,04,01,01,01)
b = datetime.datetime(2016,07,04,01,01,01)
</code></pre>
<p>I want a == b to return True by ignoring the year. To do a comparison like this, I imagine I could just create new datetime objects with the same year like:</p>
<pre><code>c = datetime.datetime(2014,a.month,a.day,a.hour,a.minute,a.second)
d = datetime.datetime(2014,b.month,b.day,b.hour,b.minute,b.second)
</code></pre>
<p>However, this doesn't seem very pythonic. Is there a more direct method to do a comparison like what I'm asking?</p>
<p>I'm using python 3.4.</p>
| 3 | 2016-08-26T05:47:26Z | 39,159,370 | <pre><code>In [70]: a
Out[70]: datetime.datetime(2015, 7, 4, 0, 0)
In [71]: b
Out[71]: datetime.datetime(2016, 7, 4, 0, 0)
In [72]: def my_date_cmp(a, b):
....: return a.replace(year = b.year) == b
....:
In [73]: my_date_cmp(a, b)
Out[73]: True
</code></pre>
| 0 | 2016-08-26T06:07:22Z | [
"python",
"datetime"
] |
Looping through (and opening) specific types of files in folder? | 39,159,131 | <p>I want to loop through files with a certain extension in a folder, in this case .txt, open the file, and print matches for a regex pattern. When I run my program however, it only prints results for one file out of the two in the folder:</p>
<blockquote>
<p>Anthony is too cool for school. I Reported the criminal. I am Cool.</p>
</blockquote>
<pre><code>1: A, I, R, I, C
</code></pre>
<p>My second file contains the text:</p>
<blockquote>
<p>Oh My initials are AK</p>
</blockquote>
<p>And finally my code:</p>
<pre><code>import re, os
Regex = re.compile(r'[A-Z]')
filepath =input('Enter a folder path: ')
files = os.listdir(filepath)
count = 0
for file in files:
if '.txt' not in file:
del files[files.index(file)]
continue
count += 1
fileobj = open(os.path.join(filepath, file), 'r')
filetext = fileobj.read()
Matches = Regex.findall(filetext)
print(str(count)+': ' +', '.join(Matches), end = ' ')
fileobj.close()
</code></pre>
<p>Is there a way to loop through (and open) a list of files? Is it because I assign every File Object returned by <code>open(os.path.join(filepath, file), 'r')</code> to the same name <code>fileobj</code>?</p>
| 0 | 2016-08-26T05:50:19Z | 39,159,248 | <p>U can do as simple as this :(its just a loop through file)</p>
<pre><code>import re, os
Regex = re.compile(r'[A-Z]')
filepath =input('Enter a folder path: ')
files = os.listdir(filepath)
count = 0
for file in files:
if '.txt' in file:
fileobj = open(os.path.join(filepath, file), 'r')
filetext = fileobj.read()
Matches = Regex.findall(filetext)
print(str(count)+': ' +', '.join(Matches), end == ' ')
fileobj.close()
</code></pre>
| 1 | 2016-08-26T05:59:25Z | [
"python",
"regex",
"loops",
"operating-system"
] |
Looping through (and opening) specific types of files in folder? | 39,159,131 | <p>I want to loop through files with a certain extension in a folder, in this case .txt, open the file, and print matches for a regex pattern. When I run my program however, it only prints results for one file out of the two in the folder:</p>
<blockquote>
<p>Anthony is too cool for school. I Reported the criminal. I am Cool.</p>
</blockquote>
<pre><code>1: A, I, R, I, C
</code></pre>
<p>My second file contains the text:</p>
<blockquote>
<p>Oh My initials are AK</p>
</blockquote>
<p>And finally my code:</p>
<pre><code>import re, os
Regex = re.compile(r'[A-Z]')
filepath =input('Enter a folder path: ')
files = os.listdir(filepath)
count = 0
for file in files:
if '.txt' not in file:
del files[files.index(file)]
continue
count += 1
fileobj = open(os.path.join(filepath, file), 'r')
filetext = fileobj.read()
Matches = Regex.findall(filetext)
print(str(count)+': ' +', '.join(Matches), end = ' ')
fileobj.close()
</code></pre>
<p>Is there a way to loop through (and open) a list of files? Is it because I assign every File Object returned by <code>open(os.path.join(filepath, file), 'r')</code> to the same name <code>fileobj</code>?</p>
| 0 | 2016-08-26T05:50:19Z | 39,159,640 | <p>The <code>del</code> is causing the problem. The <code>for</code> loop have no idea if you delete an element or not, so it always advances. There might be a hidden file in the directory, and it is the first element in the files. After it got deleted, the for loop skips one of the files and then reads the second one. To verify, you can print out the <code>files</code> and the <code>file</code> at the beginning of each loop. In short, <strong>removing the <code>del</code> line should solve the problem</strong>.</p>
<p>If this is a standalone script, bash might be more clean:</p>
<pre><code>count=0
for file in "$1"/*.txt; do
echo -n "${count}: $(grep -o '[A-Z]' "$file" | tr "\n" ",") "
((count++))
done
</code></pre>
| 0 | 2016-08-26T06:27:31Z | [
"python",
"regex",
"loops",
"operating-system"
] |
Looping through (and opening) specific types of files in folder? | 39,159,131 | <p>I want to loop through files with a certain extension in a folder, in this case .txt, open the file, and print matches for a regex pattern. When I run my program however, it only prints results for one file out of the two in the folder:</p>
<blockquote>
<p>Anthony is too cool for school. I Reported the criminal. I am Cool.</p>
</blockquote>
<pre><code>1: A, I, R, I, C
</code></pre>
<p>My second file contains the text:</p>
<blockquote>
<p>Oh My initials are AK</p>
</blockquote>
<p>And finally my code:</p>
<pre><code>import re, os
Regex = re.compile(r'[A-Z]')
filepath =input('Enter a folder path: ')
files = os.listdir(filepath)
count = 0
for file in files:
if '.txt' not in file:
del files[files.index(file)]
continue
count += 1
fileobj = open(os.path.join(filepath, file), 'r')
filetext = fileobj.read()
Matches = Regex.findall(filetext)
print(str(count)+': ' +', '.join(Matches), end = ' ')
fileobj.close()
</code></pre>
<p>Is there a way to loop through (and open) a list of files? Is it because I assign every File Object returned by <code>open(os.path.join(filepath, file), 'r')</code> to the same name <code>fileobj</code>?</p>
| 0 | 2016-08-26T05:50:19Z | 39,159,867 | <p><strong>glob module</strong> will help you much more since you want to read files with specific extension.</p>
<p>You can directly get list of files with extension "txt" i.e. you saved one <strong>'if'</strong> construct.</p>
<p>More info on <a href="https://pymotw.com/2/glob/" rel="nofollow">glob module</a>.</p>
<p>Code will be less and more readable.</p>
<pre><code>import glob
for file_name in glob.glob(r'C:/Users/dinesh_pundkar\Desktop/*.txt'):
with open(file_name,'r') as f:
text = f.read()
"""
After this you can add code for Regex matching,
which will match pattern in file text.
"""
</code></pre>
| 0 | 2016-08-26T06:41:43Z | [
"python",
"regex",
"loops",
"operating-system"
] |
Label Not Showing in Odoo-9 | 39,159,296 | <p>I created a boolean field. The boolean is showing but the label isn't.</p>
<pre><code>class product_pricelist_inherit(models.Model):
_inherit = 'product.pricelist'
myfield= fields.Boolean(string="Is this Pricelist Eligible for Me?")
</code></pre>
<p>XML:</p>
<pre><code><odoo>
<record id="product_product_pricelist_view" model="ir.ui.view">
<field name="model">product.pricelist</field>
<field name="inherit_id" ref="product.product_pricelist_view"/>
<field name="arch" type="xml">
<field name="name" position="after">
<field name="myfield"/>
</field>
</field>
</record>
</odoo>
</code></pre>
| 5 | 2016-08-26T06:02:40Z | 39,159,432 | <p>It will not show your field label because you have added field in <code><div></code></p>
<p>Try with following code.</p>
<p>Replace </p>
<pre><code><field name="myfield"/>
</code></pre>
<p>with</p>
<pre><code><label for="myfield"/>
<field name="myfield"/>
</code></pre>
| 3 | 2016-08-26T06:12:03Z | [
"python",
"xml",
"openerp",
"odoo-9"
] |
Label Not Showing in Odoo-9 | 39,159,296 | <p>I created a boolean field. The boolean is showing but the label isn't.</p>
<pre><code>class product_pricelist_inherit(models.Model):
_inherit = 'product.pricelist'
myfield= fields.Boolean(string="Is this Pricelist Eligible for Me?")
</code></pre>
<p>XML:</p>
<pre><code><odoo>
<record id="product_product_pricelist_view" model="ir.ui.view">
<field name="model">product.pricelist</field>
<field name="inherit_id" ref="product.product_pricelist_view"/>
<field name="arch" type="xml">
<field name="name" position="after">
<field name="myfield"/>
</field>
</field>
</record>
</odoo>
</code></pre>
| 5 | 2016-08-26T06:02:40Z | 39,167,275 | <p>You can use <code>group</code> to show field label: </p>
<pre><code><group>
<field name="myfield"/>
</group>
</code></pre>
<p>There is a <code>group</code> just after <code>name</code> field, It can be done using <code>xpath</code>: </p>
<pre><code><xpath expr="//group" position="inside">
<field name="myfield"/>
</xpath>
</code></pre>
<p>For the first example you can use <code>position="before"</code></p>
| 1 | 2016-08-26T13:16:18Z | [
"python",
"xml",
"openerp",
"odoo-9"
] |
Python Multithreading vs Multiprocessing vs Sequential Execution | 39,159,438 | <p>I have the below code:</p>
<pre><code>import time
from threading import Thread
from multiprocessing import Process
def fun1():
for _ in xrange(10000000):
print 'in fun1'
pass
def fun2():
for _ in xrange(10000000):
print 'in fun2'
pass
def fun3():
for _ in xrange(10000000):
print 'in fun3'
pass
def fun4():
for _ in xrange(10000000):
print 'in fun4'
pass
if __name__ == '__main__':
#t1 = Thread(target=fun1, args=())
t1 = Process(target=fun1, args=())
#t2 = Thread(target=fun2, args=())
t2 = Process(target=fun2, args=())
#t3 = Thread(target=fun3, args=())
t3 = Process(target=fun3, args=())
#t4 = Thread(target=fun4, args=())
t4 = Process(target=fun4, args=())
t1.start()
t2.start()
t3.start()
t4.start()
start = time.clock()
t1.join()
t2.join()
t3.join()
t4.join()
end = time.clock()
print("Time Taken = ",end-start)
'''
start = time.clock()
fun1()
fun2()
fun3()
fun4()
end = time.clock()
print("Time Taken = ",end-start)
'''
</code></pre>
<p>I ran the above program in three ways:</p>
<ul>
<li>First Sequential Execution ALONE(look at the commented code and comment the upper code)</li>
<li>Second Multithreaded Execution ALONE</li>
<li>Third Multiprocessing Execution ALONE</li>
</ul>
<p>The observations for end_time-start time are as follows:</p>
<p>Overall Running times</p>
<ul>
<li>('Time Taken = ', <strong>342.5981313667716</strong>) --- Running time by <strong>threaded execution</strong></li>
<li>('Time Taken = ', <strong>232.94691744899296</strong>) --- Running time by <strong>sequential Execution</strong></li>
<li>('Time Taken = ', <strong>307.91093406618216</strong>) --- Running time by <strong>Multiprocessing execution</strong></li>
</ul>
<p><strong>Question :</strong> </p>
<p>I see sequential execution takes least time and Multithreading takes highest time. Why? I am unable to understand and also surprised by results.Please clarify.</p>
<p>Since this is a CPU intensive task and GIL is acquired, my understanding was
Multiprocessing would take least time while threaded execution would take highest time.Please validate my understanding. </p>
| 4 | 2016-08-26T06:12:36Z | 39,159,940 | <p>You use <code>time.clock</code>, wich gave you CPU time and not real time : you can't use that in your case, as it gives you the execution time (how long did you use the CPU to run your code, wich will be almost the same time for each of these case)</p>
<p>Running your code with <code>time.time()</code> instead of <code>time.clock</code> gave me these time on my computer : </p>
<pre><code>Process : ('Time Taken = ', 5.226783990859985)
seq : ('Time Taken = ', 6.3122560000000005)
Thread : ('Time Taken = ', 17.10062599182129)
</code></pre>
<p>The task given here (printing) is so fast that the speedup from using multiprocessing is almost balanced by the overhead.</p>
<p>For <code>Threading</code>, as you can only have one Thread running because of the GIL, you end up running all your functions sequentially BUT you had the overhead of threading (changing threads every few iterations can cost up to several milliseconds each time). So you end up with something much slower.</p>
<p><code>Threading</code> is usefull if you have waiting times, so you can run tasks in between.</p>
<p><code>Multiprocessing</code> is usefull for computationnally expensive tasks, if possible completely independant (no shared variables). If you need to share variables, then you have to face the GIL and it's a little bit more complicated (but not impossible most of the time).</p>
<p>EDIT : Actually, using <code>time.clock</code> like you did gave you the information about how much overhead using <code>Threading</code> and <code>Multiprocessing</code> cost you.</p>
| 4 | 2016-08-26T06:46:09Z | [
"python",
"multithreading",
"python-2.7",
"multiprocessing"
] |
Python Multithreading vs Multiprocessing vs Sequential Execution | 39,159,438 | <p>I have the below code:</p>
<pre><code>import time
from threading import Thread
from multiprocessing import Process
def fun1():
for _ in xrange(10000000):
print 'in fun1'
pass
def fun2():
for _ in xrange(10000000):
print 'in fun2'
pass
def fun3():
for _ in xrange(10000000):
print 'in fun3'
pass
def fun4():
for _ in xrange(10000000):
print 'in fun4'
pass
if __name__ == '__main__':
#t1 = Thread(target=fun1, args=())
t1 = Process(target=fun1, args=())
#t2 = Thread(target=fun2, args=())
t2 = Process(target=fun2, args=())
#t3 = Thread(target=fun3, args=())
t3 = Process(target=fun3, args=())
#t4 = Thread(target=fun4, args=())
t4 = Process(target=fun4, args=())
t1.start()
t2.start()
t3.start()
t4.start()
start = time.clock()
t1.join()
t2.join()
t3.join()
t4.join()
end = time.clock()
print("Time Taken = ",end-start)
'''
start = time.clock()
fun1()
fun2()
fun3()
fun4()
end = time.clock()
print("Time Taken = ",end-start)
'''
</code></pre>
<p>I ran the above program in three ways:</p>
<ul>
<li>First Sequential Execution ALONE(look at the commented code and comment the upper code)</li>
<li>Second Multithreaded Execution ALONE</li>
<li>Third Multiprocessing Execution ALONE</li>
</ul>
<p>The observations for end_time-start time are as follows:</p>
<p>Overall Running times</p>
<ul>
<li>('Time Taken = ', <strong>342.5981313667716</strong>) --- Running time by <strong>threaded execution</strong></li>
<li>('Time Taken = ', <strong>232.94691744899296</strong>) --- Running time by <strong>sequential Execution</strong></li>
<li>('Time Taken = ', <strong>307.91093406618216</strong>) --- Running time by <strong>Multiprocessing execution</strong></li>
</ul>
<p><strong>Question :</strong> </p>
<p>I see sequential execution takes least time and Multithreading takes highest time. Why? I am unable to understand and also surprised by results.Please clarify.</p>
<p>Since this is a CPU intensive task and GIL is acquired, my understanding was
Multiprocessing would take least time while threaded execution would take highest time.Please validate my understanding. </p>
| 4 | 2016-08-26T06:12:36Z | 39,160,139 | <p>Basically you're right.
What platform do you use to run the code snippet? I guess Windows.
Be noticed that "print" <strong>is not CPU bound</strong> so you should comment out "print" and try to run it on Linux to see the difference (It should be what you expect).
Use code like this:</p>
<pre><code>def fun1():
for _ in xrange(10000000):
# No print, and please run on linux
pass
</code></pre>
| 0 | 2016-08-26T06:57:05Z | [
"python",
"multithreading",
"python-2.7",
"multiprocessing"
] |
pandas: how to do multiple groupby-apply operations | 39,159,475 | <p>I have more experience with Râs <code>data.table</code>, but am trying to learn <code>pandas</code>. In <code>data.table</code>, I can do something like this:</p>
<pre><code>> head(dt_m)
event_id device_id longitude latitude time_ category
1: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
2: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
3: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
4: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
5: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
6: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
app_id is_active
1: -5305696816021977482 0
2: -7164737313972860089 0
3: -8504475857937456387 0
4: -8807740666788515175 0
5: 5302560163370202064 0
6: 5521284031585796822 0
dt_m_summary <- dt_m[,
.(
mean_active = mean(is_active, na.rm = TRUE)
, median_lat = median(latitude, na.rm = TRUE)
, median_lon = median(longitude, na.rm = TRUE)
, mean_time = mean(time_)
, new_col = your_function(latitude, longitude, time_)
)
, by = list(device_id, category)
]
</code></pre>
<p>The new columns (<code>mean_active</code> through <code>new_col</code>), as well as <code>device_id</code> and <code>category</code>, will appear in <code>dt_m_summary</code>. I could also do a similar <code>by</code> transformation in the original table if I want a new column that has the results of the groupby-apply:</p>
<p><code>dt_m[, mean_active := mean(is_active, na.rm = TRUE), by = list(device_id, category)]</code></p>
<p>(in case I wanted, e.g., to select rows where <code>mean_active</code> is greater than some threshold, or do something else).</p>
<p>I know there is <code>groupby</code> in <code>pandas</code>, but I havenât found a way of doing the sort of easy transformations as above. The best I could think of was doing a series of groupby-applyâs and then merging the results into one <code>dataframe</code>, but that seems very clunky. Is there a better way of doing that?</p>
| 6 | 2016-08-26T06:14:58Z | 39,159,561 | <p>IIUC, use <code>groupby</code> and <code>agg</code>. See <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#applying-multiple-functions-at-once" rel="nofollow">docs</a> for more information.</p>
<pre><code>df = pd.DataFrame(np.random.rand(10, 2),
pd.MultiIndex.from_product([list('XY'), range(5)]),
list('AB'))
df
</code></pre>
<p><a href="http://i.stack.imgur.com/sqwqv.png" rel="nofollow"><img src="http://i.stack.imgur.com/sqwqv.png" alt="enter image description here"></a></p>
<pre><code>df.groupby(level=0).agg(['sum', 'count', 'std'])
</code></pre>
<p><a href="http://i.stack.imgur.com/NGOGJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/NGOGJ.png" alt="enter image description here"></a></p>
<hr>
<p>A more tailored example would be</p>
<pre><code># level=0 means group by the first level in the index
# if there is a specific column you want to group by
# use groupby('specific column name')
df.groupby(level=0).agg({'A': ['sum', 'std'],
'B': {'my_function': lambda x: x.sum() ** 2}})
</code></pre>
<p><a href="http://i.stack.imgur.com/HPtvm.png" rel="nofollow"><img src="http://i.stack.imgur.com/HPtvm.png" alt="enter image description here"></a></p>
<p><strong><em>Note</em></strong> the <code>dict</code> passed to the <code>agg</code> method has keys <code>'A'</code> and <code>'B'</code>. This means, run the functions <code>['sum', 'std']</code> for <code>'A'</code> and <code>lambda x: x.sum() ** 2</code> for <code>'B'</code> (and label it <code>'my_function'</code>)</p>
<p><strong><em>Note 2</em></strong> pertaining to your <code>new_column</code>. <code>agg</code> requires that the passed functions reduce columns to scalars. You're better off adding the new column ahead of the <code>groupby</code>/<code>agg</code></p>
| 7 | 2016-08-26T06:20:40Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
pandas: how to do multiple groupby-apply operations | 39,159,475 | <p>I have more experience with Râs <code>data.table</code>, but am trying to learn <code>pandas</code>. In <code>data.table</code>, I can do something like this:</p>
<pre><code>> head(dt_m)
event_id device_id longitude latitude time_ category
1: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
2: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
3: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
4: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
5: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
6: 1004583 -100015673884079572 NA NA 1970-01-01 06:34:52 1 free
app_id is_active
1: -5305696816021977482 0
2: -7164737313972860089 0
3: -8504475857937456387 0
4: -8807740666788515175 0
5: 5302560163370202064 0
6: 5521284031585796822 0
dt_m_summary <- dt_m[,
.(
mean_active = mean(is_active, na.rm = TRUE)
, median_lat = median(latitude, na.rm = TRUE)
, median_lon = median(longitude, na.rm = TRUE)
, mean_time = mean(time_)
, new_col = your_function(latitude, longitude, time_)
)
, by = list(device_id, category)
]
</code></pre>
<p>The new columns (<code>mean_active</code> through <code>new_col</code>), as well as <code>device_id</code> and <code>category</code>, will appear in <code>dt_m_summary</code>. I could also do a similar <code>by</code> transformation in the original table if I want a new column that has the results of the groupby-apply:</p>
<p><code>dt_m[, mean_active := mean(is_active, na.rm = TRUE), by = list(device_id, category)]</code></p>
<p>(in case I wanted, e.g., to select rows where <code>mean_active</code> is greater than some threshold, or do something else).</p>
<p>I know there is <code>groupby</code> in <code>pandas</code>, but I havenât found a way of doing the sort of easy transformations as above. The best I could think of was doing a series of groupby-applyâs and then merging the results into one <code>dataframe</code>, but that seems very clunky. Is there a better way of doing that?</p>
| 6 | 2016-08-26T06:14:58Z | 39,177,298 | <p>@piRSquared has a great answer but in your particular case I think you might be interested in using pandas very flexible <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow" title="apply function">apply function</a>. Because it can be applied to each group one at a time you can operate on multiple columns within the grouped DataFrame simultaneously.</p>
<pre><code>def your_function(sub_df):
return np.mean(np.cos(sub_df['latitude']) + np.sin(sub_df['longitude']) - np.tan(sub_df['time_']))
def group_function(g):
return pd.Series([g['is_active'].mean(), g['latitude'].median(), g['longitude'].median(), g['time_'].mean(), your_function(g)],
index=['mean_active', 'median_lat', 'median_lon', 'mean_time', 'new_col'])
dt_m.groupby(['device_id', 'category']).apply(group_function)
</code></pre>
<p>However, I definitely agree with @piRSquared that it would be very helpful to see a full example including expected output.</p>
| 0 | 2016-08-27T03:54:08Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Trouble with restoring pretrained model in tensorflow | 39,159,528 | <p>I ran the demo program of word2vec which is included in TensorFlow, and now trying to restore the pretrained model from files, but it doesn't work.</p>
<p>I ran this script file:
<a href="https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/models/embedding/word2vec.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/models/embedding/word2vec.py</a></p>
<p>Then I tried to run this file:</p>
<pre><code>#!/usr/bin/env python
import tensorflow as tf
FILENAME_META = "model.ckpt-70707299.meta"
FILENAME_CHECKPOINT = "model.ckpt-70707299"
def main():
with tf.Session() as sess:
saver = tf.train.import_meta_graph(FILENAME_META)
saver.restore(sess, FILENAME_CHECKPOINT)
if __name__ == '__main__':
main()
</code></pre>
<p>It fails with the following error message</p>
<pre><code>Traceback (most recent call last):
File "word2vec_restore.py", line 16, in <module>
main()
File "word2vec_restore.py", line 11, in main
saver = tf.train.import_meta_graph(FILENAME_META)
File "/home/kato/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/training/saver.py", line 1431, in import_meta_graph
return _import_meta_graph_def(read_meta_graph_file(meta_graph_or_file))
File "/home/kato/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/training/saver.py", line 1321, in _import_meta_graph_def
producer_op_list=producer_op_list)
File "/home/kato/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/framework/importer.py", line 247, in import_graph_def
op_def = op_dict[node.op]
KeyError: 'Skipgram'
</code></pre>
<p>I regard I have understood the API document of TensorFlow, and I implemented the code above as is written in it. Am I using the Saver object in a wrong way?</p>
| 0 | 2016-08-26T06:18:08Z | 39,161,774 | <p>Try the following:</p>
<pre><code>saver = tf.train.Saver()
with tf.Session() as sess:
checkpoint = tf.train.get_checkpoint_state(checkpoint_dir)
if checkpoint and checkpoint.model_checkpoint_path:
saver.restore(sess, checkpoint.model_checkpoint_path)
</code></pre>
<p>Where <code>checkpoint_dir</code>is path to folder that contains checkpoint files, not full path to meta or checkpoint files. Tensorflow picks the latest checkpoint itself from the specified folder.</p>
| 0 | 2016-08-26T08:28:42Z | [
"python",
"tensorflow",
"word2vec"
] |
Trouble with restoring pretrained model in tensorflow | 39,159,528 | <p>I ran the demo program of word2vec which is included in TensorFlow, and now trying to restore the pretrained model from files, but it doesn't work.</p>
<p>I ran this script file:
<a href="https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/models/embedding/word2vec.py" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/r0.10/tensorflow/models/embedding/word2vec.py</a></p>
<p>Then I tried to run this file:</p>
<pre><code>#!/usr/bin/env python
import tensorflow as tf
FILENAME_META = "model.ckpt-70707299.meta"
FILENAME_CHECKPOINT = "model.ckpt-70707299"
def main():
with tf.Session() as sess:
saver = tf.train.import_meta_graph(FILENAME_META)
saver.restore(sess, FILENAME_CHECKPOINT)
if __name__ == '__main__':
main()
</code></pre>
<p>It fails with the following error message</p>
<pre><code>Traceback (most recent call last):
File "word2vec_restore.py", line 16, in <module>
main()
File "word2vec_restore.py", line 11, in main
saver = tf.train.import_meta_graph(FILENAME_META)
File "/home/kato/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/training/saver.py", line 1431, in import_meta_graph
return _import_meta_graph_def(read_meta_graph_file(meta_graph_or_file))
File "/home/kato/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/training/saver.py", line 1321, in _import_meta_graph_def
producer_op_list=producer_op_list)
File "/home/kato/.pyenv/versions/3.5.1/lib/python3.5/site-packages/tensorflow/python/framework/importer.py", line 247, in import_graph_def
op_def = op_dict[node.op]
KeyError: 'Skipgram'
</code></pre>
<p>I regard I have understood the API document of TensorFlow, and I implemented the code above as is written in it. Am I using the Saver object in a wrong way?</p>
| 0 | 2016-08-26T06:18:08Z | 39,162,836 | <p>I solved this by myself. I wondered where the key 'Skipgram' comes from, and dug the source code. To solve the problem, just add the following on the top:</p>
<pre><code>from tensorflow.models.embedding import gen_word2vec
</code></pre>
<p>I still don't understand exactly what I am doing, but maybe this is because it is necessary to load a related library written in C++.</p>
<p>Thanks.</p>
| 0 | 2016-08-26T09:22:42Z | [
"python",
"tensorflow",
"word2vec"
] |
Find index of multiple queries in a multidimensional numpy array | 39,159,548 | <p>I am looking for a way to find indices of an array of queries in a multidimensional array. For example:</p>
<pre><code>arr = np.array([[17, 5, 19, 9],
[18, 13, 3, 7],
[ 8, 1, 4, 2],
[ 8, 9, 7, 19],
[ 6, 11, 8, 5],
[11, 16, 13, 18],
[ 0, 1, 2, 9],
[ 1, 7, 4, 6]])
</code></pre>
<p>I can find indices for one query:</p>
<pre><code>np.where(arr==1)
# (array([2, 6, 7]), array([1, 1, 0]))
</code></pre>
<p>Is there any numpy solution to do this for multiple values replacing the following <code>for</code> loop?</p>
<pre><code>for q in queries:
np.where(arr==q)
</code></pre>
<p>If both the array and queries were one-dimensional, I could use <code>searchsorted</code> as <a href="http://stackoverflow.com/a/9566681/3349443">this answer</a> but it doesn't work for multidimensional arrays.</p>
| 1 | 2016-08-26T06:19:37Z | 39,159,618 | <p>You can get the indices of each matching value by zipping the results of your <code>where</code> function and then using the <code>*</code> dereferencing operator.</p>
<pre><code>arr = np.array([[17, 5, 19, 9],
[18, 13, 3, 7],
[ 8, 1, 4, 2], # (2, 1)
[ 8, 9, 7, 19],
[ 6, 11, 8, 5],
[11, 16, 13, 18],
[ 0, 1, 2, 9], # (6, 1)
[ 1, 7, 4, 6]]) # (7, 0)
>>> zip(*np.where(arr == 1))
[(2, 1), (6, 1), (7, 0)]
</code></pre>
<p>I'm not sure what your intended output is, but you can use a dictionary comprehension to show the index location for a given set of numbers, e.g.:</p>
<pre><code>>>> {n: zip(*np.where(arr == n)) for n in range(5)}
{0: [(6, 0)],
1: [(2, 1), (6, 1), (7, 0)],
2: [(2, 3), (6, 2)],
3: [(1, 2)],
4: [(2, 2), (7, 2)]}
</code></pre>
| 0 | 2016-08-26T06:25:33Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] |
Find index of multiple queries in a multidimensional numpy array | 39,159,548 | <p>I am looking for a way to find indices of an array of queries in a multidimensional array. For example:</p>
<pre><code>arr = np.array([[17, 5, 19, 9],
[18, 13, 3, 7],
[ 8, 1, 4, 2],
[ 8, 9, 7, 19],
[ 6, 11, 8, 5],
[11, 16, 13, 18],
[ 0, 1, 2, 9],
[ 1, 7, 4, 6]])
</code></pre>
<p>I can find indices for one query:</p>
<pre><code>np.where(arr==1)
# (array([2, 6, 7]), array([1, 1, 0]))
</code></pre>
<p>Is there any numpy solution to do this for multiple values replacing the following <code>for</code> loop?</p>
<pre><code>for q in queries:
np.where(arr==q)
</code></pre>
<p>If both the array and queries were one-dimensional, I could use <code>searchsorted</code> as <a href="http://stackoverflow.com/a/9566681/3349443">this answer</a> but it doesn't work for multidimensional arrays.</p>
| 1 | 2016-08-26T06:19:37Z | 39,161,386 | <p>IIUC you may try this:</p>
<pre><code>In[19]:np.where((arr==4)|(arr==5))
Out[19]: (array([0, 2, 4, 7], dtype=int64), array([1, 2, 3, 2], dtype=int64))
</code></pre>
| 1 | 2016-08-26T08:07:40Z | [
"python",
"arrays",
"numpy",
"multidimensional-array"
] |
How to return value from recursive function in python? | 39,159,573 | <p>I'm working with binary tree in python. I need to create a method which searches the tree and return the best node where a new value can be inserted. But i'm have trouble returning a value from this recursive function. I'm a total newbie in python.</p>
<pre><code>def return_key(self, val, node):
if(val < node.v):
if(node.l != None):
self.return_key(val, node.l)
else:
print node.v
return node
else:
if(node.r != None):
#print node.v
self.return_key(val, node.r)
else:
print node.v
return node
</code></pre>
<p>Printing <code>node.v</code> prints the node value, but when i print the returned node :</p>
<pre><code>print ((tree.return_key(6, tree.getRoot().v)))
</code></pre>
<p>it prints</p>
<blockquote>
<p>None </p>
</blockquote>
<p>as result.</p>
| 0 | 2016-08-26T06:21:46Z | 39,159,591 | <p>You need to return the result of your <em>recursive</em> call. You are ignoring it here:</p>
<pre><code>if(node.l != None):
self.return_key(val, node.l)
</code></pre>
<p>and</p>
<pre><code>if(node.r != None):
self.return_key(val, node.r)
</code></pre>
<p>Recursive calls are no different from other function calls, you still need to handle the return value if there is one. Use a <code>return</code> statement:</p>
<pre><code>if(node.l != None):
return self.return_key(val, node.l)
# ...
if(node.r != None):
return self.return_key(val, node.r)
</code></pre>
<p>Note that since <code>None</code> is a singleton value, you can and should use <code>is not None</code> here to test for the absence:</p>
<pre><code>if node.l is not None:
return self.return_key(val, node.l)
# ...
if node.r is not None:
return self.return_key(val, node.r)
</code></pre>
<p>I suspect you are passing in the wrong arguments to the call to begin with however; if the second argument is to be a node, don't pass in the node value:</p>
<pre><code>print(tree.return_key(6, tree.getRoot())) # drop the .v
</code></pre>
<p>Also, if all your <code>node</code> classes have the same method, you could recurse to that rather than using <code>self.return_value()</code>; on the <code>Tree</code> just do:</p>
<pre><code>print tree.return_key(6)
</code></pre>
<p>where <code>Tree.return_key()</code> delegates to the root node:</p>
<pre><code>def return_key(self, val):
root = tree.getRoot()
if root is not None:
return tree.getRoot().return_key(val)
</code></pre>
<p>and <code>Node.return_key()</code> becomes:</p>
<pre><code>def return_key(self, val):
if val < self.v:
if self.l is not None:
return self.l.return_key(val)
elif val > self.v:
if self.r is not None:
return self.r.return_key(val)
# val == self.v or child node is None
return self
</code></pre>
<p>I updated the <code>val</code> testing logic here too; if <code>val < self.v</code> (or <code>val < node.v</code> in your code) is false, <em>don't</em> assume that <code>val > self.v</code> is true; <code>val</code> could be equal instead.</p>
| 4 | 2016-08-26T06:23:01Z | [
"python",
"python-2.7",
"python-3.x",
"recursion",
"binary-search-tree"
] |
Odoo Server Error ubuntu | 39,159,847 | <p>When try install any module get this error.</p>
<pre><code>Odoo Server Error
Traceback (most recent call last):
File "/home/nolimit/git/odoo/openerp/http.py", line 648, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/nolimit/git/odoo/openerp/http.py", line 685, in dispatch
result = self._call_function(**self.params)
File "/home/nolimit/git/odoo/openerp/http.py", line 321, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/nolimit/git/odoo/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/home/nolimit/git/odoo/openerp/http.py", line 314, in checked_call
result = self.endpoint(*a, **kw)
File "/home/nolimit/git/odoo/openerp/http.py", line 964, in __call__
return self.method(*args, **kw)
File "/home/nolimit/git/odoo/openerp/http.py", line 514, in response_wrap
response = f(*args, **kw)
File "/home/nolimit/git/odoo/addons/web/controllers/main.py", line 892, in call_button
action = self._call_kw(model, method, args, {})
File "/home/nolimit/git/odoo/addons/web/controllers/main.py", line 880, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/home/nolimit/git/odoo/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/home/nolimit/git/odoo/openerp/addons/base/module/module.py", line 459, in button_immediate_install
return self._button_immediate_function(cr, uid, ids, self.button_install, context=context)
File "/home/nolimit/git/odoo/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/home/nolimit/git/odoo/openerp/addons/base/module/module.py", line 533, in _button_immediate_function
registry = openerp.modules.registry.RegistryManager.new(cr.dbname, update_module=True)
File "/home/nolimit/git/odoo/openerp/modules/registry.py", line 386, in new
openerp.modules.load_modules(registry._db, force_demo, status, update_module)
File "/home/nolimit/git/odoo/openerp/modules/loading.py", line 338, in load_modules
loaded_modules, update_module)
File "/home/nolimit/git/odoo/openerp/modules/loading.py", line 237, in load_marked_modules
loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks)
File "/home/nolimit/git/odoo/openerp/modules/loading.py", line 156, in load_module_graph
_load_data(cr, module_name, idref, mode, kind='data')
File "/home/nolimit/git/odoo/openerp/modules/loading.py", line 98, in _load_data
tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
File "/home/nolimit/git/odoo/openerp/tools/convert.py", line 851, in convert_file
convert_xml_import(cr, module, fp, idref, mode, noupdate, report)
File "/home/nolimit/git/odoo/openerp/tools/convert.py", line 917, in convert_xml_import
doc = etree.parse(xmlfile)
File "lxml.etree.pyx", line 3239, in lxml.etree.parse (src/lxml/lxml.etree.c:69955)
File "parser.pxi", line 1769, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:102257)
File "parser.pxi", line 1789, in lxml.etree._parseFilelikeDocument (src/lxml/lxml.etree.c:102516)
File "parser.pxi", line 1684, in lxml.etree._parseDocFromFilelike (src/lxml/lxml.etree.c:101442)
File "parser.pxi", line 1134, in lxml.etree._BaseParser._parseDocFromFilelike (src/lxml/lxml.etree.c:97069)
File "parser.pxi", line 582, in lxml.etree._ParserContext._handleParseResultDoc (src/lxml/lxml.etree.c:91275)
File "parser.pxi", line 683, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:92461)
File "parser.pxi", line 622, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:91757)
XMLSyntaxError: StartTag: invalid element name, line 8, column 4
</code></pre>
<p>Any solution how fix this problem?</p>
<p>Structure of module </p>
<p>Folder: daily_transaction</p>
<p><strong>init</strong>.py</p>
<pre><code>daily_transaction
</code></pre>
<p><strong>openerp</strong>.py</p>
<pre><code>{
'name': 'Daily Transaction Manager',
'version': '1.0',
'author': 'Lionel Messi',
'complexity': 'normal',
'description': 'New module',
'category': '',
'depends': [],
'data': ['daily_transaction_view.xml'],
'auto_install': False,
'installable': True,
'external_dependencies': {
'python': [],
},
}
</code></pre>
<p>daily_transaction.py</p>
<pre><code>from openerp.osv import fields, osv
class daily_transaction(osv.osv):
_name = "daily.transaction"
_description = "Daily Transaction"
_colums = {
'subject': fields.char('Subject', size=128, required=True),
'date': fields.date('Date', required=True),
'note': fields.text('Notes'),
'amount': fields.float('Amount', required=True),
'type': fields.selection([
('transport', 'Transport'),
('household','Household'),
('personal', 'Personal'),
],'Type', required=True),
}
</code></pre>
<p>daily_transaction_view.xml</p>
<pre><code><openerp>
<data>
<!--Daily Transaction List View-->
<record id="view_daily_transaction_tree" model="ir.ui.view">
<!â here id is the external id for this tree view which must be unique and will be used for accessing this record -->
<field name="name">daily.transaction.tree</field>
<!â this will be our name of record in ir.ui.view -->
<field name="model">daily.transaction</field>
<!â this will map out tree view with our daily transaction model -->
<field name="arch" type="xml">
<!-- this will be our title of list/tree view -->
<tree string="Daily Transaction"> <!-- these will automatically map table headers for our list view, so weâll select out column names of our model here -->
<field name="name"/>
<field name="date"/>
<field name="type"/>
<field name="amount"/>
</tree>
</field>
</record>
<!--Daily Transaction Form View-->
<record id="view_daily_transaction_form" model="ir.ui.view">
<field name="name">daily.transaction.form.view</field>
<field name="model">daily.transaction</field>
<field name="arch" type="xml">
<!-- this will be our title of list/tree view -->
<form string="Daily Transaction" version="7.0">
<group>
<field name="name"/>
<field name="date"/>
<field name="type"/>
<field name="amount"/>
<field name="note"/>
</group>
</form>
</field>
</record>
<record id="action_daily_transaction" model="ir.actions.act_window">
<field name="name">Daily Transaction</field>
<!â name of action -->
<field name="res_model">daily.transaction</field>
<!â this action will be mapped to model specified -->
<field name="view_type">form</field>
<field name="view_mode">tree,form</field>
<!-- these are type of view our module will show for our daily transaction mode -->
<field name="search_view_id" eval="False"/>
<!â here we specify id of our search view -->
<field name="context">{}</field>
<field name="help">Create new daily transaction.</field>
<!â help text for our model -->
</record>
</data>
</openerp>
</code></pre>
<p>What is that? <a href="https://postimg.cc/image/csxssd7tx/" rel="nofollow">https://postimg.cc/image/csxssd7tx/</a></p>
<p>Module --> <a href="https://postimg.cc/image/gk1uyb0vn/" rel="nofollow">https://postimg.cc/image/gk1uyb0vn/</a></p>
| 0 | 2016-08-26T06:40:53Z | 39,161,213 | <p>It seems like you forget to declare <code>name</code> field on your Class.</p>
<p>You can resolve it with following two option:</p>
<ol>
<li>Add <em>name</em> field on your <em>class daily_transaction</em> OR</li>
<li><p>You may change field definition like</p>
<pre><code>'name': fields.char('Subject', size=128, required=True),
</code></pre></li>
</ol>
<p>Afterwards, restart your reserver and upgrade module.</p>
| 0 | 2016-08-26T07:57:15Z | [
"python",
"openerp",
"odoo-8",
"odoo-9"
] |
Redis get and set decorator | 39,160,075 | <p>Currently working on python and redis. I have Flask as my framework and working on Blueprints.</p>
<p>Looking into implementing cache with redis for my APIs, I have tried <strong>Flask-Cache</strong> and <strong>redis-simple-cache</strong>.
Downside are <a href="http://pythonhosted.org/Flask-Cache/" rel="nofollow">Flask-Cache</a> saves the function even when you change the parameter of the function. It only saves it once per function.
As per <a href="https://github.com/vivekn/redis-simple-cache" rel="nofollow">redis-simple-cache</a>, it save its keys as <code>SimpleCache-<key name></code> which not advisable on my end.</p>
<p>So my question is, how can you create a decorator which save and retrieve or check if there is a key existing for the specific key.
I know a save decorator is possible. But is a retrieve or check decorator possible?? Please correct me if I am wrong. Thank you.</p>
| 2 | 2016-08-26T06:53:55Z | 39,160,863 | <p>You can use this <a href="https://github.com/dhruvpathak/python-cache-decorator" rel="nofollow">cache decorator</a>, the cache object you create will have to be a flask cache object instead of django one i.e. should support cache.get and cache.set methods, this is pretty flexible based on how you want to create cache keys, i.e. </p>
<ul>
<li>based on what parameters being passed to the method</li>
<li>in what cases to cache/not cache the result</li>
<li>Use same cache even if kwarg order is changed, i.e. same cache for my_method(a=1,b=2) and my_method(b=2,a=1) call.</li>
</ul>
<p>"</p>
<pre><code>__author__ = 'Dhruv Pathak'
import cPickle
import logging
import time
from functools import wraps
from django.conf import settings
import traceback
"""following imports are from datautils.py in this repo, datautils
also contains many other useful data utility methods/classes
"""
from datautils import mDict, mList, get_nested_ordered_dict, nested_path_get
"""following import is specific to django framework, and can be altered
based on what type of caching library your code uses"""
from django.core.cache import cache, caches
logger = logging.getLogger(__name__)
def cache_result(cache_key=None, cache_kwarg_keys=None, seconds=900, cache_filter=lambda x: True, cache_setup = "default"):
def set_cache(f):
@wraps(f)
def x(*args, **kwargs):
if settings.USE_CACHE is not True:
result = f(*args, **kwargs)
return result
try:
# cache_conn should be a cache object supporting get,set methods
# can be from python-memcached, pylibmc, django, django-redis-cache, django-redis etc
cache_conn = caches[cache_setup]
except Exception, e:
result = f(*args, **kwargs)
return result
final_cache_key = generate_cache_key_for_method(f, kwargs, args, cache_kwarg_keys, cache_key)
try:
result = cache_conn.get(final_cache_key)
except Exception, e:
result = None
if settings.DEBUG is True:
raise
else:
logger.exception("Cache get failed,k::{0},ex::{1},ex::{2}".format(final_cache_key, str(e), traceback.format_exc()))
if result is not None and cache_filter(result) is False:
result = None
logger.debug("Cache had invalid result:{0},not returned".format(result))
if result is None: # result not in cache
result = f(*args, **kwargs)
if isinstance(result, (mDict, mList)):
result.ot = int(time.time())
if cache_filter(result) is True:
try:
cache_conn.set(final_cache_key, result, seconds)
except Exception, e:
if settings.DEBUG is True:
raise
else:
logger.exception("Cache set failed,k::{0},ex::{1},ex::{2},dt::{3}".format(final_cache_key, str(e), traceback.format_exc(), str(result)[0:100],))
#else:
# logger.debug("Result :{0} failed,not cached".format(result))
else: # result was from cache
if isinstance(result, (mDict, mList)):
result.src = "CACHE_{0}".format(cache_setup)
return result
return x
return set_cache
def generate_cache_key_for_method(method, method_kwargs, method_args, cache_kwarg_keys=None, cache_key=None):
if cache_key is None:
if cache_kwarg_keys is not None and len(cache_kwarg_keys) > 0:
if len(method_args) > 0:
raise Exception("cache_kwarg_keys mode needs set kwargs,args should be empty")
method_kwargs = get_nested_ordered_dict(method_kwargs)
cache_kwarg_values = [nested_path_get(method_kwargs, path_str=kwarg_key, strict=False) for kwarg_key in cache_kwarg_keys]
if any([kwarg_value is not None for kwarg_value in cache_kwarg_values]) is False:
raise Exception("all cache kwarg keys values are not set")
final_cache_key = "{0}::{1}::{2}".format(str(method.__module__), str(method.__name__), hash(cPickle.dumps(cache_kwarg_values)))
else:
final_cache_key = "{0}::{1}".format(str(method.__module__), str(method.__name__))
final_cache_key += "::{0}".format(str(hash(cPickle.dumps(method_args, 0)))) if len(method_args) > 0 else ''
final_cache_key += "::{0}".format(str(hash(cPickle.dumps(method_kwargs, 0)))) if len(method_kwargs) > 0 else ''
else:
final_cache_key = "{0}::{1}::{2}".format(method.__module__, method.__name__, cache_key)
return final_cache_key
</code></pre>
<p>2-3 utility methods are imported from this <a href="https://github.com/dhruvpathak/misc-python-utils/blob/master/datautils.py" rel="nofollow">file</a> in same repo, you can just put them in same file.</p>
| 0 | 2016-08-26T07:36:42Z | [
"python",
"caching",
"redis",
"decorator"
] |
Redis get and set decorator | 39,160,075 | <p>Currently working on python and redis. I have Flask as my framework and working on Blueprints.</p>
<p>Looking into implementing cache with redis for my APIs, I have tried <strong>Flask-Cache</strong> and <strong>redis-simple-cache</strong>.
Downside are <a href="http://pythonhosted.org/Flask-Cache/" rel="nofollow">Flask-Cache</a> saves the function even when you change the parameter of the function. It only saves it once per function.
As per <a href="https://github.com/vivekn/redis-simple-cache" rel="nofollow">redis-simple-cache</a>, it save its keys as <code>SimpleCache-<key name></code> which not advisable on my end.</p>
<p>So my question is, how can you create a decorator which save and retrieve or check if there is a key existing for the specific key.
I know a save decorator is possible. But is a retrieve or check decorator possible?? Please correct me if I am wrong. Thank you.</p>
| 2 | 2016-08-26T06:53:55Z | 39,319,855 | <p>You seem to not have read the <a href="http://pythonhosted.org/Flask-Cache/" rel="nofollow">Flask-Cache documentation</a> very closely. Caching does <em>not</em> ignore parameters and the cache key is customisable. The decorators the project supplies already give you the functionality you seek.</p>
<p>From the <a href="http://pythonhosted.org/Flask-Cache/#caching-view-functions" rel="nofollow"><em>Caching View Functions</em> section</a>:</p>
<blockquote>
<p>This decorator will use <code>request.path</code> by default for the <code>cache_key</code>.</p>
</blockquote>
<p>So the <em>default</em> cache key is <code>request.path</code>, but you can specify a different key. Since Flask <em>view</em> functions get their arguments from path elements, the default <code>request.path</code> makes a great key.</p>
<p>From the <a href="http://pythonhosted.org/Flask-Cache/#flask.ext.cache.Cache.cached" rel="nofollow"><code>@cached()</code> decorator documentation</a>:</p>
<blockquote>
<p><code>cached(timeout=None, key_prefix='view/%s', unless=None)</code></p>
<p>By default the cache key is <em>view/request.path</em>. You are able to use this decorator with any function by changing the <em>key_prefix</em>. If the token <em>%s</em> is located within the <em>key_prefix</em> then it will replace that with <em>request.path</em>. You are able to use this decorator with any function by changing the <em>key_prefix</em>.</p>
</blockquote>
<p>and</p>
<blockquote>
<p><code>key_prefix</code> â <em>[...]</em> Can optionally be a callable which takes no arguments but returns a string that will be used as the <code>cache_key</code>.</p>
</blockquote>
<p>So you can set <code>key_prefix</code> to a function, and it'll be called (without arguments) to produce the key.</p>
<p>Moreover:</p>
<blockquote>
<p>The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable:</p>
<p><em>[...]</em></p>
<p><code>make_cache_key</code><br>
A function used in generating the cache_key used.</p>
</blockquote>
<p>This function is passed the same arguments the view function is passed. In all, this allows you to produce any cache key you want; either use <code>key_prefix</code> and pull out more information from the <code>request</code> or <code>g</code> or other sources, or assign to <code>view_function.make_cache_key</code> and access the same arguments the view function receives.</p>
<p>Then there is the <a href="http://pythonhosted.org/Flask-Cache/#flask.ext.cache.Cache.memoize" rel="nofollow"><code>@memoize()</code> decorator</a>:</p>
<blockquote>
<p><code>memoize(timeout=None, make_name=None, unless=None)</code></p>
<p>Use this to cache the result of a function, taking its arguments into account in the cache key.</p>
</blockquote>
<p>So this decorator caches return values purely based on the arguments passed into the function. It too supports a <code>make_cache_key</code> function. </p>
<p>I've used both decorators to make a Google App Engine Flask project scale to double-digit millions of views per month for a CMS-backed site, storing results in the Google memcached structure. Doing this with Redis would only require setting a configuration option.</p>
| 0 | 2016-09-04T17:53:49Z | [
"python",
"caching",
"redis",
"decorator"
] |
Add parentheses to list elements - Python | 39,160,469 | <p>I would like to retrieve a set of data in a file in the form of a list.</p>
<p>The following is the data i am reading from the file which I want to add to list:</p>
<blockquote>
<h1>file input: (3,5),(5,2),(2,1),(4,2),(4,1),(3,1)</h1>
</blockquote>
<p>The following code shows what I have now:</p>
<pre><code>with open("partial.txt") as f:
List = f.read().splitlines()
graph1 = ','.join('({0})'.format(w) for w in List)
print (graph1)
</code></pre>
<p>The output I get is:</p>
<pre><code>>> (3,5),(5,2),(2,1),(4,2),(4,1),(3,1)
</code></pre>
<p>BUT I want the above result in [ ], like this:</p>
<pre><code>>> [(3,5),(5,2),(2,1),(4,2),(4,1),(3,1)]
</code></pre>
<p>Can someone show what I need to do to get the above result</p>
| -3 | 2016-08-26T07:15:37Z | 39,160,498 | <pre><code>import ast
s = "(3,5),(5,2),(2,1),(4,2),(4,1),(3,1)"
>>> list(ast.literal_eval(s))
[(3, 5), (5, 2), (2, 1), (4, 2), (4, 1), (3, 1)]
</code></pre>
<p>Here is an <a href="http://stackoverflow.com/questions/15197673/using-pythons-eval-vs-ast-literal-eval">SO link</a> to <code>eval</code> vs <code>ast.literal_eval</code></p>
| 3 | 2016-08-26T07:17:16Z | [
"python",
"string",
"list",
"file"
] |
Add parentheses to list elements - Python | 39,160,469 | <p>I would like to retrieve a set of data in a file in the form of a list.</p>
<p>The following is the data i am reading from the file which I want to add to list:</p>
<blockquote>
<h1>file input: (3,5),(5,2),(2,1),(4,2),(4,1),(3,1)</h1>
</blockquote>
<p>The following code shows what I have now:</p>
<pre><code>with open("partial.txt") as f:
List = f.read().splitlines()
graph1 = ','.join('({0})'.format(w) for w in List)
print (graph1)
</code></pre>
<p>The output I get is:</p>
<pre><code>>> (3,5),(5,2),(2,1),(4,2),(4,1),(3,1)
</code></pre>
<p>BUT I want the above result in [ ], like this:</p>
<pre><code>>> [(3,5),(5,2),(2,1),(4,2),(4,1),(3,1)]
</code></pre>
<p>Can someone show what I need to do to get the above result</p>
| -3 | 2016-08-26T07:15:37Z | 39,160,922 | <p>Solved it by this code, list of tuples! : </p>
<pre><code>with open('partial.txt') as f:
graph = [tuple(map(int, i.split(','))) for i in f]
print (graph)
</code></pre>
| 0 | 2016-08-26T07:40:20Z | [
"python",
"string",
"list",
"file"
] |
How can python function actually change the parameter rather than the formal parameter? | 39,160,682 | <p>I am trying to code "1024" using python basic library. In the process I try to make a list [0, 2, 4, 4] become [0, 2, 8, 0]. So here is my test code. It's very easy one.</p>
<pre><code> def merger(a, b):
if a == b:
a += b
b = 0
numlist = [0, 2, 4, 4]
merger(numlist[0], numlist[1])
merger(numlist[1], numlist[2])
merger(numlist[2], numlist[3])
print (numlist)
</code></pre>
<p>So when I try to conduct merge. I expected the output [0, 2, 8, 0]. However it gives me [0, 2, 4, 4] instead. I think maybe it's because I just changed the local variable of my function a b rather than the actual parameter? But If I want this to happen, what should I do? Thx!</p>
<p>I think I want to know generally if I want a function not return anything but just change value of the variable I passed as parameter. How can I achieve it?</p>
| 1 | 2016-08-26T07:27:27Z | 39,160,857 | <p>You can pass the list and indexes to the function:</p>
<pre><code>def merger(l, a, b):
if l[a] == l[b]:
l[a] += l[b]
l[b] = 0
numlist = [0, 2, 4, 4]
merger(numlist, 0, 1)
merger(numlist, 1, 2)
merger(numlist, 2, 3)
print(numlist)
</code></pre>
<p>As list object will be passed by reference and any changes on the list inside the function will be effective after the function call.</p>
| 2 | 2016-08-26T07:36:19Z | [
"python",
"function",
"syntax"
] |
How to use multiple 'if' statements nested inside an enumerator? | 39,160,750 | <p>I have a massive string of letters all jumbled up, 1.2k lines long.
I'm trying to find a lowercase letter that has EXACTLY three capital letters on either side of it.</p>
<p>This is what I have so far</p>
<pre><code>def scramble(sentence):
try:
for i,v in enumerate(sentence):
if v.islower():
if sentence[i-4].islower() and sentence[i+4].islower():
....
....
except IndexError:
print() #Trying to deal with the problem of reaching the end of the list
#This section is checking if
the fourth letters before
and after i are lowercase to ensure the central lower case letter has
exactly three upper case letters around it
</code></pre>
<p>But now I am stuck with the next step. What I would like to achieve is create a <code>for-loop</code> in range of <code>(-3,4)</code> and check that each of these letters is uppercase. If in fact there are three uppercase letters either side of the lowercase letter then print this out.</p>
<p>For example</p>
<pre><code>for j in range(-3,4):
if j != 0:
#Some code to check if the letters in this range are uppercase
#if j != 0 is there because we already know it is lowercase
#because of the previous if v.islower(): statement.
</code></pre>
<p>If this doesn't make sense, this would be an example output if the code worked as expected</p>
<pre><code>scramble("abcdEFGhIJKlmnop")
</code></pre>
<p>OUTPUT</p>
<pre><code>EFGhIJK
</code></pre>
<p>One lowercase letter with three uppercase letters either side of it.</p>
| 0 | 2016-08-26T07:31:09Z | 39,160,899 | <p>Here is a way to do it "Pythonically" without<br>
regular expressions:</p>
<pre><code>s = 'abcdEFGhIJKlmnop'
words = [s[i:i+7] for i in range(len(s) - 7) if s[i:i+3].isupper() and s[i+3].islower() and s[i+4:i+7].isupper()]
print(words)
</code></pre>
<p>And the output is:</p>
<pre><code>['EFGhIJK']
</code></pre>
<p>And here is a way to do it <em>with</em> regular expressions,<br>
which is, well, also Pythonic :-)</p>
<pre><code>import re
words = re.findall(r'[A-Z]{3}[a-z][A-Z]{3}', s)
</code></pre>
| 1 | 2016-08-26T07:39:13Z | [
"python"
] |
How to use multiple 'if' statements nested inside an enumerator? | 39,160,750 | <p>I have a massive string of letters all jumbled up, 1.2k lines long.
I'm trying to find a lowercase letter that has EXACTLY three capital letters on either side of it.</p>
<p>This is what I have so far</p>
<pre><code>def scramble(sentence):
try:
for i,v in enumerate(sentence):
if v.islower():
if sentence[i-4].islower() and sentence[i+4].islower():
....
....
except IndexError:
print() #Trying to deal with the problem of reaching the end of the list
#This section is checking if
the fourth letters before
and after i are lowercase to ensure the central lower case letter has
exactly three upper case letters around it
</code></pre>
<p>But now I am stuck with the next step. What I would like to achieve is create a <code>for-loop</code> in range of <code>(-3,4)</code> and check that each of these letters is uppercase. If in fact there are three uppercase letters either side of the lowercase letter then print this out.</p>
<p>For example</p>
<pre><code>for j in range(-3,4):
if j != 0:
#Some code to check if the letters in this range are uppercase
#if j != 0 is there because we already know it is lowercase
#because of the previous if v.islower(): statement.
</code></pre>
<p>If this doesn't make sense, this would be an example output if the code worked as expected</p>
<pre><code>scramble("abcdEFGhIJKlmnop")
</code></pre>
<p>OUTPUT</p>
<pre><code>EFGhIJK
</code></pre>
<p>One lowercase letter with three uppercase letters either side of it.</p>
| 0 | 2016-08-26T07:31:09Z | 39,161,006 | <p>if you can't use regular expression</p>
<p>maybe this for loop can do the trick </p>
<pre><code>if v.islower():
if sentence[i-4].islower() and sentence[i+4].islower():
for k in range(1,4):
if sentence[i-k].islower() or sentence[i+k].islower():
break
if k == 3:
return i
</code></pre>
| 1 | 2016-08-26T07:44:39Z | [
"python"
] |
How to use multiple 'if' statements nested inside an enumerator? | 39,160,750 | <p>I have a massive string of letters all jumbled up, 1.2k lines long.
I'm trying to find a lowercase letter that has EXACTLY three capital letters on either side of it.</p>
<p>This is what I have so far</p>
<pre><code>def scramble(sentence):
try:
for i,v in enumerate(sentence):
if v.islower():
if sentence[i-4].islower() and sentence[i+4].islower():
....
....
except IndexError:
print() #Trying to deal with the problem of reaching the end of the list
#This section is checking if
the fourth letters before
and after i are lowercase to ensure the central lower case letter has
exactly three upper case letters around it
</code></pre>
<p>But now I am stuck with the next step. What I would like to achieve is create a <code>for-loop</code> in range of <code>(-3,4)</code> and check that each of these letters is uppercase. If in fact there are three uppercase letters either side of the lowercase letter then print this out.</p>
<p>For example</p>
<pre><code>for j in range(-3,4):
if j != 0:
#Some code to check if the letters in this range are uppercase
#if j != 0 is there because we already know it is lowercase
#because of the previous if v.islower(): statement.
</code></pre>
<p>If this doesn't make sense, this would be an example output if the code worked as expected</p>
<pre><code>scramble("abcdEFGhIJKlmnop")
</code></pre>
<p>OUTPUT</p>
<pre><code>EFGhIJK
</code></pre>
<p>One lowercase letter with three uppercase letters either side of it.</p>
| 0 | 2016-08-26T07:31:09Z | 39,161,141 | <p>regex is probably the easiest, using a modified version of @Israel Unterman's answer to account for the outside edges and non-upper surroundings the full regex might be:</p>
<pre><code>s = 'abcdEFGhIJKlmnopABCdEFGGIddFFansTBDgRRQ'
import re
words = re.findall(r'(?:^|[^A-Z])([A-Z]{3}[a-z][A-Z]{3})(?:[^A-Z]|$)', s)
# words is ['EFGhIJK', 'TBDgRRQ']
</code></pre>
<p>using <code>(?:.)</code> groups keeps the search for beginning of line or non-upper from being included in match groups, leaving only the desired tokens in the result list. This should account for all conditions listed by OP.</p>
<p><em>(removed all my prior code as it was generally *bad*)</em></p>
| 1 | 2016-08-26T07:52:47Z | [
"python"
] |
How to get the flag/state of current operation in Odoo 9? | 39,160,816 | <p>I am new in odoo, I want to know how we get the current flag/state of every operation.</p>
<p>For example: when we create a new record how do we know the current flag/state is "add"? or when we view a record how do we know the current flag/state is "view"? </p>
<p>It something like current user id that stored in session named "uid", is there something similar to get the current flag/state in every operation?</p>
| 1 | 2016-08-26T07:34:22Z | 39,180,410 | <p>There is no such thing as 'flag/state'. </p>
<p>What you are probably trying to say is that you want to know which operations are taking place on a record. The easiest method is to take a look at your log. There will be statements there in the form <code>/web/dataset/call_kw/model/operation</code> where model is your ORM model and operation could be a search, read, unlink etc. RPC calls are logged in there as well. The format of the log output is a little bit different between different versions of odoo. You can go to a lower level by monitoring sql transactions on postgresql but I do not think that this is what you want.</p>
| 0 | 2016-08-27T11:05:30Z | [
"python",
"web",
"openerp"
] |
Putting/Updating item in DynamoDB fails for the UpdateExpression syntax | 39,161,097 | <p>I've created a DynamoDB table, and in my Python code, I have the resource initialised as follows:</p>
<pre><code>self.dynamodb = self.session.resource('dynamodb').Table('aws-ci')
</code></pre>
<p>The table has just one index/key, with the name <code>environment</code>. I am trying to <code>PUT</code> into it, an object as follows:</p>
<pre><code>{
"environment": "beta",
"X": {
"current_sha": "sha1",
"deployed": true,
"prev_sha": "sha2",
"status": "inactive"
},
"Y-Z": {
"current_sha": "sha1",
"deployed": false,
"prev_sha": "sha2",
"status": "active"
}
}
</code></pre>
<p>where, <code>X</code> and <code>Y-Z</code> are the names of micro-services. My insertion code is as follows:</p>
<pre><code>def put_service_data(self, environment, service_name, service_data, status = None):
get_previous = self.dynamodb.get_item(
Key = {
'environment': environment
}
).get(service_name)
service_data['prev'] = get_previous and get_previous.get('current_sha') or 'NULL'
if status == 'rollback' and get_previous:
service_data['current'] = get_previous.get('current_sha')
service_data['prev'] = get_previous.get('prev_sha')
set_query = "SET {0}.current_sha = :current, {0}.prev_sha = :prev, {0}.deployed = :is_deployed, {0}.current_status = :status".format(service_name)
updated = self.dynamodb.update_item(
Key = {
'environment': environment
},
UpdateExpression = set_query,
ExpressionAttributeValues = {
':current': service_data.get('current'),
':prev': service_data.get('prev'),
':status': service_data.get('status'),
':is_deployed': service_data.get('deployed')
},
ReturnValues = "ALL_NEW"
)
return updated
</code></pre>
<p>Previously, instead of <code>{0}.current_status</code>, I had <code>{0}.status</code>, but that raised the following error:</p>
<blockquote>
<p>An error occurred (<code>ValidationException</code>) when calling the
<code>UpdateItem</code> operation: Invalid <code>UpdateExpression</code>: Attribute name is
a reserved keyword; reserved keyword: <code>status</code></p>
</blockquote>
<p>Anyway, I changed that attribute name name to <code>current_status</code> and tried the insertion again, only this time I am receiving:</p>
<blockquote>
<p>An error occurred (<code>ValidationException</code>) when calling the
<code>UpdateItem</code> operation: The document path provided in the update
expression is invalid for update</p>
</blockquote>
<p>when trying to set attributes for service <strong>X</strong>, and the following when trying for <strong>Y-Z</strong>:</p>
<blockquote>
<p>An error occurred (<code>ValidationException</code>) when calling the
<code>UpdateItem</code> operation: Invalid <code>UpdateExpression</code>: Syntax error;
token: "-", near: "Y-Z"</p>
</blockquote>
<p>I'm currently unable to understand how the <code>update_item</code> call should work.</p>
| 0 | 2016-08-26T07:50:14Z | 39,161,500 | <p>Have you tried this?
<a href="http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html#ExpressionAttributeNames" rel="nofollow">http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html#ExpressionAttributeNames</a></p>
<pre><code>set_query = "SET #service_name.current_sha = :current, #service_name.prev_sha = :prev, #service_name.deployed = :is_deployed, #service_name.current_status = :current_status"
updated = self.dynamodb.update_item(
Key = {
'environment': environment
},
UpdateExpression = set_query,
ExpressionAttributeValues = {
':current': service_data.get('current'),
':prev': service_data.get('prev'),
':current_status': service_data.get('status'),
':is_deployed': service_data.get('deployed')
},
ExpressionAttributeNames = {
'#service_name': service_name,
},
ReturnValues = "ALL_NEW"
)
</code></pre>
| 1 | 2016-08-26T08:14:11Z | [
"python",
"amazon-web-services",
"amazon-dynamodb",
"boto",
"boto3"
] |
Querying more properties in Google Search Console via python script | 39,161,201 | <p>I am using a Python (2.7) script to download via API Google Search Console data. I would like to get rid of the property and dates arguments when launching the script:</p>
<pre><code>>python script. py ´http://www.example.com´ ´01-01-2000´ ´01-02-2000´
</code></pre>
<p>For the latter I managed to do it importing timedelta and commenting out the lines referring to that argument:</p>
<pre><code>argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument('property_uri', type=str,
help=('Site or app URI to query data for (including '
'trailing slash).'))
# Start and end dates are commented out as timeframe is dynamically set
'''argparser.add_argument('start_date', type=str,
help=('Start date of the requested date range in '
'YYYY-MM-DD format.'))
argparser.add_argument('end_date', type=str,
help=('End date of the requested date range in '
'YYYY-MM-DD format.'))'''
now = datetime.datetime.now()
StartDate = datetime.datetime.now()- timedelta(days=14)
EndDate = datetime.datetime.now()- timedelta(days=7)
From = StartDate.strftime('%Y-%m-%d' )
To = EndDate.strftime('%Y-%m-%d' )
request = {
'startDate': StartDate.strftime('%Y-%m-%d' ),
'endDate': EndDate.strftime('%Y-%m-%d' ),
'dimensions': ['query'],
</code></pre>
<p>Now I would like get rid also of the property argument, so that I can simply launch the script and have the property specified in the script itself. My final goal is to get data from several properties using only one script.</p>
<p>I tried to repeat the same procedure used for the dates but no luck. Needless to say I am a total beginner at coding.</p>
| 0 | 2016-08-26T07:56:30Z | 39,531,090 | <p>I think I can help as I had the same problem when working from the sample script given by google as guidance. Which is what I think you gotten your code from?</p>
<p>The problem is that the script uses the sample_tools.py script in the googleapiclient library, which is meant to abstract away all the authentication bits so you can make a quick query easily. If you want to modify the code, I would recommend writing it from scratch.</p>
<p>These are my functions that I've pieced together from various bits of documentation that you might find useful.</p>
<p>Stage 1: Authentication</p>
<pre><code>def authenticate_http():
"""Executes a searchAnalytics.query request.
Args:
service: The webmasters service to use when executing the query.
property_uri: The site or app URI to request data for.
request: The request to be executed.
Returns:
An array of response rows.
"""
# create flow object
flow = flow_from_clientsecrets('path to client_secrets.json',
scope='https://www.googleapis.com/auth/webmasters.readonly',
redirect_uri='urn:ietf:wg:oauth:2.0:oob')
storage = Storage('credentials_file')
credentials = storage.get()
if credentials:
# print "have auth code"
http_auth = credentials.authorize(Http())
else:
print "need auth code"
# get authorization server uri
auth_uri = flow.step1_get_authorize_url()
print auth_uri
# get credentials object
code_input = raw_input("Code: ")
credentials = flow.step2_exchange(code_input)
storage.put(credentials)
# apply credential headers to all requests
http_auth = credentials.authorize(Http())
return http_auth
</code></pre>
<p>Stage 2: Build the Service Object</p>
<pre><code>def build_service(api_name, version):
# use authenticate_http to return the http object
http_auth = authenticate_http()
# build gsc service object
service = build(api_name, version, http=http_auth)
return service
</code></pre>
<p>Stage 3: Execute Request</p>
<pre><code>def execute_request(service, property_uri, request):
"""Executes a searchAnalytics.query request.
Args:
service: The webmasters service to use when executing the query.
property_uri: The site or app URI to request data for.
request: The request to be executed.
Returns:
An array of response rows.
"""
return service.searchanalytics().query(
siteUrl=property_uri, body=request).execute()
</code></pre>
<p>Stage 4: Main()</p>
<pre><code>def main():
# define service object for the api service you want to use
gsc_service = build_service('webmasters', 'v3')
# define request
request = {'request goes here'}
# set your property set string you want to query
url = 'url or property set string goes here'
# response from executing request
response = execute_request(gsc_service, url, request)
print response
</code></pre>
<p>For multiple property sets you can just create a list of property sets, then create a loop and pass each property set into the 'url' argument of the 'execute_request' function</p>
<p>Hope this helps!</p>
| 0 | 2016-09-16T12:06:03Z | [
"python",
"python-2.7",
"google-api",
"google-webmaster-tools",
"google-api-python-client"
] |
How to work around missing PyModule_Create2 in AMD64 Win Python35_d.lib? | 39,161,202 | <p>I'm trying to debug an extension module that worked fine in 32 bit Python 2.7, but not so fine in 64 bit Python 3.5.</p>
<p>I've used the AMD64 Web installer from Python.org, and yet in the link I get</p>
<pre><code>__imp_PyModule_Create2 (referenced in libboost_python-vc120-mt-gd-1_57.lib(module.obj))
</code></pre>
<p>is unresolved. It's the only symbol that is unresolved.</p>
<p>Is this intentional? I saw an old bug report that seemed to indicate that the Stable ABI was exempt from debug builds. (Which is why I'm posting on SO instead of filing a bug report)</p>
<p>If it is intentional, is it expected that I would link with python35_d.lib and then python35.lib, or is there another way to resolve this?</p>
| 0 | 2016-08-26T07:56:35Z | 39,198,661 | <p>I've discovered the issue here; the AMD64 factor is irrelevant.</p>
<p>The key is that the Boost Python library expects to link against the Release version of Python, even if it is the debug version of Boost Python. By trying to link an extension module that depends on Boost Python, Boost's</p>
<pre><code>config/auto_link.hpp
</code></pre>
<p>will (by default) create a link dependency -- using</p>
<pre><code>#pragma comment(lib, string_of_library_name)
</code></pre>
<p>-- on python35.lib. This is bad news if in the makefile for your extension module you have specified python35_d.lib, with the expectation that your python will be invoked as python35_d.exe.</p>
<p>I found this by running</p>
<pre><code>dumpbin /EXPORTS python35.lib > python35_exp.txt
dumpbin /EXPORTS python35_d.lib > python35_d_exp.txt
</code></pre>
<p>and comparing the two. The key difference is that the release version exports the symbols PyModule_Create2 and PyModule_FromDefAndSpec2, whereas the debug version exports PyModule_Create2TraceRefs and PyModule_FromDefAndSpec2TraceRefs. This is an apparent deliberate choice by the Python developers to make sure that debug extension modules only work with debug Python. In the Python source code, one of the first lines in include/object.h is</p>
<pre><code>/* Py_DEBUG implies Py_TRACE_REFS. */
#if defined(Py_DEBUG) && !defined(Py_TRACE_REFS)
#define Py_TRACE_REFS
#endif
</code></pre>
<p>The giveaway is in include/modsupport.h</p>
<pre><code>#ifdef Py_TRACE_REFS
/* When we are tracing reference counts, rename module creation functions so
modules compiled with incompatible settings will generate a
link-time error. */
#define PyModule_Create2 PyModule_Create2TraceRefs
#define PyModule_FromDefAndSpec2 PyModule_FromDefAndSpec2TraceRefs
#endif
</code></pre>
<p>The solution is to build special versions of the Boost libraries that specifically link against python35_d.lib. There are a few steps involved:</p>
<ul>
<li>Run 'bootstrap.bat --with-python="C:\Program Files\Python35"'</li>
<li>Edit user-config.jam in your home directory so that it looks like (spaces are important)</li>
</ul>
<pre> using python : 3.5 : C:\\PROGRA~1\\Python35 ;
using python : 2.7 : C:\\Python27 ;
using python : 3.5 : C:\\PROGRA~1\\Python35\\python_d
: # includes
: # libs
: <python-debugging>on ;
</pre>
<ul>
<li>Invoke b2.exe with the extra option "python-debugging=on", like so</li>
</ul>
<pre>.\b2.exe toolset=msvc-12.0 threading=multi variant=debug address-model=64 --with-python --debug-configuration python-debugging=on stage</pre>
<p>Note that to resolve dependencies you are going to have to also compile date_time, thread, chrono, filesystem and system (just replace "--with-python" with "--with-otherlibname".)</p>
<ul>
<li>The final step is to make sure that the extension module that you are building links against the "right" library. I found that it was sufficient to define the preprocessor symbols BOOST_DEBUG_PYTHON and BOOST_LINKING_PYTHON, as well as the expected _DEBUG because in config/auto_link.hpp there are the lines</li>
</ul>
<pre> # if defined(_DEBUG) && defined(BOOST_DEBUG_PYTHON) && defined(BOOST_LINKING_PYTHON)
# define BOOST_LIB_RT_OPT "-gyd"
# elif defined(_DEBUG)
# define BOOST_LIB_RT_OPT "-gd"
# else
# define BOOST_LIB_RT_OPT
# endif</pre>
<p>That ought to do it - a debug version of a Python extension module that should compile and link against a Boost Python library that expects to link against python35_d.lib, and which will not crash when loaded by a script invoked with python_d.exe.</p>
| 0 | 2016-08-29T04:50:45Z | [
"python"
] |
Paraview picture generation | 39,161,205 | <p>I am trying to run a python script to generate pictures.
But every time i run i get the following error.</p>
<pre><code>File "/usr2/tmp/Krishnamoorthi/case0383/New/Pics_0.py", line 16, in <module>
case_foam.SurfaceArrays = ['meshPhi', 'phi']
File "/cax/sw-cae1/OPENFOAM/LINUX_x86_64/ParaView/ParaView-4.4.0-Qt4-Linux-64bit/lib/paraview-4.4/site-packages/paraview/servermanager.py", line 302, in __setattr__
"to add this attribute.")
AttributeError: Attribute SurfaceArrays does not exist. This class does not allow addition of new attributes to avoid mistakes due to typos. Use add_attribute() if you really want to add this attribute.
</code></pre>
<p>I checked the line 16 in the py script but it is all perfect.</p>
<p>Is it something to do with the bash for paraview?? </p>
| 0 | 2016-08-26T07:56:46Z | 39,817,906 | <p>The issue is that <code>SurfaceArrays</code> property does not exist on the <code>case_foam</code> reader instance.</p>
<p>Try opening the data data file in ParaView UI and see what properties are shown on the <code>Properties Panel</code>. There'd be some other property that should be used to select the <code>meshPhi</code> and <code>Phi</code> arrays to read for your reader.</p>
| 0 | 2016-10-02T14:18:15Z | [
"python",
"paraview"
] |
File lock (flock) compatibility between C and Python | 39,161,412 | <p>Does the python implementation of flock work transparently along with standard C libraries? If I have two programs, one in Python and the other in C, trying acquire a lock on a single file will it work?</p>
<p><strong>Quick links:</strong></p>
<ol>
<li>Python flock: <a href="https://docs.python.org/2/library/fcntl.html" rel="nofollow">https://docs.python.org/2/library/fcntl.html</a></li>
<li>Linux flock: <a href="http://linux.die.net/man/2/flock" rel="nofollow">http://linux.die.net/man/2/flock</a></li>
</ol>
| 1 | 2016-08-26T08:09:11Z | 39,161,454 | <p>Python's <code>fcntl</code> library is built directly on top of the standard C libraries; so on Linux <code>fcntl.flock()</code> uses the <code>flock</code> C function <em>directly</em>.</p>
<p>See the <a href="https://hg.python.org/cpython/file/2.7/Modules/fcntlmodule.c#l250" rel="nofollow">source code for the <code>fcntl</code> module</a>:</p>
<pre class="lang-c prettyprint-override"><code>#ifdef HAVE_FLOCK
Py_BEGIN_ALLOW_THREADS
ret = flock(fd, code);
Py_END_ALLOW_THREADS
</code></pre>
<p>This is clearly stated in the <a href="https://docs.python.org/2/library/fcntl.html#fcntl.flock" rel="nofollow"><code>fcntl.flock()</code> documentation</a> as well:</p>
<blockquote>
<p><strong><code>fcntl.flock(fd, op)</code></strong><br>
Perform the lock operation op on file descriptor <em>fd</em> (file objects providing a <code>fileno()</code> method are accepted as well). See the Unix manual <em>flock(2)</em> for details. (On some systems, this function is emulated using <code>fcntl()</code>.)</p>
</blockquote>
<p>So yes, it'll work.</p>
| 2 | 2016-08-26T08:11:25Z | [
"python",
"c",
"linux",
"locking"
] |
How to find the position of an item of a list in python? | 39,161,431 | <p>I have two lists. The first list has a specific length and the second list has unstable length. I want to assign the items from two lists.
I use <code>colour_index = sel_pos%(len(colours))</code>. The sel_pos is the item's position from the unstable list.
How to find the position every time?</p>
| -2 | 2016-08-26T08:10:02Z | 39,161,551 | <p>Use <code>l.index(n)</code> to find index of <code>n</code> in list <code>l</code>.</p>
<pre><code>>>> x = [1,3,7]
>>> x.index(3)
1
</code></pre>
| 2 | 2016-08-26T08:17:03Z | [
"python",
"list",
"colors",
"position",
"variable-length-array"
] |
How to find the position of an item of a list in python? | 39,161,431 | <p>I have two lists. The first list has a specific length and the second list has unstable length. I want to assign the items from two lists.
I use <code>colour_index = sel_pos%(len(colours))</code>. The sel_pos is the item's position from the unstable list.
How to find the position every time?</p>
| -2 | 2016-08-26T08:10:02Z | 39,161,650 | <pre><code>colour_index = selections.index(txt)%(len(colours))
</code></pre>
| 0 | 2016-08-26T08:22:07Z | [
"python",
"list",
"colors",
"position",
"variable-length-array"
] |
How to find the position of an item of a list in python? | 39,161,431 | <p>I have two lists. The first list has a specific length and the second list has unstable length. I want to assign the items from two lists.
I use <code>colour_index = sel_pos%(len(colours))</code>. The sel_pos is the item's position from the unstable list.
How to find the position every time?</p>
| -2 | 2016-08-26T08:10:02Z | 39,162,756 | <p>You can use Index function which is get the element and return the index of it in the list:</p>
<pre><code>indexNumber = MyList.Index(Element)
</code></pre>
| 0 | 2016-08-26T09:19:22Z | [
"python",
"list",
"colors",
"position",
"variable-length-array"
] |
Regex on list element in for loop | 39,161,495 | <p>I have a script that searches through config files and finds all matches of strings from another list as follows:</p>
<pre><code>dstn_dir = "C:/xxxxxx/foobar"
dst_list =[]
files = [fn for fn in os.listdir(dstn_dir)if fn.endswith('txt')]
dst_list = []
for file in files:
parse = CiscoConfParse(dstn_dir+'/'+file)
for sfarm in search_str:
int_objs = parse.find_all_children(sfarm)
if len(int_objs) > 0:
dst_list.append(["\n","#" *40,file + " " + sfarm,"#" *40])
dst_list.append(int_objs)
</code></pre>
<p>I need to change this part of the code:</p>
<pre><code> for sfarm in search_str:
int_objs = parse.find_all_children(sfarm)
</code></pre>
<p><code>search_str</code> is a list containing strings similar to <code>['xrout:55','old:23']</code> and many others.</p>
<p>So it will only find entries that end with the string from the list I am iterating through in <code>sfarm</code>. My understanding is that this would require my to use <code>re</code> and match on something like <code>sfarm$</code> but Im not sure on how to do this as part of the loop.</p>
<p>Am I correct in saying that <code>sfarm</code> is an iterable? If so I need to know how to regex on an iterable object in this context.</p>
| 2 | 2016-08-26T08:13:31Z | 39,161,847 | <p>Strings in python are iterable, so <code>sfarm</code> is an iterable, but that has little meaning in this case. From reading what <a href="http://www.pennington.net/py/ciscoconfparse/api_CiscoConfParse.html#ciscoconfparse.CiscoConfParse.find_all_children" rel="nofollow"><code>CiscoConfParse.find_all_children()</code></a> does, it is apparent that your <code>sfarm</code> is the <code>linespec</code>, which is a regular expression string. You do not need to explicitly use the <code>re</code> module here; just pass <code>sfarm</code> concatenated with <code>'$'</code>:</p>
<pre><code>search_string = ['xrout:55','old:23']
...
for sfarm in search_str:
int_objs = parse.find_all_children(sfarm + '$') # one of many ways to concat
...
</code></pre>
| 2 | 2016-08-26T08:32:34Z | [
"python"
] |
Regex on list element in for loop | 39,161,495 | <p>I have a script that searches through config files and finds all matches of strings from another list as follows:</p>
<pre><code>dstn_dir = "C:/xxxxxx/foobar"
dst_list =[]
files = [fn for fn in os.listdir(dstn_dir)if fn.endswith('txt')]
dst_list = []
for file in files:
parse = CiscoConfParse(dstn_dir+'/'+file)
for sfarm in search_str:
int_objs = parse.find_all_children(sfarm)
if len(int_objs) > 0:
dst_list.append(["\n","#" *40,file + " " + sfarm,"#" *40])
dst_list.append(int_objs)
</code></pre>
<p>I need to change this part of the code:</p>
<pre><code> for sfarm in search_str:
int_objs = parse.find_all_children(sfarm)
</code></pre>
<p><code>search_str</code> is a list containing strings similar to <code>['xrout:55','old:23']</code> and many others.</p>
<p>So it will only find entries that end with the string from the list I am iterating through in <code>sfarm</code>. My understanding is that this would require my to use <code>re</code> and match on something like <code>sfarm$</code> but Im not sure on how to do this as part of the loop.</p>
<p>Am I correct in saying that <code>sfarm</code> is an iterable? If so I need to know how to regex on an iterable object in this context.</p>
| 2 | 2016-08-26T08:13:31Z | 39,161,912 | <p>Please check this code. Used glob module to get all "*.txt" files in folder.</p>
<p>Please check here for more info on <a href="https://pymotw.com/2/glob/" rel="nofollow">glob module</a>.</p>
<pre><code>import glob
import re
dst_list = []
search_str = ['xrout:55','old:23']
for file_name in glob.glob(r'C:/Users/dinesh_pundkar\Desktop/*.txt'):
with open(file_name,'r') as f:
text = f.read()
for sfarm in search_str:
regex = re.compile('%s$'%sfarm)
int_objs = regex.findall(text)
if len(int_objs) > 0:
dst_list.append(["\n","#" *40,file_name + " " + sfarm,"#" *40])
dst_list.append(int_objs)
print dst_list
</code></pre>
<p>Output:</p>
<pre><code> C:\Users\dinesh_pundkar\Desktop>python a.py
[['\n', '########################################', 'C:/Users/dinesh_pundkar\\De
sktop\\out.txt old:23', '########################################'], ['old:23']]
C:\Users\dinesh_pundkar\Desktop>
</code></pre>
| 1 | 2016-08-26T08:35:29Z | [
"python"
] |
collections counter python can't access the key | 39,161,593 | <p>I am using the collections counter to count each string (they might not be unique) inside lists. The problem is that now I can't access the dictionary, and I am not sure why.</p>
<p>My code is:</p>
<pre><code>from collections import Counter
result1 = Counter(list_final1) #to count strings inside list
</code></pre>
<p>If I print result1, output is for example:</p>
<pre><code>Counter({'BAM': 44, 'CCC': 20, 'APG': 14, 'MBI': 11, 'BAV': 10})
</code></pre>
<p>To access the number 44 for exampke I would expect to use Counter['BAM']</p>
<p>But this above doesnt work and I get the error:</p>
<pre><code> print (Counter['BAM'])
TypeError: 'type' object is not subscriptable
</code></pre>
<p>What am I doing wrong? Thanks a lot.</p>
| 0 | 2016-08-26T08:18:53Z | 39,161,633 | <p>Use your <code>key</code> with the variable in which you stored the value of <code>Counter</code>, in your case <code>result1</code>. Sample:</p>
<pre><code>>>> from collections import Counter
>>> my_dict = {'BAM': 44, 'CCC': 20, 'APG': 14, 'MBI': 11, 'BAV': 10}
>>> result = Counter(my_dict)
>>> result['BAM']
44
</code></pre>
<p><strong>Explaination</strong>:</p>
<p>You are doing <code>Counter['BAM']</code>, i.e making new <code>Counter</code> object with <code>'BAM'</code> as param, which is invalid. Instead if you do <code>Counter(my_dict)['BAM']</code>, it will also work since it is the same object in which your dict is passed, and you are accessing <code>'BAM'</code> key within it </p>
| 2 | 2016-08-26T08:21:33Z | [
"python",
"python-collections"
] |
python 2 stdin can't read individual lines | 39,161,608 | <p>I have the following very simple-looking code:</p>
<pre><code>from __future__ import print_function
import sys
for line in sys.stdin:
print("hello!")
sys.stdout.flush()
</code></pre>
<p>When I run it, I expect to type in a line and then immediately see <code>hello!</code> printed out after it, after which I can type in another line. </p>
<p>When I run it with <code>py -3</code> I get expected results:</p>
<pre><code>py -3 test.py
asdf
hello!
asdf
hello!
asdf
hello!
^C
</code></pre>
<p>When I run it with <code>py -2</code>, it won't print <code>hello!</code> unless I send ctrl-Z:</p>
<pre><code>py -2 test.py
asdf
asdf
asdf
^Z
hello!
hello!
hello!
asdf
^Z
hello!
^Z
</code></pre>
<p>I ran this test on Windows with Python 2.7.12 and on Linux (using ctrl-D instead of ctrl-Z) with Python 2.6.6.</p>
<p>How can I get the Python 2 behavior to match that of Python3?</p>
<h3>EDIT:</h3>
<p>Working Python 3 example on repl.it: <a href="https://repl.it/Cs6n/0" rel="nofollow">https://repl.it/Cs6n/0</a></p>
<p>Broken Python 2 example on repl.it: <a href="https://repl.it/Cs7C/0" rel="nofollow">https://repl.it/Cs7C/0</a></p>
| 0 | 2016-08-26T08:19:54Z | 39,162,912 | <p>Answer to your question is here <a href="http://stackoverflow.com/questions/107705/disable-output-buffering">Disable output buffering</a>. (4th comment of accepted answer). Your working code should be like this:</p>
<pre><code>from __future__ import print_function
import sys
while True:
line = sys.stdin.readline()
print("hello!")
</code></pre>
<p>Works perfect in python 2.7.11</p>
<p><strong>EDIT</strong>:
last line <code>sys.stdout.flush()</code> has been removed. There is no need to use it in this situation.</p>
| 3 | 2016-08-26T09:26:27Z | [
"python",
"io",
"buffer",
"stdin",
"python-2.x"
] |
How to keep update the files using PYTHON | 39,161,653 | <pre><code>import os
import glob
import CameraID
files = glob.glob('/tmp/image/*.png')
count = 1
while (count==1):
for image in files:
if ( not os.path.isfile(image)):
print("Error: %s file not found" %image)
else:
print("Sending file %s ..." % image)
print CameraID.run()
print os.remove(image)
</code></pre>
<p>When I put the while loop, it will keep run and look for the old file instead the latest file. Anybody can help?</p>
| 1 | 2016-08-26T08:22:12Z | 39,161,992 | <p>moves the line:</p>
<pre><code>files = glob.glob('/tmp/image/*.png')
</code></pre>
<p>into the <code>while loop</code> to keep that updated</p>
| 2 | 2016-08-26T08:39:55Z | [
"python",
"python-2.7"
] |
TemplateSyntaxError at /cart/, Invalid block tag: '"cart:cart_remove"', expected 'endwith' | 39,161,736 | <p>I'm doing the webshop following the code in the book "Django by Example". I tried Google and searches in Stackoverflow but I did not find answers to this problem. </p>
<p>The product list page and the product detail page work fine but when I try to add items to the cart, the browser says:
TemplateSyntaxError at /cart/, Invalid block tag: '"cart:cart_remove"', expected 'endwith'.</p>
<p>Here is a screenshot of a part of the error page:
<a href="http://i.stack.imgur.com/FhHJC.png" rel="nofollow">error page code lines, maybe the picture is more clear</a>. Here you can also see the code of the error page:</p>
<pre><code>23 {% with product=item.product %}
24 <tr>
25 <td>
26 <a href="{{ product.get_absolute_url }}">
27 <img src="{% if product.image %}{{ product.image.url
28 }}{% else %}{% static "img/no_image.png" %}{% endif %}">
29 </a>
30 </td>
31 <td>{{ product.name }}</td>
32 <td>{{ item.quantity }}</td>
33
<td><a href="
{% "cart:cart_remove" product.id %}
">Remove</a></td>
34 <td class="num">${{ item.price }}</td>
35 <td class="num">${{ item.total_price }}</td>
36 </tr>
37 {% endwith %}
</code></pre>
<p>I checked the code. As you can see below, I have the endwith tag so I don't understand why it gives me that kind of an error. Pycharm was complaining about the " so I changed it to ' for the 'no_image.png' and 'cart:cart_remove'. However, I tried to run the website after replacing ' with ", but it gives me the same error. </p>
<p>Maybe this problem is related. Pycharm is complaining about the shop models at cart\view.py and underlines it with red:</p>
<pre><code>from shop.models import Product
</code></pre>
<p>Pycharm says Unresolved reference 'shop'. </p>
<p>Also the shop\view.py has a similar problem with this:</p>
<pre><code>from cart.forms import CartAddProductForm
</code></pre>
<p>I had some similar unresolved reference problem earlier but it seemed to have disappeared by itself somehow.</p>
| 0 | 2016-08-26T08:26:59Z | 39,161,890 | <p>The problem is not with <code>endwith</code>, but with the tag that is highlighted. <code>"cart:cart_remove"</code> is not a tag; I expect you meant to use <code>{% url "cart:cart_remove" ... %}</code> there.</p>
| 1 | 2016-08-26T08:34:24Z | [
"python",
"django"
] |
Shopify app: adding a new shipping address via webhook | 39,161,806 | <p>I'm planning to create a simple app using Django/Python that shows a nice button when installed by the store owner on user's account.</p>
<p>Clicking on that button should trigger a webhook request to our servers that would send back the generated shipping address for the user.</p>
<p>My questions:</p>
<ol>
<li>Is it possible to create such button through shopify API or this something the store owner must manually add?</li>
<li>Is it possible to add a shipping address upon user request?</li>
</ol>
<p>Thanks</p>
| 0 | 2016-08-26T08:30:33Z | 39,170,945 | <p>Here is the recipe:</p>
<ul>
<li>create a Proxy in your App to accept incoming Ajax call from customer</li>
<li>create a form and button in customer liquid that submits to your Proxy</li>
<li>in the App Proxy, validate the call from Shopify and when valid, look for your form params. </li>
<li>open the customer record with the ID of the customer you sent along with the form data, and add an address to their account</li>
</ul>
<p>Done. Simple. </p>
| 0 | 2016-08-26T16:35:56Z | [
"python",
"django",
"shopify"
] |
FileNotFoundError: [Errno 2] No such file or directory in Pycharm | 39,161,868 | <p>I'm pretty new with Python and finding some issues on a trivial code.
I'm using Pycharm together with Anaconda. </p>
<p>This is my code: </p>
<pre><code>posSentences = open('rt-polarity-pos.txt', 'r')
print (posSentences.read())
</code></pre>
<p>There is no issue in reading the file and printing it out when running it/terminal. </p>
<p>But when I try to run the same command in the console I get:</p>
<pre><code>FileNotFoundError: [Errno 2] No such file or directory
</code></pre>
<p>I so checked the directories of the console, but they seem fine and are the same of the running file: </p>
<p><a href="http://i.stack.imgur.com/61R4a.jpg" rel="nofollow">console setup</a></p>
<p>Thank you for your help!</p>
| 0 | 2016-08-26T08:33:29Z | 39,161,923 | <p>Python interpreter is run from <code>Desktop\textan</code> but the file is in <code>Desktop\textan\textan\</code> directory, so the path to the file in python code becomes <code>textan\rt...txt</code></p>
| 0 | 2016-08-26T08:36:11Z | [
"python",
"pycharm",
"anaconda"
] |
Writing a line of row per iteration to file without overwriting the file in python | 39,161,959 | <p>I have searched this on Stackoverflow and all of the "duplicates" for this topic but it seems remained unanswered. I have tried all these:</p>
<p><strong>Attempt#1:</strong></p>
<pre><code>for word in header:
writer.writerow([word]
</code></pre>
<p><em>Pasted from <a href="http://stackoverflow.com/questions/14134237/writing-data-from-a-python-list-to-csv-row-wise">writing data from a python list to csv row-wise</a></em> </p>
<p><strong>Attempt#2:</strong></p>
<p>And this one, should have been close but it has a bug:</p>
<pre><code># Open a file in witre mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
Pasted from <http://www.tutorialspoint.com/python/file_writelines.htm>
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()
</code></pre>
<p><em>Pasted from <a href="http://www.tutorialspoint.com/python/file_writelines.htm" rel="nofollow">http://www.tutorialspoint.com/python/file_writelines.htm</a></em> </p>
<p><strong>Attempt#3</strong>:</p>
<pre><code>>>>outF = open("myOutFile.txt", "w")
>>>for line in textList:
...   outF.write(line)
...   outF.write("\n")
>>>outF.close()
</code></pre>
<p><em>Pasted from <a href="http://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/" rel="nofollow">http://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/</a></em> </p>
<p><strong>Attempt#4:</strong> </p>
<pre><code>with open('file_to_write', 'w') as f:
f.write('file contents')
</code></pre>
<p><em>Pasted from <a href="http://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python">Correct way to write line to file in Python</a></em> </p>
<p><strong>Attempt#5:</strong> </p>
<p>This one which uses the append when writing to file.. but it appends each line at the end of each row. So it would be hard for me to separate all the rows. </p>
<pre><code>append_text = str(alldates)
with open('my_file.txt', 'a') as lead:
lead.write(append_text)
</code></pre>
<p><em>Pasted from <a href="http://stackoverflow.com/questions/22371625/python-saving-a-string-to-file-without-overwriting-files-contents">Python: Saving a string to file without overwriting file's contents</a></em> </p>
<p><em>Can someone help me how to write a newline of row per iteration in a loop to a file without overwriting the file?</em></p>
| -1 | 2016-08-26T08:38:03Z | 39,162,141 | <pre><code>data = [1,2,3,4,5]
with open('asd.txt', 'w') as fn:
for i in data:
fn.write(str(i) + '\n') # Add a \n (newline) so the next write will occure in the next line
</code></pre>
<p>Content of <code>asd.txt</code>:</p>
<pre><code>1
2
3
4
5
</code></pre>
<p>If you want to append to a file use <code>with open('asd.txt', 'a') as fn:</code></p>
| 0 | 2016-08-26T08:47:54Z | [
"python",
"python-2.7"
] |
Writing a line of row per iteration to file without overwriting the file in python | 39,161,959 | <p>I have searched this on Stackoverflow and all of the "duplicates" for this topic but it seems remained unanswered. I have tried all these:</p>
<p><strong>Attempt#1:</strong></p>
<pre><code>for word in header:
writer.writerow([word]
</code></pre>
<p><em>Pasted from <a href="http://stackoverflow.com/questions/14134237/writing-data-from-a-python-list-to-csv-row-wise">writing data from a python list to csv row-wise</a></em> </p>
<p><strong>Attempt#2:</strong></p>
<p>And this one, should have been close but it has a bug:</p>
<pre><code># Open a file in witre mode
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
Pasted from <http://www.tutorialspoint.com/python/file_writelines.htm>
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
line = fo.next()
print "Line No %d - %s" % (index, line)
# Close opend file
fo.close()
</code></pre>
<p><em>Pasted from <a href="http://www.tutorialspoint.com/python/file_writelines.htm" rel="nofollow">http://www.tutorialspoint.com/python/file_writelines.htm</a></em> </p>
<p><strong>Attempt#3</strong>:</p>
<pre><code>>>>outF = open("myOutFile.txt", "w")
>>>for line in textList:
...   outF.write(line)
...   outF.write("\n")
>>>outF.close()
</code></pre>
<p><em>Pasted from <a href="http://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/" rel="nofollow">http://cmdlinetips.com/2012/09/three-ways-to-write-text-to-a-file-in-python/</a></em> </p>
<p><strong>Attempt#4:</strong> </p>
<pre><code>with open('file_to_write', 'w') as f:
f.write('file contents')
</code></pre>
<p><em>Pasted from <a href="http://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python">Correct way to write line to file in Python</a></em> </p>
<p><strong>Attempt#5:</strong> </p>
<p>This one which uses the append when writing to file.. but it appends each line at the end of each row. So it would be hard for me to separate all the rows. </p>
<pre><code>append_text = str(alldates)
with open('my_file.txt', 'a') as lead:
lead.write(append_text)
</code></pre>
<p><em>Pasted from <a href="http://stackoverflow.com/questions/22371625/python-saving-a-string-to-file-without-overwriting-files-contents">Python: Saving a string to file without overwriting file's contents</a></em> </p>
<p><em>Can someone help me how to write a newline of row per iteration in a loop to a file without overwriting the file?</em></p>
| -1 | 2016-08-26T08:38:03Z | 39,162,677 | <p>There is 2 ways to do that:</p>
<p>First by adding '\n' character at the end of your output line :</p>
<pre><code>for x in row:
writer.write(x + "\n")
</code></pre>
<p>Second by opening file in Append mode, it is going to add lines existing text file but be careful.it's not overwrite the file :</p>
<pre><code>fw = open(myfile.txt,'a')
</code></pre>
| 0 | 2016-08-26T09:14:53Z | [
"python",
"python-2.7"
] |
Mysql fails to run after reboot using crontab | 39,161,966 | <p>I have made a script which saves data to Mysql database using mysqldp and python. When I run script from console (python myscript.py) it works, but when I run it on reboot using Crontab I get an email with following error:</p>
<blockquote>
<p><strong>_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)")</strong> </p>
</blockquote>
<p>When I try to run the script using <strong>Crontab</strong> not on reboot, but accordingly to time I don't get following error. </p>
<p>Maybe you have some ideas? </p>
<p>What if I would call the same script with <code>while(1)</code> loop once and once again (It will start the new background task every time)?</p>
| -2 | 2016-08-26T08:38:24Z | 39,165,472 | <p>Thanks to Shadow's hint I have solved the problem.
I just have started the <strong>Mysql</strong> server manually from the script and now it works.</p>
<p>I have used this command to start the server</p>
<blockquote>
<p><strong>from subprocess import call</strong></p>
<p><strong>call(['sudo','service','mysql','start'])</strong></p>
</blockquote>
| 0 | 2016-08-26T11:42:10Z | [
"python",
"mysql",
"crontab"
] |
MDM server - M2Crypto: undefined symbol: SSLv2_method | 39,161,999 | <p>I have downloaded a code from <a href="https://github.com/project-imas/mdm-server.git" rel="nofollow">GitHub</a>. I tried to run that code in my linux machine and i have installed all required libraries.But the code is not working and displaying the following error. Please help me to get out of this problem.I will be thankful to you. </p>
<pre><code>Traceback (most recent call last):
File "server.py", line 9, in <module>
from M2Crypto import SMIME, X509, BIO
File "/usr/local/lib/python2.7/dist-packages/M2Crypto-0.25.1-py2.7-linux-x86_64.egg/M2Crypto/__init__.py", line 26, in <module>
from M2Crypto import (ASN1, AuthCookie, BIO, BN, DH, DSA, EVP, Engine, Err,
File "/usr/local/lib/python2.7/dist-packages/M2Crypto-0.25.1-py2.7-linux-x86_64.egg/M2Crypto/ASN1.py", line 15, in <module>
from M2Crypto import BIO, m2, util
File "/usr/local/lib/python2.7/dist-packages/M2Crypto-0.25.1-py2.7-linux-x86_64.egg/M2Crypto/BIO.py", line 10, in <module>
from M2Crypto import m2, util
File "/usr/local/lib/python2.7/dist-packages/M2Crypto-0.25.1-py2.7-linux-x86_64.egg/M2Crypto/m2.py", line 30, in <module>
from M2Crypto._m2crypto import *
File "/usr/local/lib/python2.7/dist-packages/M2Crypto-0.25.1-py2.7-linux-x86_64.egg/M2Crypto/_m2crypto.py", line 26, in <module>
__m2crypto = swig_import_helper()
File "/usr/local/lib/python2.7/dist-packages/M2Crypto-0.25.1-py2.7-linux-x86_64.egg/M2Crypto/_m2crypto.py", line 22, in swig_import_helper
_mod = imp.load_module('__m2crypto', fp, pathname, description)
ImportError: /usr/local/lib/python2.7/dist-packages/M2Crypto-0.25.1-py2.7-linux-x86_64.egg/M2Crypto/__m2crypto.so: undefined symbol: SSLv2_method
</code></pre>
| 0 | 2016-08-26T08:40:24Z | 39,519,917 | <p>Although <a href="http://stackoverflow.com/a/11072709/780190">this</a> answer suggests a patch for <code>M2Crypto-0.21.1</code>, it never worked for me.<br>
By default ubuntu has <code>openssl</code> built without <code>SSLv2</code> support as <a href="http://stackoverflow.com/a/8219807/780190">explained here</a>, I had to compile <code>openssl</code> from source to get it working.</p>
| 0 | 2016-09-15T20:34:22Z | [
"python",
"mdm",
"m2crypto"
] |
Python readinto: How to convert from an array.array to a custom ctype structure | 39,162,028 | <p>I have created an array of integers and I would like them to be interpreted by the structure definition which I have created</p>
<pre><code>from ctypes import *
from array import array
class MyStruct(Structure):
_fields_ = [("init", c_uint),
("state", c_char),
("constant", c_int),
("address", c_uint),
("size", c_uint),
("sizeMax", c_uint),
("start", c_uint),
("end", c_uint),
("timestamp", c_uint),
("location", c_uint),
("nStrings", c_uint),
("nStringsMax", c_uint),
("maxWords", c_uint),
("sizeFree", c_uint),
("stringSizeMax", c_uint),
("stringSizeFree", c_uint),
("recordCount", c_uint),
("categories", c_uint),
("events", c_uint),
("wraps", c_uint),
("consumed", c_uint),
("resolution", c_uint),
("previousStamp", c_uint),
("maxTimeStamp", c_uint),
("threshold", c_uint),
("notification", c_uint),
("version", c_ubyte)]
# arr = array.array('I', [1])
# How can I do this?
# mystr = MyStruct(arr) magic
# (mystr.helloworld == 1) == True
</code></pre>
<p>I can do the following:</p>
<pre><code>mystr = MyStruct()
rest = array.array('I')
with open('myfile.bin', 'rb') as binaryFile:
binaryFile.readinto(mystr)
rest.fromstring(binaryFile.read())
# Now create another struct with rest
rest.readinto(mystr) # Does not work
</code></pre>
<p>How can I avoid using a file to convert an array of Ints to a struct if the data is contained in an array.array('I')? I am not sure what the Structure constructor accepts or how the readinto works.</p>
| 0 | 2016-08-26T08:41:59Z | 39,162,081 | <p>Does this have to be an array? could you use a list maybe? you can unpack from a list in to a function you can use the * operator:</p>
<p>mystr = MyStruct(*arr)</p>
<p>or a dict with:</p>
<p>mystr = MyStruct(**arr)</p>
| 0 | 2016-08-26T08:45:02Z | [
"python",
"arrays",
"ctypes",
"python-2.x"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.