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 |
|---|---|---|---|---|---|---|---|---|---|
Plotting 3D surface in python
| 39,414,278
|
<p>Although there are several sources on how to plot 3D surfaces with XYZ format. I have a CSV file from a scanning laser that provides no coordinate information on X and Y, just Z coordinates of a rectangular grid.</p>
<p>The file is 800 x 1600 with just z coordinates. Excel can plot it very easily with surface plot, but is limited by size.</p>
<p>How can I approach this problem?</p>
<p><a href="http://i.stack.imgur.com/zSemc.png" rel="nofollow">Screenshot of data format</a></p>
| 0
|
2016-09-09T14:46:36Z
| 39,415,557
|
<p>You just need to create arrays of the <code>X</code> and <code>Y</code> coordinates. We can do this with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>numpy.meshgrid</code></a>. In the example below, I set the cell size to 1., but you can easily scale that by changing the <code>cellsize</code> variable.</p>
<pre><code>import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# dummy data
nx, ny = 800, 1600
Z = np.random.rand(nx, ny)
# Create x, y coords
cellsize = 1.
x = np.arange(0., float(nx), 1.) * cellsize
y = np.arange(0., float(ny), 1.) * cellsize
X, Y = np.meshgrid(x, y)
# Create matplotlib Figure and Axes
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
ax.plot_surface(X, Y, Z)
plt.show()
</code></pre>
| 0
|
2016-09-09T16:02:01Z
|
[
"python",
"matplotlib",
"plot",
"surface"
] |
Adding javascript to a Django redirect (HttpResponse)
| 39,414,365
|
<p>I am using a redirect in Django <code>from django.shortcuts import redirect</code></p>
<p>What I want, is for the user to be displayed a Javascript alert message before being redirected.</p>
<p>Here is what I've got so far:</p>
<pre><code>response = redirect("someUrl")
response.write('<script>alert(\'You must remove an item before adding another\');</script>')
response['location'] += "?active=" + "all"
return response
</code></pre>
<p>The redirect works, but the Javascript does not. I also tried</p>
<pre><code>response = HttpResponse('<script>alert(\'You must remove an item before adding another\');</script>')
return response
</code></pre>
<p>This triggers the alert window, but I'm not sure how to add an equivalent redirect as the method above.</p>
| 0
|
2016-09-09T14:51:29Z
| 39,414,471
|
<p>You are getting confused between frontend and backend. When this view is requested by the user, the server (via Django's <a href="https://docs.djangoproject.com/en/1.10/_modules/django/http/response/#HttpResponseRedirect" rel="nofollow"><code>HTTPResponseRedirect</code></a>) is sending a <a href="https://en.wikipedia.org/wiki/HTTP_302" rel="nofollow"><code>302</code> redirect HTTP response</a> that tells the browser to redirect to a different page. This is different to a normal <code>200</code> response (i.e. a normal Django response object, not a redirect) within which you could include a javascript alert. </p>
<p>You need to show that javascript on the view you are initially loading <em>before</em> the user is returned the redirect response. </p>
| 1
|
2016-09-09T14:56:53Z
|
[
"python",
"django",
"redirect",
"httpresponse"
] |
Adding javascript to a Django redirect (HttpResponse)
| 39,414,365
|
<p>I am using a redirect in Django <code>from django.shortcuts import redirect</code></p>
<p>What I want, is for the user to be displayed a Javascript alert message before being redirected.</p>
<p>Here is what I've got so far:</p>
<pre><code>response = redirect("someUrl")
response.write('<script>alert(\'You must remove an item before adding another\');</script>')
response['location'] += "?active=" + "all"
return response
</code></pre>
<p>The redirect works, but the Javascript does not. I also tried</p>
<pre><code>response = HttpResponse('<script>alert(\'You must remove an item before adding another\');</script>')
return response
</code></pre>
<p>This triggers the alert window, but I'm not sure how to add an equivalent redirect as the method above.</p>
| 0
|
2016-09-09T14:51:29Z
| 39,415,401
|
<p>You can use <code>js appproach</code> <code>window.location</code></p>
<pre><code>url = 'someUrl'
resp_body = '<script>alert("You must remove an item before adding another");\
window.location="%s"</script>' % url
return HttpResponse(resp_body)
</code></pre>
| 0
|
2016-09-09T15:51:16Z
|
[
"python",
"django",
"redirect",
"httpresponse"
] |
Is there a way to prevent pandas to_json from adding \?
| 39,414,370
|
<p>I am trying to send a pandas dataframe to_json and I am having some issues with the date. I am getting an addtional \ so that my records look like <code>Updated:09\/06\/2016 03:09:44</code>. Is it possible to not have this additional \ added? I am assuming that it is an escape character of some sort but I haven't been able to find any additional information regarding this.</p>
<p>I have been adjusting the various parameters but I havent had any luck <code>df[0:10].to_json('splunkJsonFormat.txt', orient='records', date_format='ISO8601')</code></p>
<p>Sample Data:</p>
<pre><code>b_Updated,
Updated:09/06/2016 03:09:44,
Updated:06/29/2016 08:16:52,
Updated:09/07/2016 07:54:37,
</code></pre>
| 2
|
2016-09-09T14:51:48Z
| 39,415,510
|
<p>The JSON ouput you obtained is indeed correct and is the right behavior.</p>
<p>Allowing <code>\/</code> helps when embedding JSON in a <code><script></code> tag, which doesn't allow <code></</code> inside strings. Hence, in JSON <code>/</code> and <code>\/</code> are equivalent.</p>
<p>One workaround would be to separate the date from the string and convert it to a format more suitable where the datetime format is more evident.</p>
<pre><code>df['b_Updated'] = df['b_Updated'].str.split(':', 1) \
.apply(lambda x: x[0] + ':' + str(pd.to_datetime(x[1])))
df.to_json(orient='records', date_format='iso')
[{"b_Updated":"Updated:2016-09-06 03:09:44"},
{"b_Updated":"Updated:2016-06-29 08:16:52"},
{"b_Updated":"Updated:2016-09-07 07:54:37"}]
</code></pre>
| 3
|
2016-09-09T15:58:19Z
|
[
"python",
"json",
"pandas",
"to-json"
] |
python patch with side_effect on Object's method is not called with self
| 39,414,429
|
<p>I encounter a surprising behaviour of the side_effect parameter in patch.object where the function replacing the original does not receive <code>self</code></p>
<pre class="lang-py prettyprint-override"><code>class Animal():
def __init__(self):
self.noise = 'Woof'
def make_noise(self):
return self.noise
def loud(self):
return self.noise.upper() + '!!'
from unittest.mock import patch
dog = Animal()
dog.make_noise()
with patch.object(Animal, 'make_noise', side_effect=loud):
dog.make_noise()
</code></pre>
<p>This give:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/lustre/home/production/Applications/python/python-3.4.4/lib/python3.4/unittest/mock.py", line 902, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "/lustre/home/production/Applications/python/python-3.4.4/lib/python3.4/unittest/mock.py", line 968, in _mock_call
ret_val = effect(*args, **kwargs)
TypeError: loud() missing 1 required positional argument: 'self'
</code></pre>
<p>If I change the <code>loud</code> function to </p>
<pre><code>def loud(*args, **kwargs):
print(args)
print(kwargs)
</code></pre>
<p>I get the following output:</p>
<pre><code>()
{}
</code></pre>
<p>Is there a way to replace a function from an object and still receive self?</p>
| 0
|
2016-09-09T14:54:45Z
| 39,414,488
|
<p><code>self</code> is only supplied for <em>bound methods</em> (because functions are <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptors</a>). A <code>Mock</code> object is not such a method, and the <code>side_effect</code> function is not bound, so <code>self</code> is indeed not going to be passed in.</p>
<p>If you <em>must</em> have access the instance in a <code>side_effect</code> object, you'll have to patch the function on the class with an actual function:</p>
<pre><code>with patch.object(Animal, 'make_noise', new=loud):
</code></pre>
<p>Now <code>make_noise</code> is replaced by the <code>loud</code> function on the <code>Animal</code> class, so it'll be bound:</p>
<pre><code>>>> with patch.object(Animal, 'make_noise', new=loud):
... dog.make_noise()
...
'WOOF!!'
</code></pre>
<p>The alternative is to set <code>autospec=True</code>, at which point <code>mock</code> will use a real function to mock out <code>make_noise()</code>:</p>
<pre><code>>>> with patch.object(Animal, 'make_noise', autospec=True, side_effect=loud):
... dog.make_noise()
...
'WOOF!!'
</code></pre>
<p>Also see the <a href="https://docs.python.org/3/library/unittest.mock-examples.html#mocking-unbound-methods" rel="nofollow"><em>Mocking Unbound Methods</em> section</a> in the mock <em>getting started</em> section.</p>
| 0
|
2016-09-09T14:57:53Z
|
[
"python",
"unit-testing",
"mocking"
] |
django class based view multiple form validatiton
| 39,414,456
|
<p>I'm currently trying to have <b>two</b> forms on a single page. I'm using Class Based Views.</p>
<pre><code>class TaskDetailView(FormMixin, generic.DetailView):
model = Task
template_name="tasks/detail.html"
form_class = NoteForm
form_class2 = DurationForm
def get_context_data(self, **kwargs):
context = super(TaskDetailView, self).get_context_data(**kwargs)
context['note_form'] = self.get_form()
context['notes'] = Note.objects.filter(task__slug=self.kwargs['slug'])
context['duration_form'] = self.form_class2()
context['duration'] = Duration.objects.all()
return context
def get_success_url(self):
return reverse('task_detail', kwargs={'slug': self.kwargs['slug']})
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
current_task = get_object_or_404(Task, slug=self.kwargs['slug'])
self.object = form.save(commit=False)
self.object.task = current_task
self.object.save()
return HttpResponse(self.get_success_url())
</code></pre>
<p>My current status is that I'm able to display all the forms and save ONLY the Notes form. I'm not able to save the Duration Form despite there's a 200 status POST, the data is not being saved to the database.</p>
<p>I think my mistake is that I'm not validating it but I'm really not sure how to, and there isn't much information on multiple forms on CBVs in Django.</p>
<p>I would really appreciate some guidance and assistance.</p>
<p>Thanks</p>
| 0
|
2016-09-09T14:56:03Z
| 39,414,527
|
<p>Your <code>post</code> method doesn't do anything with the second form. You'd need to instantiate it and check its validity as you do with the first one.</p>
| 0
|
2016-09-09T14:59:58Z
|
[
"python",
"django",
"forms"
] |
django class based view multiple form validatiton
| 39,414,456
|
<p>I'm currently trying to have <b>two</b> forms on a single page. I'm using Class Based Views.</p>
<pre><code>class TaskDetailView(FormMixin, generic.DetailView):
model = Task
template_name="tasks/detail.html"
form_class = NoteForm
form_class2 = DurationForm
def get_context_data(self, **kwargs):
context = super(TaskDetailView, self).get_context_data(**kwargs)
context['note_form'] = self.get_form()
context['notes'] = Note.objects.filter(task__slug=self.kwargs['slug'])
context['duration_form'] = self.form_class2()
context['duration'] = Duration.objects.all()
return context
def get_success_url(self):
return reverse('task_detail', kwargs={'slug': self.kwargs['slug']})
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
current_task = get_object_or_404(Task, slug=self.kwargs['slug'])
self.object = form.save(commit=False)
self.object.task = current_task
self.object.save()
return HttpResponse(self.get_success_url())
</code></pre>
<p>My current status is that I'm able to display all the forms and save ONLY the Notes form. I'm not able to save the Duration Form despite there's a 200 status POST, the data is not being saved to the database.</p>
<p>I think my mistake is that I'm not validating it but I'm really not sure how to, and there isn't much information on multiple forms on CBVs in Django.</p>
<p>I would really appreciate some guidance and assistance.</p>
<p>Thanks</p>
| 0
|
2016-09-09T14:56:03Z
| 39,415,039
|
<p>A quite simple way of having multiple forms on one page would be to define some hidden parameter to differentiate between your POST actions, like:</p>
<pre><code><input name="formType" type="hidden" value="note">
</code></pre>
<p>In your CBV post method, you could:</p>
<pre><code>form_type = request.POST.get('formType', None)
if form_type == 'note':
</code></pre>
| 0
|
2016-09-09T15:28:56Z
|
[
"python",
"django",
"forms"
] |
how to convert type of variables in python?
| 39,414,492
|
<p>Suppose</p>
<pre><code> type(a) = <type 'numpy.ndarray'>
</code></pre>
<p>now I have another variable <code>b</code> (maybe a <code><type 'list'></code>), I want to convert it into the same type of <code>a</code>. How to do this? For example, </p>
<pre><code> >>> type(a)
<type 'numpy.ndarray'>
>>> b = [[[100, 200, 300]]]
>>> type(b)
<type 'list'>
</code></pre>
<p>Now, I want to </p>
<pre><code> >>> type(b)
<type 'numpy.ndarray'>
</code></pre>
<p>I want to do this in a python script. I don't know in advance what is the type of <code>a</code>. I just take <code>numpy.ndarray</code> as an example.</p>
<p><strong>UPDATE:</strong></p>
<p>In fact, in the python script, it receive some strings from <code>sys.argv</code>. And then it will assign these strings into some predefined variables in this script. These predefined variables may be <code>int</code>, <code>list</code>, <code>numpy.ndarray</code>, or else. For <code>int</code> or <code>list</code>, this can be done by <code>from ast import literal_eval; MyDict[sys.argv[1]] = literal_eval(sys.argv[2])</code>. But if <code>MyDict[sys.argv[1]]</code> is a <code>numpy.ndarray</code>, the <code>literal_eval</code> cann't reassign the list <code>[[[100, 200, 300]]]</code> into a <code>numpy.ndarray</code>. So I'm seeking a more effective way to do this.</p>
| -1
|
2016-09-09T14:57:57Z
| 39,414,570
|
<p>To convert a <code>list</code> into a python array, use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html" rel="nofollow"><code>numpy.asarray</code></a>.
For example:</p>
<pre><code>>>> import numpy as np
>>> a = [1, 2, 3, 4]
>>> a = np.asarray(a)
>>> a
array([1, 2, 3, 4])
>>> type(a)
<class 'numpy.ndarray'>
</code></pre>
<p>More generally, how to convert the type depends on what conversion you want.
To convert to a string use <a href="https://docs.python.org/3/library/stdtypes.html#textseq" rel="nofollow"><code>str</code></a>, to convert to an integer use <code>int</code>, and so on.
Note that in python the variables to not have a fixed "type", so you can simply reassign a variable to convert its type. For example</p>
<pre><code>>>> a = '2' # we can start from a string..
>>> a = int(a) # and than get an int
>>> a
2
>>> a = [1, 2, 3] # we can now completely change and make *a* a list
>>> a = tuple(a) # or maybe you want a tuple?
>>> a
(1, 2, 3)
</code></pre>
<p>To check if a variable is of a certain type you can use <code>isinstance</code>, so to convert the type of <code>b</code> depending on the type of <code>a</code> you can do something like</p>
<pre><code>def conditional_conversion(a, b):
if isinstance(a, int):
b = int(b)
elif isinstance(a, str):
b = str(b)
elif isinstance(a, list):
b = list(b)
return b
>>> a = 12
>>> b = '51'
>>> b = conditional_conversion(a, b)
51
</code></pre>
<p>Of course, you'd need to consider the various possibilities that you could incur into.
Also, this type of conversion will likely throw exception if <code>b</code> cannot be converted into the type of <code>a</code>, so a try-catch construct will probably be beneficial.</p>
| 1
|
2016-09-09T15:03:29Z
|
[
"python"
] |
how to convert type of variables in python?
| 39,414,492
|
<p>Suppose</p>
<pre><code> type(a) = <type 'numpy.ndarray'>
</code></pre>
<p>now I have another variable <code>b</code> (maybe a <code><type 'list'></code>), I want to convert it into the same type of <code>a</code>. How to do this? For example, </p>
<pre><code> >>> type(a)
<type 'numpy.ndarray'>
>>> b = [[[100, 200, 300]]]
>>> type(b)
<type 'list'>
</code></pre>
<p>Now, I want to </p>
<pre><code> >>> type(b)
<type 'numpy.ndarray'>
</code></pre>
<p>I want to do this in a python script. I don't know in advance what is the type of <code>a</code>. I just take <code>numpy.ndarray</code> as an example.</p>
<p><strong>UPDATE:</strong></p>
<p>In fact, in the python script, it receive some strings from <code>sys.argv</code>. And then it will assign these strings into some predefined variables in this script. These predefined variables may be <code>int</code>, <code>list</code>, <code>numpy.ndarray</code>, or else. For <code>int</code> or <code>list</code>, this can be done by <code>from ast import literal_eval; MyDict[sys.argv[1]] = literal_eval(sys.argv[2])</code>. But if <code>MyDict[sys.argv[1]]</code> is a <code>numpy.ndarray</code>, the <code>literal_eval</code> cann't reassign the list <code>[[[100, 200, 300]]]</code> into a <code>numpy.ndarray</code>. So I'm seeking a more effective way to do this.</p>
| -1
|
2016-09-09T14:57:57Z
| 39,414,717
|
<p>Presumably you don't <em>just</em> want to convert the type; you also want to preserve the existing value. (Otherwise you could just assign <code>b</code> to an empty object of the new type and be done with it.)</p>
<p>Very generally, you would call the new type's constructor, passing in the old value. For example, if you have an integer and you want to covert it to a string, call <code>str()</code> on the integer value:</p>
<pre><code>a = 5 # type(a) is <type 'int'>
a = str(a) # type(a) is now <type 'str'>
</code></pre>
<p>Or to convert a string to a list:</p>
<pre><code>a = "hello" # type(a) is <type 'str'>
a = list(a) # type(a) is now <type 'list'>
</code></pre>
<p>However this method is <em>very</em> generic and won't be usable in a lot of cases.</p>
| 0
|
2016-09-09T15:11:45Z
|
[
"python"
] |
How to write/print the lines breaks of a attribute of a json on Pyhon
| 39,414,569
|
<p>I have a little problema here.</p>
<p>I have the follow situation:</p>
<ul>
<li>I have the following json file</li>
</ul>
<blockquote>
<p>{ <br/>
"name":"whatever",<br/>
"lyric":"here comes the music <br/>
another line <br/>
whatever... <br/>
bla bla bla <br/>
final"<br/>
}</p>
</blockquote>
<ul>
<li><p>the next step would be loading the json file and change the attribute "name" to the "songs real name".</p></li>
<li><p>The final step would be writing the json to an output file, keepint the same input format (to make easier the json reading ), but it does print the lines break as scaped characters, like that:</p></li>
</ul>
<blockquote>
<p>{ <br/>
"name":"songs real name",<br/>
"lyric":"here comes the music \n
another line \n
whatever... \n
bla bla bla \n
final"<br/>
}</p>
</blockquote>
<p>Desired output:</p>
<blockquote>
<p>{ <br/>
"name":"songs real name",<br/>
"lyric":"here comes the music <br/>
another line <br/>
whatever... <br/>
bla bla bla <br/>
final"<br/>
}</p>
</blockquote>
<p>That's the python code:</p>
<pre><code>with open(file, "r") as data_file:
json_data=data_file.read()
data_file.close()
json_data["name"]="song's real name"
with open(outputfile)
jsonFile.write(json.dumps(data,indent=4, sort_keys=True)
</code></pre>
<p>everything works fine, except that it is not printing the lines break.</p>
<p>Thanks, I appreciate your help.</p>
| -1
|
2016-09-09T15:03:17Z
| 39,453,606
|
<p>I have got the answer, basicaly what I did was a replace over a json.dumps:</p>
<pre><code>with open(file, "r") as data_file:
json_data=data_file.read()
data_file.close()
json_data["name"]="song's real name"
with open(outputfile)
jsonFile.write(json.dumps(data,indent=4, sort_keys=True, separators=(',', ': ')).replace('\\n','\n'))
</code></pre>
<p>after that, I got the output file as I would like:</p>
<blockquote>
<p>{ <BR/>
"name" : "songs real name", <BR/>
"lyric" : "here comes the music <BR/>
another line <BR/>
whatever... <BR/>
bla bla bla <BR/>
final"<BR/>
}<BR/></p>
</blockquote>
<p>Thank you guys.</p>
| 0
|
2016-09-12T15:14:56Z
|
[
"python",
"json"
] |
Python Error's when I try to optimize those lines of code
| 39,414,574
|
<p>I use python 2.7, I want to reduce and optimize this code lines but I have a problem, could anybody help me please? </p>
<p>I have this list <code>B = [[0, Act1, XX1, u'P-Um'],.....[0, Act100, ZZ30, u'D- MOM']]</code> </p>
<ol>
<li>I want to take only the 4th value from B </li>
<li>Take just the part after hyphen and the space which is sometimes</li>
<li>Bring back to B</li>
</ol>
<p>Right now I wrote this code </p>
<pre><code>for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1] for i in x]
#A=[u'Um', u' LY', u' NO', ......, u' MOM']
for i in range(len(B)):
A[i].lstrip()
p = []
for i in range(len(B)):
p.append(A[i].lstrip())
for i in range(len(B)):
B[i][3] = p[i]
</code></pre>
<p>When I try to make it shorter at follows I have two errors.</p>
<pre><code>#Short version
for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1], x] #Error:AttributeError: 'int' object has no attribute 'split'
B[i][3].append(A[i].lstrip()) #Error:AttributeError: 'unicode' object has no attribute 'append'
</code></pre>
<p>I try many ways to solve the errors but still not working. Could you help please? Do you think is possible to make the top part shorter without errors?</p>
<p>Thank you very much in advance.</p>
| -3
|
2016-09-09T15:03:40Z
| 39,414,753
|
<p>You can use a list comprehension:</p>
<pre><code> B=[[B_element[0],B_element[1],B_element[2],B_element[3].split('-',1)[1].lstrip()] for B_element in B]
</code></pre>
| 0
|
2016-09-09T15:14:02Z
|
[
"python"
] |
Python Error's when I try to optimize those lines of code
| 39,414,574
|
<p>I use python 2.7, I want to reduce and optimize this code lines but I have a problem, could anybody help me please? </p>
<p>I have this list <code>B = [[0, Act1, XX1, u'P-Um'],.....[0, Act100, ZZ30, u'D- MOM']]</code> </p>
<ol>
<li>I want to take only the 4th value from B </li>
<li>Take just the part after hyphen and the space which is sometimes</li>
<li>Bring back to B</li>
</ol>
<p>Right now I wrote this code </p>
<pre><code>for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1] for i in x]
#A=[u'Um', u' LY', u' NO', ......, u' MOM']
for i in range(len(B)):
A[i].lstrip()
p = []
for i in range(len(B)):
p.append(A[i].lstrip())
for i in range(len(B)):
B[i][3] = p[i]
</code></pre>
<p>When I try to make it shorter at follows I have two errors.</p>
<pre><code>#Short version
for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1], x] #Error:AttributeError: 'int' object has no attribute 'split'
B[i][3].append(A[i].lstrip()) #Error:AttributeError: 'unicode' object has no attribute 'append'
</code></pre>
<p>I try many ways to solve the errors but still not working. Could you help please? Do you think is possible to make the top part shorter without errors?</p>
<p>Thank you very much in advance.</p>
| -3
|
2016-09-09T15:03:40Z
| 39,414,790
|
<p>I'm not seeing the many ways you've tried, but your code does have a handful of missteps. Even after correcting the indentation errors, your first variant iterates over an index which you don't need four times, and strips every entry twice (only using the result the second time). The second version fails firstly because that index isn't the entry and secondly because you're trying to alter a string instead of replacing it. </p>
<pre><code>A=[]
x=[]
for Bi in B:
Bi3 = Bi[3]
part = Bi3.split('-',1)[1].lstrip()
x.append(Bi3) # Original B[i][3] data
A.append(part) # What is this for?
Bi[3] = part # replaces B[i][3]
</code></pre>
<p>If you actually need performance, it's quite likely a regular expression might extract the part more efficiently than the split/strip combination, since those functions create new strings for each call. </p>
| 0
|
2016-09-09T15:16:04Z
|
[
"python"
] |
Python Error's when I try to optimize those lines of code
| 39,414,574
|
<p>I use python 2.7, I want to reduce and optimize this code lines but I have a problem, could anybody help me please? </p>
<p>I have this list <code>B = [[0, Act1, XX1, u'P-Um'],.....[0, Act100, ZZ30, u'D- MOM']]</code> </p>
<ol>
<li>I want to take only the 4th value from B </li>
<li>Take just the part after hyphen and the space which is sometimes</li>
<li>Bring back to B</li>
</ol>
<p>Right now I wrote this code </p>
<pre><code>for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1] for i in x]
#A=[u'Um', u' LY', u' NO', ......, u' MOM']
for i in range(len(B)):
A[i].lstrip()
p = []
for i in range(len(B)):
p.append(A[i].lstrip())
for i in range(len(B)):
B[i][3] = p[i]
</code></pre>
<p>When I try to make it shorter at follows I have two errors.</p>
<pre><code>#Short version
for i in range(len(B)):
x.append(B[i][3])
A = [i.split('-',1)[1], x] #Error:AttributeError: 'int' object has no attribute 'split'
B[i][3].append(A[i].lstrip()) #Error:AttributeError: 'unicode' object has no attribute 'append'
</code></pre>
<p>I try many ways to solve the errors but still not working. Could you help please? Do you think is possible to make the top part shorter without errors?</p>
<p>Thank you very much in advance.</p>
| -3
|
2016-09-09T15:03:40Z
| 39,414,791
|
<p>You don't have to index the items of B to iterate over them. This may help.</p>
<pre><code>>>> Act1 = XX1 = Act100 = ZZ30 = None # simply to avoid NameError exceptions
>>> B = [[0, Act1, XX1, u'P-Um'],[0, Act100, ZZ30, u'D- MOM']]
>>> result = [b[3].split('-')[1].strip() for b in B]
>>> result
['Um', 'MOM']
</code></pre>
<p><code>result</code> is a list, produced by taking element 3 of each item in B, splitting it on the <code>'-'</code> and stripping leading and trailing spaces from element 1 of the split string. The technique I have used is known as a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>.</p>
<p>If you then want to replace the fourth elements with these new values, one way to achieve this is as follows.</p>
<pre><code>>>> final = []
>>> for b, r in zip(B, result):
... final.append([b[0], b[1], b[2], r])
...
>>> final
[[0, None, None, 'Um'], [0, None, None, 'MOM']]
</code></pre>
<p>Then just replace <code>B</code> with <code>final</code>:</p>
<pre><code>>>> B = final
</code></pre>
| 0
|
2016-09-09T15:16:07Z
|
[
"python"
] |
How using select Query in Python?
| 39,414,642
|
<p>How can i use a <strong>SELECT</strong> Query in Python ?</p>
<p><em>I just need a very sample example !</em></p>
<p>Example in PHP :</p>
<pre><code>$query = $db_connection -> prepare ("SELECT * FROM table WHERE name = :name");
$query -> execute (array (":name" => $name));
$rows = $query -> fetchAll (PDO::FETCH_ASSOC);
foreach ($rows as $row)
{
$id = $row["id"];
}
echo $id;
</code></pre>
<p>I need same function in Python where <em>name</em> is an input !</p>
| -2
|
2016-09-09T15:07:21Z
| 39,415,244
|
<p>The Answer :</p>
<pre><code>query = ("""SELECT * FROM table WHERE name = '%s'""" % (name))
cursor.execute (query)
results = cursor.fetchall()
for row in results:
id = row[0]
print (id)
</code></pre>
| 0
|
2016-09-09T15:41:12Z
|
[
"python",
"select"
] |
GAE Flask global variable persistent across browsers
| 39,414,664
|
<p>Here's my Flask setup:</p>
<p><code>main.py</code></p>
<pre><code>from flask import Flask
from app.views import main_bp
app = Flask(__name__)
app.register_blueprint(main_bp, url_prefix='')
</code></pre>
<p><code>app.config.py</code> (Shortened with "..." for this example)</p>
<pre><code>CONFIG = {
'SITE_NAME': 'Test Site',
'SSL': False,
'DEBUG': True,
'LOGGED_IN': False,
...
}
</code></pre>
<p><code>views.py</code></p>
<pre><code>from config import CONFIG
@main_bp.route('/')
@main_bp.route('/<page_slug>/')
def fallback(page_slug='home'):
# Check if logged in
if CONFIG['LOGGED_IN']:
return 'Logged In'
else
return 'Logged Out'
</code></pre>
<p>Now if I change <code>CONFIG['LOGGED_IN']</code> to <code>True</code> in one of my browsers (Let's say Google Chrome), and then open another browser to the website (Let's say Firefox), then I'm already logged in on both. If I then log out in Firefox and refresh Chrome, I'm logged out on both.</p>
<p>When I was using Django I never noticed a problem like this... my global CONFIG variable is persisting across browsers. Weird!</p>
<p>Do I need to make my CONFIG into a class? Maybe this only happens when running through dev_appserver.py and won't happen in production? I'm still learning, so please be nice! Thanks :)</p>
<p>Note: Please ignore the blatant security issues with this example. I assure you this is not how I plan to use this code.</p>
| -1
|
2016-09-09T15:08:44Z
| 39,414,953
|
<p>As davidism pointed out, I should not be storing variables that change per session as a global. I will instead decide on these variables after loading pertinent session variables like UID and Session ID.</p>
<p>Thanks.</p>
<p>Update: Athough, I find it interesting that Flask documentation would advocate setting globals via <code>g</code> (see: <a href="http://flask.pocoo.org/docs/0.11/api/" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/</a>)</p>
| 0
|
2016-09-09T15:24:09Z
|
[
"python",
"google-app-engine",
"flask"
] |
Error when trying to redefine the division operator with __div__
| 39,414,772
|
<p>Why does numpy throw an exception for the following code? <code>foo/3</code> works fine.</p>
<pre><code>import numpy as np
class item(object):
def __init__(self, val = 0.0):
self._val = val
@property
def value(self):
return self._val
def __add__(self, other):
return item(self.value + other.value)
def __sub__(self, other):
return item(self.value - other.value)
def __mul__(self, other):
if isinstance(other, item):
return self.value * other.value
if isinstance(other, (int, float, long)):
return item(other*self.value)
raise TypeError("unsupported operand")
def __div__(self, other):
if isinstance(other, (int, float, long)):
return item(self.value/other)
raise TypeError("unsupported operand")
def __cmp__(self, other):
if self.value < other.value:
return -1
if self.value == other.value:
return 0
return 1
def __str__(self):
return "item <%f>" % self.value
data = [ item(x) for x in np.random.random(size = 1000) ]
foo = item(3.1)
foo/3
np.mean(data)
</code></pre>
<p>error message:</p>
<pre><code> 45 foo/3
46
---> 47 np.mean(data)
48
/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.pyc in mean(a, axis, dtype, out, keepdims) 2714 2715 return
_methods._mean(a, axis=axis, dtype=dtype,
-> 2716 out=out, keepdims=keepdims) 2717 2718 def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
/usr/lib/python2.7/dist-packages/numpy/core/_methods.pyc in _mean(a, axis, dtype, out, keepdims)
67 ret = ret.dtype.type(ret / rcount)
68 else:
---> 69 ret = ret / rcount
70
71 return ret
TypeError: unsupported operand type(s) for /: 'item' and 'int'
</code></pre>
| 3
|
2016-09-09T15:15:11Z
| 39,415,190
|
<p>I need to define <code>__truediv__</code>. The documentation says: </p>
<blockquote>
<p>object.<code>__div__</code>(self, other) </p>
<p>object.<code>__truediv__</code>(self, other) </p>
<p>The division operator (/) is implemented by these methods. The
<code>__truediv__()</code> method is used when <code>__future__.division</code> is in effect, otherwise <code>__div__()</code> is used. If only one of these two methods is
defined, the object will not support division in the alternate
context; TypeError will be raised instead.</p>
</blockquote>
<p>see <a href="https://docs.python.org/2.7/reference/datamodel.html?highlight=__len__#object.__truediv__" rel="nofollow">https://docs.python.org/2.7/reference/datamodel.html?highlight=<strong>len</strong>#object.<strong>truediv</strong></a></p>
| 3
|
2016-09-09T15:38:18Z
|
[
"python",
"python-2.7",
"numpy"
] |
Django Rest Create with a Writable Nested Serializer
| 39,415,005
|
<p>I'm trying to perform a create in Django Rest Framework using a writable nested serializer.</p>
<p>With the code bellow I can create a ScriptQuestion but I can't add a RecordedInterview into it. Django says OrderedDict is None.</p>
<p>What am I doing wrong?</p>
<p>Thanks in advance</p>
<pre><code>#models.py
class ScriptQuestion(models.Model):
interview = models.ManyToManyField(RecordedInterview)
...
class RecordedInterview(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
...
</code></pre>
<p>The serializers</p>
<pre><code>#serializers.py
class InterviewTitleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = RecordedInterview
fields = ('id', 'title')
extra_kwargs = {
'title': { 'read_only': True }
}
class QuestionDetailSerializer(serializers.HyperlinkedModelSerializer):
interview = InterviewTitleSerializer(many=True)
class Meta:
model = ScriptQuestion
fields = ('id', 'title', 'prep_time', 'answer_time', 'interview')
depth = 1
def create(self, validated_data):
interview_data = validated_data.pop('interview')
question = ScriptQuestion.objects.create(**validated_data)
for item in interview_data:
item = interview_data['id']
question.interview.add(item)
return question
</code></pre>
<p>Here is my view</p>
<pre><code>#views.py
class CreateQuestion(generics.CreateAPIView):
queryset = ScriptQuestion.objects.all()
serializer_class = QuestionDetailSerializer
</code></pre>
<p>And the json</p>
<pre><code>{
"title": "Question Test Json",
"prep_time": "1",
"answer_time":"1",
"interview": [
{
"id": "a450aeb0-8446-47b0-95bd-5accbb8b4afa"
}
]
}
</code></pre>
<p>If I do manually, I can add the RecordedInterview into the ScriptQuestion:</p>
<pre><code>#serializers.py
def create(self, validated_data):
interview_data = validated_data.pop('interview')
question = ScriptQuestion.objects.create(**validated_data)
item = 'a450aeb0-8446-47b0-95bd-5accbb8b4afa'
question.interview.add(item)
return question
</code></pre>
| 0
|
2016-09-09T15:26:27Z
| 39,415,462
|
<p>I cannot add a comment because of low reputation. SO adding as an answer. I think you should use 'serializers.ModelSerializer' instead of 'serializers.HyperLinkedModelSerializer'</p>
| 1
|
2016-09-09T15:55:14Z
|
[
"python",
"django",
"nested",
"django-rest-framework"
] |
Django Rest Create with a Writable Nested Serializer
| 39,415,005
|
<p>I'm trying to perform a create in Django Rest Framework using a writable nested serializer.</p>
<p>With the code bellow I can create a ScriptQuestion but I can't add a RecordedInterview into it. Django says OrderedDict is None.</p>
<p>What am I doing wrong?</p>
<p>Thanks in advance</p>
<pre><code>#models.py
class ScriptQuestion(models.Model):
interview = models.ManyToManyField(RecordedInterview)
...
class RecordedInterview(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
...
</code></pre>
<p>The serializers</p>
<pre><code>#serializers.py
class InterviewTitleSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = RecordedInterview
fields = ('id', 'title')
extra_kwargs = {
'title': { 'read_only': True }
}
class QuestionDetailSerializer(serializers.HyperlinkedModelSerializer):
interview = InterviewTitleSerializer(many=True)
class Meta:
model = ScriptQuestion
fields = ('id', 'title', 'prep_time', 'answer_time', 'interview')
depth = 1
def create(self, validated_data):
interview_data = validated_data.pop('interview')
question = ScriptQuestion.objects.create(**validated_data)
for item in interview_data:
item = interview_data['id']
question.interview.add(item)
return question
</code></pre>
<p>Here is my view</p>
<pre><code>#views.py
class CreateQuestion(generics.CreateAPIView):
queryset = ScriptQuestion.objects.all()
serializer_class = QuestionDetailSerializer
</code></pre>
<p>And the json</p>
<pre><code>{
"title": "Question Test Json",
"prep_time": "1",
"answer_time":"1",
"interview": [
{
"id": "a450aeb0-8446-47b0-95bd-5accbb8b4afa"
}
]
}
</code></pre>
<p>If I do manually, I can add the RecordedInterview into the ScriptQuestion:</p>
<pre><code>#serializers.py
def create(self, validated_data):
interview_data = validated_data.pop('interview')
question = ScriptQuestion.objects.create(**validated_data)
item = 'a450aeb0-8446-47b0-95bd-5accbb8b4afa'
question.interview.add(item)
return question
</code></pre>
| 0
|
2016-09-09T15:26:27Z
| 39,419,600
|
<p>Oh, I could make it.</p>
<p>For someone in the future, just add "id = serializers.CharField()" in the Serializer</p>
<pre><code>class InterviewTitleSerializer(serializers.ModelSerializer):
id = serializers.CharField()
class Meta:
model = RecordedInterview
fields = ('id', 'title')
extra_kwargs = {'title': { 'read_only': True }}
</code></pre>
| 0
|
2016-09-09T20:58:19Z
|
[
"python",
"django",
"nested",
"django-rest-framework"
] |
How can I prevent a logged in user from accessing a 'Log In' or 'Sign Up' page in Django version 1.9?
| 39,415,019
|
<p>I'm pretty new to Python.</p>
<p>My problem is that I want to restrict users who are already logged in from being able to visit the log in and sign up pages.</p>
<p>Essentially, what I'm looking for is something like the @login_required decorator, that will allow access to these pages for users who are <strong>not</strong> logged in.</p>
<p>So far, I have </p>
<ul>
<li>Looked at other SO questions such as <a href="http://stackoverflow.com/questions/15263102/django-registration-how-to-prevent-logged-in-user-from-registering">Django-Registration: How to prevent logged in user from registering?</a>, however I've tried the solution here, and it does not work for me.</li>
<li>I've searched through the Django Documentation, Django Girls and other websites that offer tutorials for learning Django.</li>
</ul>
<p>Here's my views.py for the log in:</p>
<pre><code>def login_view(request): # Login View to begin user session
print(request.user.is_authenticated())
if request.method == 'POST':
form = UserLogInForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
print(request.user.is_authenticated())
return HttpResponseRedirect('/')
else:
form = UserLogInForm()
return render(request, 'login.html', {'form': form})
else:
form = UserLogInForm()
return render(request, 'login.html', {'form': form})
</code></pre>
<p>and the sign up:</p>
<pre><code>class signup_view(View):
form_class = UserSignUpForm
template_name = 'signup.html'
# Blank form is requested
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# Form is filled in and posted to DB - Process the Data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
# Further checks before committing object to the DB
# Cleaned Data
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(first_name=first_name,
last_name=last_name,
email=email,
username=username,
password=password
)
user.set_password(password)
user.save()
user = authenticate(email=email, username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
return render(request, self.template_name, {'form': form})
</code></pre>
<p>If anybody knows any solutions then that would be amazing, thank you.</p>
| 2
|
2016-09-09T15:27:59Z
| 39,415,109
|
<p>Since you are using a class-based view, you can use the <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin">UserPassesTestMixin</a> and in the check method test that the user is anonymous:</p>
<pre><code>class signup_view(UserPassesTestMixin, View):
...
def test_func(self):
return self.request.user.is_anonymous()
</code></pre>
<p>You can do a similar thing for the other view using the <code>@user_passes_test</code> decorator.</p>
| 5
|
2016-09-09T15:32:54Z
|
[
"python",
"django"
] |
How can I prevent a logged in user from accessing a 'Log In' or 'Sign Up' page in Django version 1.9?
| 39,415,019
|
<p>I'm pretty new to Python.</p>
<p>My problem is that I want to restrict users who are already logged in from being able to visit the log in and sign up pages.</p>
<p>Essentially, what I'm looking for is something like the @login_required decorator, that will allow access to these pages for users who are <strong>not</strong> logged in.</p>
<p>So far, I have </p>
<ul>
<li>Looked at other SO questions such as <a href="http://stackoverflow.com/questions/15263102/django-registration-how-to-prevent-logged-in-user-from-registering">Django-Registration: How to prevent logged in user from registering?</a>, however I've tried the solution here, and it does not work for me.</li>
<li>I've searched through the Django Documentation, Django Girls and other websites that offer tutorials for learning Django.</li>
</ul>
<p>Here's my views.py for the log in:</p>
<pre><code>def login_view(request): # Login View to begin user session
print(request.user.is_authenticated())
if request.method == 'POST':
form = UserLogInForm(request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
print(request.user.is_authenticated())
return HttpResponseRedirect('/')
else:
form = UserLogInForm()
return render(request, 'login.html', {'form': form})
else:
form = UserLogInForm()
return render(request, 'login.html', {'form': form})
</code></pre>
<p>and the sign up:</p>
<pre><code>class signup_view(View):
form_class = UserSignUpForm
template_name = 'signup.html'
# Blank form is requested
def get(self, request):
form = self.form_class(None)
return render(request, self.template_name, {'form': form})
# Form is filled in and posted to DB - Process the Data
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
# Further checks before committing object to the DB
# Cleaned Data
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
email = form.cleaned_data['email']
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = User.objects.create_user(first_name=first_name,
last_name=last_name,
email=email,
username=username,
password=password
)
user.set_password(password)
user.save()
user = authenticate(email=email, username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/')
return render(request, self.template_name, {'form': form})
</code></pre>
<p>If anybody knows any solutions then that would be amazing, thank you.</p>
| 2
|
2016-09-09T15:27:59Z
| 39,416,220
|
<p>i guess you can add a middleware something like this :
your_app/middlewares/user_restriction_middleware.py</p>
<p>and that files be like:</p>
<pre><code>class UserRestrictionMiddleware:
def process_request(self, request):
if request.user.is_authenticated():
request_path = request.path_info
if request_path.startswith('/login/') or request_path.startswith('/register/') :
return HttpResponseRedirect('.... to whereever you want...')
</code></pre>
<p>add this to your settings.py's MIDDLEWARE_CLASSES like :
'your_app.middlewares.user_restriction_middleware.UserRestrictionMiddleware',</p>
| 0
|
2016-09-09T16:43:06Z
|
[
"python",
"django"
] |
Python - Iterating over Arguments passed to a Function
| 39,415,030
|
<p>Suppose I have the following example:</p>
<pre><code>class foo:
...
def bar(self, w, x, y, z, ...):
self.w = w
self.x = x
self.y = y
self.z = z
...
</code></pre>
<p>I wish to reduce the n-number of attribute assignment lines in <code>bar()</code> to one assignment line set using a <code>setattr()</code> cycle through the arguments. Is there a good way to cycle through said arguments for this purpose?</p>
<p>I wish to retain the defined parameter names so as to limit the number of parameters passed to the function as well as the order in which they are passed. I also understand that <a href="http://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators-in-python/1594484#1594484">functions can be handled like objects</a>; so is it possible to obtain a list of the defined parameters as an attribute of the function and iterate through that?</p>
| 3
|
2016-09-09T15:28:32Z
| 39,415,454
|
<p>The <a href="https://docs.python.org/3/reference/datamodel.html#object.__setattr__" rel="nofollow"><code>__setattr__</code></a> attribute only assigns one attribute at a time, if you want to assign multiple attribute, you can use <code>**kwargs</code> in your function header and for limiting the number of arguments you can simply check the length of <code>kwargs</code> within your function. and call the <code>__setattr__</code> for each each of the arguments one by one. One good reason for this recipe is that basically assigning attribute to an object without considering anything is not a correct and desirable job, due to a lot of reasons. Thus you have to assign each attribute one at a time by considering all the required conditions.</p>
<p>You can also do this manually by updating the instance dictionary but you should handle the exceptions too. </p>
<pre><code>In [80]: class foo:
def bar(self, **kwargs):
if len(kwargs) != 4:
raise Exception("Please enter 4 keyword argument")
for k, v in kwargs.items():
foo.__setattr__(self, k, v)
....:
In [81]: f = foo()
In [82]: f.bar(w=1, x=2, y=3, z=4)
In [83]: f.w
Out[83]: 1
In [84]: f.bar(w=1, x=2, y=3, z=4, r=5)
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-84-758f669d08e0> in <module>()
----> 1 f.bar(w=1, x=2, y=3, z=4, r=5)
<ipython-input-80-9e46a6a78787> in bar(self, **kwargs)
2 def bar(self, **kwargs):
3 if len(kwargs) != 4:
----> 4 raise Exception("Please enter 4 keyword argument")
5 for k, v in kwargs.items():
6 foo.__setattr__(self, k, v)
Exception: Please enter 4 keyword argument
</code></pre>
<p>By using <code>__setatter__</code> it will take care of the exception automatically:</p>
<pre><code>In [70]: f.bar(1, 2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-70-07d1f3c9e27f> in <module>()
----> 1 f.bar(1, 2)
<ipython-input-65-1049e26120c1> in bar(self, *args)
2 def bar(self, *args):
3 for item in args:
----> 4 foo.__setattr__(self, item, item)
5
TypeError: attribute name must be string, not 'int'
</code></pre>
| -1
|
2016-09-09T15:54:44Z
|
[
"python",
"arguments",
"variable-assignment",
"setattr"
] |
Python - Iterating over Arguments passed to a Function
| 39,415,030
|
<p>Suppose I have the following example:</p>
<pre><code>class foo:
...
def bar(self, w, x, y, z, ...):
self.w = w
self.x = x
self.y = y
self.z = z
...
</code></pre>
<p>I wish to reduce the n-number of attribute assignment lines in <code>bar()</code> to one assignment line set using a <code>setattr()</code> cycle through the arguments. Is there a good way to cycle through said arguments for this purpose?</p>
<p>I wish to retain the defined parameter names so as to limit the number of parameters passed to the function as well as the order in which they are passed. I also understand that <a href="http://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators-in-python/1594484#1594484">functions can be handled like objects</a>; so is it possible to obtain a list of the defined parameters as an attribute of the function and iterate through that?</p>
| 3
|
2016-09-09T15:28:32Z
| 39,415,544
|
<p>Use <code>locals()</code> and you can get all the arguments (and any other local variables):</p>
<pre><code>class foo:
def bar(self, w, x, y, z):
argdict = {arg: locals()[arg] for arg in ('w', 'x', 'y', 'z')}
for key, value in argdict.iteritems():
setattr(self, key, value)
...
</code></pre>
<p>Might be possible to do it more efficiently, and you could inline argdict if you prefer less lines to readability or find it more readable that way.</p>
| 0
|
2016-09-09T16:00:27Z
|
[
"python",
"arguments",
"variable-assignment",
"setattr"
] |
how to get the attribute value from tags html with python 3.5.2
| 39,415,106
|
<p>hi i have a problem with python 3.5.2
i don't know where is the problem when i want to get the value of atribute a get all tags (atribute + value) but i want just the value of title ??
this is my code</p>
<pre><code>from bs4 import BeautifulSoup as bs
import requests
url = "http://bestofgeeks.com/en/"
html = requests.get(url).text
soup = bs(html,'html.parser')
tagss = soup.findAll('a',{'class':'titre_post'})
print(tagss)
</code></pre>
<p>and i get this </p>
<pre><code>[<a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Last-Technology&amp;name=854&amp;title=Apple-Watch-Series-2-Waterproof-50-meters-with-Pokemon-Go" hreflang="en" rel="tag" titre="Apple Watch Series 2 Waterproof 50 meters with Pokemon Go">
Apple Watch Series 2 Waterproof 50 meters with Pokemon Go </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Security&amp;name=853&amp;title=Warning-This-Cross-Platform-Malware-Can-Hack-Windows-Linux-and-OS-X-Computers" hreflang="en" rel="tag" titre="Warning This Cross Platform Malware Can Hack Windows Linux and OS X Computers">
Warning This Cross Platform Malware Can Hack Windows Linux and OS X Computers </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Games&amp;name=852&amp;title=PS4-Slim-Announced,-Launching-This-Month-coming-september-15-for-299$-" hreflang="en" rel="tag" titre="PS4 Slim Announced, Launching This Month coming september 15 for 299$ ">
PS4 Slim Announced, Launching This Month coming september 15 for 299$ </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Last-Technology&amp;name=851&amp;title=Sony-New-IFA-products" hreflang="en" rel="tag" titre="Sony New IFA products">
Sony New IFA products </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Phone&amp;name=850&amp;title=This-is-the-iPhone-7-waterproofing,-stereo-speakers,-and-dual-cameras" hreflang="en" rel="tag" titre="This is the iPhone 7 waterproofing, stereo speakers, and dual cameras">
This is the iPhone 7 waterproofing, stereo speakers, and dual cameras </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Security&amp;name=849&amp;title=Russia-is-Largest-Portal-HACKED;-Nearly-100-Million-Plaintext-Passwords-Leaked" hreflang="en" rel="tag" titre="Russia is Largest Portal HACKED; Nearly 100 Million Plaintext Passwords Leaked">
Russia is Largest Portal HACKED; Nearly 100 Million Plaintext Passwords Leaked </a>]
</code></pre>
| -2
|
2016-09-09T15:32:43Z
| 39,415,183
|
<p>If you just want the text from the "a" tags, since all your web links are stored in <code>tagss</code>, just iterate and print like shown below: </p>
<pre><code>for t in tagss:
print t.text.strip()
</code></pre>
| 0
|
2016-09-09T15:37:53Z
|
[
"python",
"html",
"beautifulsoup"
] |
how to get the attribute value from tags html with python 3.5.2
| 39,415,106
|
<p>hi i have a problem with python 3.5.2
i don't know where is the problem when i want to get the value of atribute a get all tags (atribute + value) but i want just the value of title ??
this is my code</p>
<pre><code>from bs4 import BeautifulSoup as bs
import requests
url = "http://bestofgeeks.com/en/"
html = requests.get(url).text
soup = bs(html,'html.parser')
tagss = soup.findAll('a',{'class':'titre_post'})
print(tagss)
</code></pre>
<p>and i get this </p>
<pre><code>[<a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Last-Technology&amp;name=854&amp;title=Apple-Watch-Series-2-Waterproof-50-meters-with-Pokemon-Go" hreflang="en" rel="tag" titre="Apple Watch Series 2 Waterproof 50 meters with Pokemon Go">
Apple Watch Series 2 Waterproof 50 meters with Pokemon Go </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Security&amp;name=853&amp;title=Warning-This-Cross-Platform-Malware-Can-Hack-Windows-Linux-and-OS-X-Computers" hreflang="en" rel="tag" titre="Warning This Cross Platform Malware Can Hack Windows Linux and OS X Computers">
Warning This Cross Platform Malware Can Hack Windows Linux and OS X Computers </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Games&amp;name=852&amp;title=PS4-Slim-Announced,-Launching-This-Month-coming-september-15-for-299$-" hreflang="en" rel="tag" titre="PS4 Slim Announced, Launching This Month coming september 15 for 299$ ">
PS4 Slim Announced, Launching This Month coming september 15 for 299$ </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Last-Technology&amp;name=851&amp;title=Sony-New-IFA-products" hreflang="en" rel="tag" titre="Sony New IFA products">
Sony New IFA products </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Phone&amp;name=850&amp;title=This-is-the-iPhone-7-waterproofing,-stereo-speakers,-and-dual-cameras" hreflang="en" rel="tag" titre="This is the iPhone 7 waterproofing, stereo speakers, and dual cameras">
This is the iPhone 7 waterproofing, stereo speakers, and dual cameras </a>, <a charset="UTF-8" class="titre_post" href="article_to_read.php?category=Security&amp;name=849&amp;title=Russia-is-Largest-Portal-HACKED;-Nearly-100-Million-Plaintext-Passwords-Leaked" hreflang="en" rel="tag" titre="Russia is Largest Portal HACKED; Nearly 100 Million Plaintext Passwords Leaked">
Russia is Largest Portal HACKED; Nearly 100 Million Plaintext Passwords Leaked </a>]
</code></pre>
| -2
|
2016-09-09T15:32:43Z
| 39,415,230
|
<p>If you meant you want the contents of the <code>titre</code> attribute:</p>
<pre><code>tagss = [tag.get('titre') for tag in soup.findAll('a',{'class':'titre_post'})]
</code></pre>
| 0
|
2016-09-09T15:40:33Z
|
[
"python",
"html",
"beautifulsoup"
] |
Selecting all Columns based on Row value in a Dataframe Pandas
| 39,415,232
|
<blockquote>
<p>I have a similar df1 with thousand columns and thousands rows. I would
like to do a random sampling based on a condition in cells in row 1
(date0) Basically i would like to filter the columns and return
them and the Datetime index based on the condition if the cell on
date0 row is equal to V1 and then do the same sampling for cell==V2 and then
V3..etc.</p>
<p>Then I would concatenate all those samples into a singular
dataframe. I want to make sure I return the original Datetime Index
and not a generic Index 0,1,2,3...</p>
</blockquote>
<pre><code> abc def ghi jkl mno pqr
date0 'V1' 'V1' 'V2' 'V3' 'V0' 'V1'
date1 2 5 6 3 2 1
date2 3 1 1 3 5 6
date3 4 4 2 7 8 0
</code></pre>
<p>To filter I have tried this so far but it does not work
Dataset1= <code>Dataset.ix[:,(random.sample(list(Dataset.iloc[0,:]=='V2'), 4))].copy()</code>
4 is just an arbitrary number for the number of columns to return.
Then I would need to concatenate.</p>
<p>thanks!</p>
| 0
|
2016-09-09T15:40:38Z
| 39,416,950
|
<p>You want to include <code>date0</code> as part of the column index.</p>
<pre><code>df1 = df.T.set_index('date0', append=True).T
df1
</code></pre>
<p><a href="http://i.stack.imgur.com/WFJx3.png" rel="nofollow"><img src="http://i.stack.imgur.com/WFJx3.png" alt="enter image description here"></a></p>
<p>Then you can use <code>xs</code> to take cross sections</p>
<pre><code>df1.xs('V1', axis=1, level=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/ImWI2.png" rel="nofollow"><img src="http://i.stack.imgur.com/ImWI2.png" alt="enter image description here"></a></p>
<hr>
<p><strong><em>Response to Comment</em></strong><br>
This works for using the first row without knowing the row index value</p>
<pre><code>df1 = df.iloc[1:].T.set_index(df.iloc[0], append=True).T
df1.xs('V1', axis=1, level=1)
</code></pre>
<hr>
<p><strong><em>Response to 2nd Comment</em></strong><br>
<code>iloc[1:]</code> is intended to explicity drop the first row. If you want to keep it, don't include that part.</p>
<pre><code>df1 = df.T.set_index(df.iloc[0], append=True).T
df1
</code></pre>
<p><a href="http://i.stack.imgur.com/XDT99.png" rel="nofollow"><img src="http://i.stack.imgur.com/XDT99.png" alt="enter image description here"></a></p>
<pre><code>df1.xs('V1', axis=1, level=1)
</code></pre>
<p><a href="http://i.stack.imgur.com/iErTJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/iErTJ.png" alt="enter image description here"></a></p>
| 2
|
2016-09-09T17:35:41Z
|
[
"python",
"pandas",
"random",
"dataframe"
] |
Download and install scapy for windows for python 3.5?
| 39,415,278
|
<p>I installed python 3.5 for my windows 8.1 computer. I need to install scapy for this version (I deleted all the files of the last one). How do i download and install it? can't find anything that help me to do that no matter how i searched.</p>
| 0
|
2016-09-09T15:43:15Z
| 39,415,327
|
<p><s> Use pip from the command line:</s></p>
<p><s> pip install scrapy</s></p>
<p>Apologies, realised that according to the docs scrapy is not supported on Windows with Python 3.x due to missing dependency (Twisted)</p>
<p>Source: <a href="http://doc.scrapy.org/en/latest/intro/install.html" rel="nofollow">http://doc.scrapy.org/en/latest/intro/install.html</a></p>
| 1
|
2016-09-09T15:46:40Z
|
[
"python",
"download",
"install",
"python-3.5",
"scapy"
] |
Python pandas: change one column conditional on another
| 39,415,286
|
<p>How can I reverse the sign in the quantity column whenever the side column has a sell? All other values should not be changed. The following is simply not working, it has no effect.</p>
<pre><code>df[df['side'] == 'Sell']['quantity'] = df[df['side'] == 'Sell']['quantity'] * -1
</code></pre>
| 3
|
2016-09-09T15:43:37Z
| 39,415,469
|
<p>Refer to the <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#different-choices-for-indexing" rel="nofollow">Pandas indexing documentation</a>, and never use chain indexing per your example when setting values.</p>
<pre><code>df.loc[df.side == 'Sell', 'quantity'] *= -1
</code></pre>
| 3
|
2016-09-09T15:55:50Z
|
[
"python",
"pandas"
] |
calculate catalan numbers up to a billion
| 39,415,300
|
<p>I'm new to python (and programming in general), I was asked in my class to calculate Catalan numbers up to a billion but the program I wrote for it is not working as intended.</p>
<pre><code> from numpy import division
C=1
n=0
while C<=10000000000:
print (C)
C=(4*n+2)/(n+2)*C
n=n+1
</code></pre>
<p>This is what it prints</p>
<p>1,
1,
2,
4,
8,
24,
72,
216,
648,
1944,
5832,
17496,
52488,
157464,
472392,
1417176,
4251528,
12754584,
38263752,
114791256,
344373768,
1033121304,
3099363912,
9298091736,</p>
<p>As you can see from my fourth iteration onwards, I get the wrong number and I don't understand why.</p>
<p>EDIT:
The mathematical definition I used is not wrong! I know the Wiki has another definition but this one is not wrong.
Co=1, Cn+1 = (4*n+2)/(n+2)*Cn</p>
| 0
|
2016-09-09T15:44:41Z
| 39,415,416
|
<p>Try this:</p>
<pre><code>from scipy.special import factorial
C = 1
n = 0
while C <= 10000000000:
print(C)
C = factorial(2*n, exact=True)/(factorial((n+1), exact=True)*factorial(n, exact=True))
n = n + 1
</code></pre>
<p>It works for me :)</p>
| 0
|
2016-09-09T15:52:58Z
|
[
"python"
] |
calculate catalan numbers up to a billion
| 39,415,300
|
<p>I'm new to python (and programming in general), I was asked in my class to calculate Catalan numbers up to a billion but the program I wrote for it is not working as intended.</p>
<pre><code> from numpy import division
C=1
n=0
while C<=10000000000:
print (C)
C=(4*n+2)/(n+2)*C
n=n+1
</code></pre>
<p>This is what it prints</p>
<p>1,
1,
2,
4,
8,
24,
72,
216,
648,
1944,
5832,
17496,
52488,
157464,
472392,
1417176,
4251528,
12754584,
38263752,
114791256,
344373768,
1033121304,
3099363912,
9298091736,</p>
<p>As you can see from my fourth iteration onwards, I get the wrong number and I don't understand why.</p>
<p>EDIT:
The mathematical definition I used is not wrong! I know the Wiki has another definition but this one is not wrong.
Co=1, Cn+1 = (4*n+2)/(n+2)*Cn</p>
| 0
|
2016-09-09T15:44:41Z
| 39,415,434
|
<h3>The problem</h3>
<p>Your mathematical definition of Catalan numbers is incorrect when translated into code.</p>
<p>This is because of operator precedence in programming languages such as Python.</p>
<p>Multiplication and division both have the same precedence, so they are computed left to right. What happens is that the division operation <code>(4*n+2)/(n+2)</code> happens before the multiplication with <code>C</code>. When <code>n</code> is 2, <code>2*(2*n+2)/(n+2)</code> becomes <code>10/4</code> which is <code>2</code> in integer arithmetic. <code>1*C</code> which is <code>2</code> at this stage, gives <code>4</code> instead of giving the expected <code>5</code>.
Once a number in the series is incorrect, being computed iteratively is incorrect.</p>
<hr>
<h3>A possible work around</h3>
<p>Here's the definition <a href="https://en.wikipedia.org/wiki/Catalan_number" rel="nofollow">Catalan Numbers</a></p>
<p><a href="http://i.stack.imgur.com/816F2.png" rel="nofollow"><img src="http://i.stack.imgur.com/816F2.png" alt="enter image description here"></a></p>
<p>Which means, the nth Catalan number is given by:</p>
<pre><code>import operator as op
def ncr(n, r):
r = min(r, n-r)
if r == 0: return 1
numer = reduce(op.mul, xrange(n, n-r, -1))
denom = reduce(op.mul, xrange(1, r+1))
return numer//denom
def catalan(n):
return ncr(2*n, n)/(n+1)
</code></pre>
<p>This is not very efficient, but it is at least correct.</p>
<hr>
<h3>The right fix</h3>
<p>To compute the series, you can do, using the recursive formula.</p>
<p><a href="http://i.stack.imgur.com/BYSSY.png" rel="nofollow"><img src="http://i.stack.imgur.com/BYSSY.png" alt="enter image description here"></a></p>
<pre><code>N=1000000 # limit
C=1
for i in xrange(0, N+1):
print i,C
C = (2*(2*i +1)*C)/(i+2)
</code></pre>
<p>For the first few, it looks like this:</p>
<pre><code>0 1
1 1
2 2
3 5
4 14
5 42
6 132
7 429
8 1430
9 4862
10 16796
</code></pre>
| 0
|
2016-09-09T15:54:06Z
|
[
"python"
] |
calculate catalan numbers up to a billion
| 39,415,300
|
<p>I'm new to python (and programming in general), I was asked in my class to calculate Catalan numbers up to a billion but the program I wrote for it is not working as intended.</p>
<pre><code> from numpy import division
C=1
n=0
while C<=10000000000:
print (C)
C=(4*n+2)/(n+2)*C
n=n+1
</code></pre>
<p>This is what it prints</p>
<p>1,
1,
2,
4,
8,
24,
72,
216,
648,
1944,
5832,
17496,
52488,
157464,
472392,
1417176,
4251528,
12754584,
38263752,
114791256,
344373768,
1033121304,
3099363912,
9298091736,</p>
<p>As you can see from my fourth iteration onwards, I get the wrong number and I don't understand why.</p>
<p>EDIT:
The mathematical definition I used is not wrong! I know the Wiki has another definition but this one is not wrong.
Co=1, Cn+1 = (4*n+2)/(n+2)*Cn</p>
| 0
|
2016-09-09T15:44:41Z
| 39,415,487
|
<p>This is solved using recursion:</p>
<pre><code>def catalan(n):
if n <=1 :
return 1
res = 0
for i in range(n):
res += catalan(i) * catalan(n-i-1)
return res
for i in range(10000000000):
print (catalan(i))
</code></pre>
<p>you can read more about Catalan numbers <a href="http://www.geeksforgeeks.org/program-nth-catalan-number/" rel="nofollow">here</a> or <a href="http://mathworld.wolfram.com/CatalanNumber.html" rel="nofollow">here</a></p>
| 0
|
2016-09-09T15:56:56Z
|
[
"python"
] |
calculate catalan numbers up to a billion
| 39,415,300
|
<p>I'm new to python (and programming in general), I was asked in my class to calculate Catalan numbers up to a billion but the program I wrote for it is not working as intended.</p>
<pre><code> from numpy import division
C=1
n=0
while C<=10000000000:
print (C)
C=(4*n+2)/(n+2)*C
n=n+1
</code></pre>
<p>This is what it prints</p>
<p>1,
1,
2,
4,
8,
24,
72,
216,
648,
1944,
5832,
17496,
52488,
157464,
472392,
1417176,
4251528,
12754584,
38263752,
114791256,
344373768,
1033121304,
3099363912,
9298091736,</p>
<p>As you can see from my fourth iteration onwards, I get the wrong number and I don't understand why.</p>
<p>EDIT:
The mathematical definition I used is not wrong! I know the Wiki has another definition but this one is not wrong.
Co=1, Cn+1 = (4*n+2)/(n+2)*Cn</p>
| 0
|
2016-09-09T15:44:41Z
| 39,415,490
|
<pre><code> C=(4*n+2)/(n+2)*C
</code></pre>
<p>This applies the calculation in the wrong order. Because you are using integer arithmetic, <code>(4*n+2)/(n+2)</code> loses information if you have not already factored in <code>C</code>. The correct calculation is:</p>
<pre><code> C=C*(4*n+2)/(n+2)
</code></pre>
| 1
|
2016-09-09T15:57:05Z
|
[
"python"
] |
calculate catalan numbers up to a billion
| 39,415,300
|
<p>I'm new to python (and programming in general), I was asked in my class to calculate Catalan numbers up to a billion but the program I wrote for it is not working as intended.</p>
<pre><code> from numpy import division
C=1
n=0
while C<=10000000000:
print (C)
C=(4*n+2)/(n+2)*C
n=n+1
</code></pre>
<p>This is what it prints</p>
<p>1,
1,
2,
4,
8,
24,
72,
216,
648,
1944,
5832,
17496,
52488,
157464,
472392,
1417176,
4251528,
12754584,
38263752,
114791256,
344373768,
1033121304,
3099363912,
9298091736,</p>
<p>As you can see from my fourth iteration onwards, I get the wrong number and I don't understand why.</p>
<p>EDIT:
The mathematical definition I used is not wrong! I know the Wiki has another definition but this one is not wrong.
Co=1, Cn+1 = (4*n+2)/(n+2)*Cn</p>
| 0
|
2016-09-09T15:44:41Z
| 39,415,497
|
<p>Based on this expression for <a href="https://en.wikipedia.org/wiki/Catalan_number" rel="nofollow">Catalan Numbers</a>:</p>
<p><a href="http://i.stack.imgur.com/sfa7X.png" rel="nofollow"><img src="http://i.stack.imgur.com/sfa7X.png" alt="enter image description here"></a></p>
<pre><code>from math import factorial
C = 1
n = 0
while C <= 10000000000:
print(C)
C = (factorial(2 * n)) / (factorial(n + 1) * factorial(n))
n = n + 1
</code></pre>
<p><strong>Returns:</strong></p>
<pre><code>1
1.0
1.0
2.0
5.0
14.0
42.0
132.0
429.0
1430.0
4862.0
16796.0
58786.0
208012.0
742900.0
2674440.0
9694845.0
35357670.0
129644790.0
477638700.0
1767263190.0
6564120420.0
</code></pre>
| 0
|
2016-09-09T15:57:39Z
|
[
"python"
] |
Marker colour still not showing up
| 39,415,554
|
<p>The markers produced by the following are just showing up as grey:</p>
<pre><code>plt.style.use('ggplot')
ax1.scatter(x
, y
, edgecolor='black'
, color='black'
, marker='x'
, label='Cluster 1')
</code></pre>
| 1
|
2016-09-09T16:01:43Z
| 39,417,730
|
<p>The marker probably looked grey because of the small line width, which can be controlled with the <code>linewidths</code> property:</p>
<pre><code>plt.scatter(1, 1, s=300, edgecolor='black',
color='black', marker='x')
plt.scatter(2, 2, s=300, edgecolor='black',
color='black', marker='x', linewidths=2)
</code></pre>
<p><a href="http://i.stack.imgur.com/XrUTD.png" rel="nofollow"><img src="http://i.stack.imgur.com/XrUTD.png" alt="enter image description here"></a></p>
| 2
|
2016-09-09T18:30:06Z
|
[
"python",
"pandas",
"matplotlib"
] |
How to know node execution (before, middle, after calls) using DFS
| 39,415,724
|
<p>Let's say I implemented a simple version of an iterative DFS like this:</p>
<pre><code>import sys
import traceback
def dfs(graph, start):
visited, stack = [], [start]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
childs = reversed(graph.get(node, list()))
stack.extend([item for item in childs if item not in visited])
return visited
if __name__ == "__main__":
graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
for i, g in enumerate(graphs):
try:
print "{0}Graph {1}{2}".format('-' * 40, i, '-' * 33)
for f in [dfs]:
print f.__name__, '-->', f(g, 'A')
print '-' * 80
except Exception as e:
print "Exception in user code: {0}".format(e)
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
</code></pre>
<p>The output of the above snippet is this:</p>
<pre><code>----------------------------------------Graph 0---------------------------------
dfs --> ['A', 'B', 'D', 'C']
--------------------------------------------------------------------------------
</code></pre>
<p>Now, I'm trying to figure out how to get the following output (instead running node's method just printing is fine):</p>
<pre><code>A_start, B_start, D_start, D_end, B_end, A_middle, C_start, C_end, A_end
</code></pre>
<p>*_middle will only be executed between subnodes execution. For instance, if a node doesn't have any subnodes, or has only a single one, it never gets executed. That's why my desired output only has A_middle (none of the B_middle, C_middle, D_middle) in the above example.</p>
<p>How can I do this?</p>
<p><strong>EDIT:</strong></p>
<p>Trying to find the recursive solution to my problem:</p>
<pre><code>def dfs(graph, node):
if node not in graph:
return
print '{0}_start'.format(node)
for i, node in enumerate(graph[node]):
if i > 0:
print '{0}_middle'.format(node)
dfs(graph, node)
print '{0}_end'.format(node)
if __name__ == "__main__":
graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
for i, g in enumerate(graphs):
try:
print "{0}Graph {1}{2}".format('-' * 40, i, '-' * 33)
for f in [dfs]:
print f.__name__, '-->'
f(g, 'A')
print '-' * 80
except Exception as e:
print "Exception in user code: {0}".format(e)
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
</code></pre>
<p>Will give me the wrong output:</p>
<pre><code>----------------------------------------Graph 0---------------------------------
dfs -->
A_start
B_start
D_end
C_middle
C_end
--------------------------------------------------------------------------------
</code></pre>
<p><strong>EDIT2:</strong></p>
<p>I will explain the reasons about my validated answer. First of all, I do really appreciate the effort from all you guys, @Gerrat, @ffledgling and @Blckknght</p>
<p>1) Gerrrat's -> It meets the requirements and it <strong>was the first answer</strong>. At first of my post I had only posted the iterative version but then I edited my question and said a recursive one would be good enough. One little note, when dealing with graphs containing cycles will spawn <code>maximum recursion depth exceeded</code> though. It wouldn't be a bad thing whether I could iterate/repeat infinitely over the graph, take a look to the nodes called <code>repeat</code> of this <a href="http://www.bitfellas.org/e107_plugins/content/content.php?content.674" rel="nofollow">tool</a></p>
<p>2) ffledgling -> It doesn't meet the requirements, it's giving this output <code>A_start, B_start, D_start, D_end, B_middle, B_end, A_middle, C_start, C_end, A_middle, A_end</code> and it should give <code>A_start, B_start, D_start, D_end, B_end, A_middle, C_start, C_end, A_end</code> instead</p>
<p>3) Blckknght -> It meets the requirements. It answers the first version I had posted and it won't crash with cyclic graphs, even if it has been the last answer, I think it deserves to be validated.</p>
<p>NS: It's not an easy decission to validate answers like these ones when they've shown a good effort, I've upvoted all of them though. In case of any concern, please let me know. </p>
| 1
|
2016-09-09T16:12:19Z
| 39,420,245
|
<p>You were really close with your recursive attempt actually.<br>
I added comments for the small tweaks I made. </p>
<pre><code>import sys, traceback
def dfs(graph, node):
print '{0}_start'.format(node) # need this right at the top
if node not in graph:
print '{0}_end'.format(node) # need to record the end if we can't find
return
for i, nd in enumerate(graph[node]): # need a different `node` variable here!!!
if i > 0:
print '{0}_middle'.format(node)
dfs(graph, nd)
print '{0}_end'.format(node)
if __name__ == "__main__":
graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
for i, g in enumerate(graphs):
try:
print "{0}Graph {1}{2}".format('-' * 40, i, '-' * 33)
for f in [dfs]:
print f.__name__, '-->'
f(g, 'A')
print '-' * 80
except Exception as e:
print "Exception in user code: {0}".format(e)
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
</code></pre>
<p>This produces the output you were looking for.</p>
| 2
|
2016-09-09T21:56:20Z
|
[
"python",
"depth-first-search"
] |
How to know node execution (before, middle, after calls) using DFS
| 39,415,724
|
<p>Let's say I implemented a simple version of an iterative DFS like this:</p>
<pre><code>import sys
import traceback
def dfs(graph, start):
visited, stack = [], [start]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
childs = reversed(graph.get(node, list()))
stack.extend([item for item in childs if item not in visited])
return visited
if __name__ == "__main__":
graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
for i, g in enumerate(graphs):
try:
print "{0}Graph {1}{2}".format('-' * 40, i, '-' * 33)
for f in [dfs]:
print f.__name__, '-->', f(g, 'A')
print '-' * 80
except Exception as e:
print "Exception in user code: {0}".format(e)
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
</code></pre>
<p>The output of the above snippet is this:</p>
<pre><code>----------------------------------------Graph 0---------------------------------
dfs --> ['A', 'B', 'D', 'C']
--------------------------------------------------------------------------------
</code></pre>
<p>Now, I'm trying to figure out how to get the following output (instead running node's method just printing is fine):</p>
<pre><code>A_start, B_start, D_start, D_end, B_end, A_middle, C_start, C_end, A_end
</code></pre>
<p>*_middle will only be executed between subnodes execution. For instance, if a node doesn't have any subnodes, or has only a single one, it never gets executed. That's why my desired output only has A_middle (none of the B_middle, C_middle, D_middle) in the above example.</p>
<p>How can I do this?</p>
<p><strong>EDIT:</strong></p>
<p>Trying to find the recursive solution to my problem:</p>
<pre><code>def dfs(graph, node):
if node not in graph:
return
print '{0}_start'.format(node)
for i, node in enumerate(graph[node]):
if i > 0:
print '{0}_middle'.format(node)
dfs(graph, node)
print '{0}_end'.format(node)
if __name__ == "__main__":
graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
for i, g in enumerate(graphs):
try:
print "{0}Graph {1}{2}".format('-' * 40, i, '-' * 33)
for f in [dfs]:
print f.__name__, '-->'
f(g, 'A')
print '-' * 80
except Exception as e:
print "Exception in user code: {0}".format(e)
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
</code></pre>
<p>Will give me the wrong output:</p>
<pre><code>----------------------------------------Graph 0---------------------------------
dfs -->
A_start
B_start
D_end
C_middle
C_end
--------------------------------------------------------------------------------
</code></pre>
<p><strong>EDIT2:</strong></p>
<p>I will explain the reasons about my validated answer. First of all, I do really appreciate the effort from all you guys, @Gerrat, @ffledgling and @Blckknght</p>
<p>1) Gerrrat's -> It meets the requirements and it <strong>was the first answer</strong>. At first of my post I had only posted the iterative version but then I edited my question and said a recursive one would be good enough. One little note, when dealing with graphs containing cycles will spawn <code>maximum recursion depth exceeded</code> though. It wouldn't be a bad thing whether I could iterate/repeat infinitely over the graph, take a look to the nodes called <code>repeat</code> of this <a href="http://www.bitfellas.org/e107_plugins/content/content.php?content.674" rel="nofollow">tool</a></p>
<p>2) ffledgling -> It doesn't meet the requirements, it's giving this output <code>A_start, B_start, D_start, D_end, B_middle, B_end, A_middle, C_start, C_end, A_middle, A_end</code> and it should give <code>A_start, B_start, D_start, D_end, B_end, A_middle, C_start, C_end, A_end</code> instead</p>
<p>3) Blckknght -> It meets the requirements. It answers the first version I had posted and it won't crash with cyclic graphs, even if it has been the last answer, I think it deserves to be validated.</p>
<p>NS: It's not an easy decission to validate answers like these ones when they've shown a good effort, I've upvoted all of them though. In case of any concern, please let me know. </p>
| 1
|
2016-09-09T16:12:19Z
| 39,420,269
|
<p>I suspect this does what you want.</p>
<pre><code>graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
def dfs(graph, start):
print '{}_start'.format(start)
try:
for child in graph[start]:
dfs(graph, child)
print '{}_middle'.format(start)
except KeyError:
# We found a leaf node, it has no children.
pass
print '{}_end'.format(start)
# Test it for one graph
dfs(graphs[0], 'A')
# Output:
# A_start
# B_start
# D_start
# D_end
# B_middle
# B_end
# A_middle
# C_start
# C_end
# A_middle
# A_end
</code></pre>
| 1
|
2016-09-09T21:58:10Z
|
[
"python",
"depth-first-search"
] |
How to know node execution (before, middle, after calls) using DFS
| 39,415,724
|
<p>Let's say I implemented a simple version of an iterative DFS like this:</p>
<pre><code>import sys
import traceback
def dfs(graph, start):
visited, stack = [], [start]
while stack:
node = stack.pop()
if node not in visited:
visited.append(node)
childs = reversed(graph.get(node, list()))
stack.extend([item for item in childs if item not in visited])
return visited
if __name__ == "__main__":
graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
for i, g in enumerate(graphs):
try:
print "{0}Graph {1}{2}".format('-' * 40, i, '-' * 33)
for f in [dfs]:
print f.__name__, '-->', f(g, 'A')
print '-' * 80
except Exception as e:
print "Exception in user code: {0}".format(e)
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
</code></pre>
<p>The output of the above snippet is this:</p>
<pre><code>----------------------------------------Graph 0---------------------------------
dfs --> ['A', 'B', 'D', 'C']
--------------------------------------------------------------------------------
</code></pre>
<p>Now, I'm trying to figure out how to get the following output (instead running node's method just printing is fine):</p>
<pre><code>A_start, B_start, D_start, D_end, B_end, A_middle, C_start, C_end, A_end
</code></pre>
<p>*_middle will only be executed between subnodes execution. For instance, if a node doesn't have any subnodes, or has only a single one, it never gets executed. That's why my desired output only has A_middle (none of the B_middle, C_middle, D_middle) in the above example.</p>
<p>How can I do this?</p>
<p><strong>EDIT:</strong></p>
<p>Trying to find the recursive solution to my problem:</p>
<pre><code>def dfs(graph, node):
if node not in graph:
return
print '{0}_start'.format(node)
for i, node in enumerate(graph[node]):
if i > 0:
print '{0}_middle'.format(node)
dfs(graph, node)
print '{0}_end'.format(node)
if __name__ == "__main__":
graphs = [
{
'A': ['B', 'C'],
'B': ['D']
}
]
for i, g in enumerate(graphs):
try:
print "{0}Graph {1}{2}".format('-' * 40, i, '-' * 33)
for f in [dfs]:
print f.__name__, '-->'
f(g, 'A')
print '-' * 80
except Exception as e:
print "Exception in user code: {0}".format(e)
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
</code></pre>
<p>Will give me the wrong output:</p>
<pre><code>----------------------------------------Graph 0---------------------------------
dfs -->
A_start
B_start
D_end
C_middle
C_end
--------------------------------------------------------------------------------
</code></pre>
<p><strong>EDIT2:</strong></p>
<p>I will explain the reasons about my validated answer. First of all, I do really appreciate the effort from all you guys, @Gerrat, @ffledgling and @Blckknght</p>
<p>1) Gerrrat's -> It meets the requirements and it <strong>was the first answer</strong>. At first of my post I had only posted the iterative version but then I edited my question and said a recursive one would be good enough. One little note, when dealing with graphs containing cycles will spawn <code>maximum recursion depth exceeded</code> though. It wouldn't be a bad thing whether I could iterate/repeat infinitely over the graph, take a look to the nodes called <code>repeat</code> of this <a href="http://www.bitfellas.org/e107_plugins/content/content.php?content.674" rel="nofollow">tool</a></p>
<p>2) ffledgling -> It doesn't meet the requirements, it's giving this output <code>A_start, B_start, D_start, D_end, B_middle, B_end, A_middle, C_start, C_end, A_middle, A_end</code> and it should give <code>A_start, B_start, D_start, D_end, B_end, A_middle, C_start, C_end, A_end</code> instead</p>
<p>3) Blckknght -> It meets the requirements. It answers the first version I had posted and it won't crash with cyclic graphs, even if it has been the last answer, I think it deserves to be validated.</p>
<p>NS: It's not an easy decission to validate answers like these ones when they've shown a good effort, I've upvoted all of them though. In case of any concern, please let me know. </p>
| 1
|
2016-09-09T16:12:19Z
| 39,421,419
|
<p>As the other answers have shown, the main issue with your current recursive code is the base case:</p>
<pre><code>if node not in graph:
return
</code></pre>
<p>This incorrectly skips the output when there are no children from a node. Get rid of those lines and, just use <code>enumerate(graph.get(start, []))</code> instead of <code>enumerate(graph[start])</code> in the <code>for</code> loop and it should work as desired.</p>
<p>Making your iterative code work is quite a bit more complicated. One way of attempting it would be to push 2-tuples to the stack. The first value would a node, as before, but the second will be either a predecessor of the node (so we can print a <code>middle</code> message for the parent), or <code>None</code> indicating that we need to print the <code>end</code> marker for the node.</p>
<p>However, keeping track of which nodes have been visited gets a bit more complicated. Rather than a single list of nodes, I'm using a dictionary mapping from node to an integer. A non-existent value means the node has not yet been visited. A one means the node has been visited and it's <code>start</code> message has been printed. A <code>2</code> means that at least one of the node's children has been visited, and each further child should print a <code>middle</code> message on the parent's behalf. A <code>3</code> means the <code>end</code> message has been printed.</p>
<pre><code>def dfs(graph, start):
visited = {}
stack = [(start, "XXX_THIS_NODE_DOES_NOT_EXIST_XXX")]
while stack:
node, parent = stack.pop()
if parent is None:
if visited[node] < 3:
print "{}_end".format(node)
visited[node] = 3
elif node not in visited:
if visited.get(parent) == 2:
print "{}_middle".format(parent)
elif visited.get(parent) == 1:
visited[parent] = 2
print "{}_start".format(node)
visited[node] = 1
stack.append((node, None))
for child in reversed(graph.get(node, [])):
if child not in visited:
stack.append((child, node))
</code></pre>
<p>Because I'm using an dictionary for <code>visited</code>, returning it at the end is probably not appropriate, so I've removed the <code>return</code> statement. I think you could restore it if you really wanted to by using a <code>collections.OrderedDict</code> rather than a normal <code>dict</code>, and returning its <code>keys()</code>.</p>
| 2
|
2016-09-10T00:41:40Z
|
[
"python",
"depth-first-search"
] |
Getting wrong texture by glBindTexture
| 39,415,739
|
<p>I have two textures in .png format (floor and wall), I load them during the initialization, and choose before rendering by <code>glBindTexture</code>, but I get this:
<a href="http://i.stack.imgur.com/ViC4F.png" rel="nofollow">screen_shot_1</a>
instead of this:
<a href="http://i.stack.imgur.com/6XkUW.png" rel="nofollow">screen_shot_2</a>
Initialization:</p>
<pre><code>def __init__(self, screen_info, wall_number):
self.screen = screen_info
self.inscription = font.Font(get_path([RES_PATH[0], 'font', 'main.ttf']), 12)
self.path = get_path([RES_PATH[0], RES_PATH[1], ''])
self.sprite_list = {}
self.tex_list = {}
self.generate_list()
self.wall_coordinates = []
self.wall_number = wall_number
self.wall_counter = 0
glClearColor(*BACKGROUND_COLOR)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(FOV, self.screen.current_w / self.screen.current_h, DISTANCE_NEAR, DISTANCE_FAR)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glEnable(GL_DEPTH_TEST)
glEnable(GL_TEXTURE_2D)
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)
</code></pre>
<p>Main loop:</p>
<pre><code>gi = interaction.GI(screen_info, 11)
while True:
timer.tick(60)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
camera.update_view()
camera.update_move(forward, backward, left, right, gi.get_wall_coordinates())
gi.draw_ground(0, 0)
gi.draw_square(-2, 1.5, -4)
gi.draw_square(0, 1.5, -4)
gi.draw_square(2, 1.5, -4)
gi.draw_square(4, 1.5, -4, rot=True)
gi.draw_square(4, 1.5, -2, rot=True)
gi.draw_square(4, 1.5, 0, rot=True)
gi.draw_square(2, 1.5, 2)
gi.draw_square(0, 1.5, 2)
gi.draw_square(-2, 1.5, 2)
gi.draw_square(-2, 1.5, 0, rot=True)
gi.draw_square(-2, 1.5, -4, rot=True)
pygame.display.flip()
</code></pre>
<p>Texture loader:</p>
<pre><code>def load_tex(self, filename, rotate=False, text_render=False, text=''):
if not text_render:
surface = image.load(filename)
if rotate:
surface = transform.rotate(surface, 180)
else:
surface = self.inscription.render(str(text), 1, (255, 255, 255), (0, 0, 0))
surface = transform.scale(surface, (64, 64))
surface = transform.rotate(surface, 180)
size = surface.get_size()
surface = image.tostring(surface, 'RGB', True)
texture = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texture)
glPixelStorei(GL_UNPACK_ALIGNMENT, 1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
glTexImage2D(GL_TEXTURE_2D, 0, 3, size[0], size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, surface)
return texture
</code></pre>
<p>Loading texture during the initialization:</p>
<pre><code>def generate_list(self):
for filename in listdir(self.path):
self.tex_list[filename] = self.load_tex(get_path([RES_PATH[0], RES_PATH[1], filename]))
</code></pre>
<p>Drawing ground:</p>
<pre><code>def draw_ground(self, x, z, length=50):
glBindTexture(GL_TEXTURE_2D, self.tex_list['floor.png'])
# glBindTexture(GL_TEXTURE_2D, self.load_tex(get_path([RES_PATH[0], RES_PATH[1], 'floor.png'])))
glBegin(GL_QUADS)
glTexCoord2f(0, length)
glVertex3f(x - length, -0.5, z + length)
glTexCoord2f(length, length)
glVertex3f(x + length, -0.5, z + length)
glTexCoord2f(length, 0)
glVertex3f(x + length, -0.5, z - length)
glTexCoord2f(0, 0)
glVertex3f(x - length, -0.5, z - length)
glEnd()
</code></pre>
<p>Drawing walls:</p>
<pre><code>def draw_square(self, x, y, z, length=2, rot=False):
glBindTexture(GL_TEXTURE_2D, self.tex_list['wall.png'])
# glBindTexture(GL_TEXTURE_2D, self.load_tex(get_path([RES_PATH[0], RES_PATH[1], 'wall.png'])))
glBegin(GL_QUADS)
glTexCoord2f(0, 1)
glVertex3f(x, y, z)
glTexCoord2f(1, 1)
if not rot:
glVertex3f(x + length, y, z)
glTexCoord2f(1, 0)
glVertex3f(x + length, y - length, z)
else:
glVertex3f(x, y, z + length)
glTexCoord2f(1, 0)
glVertex3f(x, y - length, z + length)
glTexCoord2f(0, 0)
glVertex3f(x, y - length, z)
glEnd()
</code></pre>
<p>So what is the problem?</p>
| 0
|
2016-09-09T16:13:36Z
| 39,422,615
|
<p>These are some things I noticed in your code that may or may not be related to your texturing issues:</p>
<ul>
<li>For your glTexParameterf calls, I saw you used GL_NEAREST. This will lead to pixelated textures. If you are not working with pixel art, you might want to consider GL_LINEAR for your final parameter as this performs bilinear interpolation, removing significant pixelation.</li>
<li>I don't think you need the glTexEnvf nor the glPixelStorei calls.</li>
<li>As good habit, once you are done using a texture, you should unbind it by calling glBindTexture(GL_TEXTURE_0, 0). OpenGL is all about state, so it is a good idea to return things to how they were after you are done so you aren't surprised later by odd behavior. My guess is that you are not binding the second texture correctly (check the texture ids), resulting in the first texture being used for all calls. Try to reorder the draw calls and see if the texture changes. This is speculation though as I could not run your example code.</li>
<li>Your parameters for glTexImage2D look odd. You might want to take a look at the <a href="https://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml" rel="nofollow">opengl docs</a> as well as their <a href="http://pyopengl.sourceforge.net/documentation/manual-3.0/glTexImage2D.html" rel="nofollow">python</a> equivalents. I personally like to use enums like GL_RGBA for formats to make the code clearer.</li>
</ul>
<p>Here is a simple demo I made that uses pyopengl and pygame. It renders two 2d squares, each with a different texture. The main while loop and the load_texture function are the important parts:</p>
<pre><code>import pygame
from pygame.locals import *
from OpenGL.GL import *
import sys
def init_gl():
window_size = width, height = (550, 400)
pygame.init()
pygame.display.set_mode(window_size, OPENGL | DOUBLEBUF)
glEnable(GL_TEXTURE_2D)
glMatrixMode(GL_PROJECTION)
glOrtho(0, width, height, 0, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
def load_texture(texture_url):
tex_id = glGenTextures(1)
tex = pygame.image.load(texture_url)
tex_surface = pygame.image.tostring(tex, 'RGBA')
tex_width, tex_height = tex.get_size()
glBindTexture(GL_TEXTURE_2D, tex_id)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_surface)
glBindTexture(GL_TEXTURE_2D, 0)
return tex_id
if __name__ == "__main__":
init_gl()
texture1 = load_texture("texture1.png")
texture2 = load_texture("texture2.png")
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
glClear(GL_COLOR_BUFFER_BIT)
glBindTexture(GL_TEXTURE_2D, texture1)
glBegin(GL_QUADS)
glTexCoord(0, 0)
glVertex(50, 50, 0)
glTexCoord(0, 1)
glVertex(50, 100, 0)
glTexCoord(1, 1)
glVertex(100, 100, 0)
glTexCoord(1, 0)
glVertex(100, 50, 0)
glEnd()
glBindTexture(GL_TEXTURE_2D, 0)
glBindTexture(GL_TEXTURE_2D, texture2)
glBegin(GL_QUADS)
glTexCoord(0, 0)
glVertex(450, 300, 0)
glTexCoord(0, 1)
glVertex(450, 350, 0)
glTexCoord(1, 1)
glVertex(500, 350, 0)
glTexCoord(1, 0)
glVertex(500, 300, 0)
glEnd()
glBindTexture(GL_TEXTURE_2D, 0)
pygame.display.flip()
</code></pre>
<p>As a side note, most of both your code and the demo code I have posted is deprecated in modern OpenGL, which does not support slow immediate mode calls like glBegin and glEnd. If you run into performance issues later on, that might be something to consider refactoring to use more modern techniques, like VBOs (Vertex Buffer Objects). But for simple applications, this should not be too much of an issue. Let me know if this helps!</p>
| 1
|
2016-09-10T04:38:39Z
|
[
"python",
"opengl",
"pygame",
"pyopengl"
] |
Tranpose Rows to Columns while keeping part of dataframe in tact
| 39,415,851
|
<p>I am trying to move some of my rows and make the them columns, but keep a large portion of the dataframe the same. </p>
<p>My Dataframe looks something like this:</p>
<pre><code>ID Thing Level1 Level2 Time OAttribute IsTrue Score Value
1 bicycle value value 9:30 whatever yes 1 type1
2 non-cycle value value 1:30 whatever no 2 type2
3 bicycle value value 2:30 whatever yes
4 bicycle value value 3:30 whatever no 4 type3
</code></pre>
<p>And I want something like this:</p>
<pre><code>ID Thing Level1 Level2 Time OAttribute IsTrue Type1 Type2 Type 3
1 bicycle value value 9:30 whatever yes 1
2 non-cycle value value 1:30 whatever no 2
3 bicycle value value 2:30 whatever yes
4 bicycle value value 3:30 whatever no 4
</code></pre>
| 3
|
2016-09-09T16:20:44Z
| 39,416,345
|
<p>Something like this?</p>
<pre><code>In [112]: df
Out[112]:
ID Thing Level1 Level2 Time OAttribute IsTrue Score Value
0 1 bicycle value value 9:30 whatever yes 1 type1
1 2 non-cycle value value 1:30 whatever no 2 type2
2 3 bicycle value value 2:30 whatever yes NaN NaN
3 4 bicycle value value 3:30 whatever no 4 type3
In [113]: dg = pd.DataFrame(columns=df['Value'].dropna().unique())
In [114]: for i in range(len(df)):
...: key = df.loc[i]['Value']
...: value = df.loc[i]['Score']
...: if key is not pd.np.nan:
...: dg.loc[i, key] = value
...:
In [115]: dg
Out[115]:
Value type1 type2 type3
0 1 NaN NaN
1 NaN 2 NaN
3 NaN NaN 4
In [116]: df.join(dg).drop('Value', 1).fillna('')
Out[116]:
ID Thing Level1 Level2 Time OAttribute IsTrue Score type1 type2 type3
0 1 bicycle value value 9:30 whatever yes 1 1
1 2 non-cycle value value 1:30 whatever no 2 2
2 3 bicycle value value 2:30 whatever yes
3 4 bicycle value value 3:30 whatever no 4 4
</code></pre>
| 2
|
2016-09-09T16:51:27Z
|
[
"python",
"pandas",
"dataframe"
] |
Tranpose Rows to Columns while keeping part of dataframe in tact
| 39,415,851
|
<p>I am trying to move some of my rows and make the them columns, but keep a large portion of the dataframe the same. </p>
<p>My Dataframe looks something like this:</p>
<pre><code>ID Thing Level1 Level2 Time OAttribute IsTrue Score Value
1 bicycle value value 9:30 whatever yes 1 type1
2 non-cycle value value 1:30 whatever no 2 type2
3 bicycle value value 2:30 whatever yes
4 bicycle value value 3:30 whatever no 4 type3
</code></pre>
<p>And I want something like this:</p>
<pre><code>ID Thing Level1 Level2 Time OAttribute IsTrue Type1 Type2 Type 3
1 bicycle value value 9:30 whatever yes 1
2 non-cycle value value 1:30 whatever no 2
3 bicycle value value 2:30 whatever yes
4 bicycle value value 3:30 whatever no 4
</code></pre>
| 3
|
2016-09-09T16:20:44Z
| 39,416,787
|
<p><strong><em>Option 1</em></strong><br>
Use <code>merge</code></p>
<pre><code>df_ = df[['ID', 'Value']].dropna().set_index('Value', append=True).ID.unstack()
df.drop('Value', 1).merge(df_, right_index=True, left_index=True, how='left').fillna('')
</code></pre>
<p><a href="http://i.stack.imgur.com/2YKUK.png" rel="nofollow"><img src="http://i.stack.imgur.com/2YKUK.png" alt="enter image description here"></a></p>
<p><strong><em>Option 2</em></strong><br>
Use <code>pd.concat</code></p>
<pre><code>df_ = df[['ID', 'Value']].dropna().set_index('Value', append=True).ID.unstack()
pd.concat([df, df_], axis=1).drop('Value', 1).fillna('')
</code></pre>
| 3
|
2016-09-09T17:23:55Z
|
[
"python",
"pandas",
"dataframe"
] |
Python encoding issue while reading a file
| 39,415,856
|
<p>I am trying to read a file that contains this character in it "ë". The problem is that I can not figure out how to read it no matter what I try to do with the encoding. When I manually look at the file in textedit it is listed as a unknown 8-bit file. If I try changing it to utf-8, utf-16 or anything else it either does not work or messes up the entire file. I tried reading the file just in standard python commands as well as using codecs and can not come up with anything that will read it correctly. I will include a code sample of the read below. Does anyone have any clue what I am doing wrong? This is Python 2.17.10 by the way.</p>
<pre><code>readFile = codecs.open("FileName",encoding='utf-8')
</code></pre>
<p>The line I am trying to read is this with nothing else in it.</p>
<pre><code>Aeëtes
</code></pre>
<p>Here are some of the errors I get:</p>
<blockquote>
<p>UnicodeDecodeError: 'utf8' codec can't decode byte 0x91 in position 0: invalid start byte</p>
<p>UTF-16 stream does not start with BOM"
UnicodeError: UTF-16 stream does not start with BOM -- I know this one is that it is not a utf-16 file.</p>
<p>UnicodeDecodeError: 'ascii' codec can't decode byte 0x91 in position 0: ordinal not in range(128)</p>
</blockquote>
<p>If I don't use a Codec the word comes in as <code>Ae?tes</code> which then crashes later in the program. Just to be clear, none of the suggested questions or any other anywhere on the net have pointed to an answer. One other detail that might help is that I am using OS X, not Windows.</p>
| 0
|
2016-09-09T16:21:09Z
| 39,420,503
|
<p>Credit for this answer goes to RadLexus for figuring out the proper encoding and also to Mad Physicist who pointed me in the right track even if I did not consider all possible encodings. </p>
<p>The issue is apparently a Mac will convert the .txt file to mac_roman. If you use that encoding it will work perfectly.</p>
<p>This is the line of code that I used to convert it.</p>
<pre><code>readFile = codecs.open("FileName",encoding='mac_roman')
</code></pre>
| 1
|
2016-09-09T22:23:18Z
|
[
"python",
"python-2.7"
] |
Processing html text nodes with scrapy and XPath
| 39,415,890
|
<p>I'm using scrapy to process documents like this one:</p>
<pre><code>...
<div class="contents">
some text
<ol>
<li>
more text
</li>
...
</ol>
</div>
...
</code></pre>
<p>I want to collect all the text inside the contents area into a string.
I also need the '1., 2., 3....' from the <code><li></code> elements, so my result should be <code>'some text 1. more text...'</code> <br></p>
<p>So, I'm looping over <code><div class="contents"></code>'s children </p>
<pre><code>for n in response.xpath('//div[@class="contents"]/node()'):
if n.xpath('self::ol'):
result += process_list(n)
else:
result += n.extract()
</code></pre>
<p>If <code>n</code>is an ordered list, I loop over its elements and add a number to <code>li/text()</code> (in <code>process_list()</code>). If <code>n</code>is a text node itself, I just read its value.
However, <code>'some text'</code> doesn't seem to be part of the node set, since the loop doesn't get inside the <code>else</code> part. My result is <code>'1. more text'</code></p>
<p>Finding text nodes relative to their parent node works:</p>
<pre><code>response.xpath('//div[@class="contents"]//text()')
</code></pre>
<p>finds all the text, but this way I can't add the list item numbers.</p>
<p>What am I doing wrong and is there a better way to achieve my task?</p>
| 0
|
2016-09-09T16:22:58Z
| 39,419,761
|
<p>If <code>n</code> is not an <code>ol</code> element, <code>self::ol</code> yields an empty node set. What is <code>n.xpath(...)</code> supposed to return when the result of the expression is an empty node set?</p>
<p>An empty node set is "falsy" in XPath, but you're not evaluating it as a boolean in XPath, only in Python. Is an empty node set falsy in Python?</p>
<p>If that's the problem, you could fix it by changing the <code>if</code> statement to</p>
<pre><code>if n.xpath('boolean(self::ol)'):
</code></pre>
<p>or</p>
<pre><code>if n.xpath('count(self::ol) > 1'):
</code></pre>
| 0
|
2016-09-09T21:11:25Z
|
[
"python",
"xpath",
"scrapy"
] |
Processing html text nodes with scrapy and XPath
| 39,415,890
|
<p>I'm using scrapy to process documents like this one:</p>
<pre><code>...
<div class="contents">
some text
<ol>
<li>
more text
</li>
...
</ol>
</div>
...
</code></pre>
<p>I want to collect all the text inside the contents area into a string.
I also need the '1., 2., 3....' from the <code><li></code> elements, so my result should be <code>'some text 1. more text...'</code> <br></p>
<p>So, I'm looping over <code><div class="contents"></code>'s children </p>
<pre><code>for n in response.xpath('//div[@class="contents"]/node()'):
if n.xpath('self::ol'):
result += process_list(n)
else:
result += n.extract()
</code></pre>
<p>If <code>n</code>is an ordered list, I loop over its elements and add a number to <code>li/text()</code> (in <code>process_list()</code>). If <code>n</code>is a text node itself, I just read its value.
However, <code>'some text'</code> doesn't seem to be part of the node set, since the loop doesn't get inside the <code>else</code> part. My result is <code>'1. more text'</code></p>
<p>Finding text nodes relative to their parent node works:</p>
<pre><code>response.xpath('//div[@class="contents"]//text()')
</code></pre>
<p>finds all the text, but this way I can't add the list item numbers.</p>
<p>What am I doing wrong and is there a better way to achieve my task?</p>
| 0
|
2016-09-09T16:22:58Z
| 39,446,213
|
<p>Scrapy's Selectors use <code>lxml</code> under the hood, but <a href="https://bugs.launchpad.net/lxml/+bug/996134" rel="nofollow"><code>lxml</code> doesn't work with XPath calls on text nodes</a>. </p>
<pre><code>>>> import scrapy
>>> s = scrapy.Selector(text='''<div class="contents">
... some text
... <ol>
... <li>
... more text
... </li>
... ...
... </ol>
... </div>''')
>>> s.xpath('.//div[@class="contents"]/node()')
[<Selector xpath='.//div[@class="contents"]/node()' data='\n some text\n '>, <Selector xpath='.//div[@class="contents"]/node()' data='<ol>\n <li>\n more text\n'>, <Selector xpath='.//div[@class="contents"]/node()' data='\n'>]
>>> for n in s.xpath('.//div[@class="contents"]/node()'):
... print(n.xpath('self::ol'))
...
[]
[<Selector xpath='self::ol' data='<ol>\n <li>\n more text\n'>]
[]
</code></pre>
<p>But you could hack into the underlying lxml object to test it's type for a text node (it's "hidden" in a <code>.root</code> attribute of each scrapy Selector):</p>
<pre><code>>>> for n in s.xpath('.//div[@class="contents"]/node()'):
... print([type(n.root), n.root])
...
[<class 'str'>, '\n some text\n ']
[<class 'lxml.etree._Element'>, <Element ol at 0x7fa020f2f9c8>]
[<class 'str'>, '\n']
</code></pre>
<p>An alternative is to use some HTML-to-text conversion library like <a href="https://pypi.python.org/pypi/html2text" rel="nofollow">html2text</a></p>
<pre><code>>>> import html2text
>>> html2text.html2text("""<div class="contents">
... some text
... <ol>
... <li>
... more text
... </li>
... ...
... </ol>
... </div>""")
'some text\n\n 1. more text \n...\n\n'
</code></pre>
| 1
|
2016-09-12T08:31:03Z
|
[
"python",
"xpath",
"scrapy"
] |
Python Plugin for Notepad++
| 39,415,924
|
<p>I installed PythonScript_1.0.8.0 for notepad++, saved my first script as Test.py
and filled it as follows:</p>
<pre><code> Editor.selectAll()
Editor.paste()
notepad.runPluginCommand('NPPExport', 'Copy RTF to clipboard')
</code></pre>
<p>However when running, I got the following error:</p>
<blockquote>
<p>File
"C:\Users\AA\AppData\Roaming\Notepad++\plugins\Config\PythonScript\scripts\Test.py",
line 1, in </p>
<p>Editor.selectAll() </p>
<p>TypeError: unbound method Boost.Python.function object must be called
with Editor instance as first argument (got nothing instead)</p>
</blockquote>
<p>Any Help?</p>
| -1
|
2016-09-09T16:25:11Z
| 39,415,966
|
<p>You need to use <code>editor</code> instead of <code>Editor</code>. <code>Editor</code> is the class and <code>editor</code> is the instance. Example:</p>
<pre><code>editor.selectAll()
</code></pre>
| 2
|
2016-09-09T16:28:16Z
|
[
"python",
"notepad++"
] |
How to average hourly observations stored on a .csv file into daily observations?
| 39,415,988
|
<p>I have a .csv file (mydb.csv) with the following entries (+1 million rows). The 7th row of this table contains dates. The dates repeat themselves many times, because this dataset contains hourly records.</p>
<pre><code>QTEwOA==,81881,-7.610773,-72.681333,220,A108,2016-06-11,08,21.4,95,994.3,3.3,0,0,,
QTEwOA==,81881,-7.610773,-72.681333,220,A108,2016-06-11,09,21.3,95,994.1,1.2,0,0,,
QTEwOA==,81881,-7.610773,-72.681333,220,A108,2016-06-11,10,21.2,94,994.5,2.1,0,0,,
QTEwOA==,81881,-7.610773,-72.681333,220,A108,2016-06-11,11,20.9,94,994.7,1.3,0,0,,
QTEwOA==,81881,-7.610773,-72.681333,220,A108,2016-06-11,12,20.9,93,995.6,1.7,0,0,0.0,0.0
</code></pre>
<p>I need to calculate the averages for the day for each recorded observation.</p>
<p>Can I do it in python or should I transform my .csv file into a sqlite file to query?</p>
| -2
|
2016-09-09T16:29:40Z
| 39,416,517
|
<p>You can use the <code>pandas</code> library in python to do it very quickly. It would look like that:</p>
<pre><code>import pandas as pd
df = pd.read_csv("initial.csv")
avgd_df = df.groupby('date').mean()
avgd_df.to_csv("averaged.csv")
</code></pre>
| 0
|
2016-09-09T17:04:27Z
|
[
"python",
"sqlite",
"csv",
"numpy"
] |
breaking a complex string ('2,3-5,50-60,70') into list inplace
| 39,415,993
|
<p>complexstring: '2,3-5,50-52,70'</p>
<p>output required: [2,3,4,5,50,51,52,70]</p>
<p>Here is what I attempted and succeeded</p>
<pre><code>a = '2,3-5,50-52,70'
data = []
[data.extend(range(int(r.split('-')[0]),int(r.split('-')[1])+1)) if r.find('-') != -1 else data.append(int(r)) for r in a.split(',')]
print data
</code></pre>
<blockquote>
<p>output achieved: [2, 3, 4, 5, 50, 51, 52, 70]</p>
</blockquote>
<p>But my question is there a way to do in place with in list comprehension? What I exactly mean is </p>
<p><code>data = [#perform some processing on a here to get directly output]</code></p>
<p>instead of pre-declaring list <code>data</code> and keep appending or extending it.</p>
<p>P.S: I want to achieve it with just list comprehension without defining additional function.</p>
| 3
|
2016-09-09T16:29:53Z
| 39,416,092
|
<p>Oneliner:</p>
<pre><code>a = '2,3-5,50-52,70'
data = sum([[int(x)] if x.isdigit() else list(range(int(x.split('-')[0]),1+int(x.split('-')[1]))) for x in a.split(",")],[])
print(data)
</code></pre>
<p>variant without <code>isdigit</code>:</p>
<pre><code>data = sum([list(range(int(x.split('-')[0]),1+int(x.split('-')[1]))) if "-" in x else [int(x)] for x in a.split(",")],[])
</code></pre>
<p>(I use sum with a start value of <code>[]</code> which allows to "flatten" the created lists of one level)</p>
<p>result:</p>
<pre><code>[2, 3, 4, 5, 50, 51, 52, 70]
</code></pre>
<p>That said, that's just for fun:</p>
<ul>
<li>I don't know if the performance is good, though, since there are a lot of list creations and split calls that could be avoided (actually I think it's bad)</li>
<li>It's rather easy to build, but hard to maintain/understand</li>
</ul>
| 2
|
2016-09-09T16:35:51Z
|
[
"python",
"python-2.7",
"list-comprehension"
] |
breaking a complex string ('2,3-5,50-60,70') into list inplace
| 39,415,993
|
<p>complexstring: '2,3-5,50-52,70'</p>
<p>output required: [2,3,4,5,50,51,52,70]</p>
<p>Here is what I attempted and succeeded</p>
<pre><code>a = '2,3-5,50-52,70'
data = []
[data.extend(range(int(r.split('-')[0]),int(r.split('-')[1])+1)) if r.find('-') != -1 else data.append(int(r)) for r in a.split(',')]
print data
</code></pre>
<blockquote>
<p>output achieved: [2, 3, 4, 5, 50, 51, 52, 70]</p>
</blockquote>
<p>But my question is there a way to do in place with in list comprehension? What I exactly mean is </p>
<p><code>data = [#perform some processing on a here to get directly output]</code></p>
<p>instead of pre-declaring list <code>data</code> and keep appending or extending it.</p>
<p>P.S: I want to achieve it with just list comprehension without defining additional function.</p>
| 3
|
2016-09-09T16:29:53Z
| 39,416,193
|
<p>I doubt it's possible to do it with a single list comprehension. You could abuse <code>sum()</code> and do other horrible things in one line, though:</p>
<pre><code>sum([range(*(2 * map(int, c.split('-')))[:2]) + [int(c.split('-')[-1])] for c in text.split(',')], [])
</code></pre>
<p>A cleaner way would be to use a generator:</p>
<pre><code>def parse_sequence(text):
for chunk in text.split(','):
parts = map(int, chunk.split('-'))
if len(parts) == 1:
yield parts[0]
else:
for n in xrange(parts[0], parts[1] + 1):
yield n
</code></pre>
<p>Please don't do it in one line. The second approach is twice as fast and isn't written to be hard to read. There's no reason to use the first one.</p>
| 3
|
2016-09-09T16:41:44Z
|
[
"python",
"python-2.7",
"list-comprehension"
] |
Send XLS with Spyne
| 39,416,001
|
<p>I have a problem.. </p>
<p>I want to send XLS throught webservices with spyne, but I need, that if this URL</p>
<pre><code>http://127.0.0.1:5000/download/file?A=1
</code></pre>
<p>will be pressed, whole XLS will download. Is this possible?</p>
<p>Here is mine code:</p>
<pre><code>class xlsDownload(spyne.Service):
__service_url_path__ = '/download';
__in_protocol__ = HttpRpc(validator='soft');
__out_protocol__ = MessagePackDocument()#HtmlRowTable()#MessagePackRpc()
@spyne.srpc(Unicode, _returns=File)
def Function(A):
GetXLS(A)
return File.Value(data=open("File.xls", 'rb', type='application/vnd.ms-excel');
</code></pre>
<p>Can someone tell me, if I can download whole XLS (I can do anything with that file after URL has been clicked) with Spyne? </p>
<p>Thank You very much,
Have a Good Day</p>
| 0
|
2016-09-09T16:30:34Z
| 39,457,091
|
<p>So, this is it in Flask</p>
<pre><code>@app.route("/download/file")
def xlsDownload(A):
GetXLS(A)
response = Response(bytearray(open("file.xls", "rb").read()))
response.headers["Content-Type"] = "application/vnd.ms-excel"
response.headers["Content-Disposition"] = "attachment; filename = file.xls"
return response
</code></pre>
<p>You will ask it with:</p>
<pre><code>http://127.0.0.1:5000/download/file?A=1
</code></pre>
<p>I hope this will help someone sometimes.. :)</p>
| 0
|
2016-09-12T19:06:33Z
|
[
"python",
"excel",
"web-services",
"spyne"
] |
matplotlib not displaying image on Jupyter Notebook
| 39,416,004
|
<p>I am using ubuntu 14.04 and coding in jupyter notebook using anaconda2.7 and everything else is up to date . Today I was coding, every thing worked fine. I closed the notebook and when I reopened it, every thing worked fine except that the image was not being displayed.</p>
<pre><code>%matplotlib inline
import numpy as np
import skimage
from skimage import data
from matplotlib import pyplot as plt
%pylab inline
img = data.camera()
plt.imshow(img,cmap='gray')
</code></pre>
<p>this is the code i am using, a really simple one but doesn't display the image</p>
<pre><code><matplotlib.image.AxesImage at 0xaf7017ac>
</code></pre>
<p>this is displayed in the output area
please help</p>
| 1
|
2016-09-09T16:30:36Z
| 39,416,963
|
<p>You need to tell matplotlib to actually show the image. Add this at the end of your segment:</p>
<pre><code>plt.show()
</code></pre>
| 0
|
2016-09-09T17:36:49Z
|
[
"python",
"image",
"matplotlib",
"jupyter"
] |
Border for tkinter Label
| 39,416,021
|
<p>Not really relevant but i'm building a calendar and I have a lot of Label widgets, and therefore it will look alot nicer if I had some borders for them!</p>
<p>I have seen you can do this for other widgets such as Button, Entry and Text.</p>
<p>Minimal code:</p>
<pre><code>from tkinter import *
root = Tk()
L1 = Label(root, text="This")
L2 = Label(root, text="That")
L1.pack()
L2.pack()
</code></pre>
<p>I have tried setting</p>
<pre><code>highlightthickness=4
highlightcolor="black"
highlightbackground="black"
borderwidth=4
</code></pre>
<p>inside the widget, but still the same result.</p>
<p><a href="http://i.stack.imgur.com/h2NUB.png" rel="nofollow"><img src="http://i.stack.imgur.com/h2NUB.png" alt="example pic tkinter"></a></p>
<p>Is this even possible to do? Thank you!</p>
| 0
|
2016-09-09T16:31:47Z
| 39,416,145
|
<p>If you want a border, the option is <code>borderwidth</code>. You can also choose the relief of the border (<code>"flat"</code>, <code>"raised"</code>, <code>"sunken"</code>, <code>"ridge"</code>, <code>"solid"</code>, <code>"groove"</code>).</p>
<p>For example:</p>
<pre><code>l1 = Label(root, text="This", borderwidth=2, relief="groove")
</code></pre>
<hr>
<p>Note: <code>"ridge"</code> and <code>"groove"</code> require at least two pixels of width to render properly</p>
<p><a href="http://i.stack.imgur.com/DduC2.png" rel="nofollow"><img src="http://i.stack.imgur.com/DduC2.png" alt="examples of tkinter borders"></a></p>
| 1
|
2016-09-09T16:38:35Z
|
[
"python",
"tkinter"
] |
Optimizing for loop in python
| 39,416,026
|
<p>I have a dataframe (df) with distance traveled and I have assigned a label based on certain conditions.</p>
<pre><code>distance=[0,0.0001,0.20,1.23,4.0]
df = pd.DataFrame(distance,columns=["distance"])
df['label']=0
for i in range(0, len(df['distance'])):
if (df['distance'].values[i])<=0.10:
df['label'][i]=1
elif (df['distance'].values[i])<=0.50:
df['label'][i]=2
elif (df['distance'].values[i])>0.50:
df['label'][i]=3
</code></pre>
<p>This is working fine. However, I have more than 1 million records with distance and this for loop is taking longer time than expected. Can we optimize this code to reduce the execution time?</p>
| 3
|
2016-09-09T16:31:58Z
| 39,416,489
|
<p>Comes with a warning about setting a value on a copy of a slice, but maybe someone can suggest a cleaner alternative? </p>
<p>Just based on fancy indexing to get the sub-array based on distance and then writing the values you want to it.</p>
<pre><code>df.loc[:, "label"][df.loc[:, "distance"] <= 0.1] = 1
df.loc[:, "label"][(0.1 < df.loc[:, "distance"]) & (df.loc[:, "distance"] <= 0.5)] = 2
df.loc[:, "label"][df.loc[:, "distance"] > 0.5] = 3
</code></pre>
<p>EDIT: New and improved, without chained indexing.</p>
| 0
|
2016-09-09T17:02:51Z
|
[
"python",
"pandas",
"for-loop",
"optimization"
] |
Optimizing for loop in python
| 39,416,026
|
<p>I have a dataframe (df) with distance traveled and I have assigned a label based on certain conditions.</p>
<pre><code>distance=[0,0.0001,0.20,1.23,4.0]
df = pd.DataFrame(distance,columns=["distance"])
df['label']=0
for i in range(0, len(df['distance'])):
if (df['distance'].values[i])<=0.10:
df['label'][i]=1
elif (df['distance'].values[i])<=0.50:
df['label'][i]=2
elif (df['distance'].values[i])>0.50:
df['label'][i]=3
</code></pre>
<p>This is working fine. However, I have more than 1 million records with distance and this for loop is taking longer time than expected. Can we optimize this code to reduce the execution time?</p>
| 3
|
2016-09-09T16:31:58Z
| 39,416,568
|
<p>In general, you shouldn't loop over DataFrames unless it's absolutely necessary. You'll usually get much better performance using a built-in Pandas function that's already been optimized, or by using a vectorized approach. </p>
<p>In this case, you can use <code>loc</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">Boolean indexing</a> to do the assignments:</p>
<pre><code># Initialize as 1 (eliminate need to check the first condition).
df['label'] = 1
# Case 1: Between 0.1 and 0.5
df.loc[(df['distance'] > 0.1) & (df['distance'] <= 0.5), 'label'] = 2
# Case 2: Greater than 0.5
df.loc[df['distance'] > 0.5, 'label'] = 3
</code></pre>
<p>Another option is to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>pd.cut</code></a>. This is a method is a little more specialized to the example problem in the question. Boolean indexing is a more general method.</p>
<pre><code># Get the low and high bins.
low, high = df['distance'].min()-1, df['distance'].max()+1
# Perform the cut. Add one since the labels start at zero by default.
df['label'] = pd.cut(df['distance'], bins=[low, 0.1, 0.5, high], labels=False) + 1
</code></pre>
<p>You could also use <code>labels=[1,2,3]</code> in the code above, and not add 1 to the result. This would give <code>df['labels']</code> categorical dtype instead of integer dtype though. Depending on your use case this may or may not be important.</p>
<p>The resulting output for either method:</p>
<pre><code> distance label
0 0.0000 1
1 0.0001 1
2 0.2000 2
3 1.2300 3
4 4.0000 3
</code></pre>
| 3
|
2016-09-09T17:08:21Z
|
[
"python",
"pandas",
"for-loop",
"optimization"
] |
Optimizing for loop in python
| 39,416,026
|
<p>I have a dataframe (df) with distance traveled and I have assigned a label based on certain conditions.</p>
<pre><code>distance=[0,0.0001,0.20,1.23,4.0]
df = pd.DataFrame(distance,columns=["distance"])
df['label']=0
for i in range(0, len(df['distance'])):
if (df['distance'].values[i])<=0.10:
df['label'][i]=1
elif (df['distance'].values[i])<=0.50:
df['label'][i]=2
elif (df['distance'].values[i])>0.50:
df['label'][i]=3
</code></pre>
<p>This is working fine. However, I have more than 1 million records with distance and this for loop is taking longer time than expected. Can we optimize this code to reduce the execution time?</p>
| 3
|
2016-09-09T16:31:58Z
| 39,416,804
|
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow"><code>cut</code></a> by assigning labels to the bins:</p>
<pre><code>pd.cut(df.distance, [-np.inf, 0.1, 0.5, np.inf], labels=[1,2,3])
0 1
1 1
2 2
3 3
4 3
</code></pre>
| 1
|
2016-09-09T17:24:47Z
|
[
"python",
"pandas",
"for-loop",
"optimization"
] |
How to exclude a part of a Django template file from processing?
| 39,416,053
|
<p>I have a Django template file that has a couple of <strong>enormous</strong> strings in it (images encoded in Base64). When I use the Django templating engine, it chokes and takes 5 minutes to render the template. Is there a way to exclude a part of a template, with something like:</p>
<pre><code>{% ignore %}
<img src='....'>
{% endignore %}
</code></pre>
<p>Does this exist?</p>
| 1
|
2016-09-09T16:33:42Z
| 39,416,156
|
<p>Use <strong><code>verbatim</code></strong> tag!</p>
<p>From django docs <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/#verbatim" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/templates/builtins/#verbatim</a></p>
<blockquote>
<p><strong>verbatim</strong></p>
<p>Stops the template engine from rendering the contents of this block
tag.</p>
<p>A common use is to allow a JavaScript template layer that collides
with Djangoâs syntax. For example:</p>
<pre><code>{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
</code></pre>
</blockquote>
| 1
|
2016-09-09T16:39:07Z
|
[
"python",
"django",
"django-templates"
] |
Automate webpage tasks without having to have a browser open?
| 39,416,083
|
<p>I know about tampermonkey/greasemonkey and have used it a fair bit, but now my task is to write a program that runs in the background and automates mundane tasks (clicking buttons, typing into input fields etc.) on a specific webpage. Running a browser in the background takes too much RAM and processing power, so I'm looking for an alternative.</p>
<p>So far I've found <a href="http://www.seleniumhq.org/" rel="nofollow">selenium</a>, but after a bit of research it looks like that it requires to have a browser open at all times as well (or maybe not? the documentation isn't that good). I thought about python scripts too, but I don't have any experience with those nor have I any idea if they can handle anything that's not basic html. If they can, does anyone know of a good tutorial for python scripts? I have used that language a few years ago, so I shouldn't really have a problem with python itself.</p>
<p>If python scripts aren't ideal either, is there a (preferably somewhat simple) way I could achieve what I want? </p>
| 0
|
2016-09-09T16:35:34Z
| 39,416,196
|
<p>It depends on whether you want a script that interacts with a web UI, or a script that automates web requests. Do you <em>really</em> need to click buttons and type into input fields? Presumably, the data from those buttons and input fields is eventually sent to a web server. You could skip the entire UI and just make the requests directly. You don't need a browser for that and python is fine for doing these types of things (you don't even need <code>selenium</code>, you can just use <code>requests</code>)</p>
<p>On the other hand, if you're trying to test out the UI of a web page, or you actually need to interact with the web UI for some other reason, then yeah, you'll need an application (like a web browser) that's capable of rendering the UI so you can interact with it.</p>
| 0
|
2016-09-09T16:42:00Z
|
[
"python",
"selenium",
"automation"
] |
From local HTML file, shutdown down computer with Python/AJAX
| 39,416,144
|
<p>Been working with this for a while and found a few helpful things, but I'm not good with AJAX yet... </p>
<p>I'm working to make a chromium-browser kiosk on the Raspberry Pi (which has been fine) but when in kiosk mode, there's not a "shutdown" button. I'm displaying a local HTML file in the chromium-browser and I want to create a button in the local HTML file that will shutdown the computer using AJAX/JQuery by calling a simple python code I made:</p>
<pre><code>#! /usr/bin/python -u
import os
import shutil
import sys
os.system('sudo shutdown -h now')
</code></pre>
<p>I found this:</p>
<pre><code>$.ajax({
type: "POST",
url: "~/shutdown.py",
data: { param: text}
}).done(function( o ) {
// do something
});
</code></pre>
<p>How do I connect this though? there's no output from my python, just want to call the python code and have the raspberry pi shutdown.
The python code when I run it in its own terminal shuts down the computer as expected.</p>
<p>Or if you have any other ideas for shutting down the Rpi while in Kiosk mode in the most "user friendly" way, let me know! The people using this won't know about using the terminal or SSH-ing in...</p>
<p>Thanks!</p>
| 2
|
2016-09-09T16:38:34Z
| 39,416,396
|
<p>Probably the easiest way would be to run a local web server that listens for a request and then shuts down the computer. Instead of just displaying a local HTML file, actually serve it from flask. This gives you much more freedom, since you can run the commands server-side (even though the server and client are the same in this case) where you don't have restrictions like you do within a browser environment.</p>
<p>You could do this with flask.</p>
<p>Create a directory like this</p>
<pre><code>/kiosk
/templates
index.html
app.py
</code></pre>
<p>The <code>index.html</code> is your current html page. Here is what <code>app.py</code> would look like.</p>
<pre><code>from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/shutdown")
def shutdown():
os.system('sudo shutdown -h now')
if __name__ == "__main__":
app.run()
</code></pre>
<p>Your ajax call would look like this</p>
<pre><code>$.ajax({
type: "POST",
url: "/shutdown"
});
</code></pre>
<p>Then just cd into the app directory and run <code>python app.py</code>, which starts the web application. Then open a browser and go to <code>localhost:5000</code></p>
| 2
|
2016-09-09T16:55:07Z
|
[
"python",
"html",
"ajax",
"raspberry-pi",
"shutdown"
] |
Get the facebook's posts' likes and share posts counts using HTTP request
| 39,416,162
|
<p>I want to get post's likes count using <code>HTTP</code> request. I am doing in this way </p>
<pre><code>https://graph.facebook.com/10153608167431961?fields=likes.limit(0).summary(true)?access_token=EAANep****
</code></pre>
<p>and getting the error </p>
<blockquote>
<p>{
"error": {
"message": "Syntax error \"Expected end of string instead of \"?\".\" at character 14: likes.limit(0)?access_token=EA*****",
"type": "OAuthException",
"code": 2500,
"fbtrace_id": "FgmjqQQgY+J"
}
}</p>
</blockquote>
<p>Is it syntactically something wrong?</p>
| -1
|
2016-09-09T16:39:48Z
| 39,417,081
|
<p>Correct:</p>
<pre><code>https://graph.facebook.com/10153608167431961?fields=likes.limit(0).summary(true)&access_token=xxx
</code></pre>
<p>You can´t have more than one questionmark, separate the different parameter with <code>&</code>.</p>
| 0
|
2016-09-09T17:44:44Z
|
[
"python",
"facebook",
"facebook-graph-api"
] |
Prevent serializer creating duplicate items (update_or_create on Nested items)
| 39,416,230
|
<p>When I post via the API, I want the serializer not duplicated a tag if one exists with the same name.</p>
<p>I tried adding "unique" to the model field of "name" in the class Tag but this did not work- it wouldn't allow me to create other Movie's that linked to a tag which exists.</p>
<ul>
<li><p>Check if the field "name" already exists (case <strong>insensitive</strong>).</p></li>
<li><p>If the tag "name" exists, just create the FK relationship with the
existing tag name & the new movie</p></li>
<li><p>If the tag "name" doesn't exist, create it</p></li>
</ul>
<h1>Models.py</h1>
<pre><code>class Tag(models.Model):
name = models.CharField("Name", max_length=5000, blank=True)
taglevel = models.IntegerField("Tag level", blank=True)
def __str__(self):
return self.name
class Movie(models.Model):
title = models.CharField("Whats happening?", max_length=100, blank=True)
tag = models.ManyToManyField('Tag', blank=True)
def __str__(self):
return self.title
</code></pre>
<h1>Serializers.py</h1>
<pre><code>class TagSerializer(serializers.ModelSerializer):
taglevel = filters.CharFilter(taglevel="taglevel")
class Meta:
model = Tag
fields = ('name', 'taglevel', 'id')
class MovieSerializer(serializers.ModelSerializer):
tag = TagSerializer(many=True, read_only=False)
info = InfoSerializer(many=True, read_only=True)
class Meta:
model = Movie
fields = ('title', 'tag')
def get_or_create(self, validated_data):
tags_data = validated_data.pop('tag')
task = Task.objects.get_or_create(**validated_data)
for tag_data in tags_data:
task.tag.get_or_create(**tag_data)
return task
</code></pre>
<p>The get_or_create doesn't work (trace here: <a href="http://dpaste.com/2G0HESS" rel="nofollow">http://dpaste.com/2G0HESS</a>) as it tells me AssertionError: The <code>.create()</code> method does not support writable nested fields by default.</p>
| 0
|
2016-09-09T16:44:02Z
| 39,423,814
|
<p>You'll have to write custom create method for your models. <a href="http://www.django-rest-framework.org/topics/3.0-announcement/#writable-nested-serialization" rel="nofollow">Here is why.</a></p>
| 1
|
2016-09-10T07:39:58Z
|
[
"python",
"django",
"django-rest-framework"
] |
How to capture all letters from different languages in python?
| 39,416,362
|
<p>I have a corpus of different texts from different languages.<br>
I want to capture all characters. I use <strong>python 2.7</strong> and <strong>defaultencodingsetting</strong> is <strong>utf-8</strong>.<br>
I do not know why when I use this code for German umlaut it prints out German umlaut correctly : </p>
<pre><code>'Erd\xC3\xA4pfel'.decode('unicode-escape').encode('latin1').decode('utf-8')
</code></pre>
<p>Result is:
<strong>Erdäpfel</strong> </p>
<p>but when I use this code : </p>
<pre><code>'Erd\xC3\xA4pfel'.decode('unicode-escape').encode('utf-8').decode('utf-8')
</code></pre>
<p>result is :
<strong>Erdäpfel</strong> which is different. </p>
<p>I am not familiar with text mining.I know that for example latin1 encoding does not contain French letter which is not desired in my project.
How can I convert all unicode escape strings in my corpus regardless of their language to respective character? </p>
<p><strong>Utf-8</strong> according to documentations contains all languages but why it does not print out German umlaut correctly while latin1 encoding prints out correctly? </p>
<p><strong>PS: Lowercase in unicode escaping characters sequences is not the case. I have tried both and results were the same.</strong></p>
| -1
|
2016-09-09T16:52:31Z
| 39,416,498
|
<p>You <em>already</em> have UTF-8 encoded data. There are no string literal characters to escape in your bytestring. You are looking at the <code>repr()</code> output of a string where non-printable ASCII characters are shown as escape sequences because that makes the value easily copy-pastable in an ASCII-safe way. The <code>\xc3</code> you see is <em>one byte</em>, not separate characters:</p>
<pre><code>>>> 'Erd\xC3\xA4pfel'
'Erd\xc3\xa4pfel'
>>> 'Erd\xC3\xA4pfel'[3]
'\xc3'
>>> 'Erd\xC3\xA4pfel'[4]
'\xa4'
>>> print 'Erd\xC3\xA4pfel'
Erdäpfel
</code></pre>
<p>You'd have to use a raw string literal or doubled backslashes to actually getting escape sequences that <code>unicode-escape</code> would handle:</p>
<pre><code>>>> '\\xc3\\xa4'
'\\xc3\\xa4'
>>> '\\xc3\\xa4'[0]
'\\'
>>> '\\xc3\\xa4'[1]
'x'
>>> '\\xc3\\xa4'[2]
'c'
>>> '\\xc3\\xa4'[3]
'3'
>>> print '\\xc3\\xa4'
\xc3\xa4
</code></pre>
<p>Note how there is a separate <code>\</code> backslash character in that string (echoed as <code>\\</code>, <em>escaped</em> again).</p>
<p>Next to interpreting actual escape sequences he <code>unicode-escape</code> decodes your data as Latin-1, so you end up with a Unicode string with the character <a href="https://codepoints.net/U+00C3" rel="nofollow">U+00C3 LATIN CAPITAL LETTER A WITH TILDE</a> in it. Encoding that back to Latin-1 bytes gives you the <code>\xC3</code> byte again, and you are back to UTF-8 bytes. Decoding then as UTF-8 works correctly.</p>
<p>But your second attempt encoded the U+00C3 LATIN CAPITAL LETTER A WITH TILDE codepoint to UTF-8, and <em>that</em> encoding gives you the byte sequence <code>\xc3\x83</code>. Printing those bytes to your UTF-8 terminal will show the <code>Ã</code> character. The other byte, <code>\xA4</code> became <a href="https://codepoints.net/U+00A4" rel="nofollow">U+00A4 CURRENCY SIGN</a>, and the UTF-8 byte sequence for that is <code>\xc2\xa4</code>, which prints as <code>¤</code>.</p>
<p>There is <em>absolutely no need</em> to decode as <code>unicode-escape</code> here. Just leave the data <em>as is</em>. Or, perhaps, decode as UTF-8 to get a <code>unicode</code> object:</p>
<pre><code>>>> 'Erd\xC3\xA4pfel'.decode('utf8')
u'Erd\xe4pfel'
>>> print 'Erd\xC3\xA4pfel'.decode('utf8')
Erdäpfel
</code></pre>
<p>If your <strong>actual</strong> data (and not the test you did) contains <code>\xhh</code> escape sequences that encode UTTF-8, then don't use <code>unicode-escape</code> to decode those sequences <em>either</em>. Use <code>string-escape</code> so you get a byte string containing UTF-8 data (which you can then decode to Unicode as needed):</p>
<pre><code>>>> 'Erd\\xc3\\xa4pfel'
'Erd\\xc3\\xa4pfel'
>>> 'Erd\\xc3\\xa4pfel'.decode('string-escape')
'Erd\xc3\xa4pfel'
>>> 'Erd\\xc3\\xa4pfel'.decode('string-escape').decode('utf8')
u'Erd\xe4pfel'
>>> print 'Erd\\xc3\\xa4pfel'.decode('string-escape').decode('utf8')
Erdäpfel
</code></pre>
| 4
|
2016-09-09T17:03:08Z
|
[
"python",
"unicode"
] |
How to update a composite list as contents of member lists are changed?
| 39,416,382
|
<p>Let's say I have:</p>
<pre><code>friendlies = []
enemies = []
everyone = [friendlies + enemies]
</code></pre>
<p>And I say:</p>
<pre><code>friendlies.append("something")
</code></pre>
<p>so that friendlies now contains:</p>
<pre><code>["something"]
</code></pre>
<p>What is the pythonic way to make it so that <code>everyone</code> updates as well? So that if I update <code>friendlies</code> in the way stated above, <code>everyone</code> would contain:</p>
<pre><code>["something"]
</code></pre>
<p>?</p>
| 0
|
2016-09-09T16:53:35Z
| 39,416,431
|
<p>Maintain a reference to <code>friendlies</code> and <code>enemies</code> in the composite list:</p>
<pre><code>everyone = [friendlies, enemies]
# ^
</code></pre>
<p>Index 0 and 1 of the compisite list will reference <code>friendlies</code> and <code>enemies</code> respectively. </p>
<p><code>friendlies + enemies</code> creates a new list which is not what you want.</p>
<hr>
<p>A more readable approach will be making <code>everyone</code> a dictionary:</p>
<pre><code>everyone = {'friendlies': friendlies, 'enemies': enemies}
</code></pre>
<p>And can be used as:</p>
<pre><code>>>> friendlies = []
>>> enemies = []
>>> everyone = {'friendlies': friendlies, 'enemies': enemies}
>>> friendlies.append("something")
>>> everyone['friendlies']
['something']
</code></pre>
| 3
|
2016-09-09T16:58:00Z
|
[
"python",
"list",
"python-3.x",
"data-structures"
] |
How to update a composite list as contents of member lists are changed?
| 39,416,382
|
<p>Let's say I have:</p>
<pre><code>friendlies = []
enemies = []
everyone = [friendlies + enemies]
</code></pre>
<p>And I say:</p>
<pre><code>friendlies.append("something")
</code></pre>
<p>so that friendlies now contains:</p>
<pre><code>["something"]
</code></pre>
<p>What is the pythonic way to make it so that <code>everyone</code> updates as well? So that if I update <code>friendlies</code> in the way stated above, <code>everyone</code> would contain:</p>
<pre><code>["something"]
</code></pre>
<p>?</p>
| 0
|
2016-09-09T16:53:35Z
| 39,416,464
|
<p>If you sum now you lose reference. Create a list of lists to maintain references</p>
<p>Hacky way of doing that:</p>
<pre><code>friendlies = []
enemies = []
everyone = [friendlies,enemies] # not sum, sublists
enemies.append("something")
print(sum(everyone,[])) # sum sublists to a new list
</code></pre>
| 2
|
2016-09-09T17:00:43Z
|
[
"python",
"list",
"python-3.x",
"data-structures"
] |
Python String Slicing from known word in string
| 39,416,503
|
<p>I'm trying to read a variable which is written by another function (outside of my control), to look for the presence of a known word and then to copy a sub string beginning at the known word and ending either at the end of the line or a <code>|</code> delimiter.
So I want to write to this variable based on a simple <code>if</code> statement I've written, but at the moment it doesn't take any consideration of what is already in the variable and it needs to. As the code I'm writing makes use of all sorts of aliases, I've tried to simplify what I am doing below</p>
<p>So, firstly the variable 'devices' is written to elsewhere but available to me.
I'm reading another variable 'area' which if specifically set to '3', I need to write the variable 'devices' with the string of 'box2|box3' (or 'box3|box2' - it doesn't matter) and I can ignore the existing content of 'devices' UNLESS it contains 'box1' in the string. It may appear anywhere within the string and will also be appended by other data, but it always either finishes at the end of the line, OR by a <code>|</code> delimiter. So I need to read the entire variable, look for the presence of 'box1' and read as many characters into another variable up until the end of the line of it hits the <code>|</code> delimiter.</p>
<p>The only code I can really share here is this:</p>
<pre><code>area = "3"
if area == "3":
devices = "box2|box3"
print devices
</code></pre>
<p>Let's say that 'devices' contains 'box5|box6_standard|box9|box8_ex_345|box1_182', I need to extra box1_182 from that string (and append it back in when I write 'devices' variable - I don't need to worry about any other pre-existing content of that variable.</p>
<p>As another example, the existing 'devices' variable may contain 'box7|box1_345|box6|box8_ex_345', in this case, I'd need to take 'box1_345' and append it to the devices string before I write 'box2|box3' to it ('box2|box3|box1_182')</p>
| 0
|
2016-09-09T17:03:30Z
| 39,416,728
|
<p>I'd use regex and the <code>in</code> word to check if <code>devices</code> has 'box1'. If so then simply append it to the new <code>devices</code> string</p>
<pre><code>import re
devices='box5|box6_standard|box9|box8_ex_345|box1_182'
area = "3"
if area == "3":
tdevices = "box2|box3"
if 'box1' in devices:
t=re.search('box1[0-9_:a-zA-Z]*', devices)
devices=tdevices+'|'+t.group()
else:
devices=tdevices
print devices
</code></pre>
| 0
|
2016-09-09T17:19:13Z
|
[
"python",
"string",
"slice"
] |
Python if else statement not working in reduce lambda function
| 39,416,588
|
<p>I'm new to <code>lambda</code> and <code>reduce</code> in Python and I don't understand why this function doesn't work:</p>
<pre><code>def my_func(str):
symbols = ['_', '-']
return reduce(lambda x, y: ' ' + y if x in symbols else x + y, str)
my_func('foo_bar-baz') # 'foo_bar-baz'
</code></pre>
<p>I expected the output to be <code>'foo bar baz'</code>.</p>
<p>Does anyone understand what's wrong here?</p>
| -2
|
2016-09-09T17:10:11Z
| 39,416,674
|
<p>You seem to be confused about the order of the arguments to <code>reduce</code>'s function argument. The first argument is the running total, the second is the new data. In your example, <code>x</code> is the built-up string, <code>y</code> is the new character.</p>
<p>Try this:</p>
<pre><code>def my_func(str):
symbols = ['_', '-']
return reduce(lambda x, y: x + (' ' if y in symbols else y), str)
print my_func('foo_bar-baz') # 'foo bar baz'
</code></pre>
<p>Note the bug in this: in the first call to the lambda expression, <code>x</code> is <code>str[0]</code>, and <code>y</code> is <code>str[1]</code>. Thus, if the first character in the passed-in string is a symbol, it is not translated. </p>
<pre><code>print my_func('-foo_bar-baz')
-foo bar baz
</code></pre>
<p>This can be solved by providing the third argument to <code>reduce()</code>:</p>
<pre><code>def my_func(str):
symbols = ['_', '-']
return reduce(lambda x, y: x + (' ' if y in symbols else y), str, '')
print my_func('foo_bar-baz') # 'foo bar baz'
print my_func('-foo_bar-baz') # ' foo bar baz'
</code></pre>
| 5
|
2016-09-09T17:16:09Z
|
[
"python",
"lambda",
"reduce"
] |
limited number of user-initiated background processes
| 39,416,623
|
<p>I need to allow users to submit requests for very, very large jobs. We are talking 100 gigabytes of memory and 20 hours of computing time. This costs our company a lot of money, so it was stipulated that only 2 jobs could be running at any time, and requests for new jobs when 2 are already running would be rejected (and the user notified that the server is busy).</p>
<p>My current solution uses an Executor from concurrent.futures, and requires setting the Apache server to run only one process, reducing responsiveness (current user count is very low, so it's okay for now).</p>
<p>If possible I would like to use Celery for this, but I did not see in the documentation any way to accomplish this particular setting.</p>
<p>How can I run up to a limited number of jobs in the background in a Django application, and notify users when jobs are rejected because the server is busy?</p>
| 9
|
2016-09-09T17:12:55Z
| 39,446,293
|
<p>First of all you need to limit concurrency on your worker (<a href="http://docs.celeryproject.org/en/latest/userguide/workers.html#starting-the-worker" rel="nofollow">docs</a>):</p>
<pre><code>celery -A proj worker --loglevel=INFO --concurrency=2 -n <worker_name>
</code></pre>
<p>This will help to make sure that you do not have more than 2 active tasks even if you will have errors in the code.</p>
<p>Now you have 2 ways to implement task number validation:</p>
<ol>
<li><p>You can use <a href="http://docs.celeryproject.org/en/latest/_modules/celery/app/control.html#Inspect" rel="nofollow">inspect</a> to get number of active and scheduled tasks:</p>
<pre><code> from celery import current_app
def start_job():
inspect = current_app.control.inspect()
active_tasks = inspect.active() or {}
scheduled_tasks = inspect.scheduled() or {}
worker_key = 'celery@%s' % <worker_name>
worker_tasks = active_tasks.get(worker_key, []) + scheduled_tasks.get(worker_key, [])
if len(worker_tasks) >= 2:
raise MyCustomException('It is impossible to start more than 2 tasks.')
else:
my_task.delay()
</code></pre></li>
<li><p>You can store number of currently executing tasks in DB and validate task execution based on it.</p></li>
</ol>
<p>Second approach could be better if you want to scale your functionality - introduce premium users or do not allow to execute 2 requests by one user. </p>
| 3
|
2016-09-12T08:36:41Z
|
[
"python",
"django",
"asynchronous",
"celery",
"background-process"
] |
limited number of user-initiated background processes
| 39,416,623
|
<p>I need to allow users to submit requests for very, very large jobs. We are talking 100 gigabytes of memory and 20 hours of computing time. This costs our company a lot of money, so it was stipulated that only 2 jobs could be running at any time, and requests for new jobs when 2 are already running would be rejected (and the user notified that the server is busy).</p>
<p>My current solution uses an Executor from concurrent.futures, and requires setting the Apache server to run only one process, reducing responsiveness (current user count is very low, so it's okay for now).</p>
<p>If possible I would like to use Celery for this, but I did not see in the documentation any way to accomplish this particular setting.</p>
<p>How can I run up to a limited number of jobs in the background in a Django application, and notify users when jobs are rejected because the server is busy?</p>
| 9
|
2016-09-09T17:12:55Z
| 39,447,549
|
<p>I have two solutions for this particular case, one an out of the box solution by celery, and another one that you implement yourself.</p>
<ol>
<li>You can do something like this with celery workers. In particular, you <strong>only create two worker processes with concurrency=1</strong> (or well, one with concurrency=2, but that's gonna be threads, not different processes), this way, only two jobs can be done asynchronously. Now you need a way to raise exceptions if both jobs are occupied, then you use <a href="http://docs.celeryproject.org/en/latest/userguide/monitoring.html#management-command-line-utilities-inspect-control" rel="nofollow">inspect</a>, to count the number of active tasks and throw exceptions if required. For implementation, you can checkout <a href="http://stackoverflow.com/questions/5544629/retrieve-list-of-tasks-in-a-queue-in-celery">this SO post</a>.</li>
</ol>
<p>You might also be interested in <a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html#Task.rate_limit" rel="nofollow">rate limits</a>.</p>
<ol start="2">
<li><p>You can do it all yourself, using a locking solution of choice. In particular, a nice implementation that makes sure only two processes are running with redis (and redis-py) is as simple as the following. (Considering you know redis, since you know celery)</p>
<pre><code>from redis import StrictRedis
redis = StrictRedis('localhost', '6379')
locks = ['compute:lock1', 'compute:lock2']
for key in locks:
lock = redis.lock(key, blocking_timeout=5)
acquired = lock.acquire()
if acquired:
do_huge_computation()
lock.release()
else:
raise SystemLimitsReached("Already at max capacity !")
</code></pre></li>
</ol>
<p>This way you make sure only two running processes can exist in the system. A third processes will block in the line <code>lock = redis.lock(key)</code> for <strong>blocking_timeout</strong> seconds, if the locking was successful, <code>acquired</code> would be True, else it's False and you'd tell your user to wait ! </p>
<p>I had the same requirement sometime in the past and what I ended up coding was something like the solution above. In particular</p>
<ol>
<li>This has the least amount of race conditions possible</li>
<li>It's easy to read</li>
<li>Doesn't depend on a sysadmin, suddenly doubling the concurrency of workers under load and blowing up the whole system.</li>
<li>You can also <strong><em>implement the limit per user</em></strong>, meaning each user can have 2 simultaneous running jobs, by only changing the lock keys from <em>compute:lock1</em> to <strong>compute:userId:lock1</strong> and lock2 accordingly. You can't do this one with vanila celery.</li>
</ol>
| 8
|
2016-09-12T09:46:39Z
|
[
"python",
"django",
"asynchronous",
"celery",
"background-process"
] |
limited number of user-initiated background processes
| 39,416,623
|
<p>I need to allow users to submit requests for very, very large jobs. We are talking 100 gigabytes of memory and 20 hours of computing time. This costs our company a lot of money, so it was stipulated that only 2 jobs could be running at any time, and requests for new jobs when 2 are already running would be rejected (and the user notified that the server is busy).</p>
<p>My current solution uses an Executor from concurrent.futures, and requires setting the Apache server to run only one process, reducing responsiveness (current user count is very low, so it's okay for now).</p>
<p>If possible I would like to use Celery for this, but I did not see in the documentation any way to accomplish this particular setting.</p>
<p>How can I run up to a limited number of jobs in the background in a Django application, and notify users when jobs are rejected because the server is busy?</p>
| 9
|
2016-09-09T17:12:55Z
| 39,476,477
|
<p><strong>First</strong></p>
<p>You need the first part of <a href="http://stackoverflow.com/a/39447549/4151886">SpiXel's solution</a>. According to him, "<strong>you only create two worker processes with concurrency=1</strong>".</p>
<p><strong>Second</strong></p>
<p>Set the <a href="http://docs.celeryproject.org/en/latest/userguide/workers.html#time-limits" rel="nofollow"><strong>time out</strong></a> for the task waiting in the queue, which is set <a href="http://docs.celeryproject.org/en/latest/configuration.html#celery-event-queue-ttl" rel="nofollow">CELERY_EVENT_QUEUE_TTL</a> and the <strong>queue length limit</strong> according to <a href="http://stackoverflow.com/a/35309730/4151886">how to limit number of tasks in queue and stop feeding when full?</a>. </p>
<p>Therefore, when the two work running jobs, and the task in the queue waiting like 10 sec or any period time you like, the task will be time out. Or if the queue has been fulfilled, new arrival tasks will be dropped out. </p>
<p><strong>Third</strong></p>
<p>you need extra things to deal with notifying "users when jobs are rejected because the server is busy".</p>
<p><a href="https://www.rabbitmq.com/dlx.html" rel="nofollow">Dead Letter Exchanges</a> is what you need. Every time a task is failed because of the queue length limit or message timeout. "Messages will be dropped or dead-lettered from the front of the queue to make room for new messages once the limit is reached." </p>
<p>You can set <strong>"x-dead-letter-exchange"</strong> to route to another queue, once this queue receive the dead lettered message, you can send a notification message to users.</p>
| 2
|
2016-09-13T18:10:50Z
|
[
"python",
"django",
"asynchronous",
"celery",
"background-process"
] |
Checking if a variable is existent within a list
| 39,416,667
|
<p>I am currently using the code</p>
<pre><code>names = ["Bob", "Joe", "Jack"]
name = raw_input("Please enter your name.")
print ("Hello", name)
</code></pre>
<p>And I want to create an if statement that checks if the inputed name is in the list of names. I assume there is some command to check this, and I couldn't find it searching the documentation or questions here. Right now, the code creates a list of names, a variable that stores the inputed name, and prints "Hello <code>name</code>". I can create the if statement; I just want to know what that command/method is. </p>
<p>Thanks!</p>
| 0
|
2016-09-09T17:15:35Z
| 39,416,699
|
<p>Use the <code>in</code> operator.</p>
<pre><code>if name in names:
print ('The entered name is in the list of names.')
else:
print ('The entered name is not in the list of names.')
</code></pre>
| 2
|
2016-09-09T17:17:28Z
|
[
"python",
"list",
"input",
"global-variables"
] |
struggling to implement a switch/case statement in python
| 39,416,686
|
<p>since there is no <code>switch/case</code> in python, i am trying to implement the same in my sample program with the help of the following link:
<a href="http://www.pydanny.com/why-doesnt-python-have-switch-case.html" rel="nofollow">why python doesnt have switch-case</a></p>
<p>below is my code:</p>
<pre><code>#switch case to get the type of action to take
def action_type(action_id, dir_path):
switcher = {
1: func1(dir_path),
2: func2(dir_path),
}
action_func = switcher.get(action_id, "Do Nothing")
print "action_func, ", action_func
sys.exit(0)
return action_func()
</code></pre>
<p>now it always goes to func1 irrespective of the argument i.e. action_id passed</p>
| 0
|
2016-09-09T17:16:40Z
| 39,416,730
|
<p>When you call <code>switcher.get(action_id, sys.exit(0))</code>, the 2nd argument is evalulated before the result can be passed in to <code>.get()</code>, which results in the program terminating immediately.</p>
| 2
|
2016-09-09T17:19:16Z
|
[
"python"
] |
struggling to implement a switch/case statement in python
| 39,416,686
|
<p>since there is no <code>switch/case</code> in python, i am trying to implement the same in my sample program with the help of the following link:
<a href="http://www.pydanny.com/why-doesnt-python-have-switch-case.html" rel="nofollow">why python doesnt have switch-case</a></p>
<p>below is my code:</p>
<pre><code>#switch case to get the type of action to take
def action_type(action_id, dir_path):
switcher = {
1: func1(dir_path),
2: func2(dir_path),
}
action_func = switcher.get(action_id, "Do Nothing")
print "action_func, ", action_func
sys.exit(0)
return action_func()
</code></pre>
<p>now it always goes to func1 irrespective of the argument i.e. action_id passed</p>
| 0
|
2016-09-09T17:16:40Z
| 39,416,896
|
<p>Your code is broken in two ways, the first way is:</p>
<pre><code>def action_type(action_id, dir_path):
print "action id is, ", action_id
def whatever():
# all code here never runs
# action_type() exits here
</code></pre>
<p>this inner function <code>whatever()</code> is defined, you never call it so it never runs, and then it stops existing when action_type exits, so nothing else can ever get to it.</p>
<p>The second problem is </p>
<pre><code>switcher = {
1: fun1(dir_path),
2: func2(dir_path),
}
</code></pre>
<p>This calls the functions (both of them) at the time Python reads and initializes the dictionary (when it's parsing your code), and you don't want them both called, and you don't want them called until you ask for it. e.g.</p>
<pre><code>test = {
1: len("hello")
}
# this immediately replaces `len("hello")` with the length of the string (5)
</code></pre>
<p>and the same with <code>switcher.get(action_id, sys.exit(0))</code> - this calls sys.exit immediately.</p>
<p><strong>To use 'first class functions' in Python - to pass them around without calling them - you need to use their name without parens.</strong> So...</p>
<pre><code>def action_type(action_id, dir_path):
print "action id is, ",action_id
switcher = {
1: fun1,
2: func2,
}
action_func = switcher.get(action_id, sys.exit)
print "action_func, ", action_func
action_func(dir_path)
action_type(1, r"c:\wherever")
</code></pre>
<p>Pass the functions around without calling them. Then call one at the end.</p>
<p>You will still have to rethink so you don't call sys.exit with a dir_path.</p>
| 1
|
2016-09-09T17:30:34Z
|
[
"python"
] |
Trouble reading from PLC with pymodbus
| 39,416,757
|
<p>I'm having some trouble reading registers from my WAGO 750-881 PLC using pymodbus, python 2.7, and Windows. I can read just fine with the Modbus Poll utility so I think the problem is in my python code. Using the following code I get the error: <code>runfile('C:/Users/Mike/modbustest2.py', wdir='C:/Users/Mike')
Exception Response(131, 3, IllegalValue)</code></p>
<pre><code>from pymodbus.client.sync import ModbusTcpClient
c = ModbusTcpClient(host="192.168.1.20")
chk = c.read_holding_registers(257,10, unit = 1)
response = c.execute(chk)
print response
</code></pre>
<p>I realize my code should read <code>print response.registers</code> but the <code>.registers</code> extension doesn't seem to be available to me. <code>print response.registers</code> throws this error: <code>AttributeError: 'ExceptionResponse' object has no attribute 'registers'</code> I only included the <code>print response</code> error because I thought it might be helpful in some way. Does anyone know what the problem may be? </p>
| 0
|
2016-09-09T17:21:34Z
| 39,416,999
|
<p>You're getting an ExceptionResponse object back, with the exception code 'IllegalValue'.</p>
<p>The most likely cause is you're reading a register the PLC doesn't think exists.</p>
<p>Of course there's no registers attribute on this object because it's not a ReadHoldingRegisters response.</p>
| 1
|
2016-09-09T17:39:39Z
|
[
"python",
"python-2.7",
"modbus",
"plc",
"modbus-tcp"
] |
Unable to install the python module aubio from github, or from pip
| 39,416,823
|
<p>For pip: </p>
<p>In my command prompt I type in: </p>
<pre><code>C:/Python/Scripts/pip install aubio
</code></pre>
<p>Recommended by this site: </p>
<p><a href="http://aubio.readthedocs.io/en/latest/python_module.html" rel="nofollow">http://aubio.readthedocs.io/en/latest/python_module.html</a></p>
<p>And get this message: </p>
<p><a href="http://imgur.com/a/vZxXg" rel="nofollow">http://imgur.com/a/vZxXg</a></p>
<p>It was suggested that I download a C++ compiler for Python, but doing so hasn't prevented the error. </p>
<p>So I tried installing the module via github. </p>
<p>For Github via pip: </p>
<p>I naturally installed Github and went back to my command prompt. </p>
<p>I typed in: </p>
<pre><code>C:/Python/Scripts/pip install git+git://git.aubio.org/git/aubio
</code></pre>
<p>And when that failed:</p>
<pre><code>C:/Python/Scripts/pip install git+git://git.aubio.org/git/aubio.git
</code></pre>
<p>I get the error: </p>
<pre><code> Error [WinError 2] The system cannot find the file specified while executing c
ommand git clone -q git://github.com/aubio/aubio.git C:\Users\luke\AppData\Local
\Temp\pip-ornio5sm-build
Cannot find command 'git'
</code></pre>
<p>A lot of the other questions had answers concerning a broken setup file, but I'm not entirely sure how I check for that. </p>
<p>Thanks.</p>
| 0
|
2016-09-09T17:26:01Z
| 39,416,979
|
<p>So this isn't the whole answer, but it will help anyone who comes here in the future. </p>
<p>I installed Github and not git. That's why the git command isn't recognized. </p>
<p>The correct place for installation[WINDOWS] is: <a href="https://git-for-windows.github.io/" rel="nofollow">https://git-for-windows.github.io/</a> </p>
| 0
|
2016-09-09T17:38:22Z
|
[
"python",
"audio",
"module",
"pip"
] |
OPEN CV - Change Pixel Coordinates
| 39,416,881
|
<p>AS the title suggests I have an image, whose pixel coordinates I want to change using a mathematical function. So far, I have the following code which works but is very time consuming because of the nested loop. Do you have any suggestions to make it faster? To be quantitative, it takes about 2-2.5 minutes to complete the process on a 12MPixel image.</p>
<pre><code>imgcor = np.zeros(img.shape, dtype=img.dtype)
for f in range(rowc):
for k in range(colc):
offX = k + (f*b*c*(math.sin(math.radians(a))))
offY = f + (f*b*d*(math.cos(math.radians(a))))
imgcor[f, k] = img[int(offY)%rowc, int(offX)%colc]
</code></pre>
<p>P.S. I am using opencv 2.4.13 and python 2.7</p>
| 0
|
2016-09-09T17:29:19Z
| 39,417,869
|
<p>There may be a way to get numpy to do some vectorized work for you, but one easy speedup is to not re-calculate some of the values every time you loop (I'm assuming a,b,c, and d are not changing in the loop). I'm curious what the speedup would be, can you report back?</p>
<pre><code>imgcor = np.zeros(img.shape, dtype=img.dtype)
offX_precalc = b*c*(math.sin(math.radians(a)))
offY_precalc = b*d*(math.cos(math.radians(a)))
for f in range(rowc):
for k in range(colc):
offX = k + (f*offX_precalc)
offY = f + (f*offY_precalc)
imgcor[f, k] = img[int(offY)%rowc, int(offX)%colc]
</code></pre>
<p>ok since the above was too slow, I added a bit of vectorization and I'm curious if it's faster:</p>
<pre><code>imgcor = np.zeros(img.shape, dtype=img.dtype)
off_base = b*(math.sin(math.radians(a)))
offX_precalc = off_base*c
offY_precalc = off_base*d+1
for f in range(rowc):
offY = int(f*offY_precalc)%rowc
offXs = [int(k + (f*offX_precalc))%colc for k in range(colc)]
imgcor[f,:] = img[offY, offXs]
</code></pre>
| 0
|
2016-09-09T18:40:36Z
|
[
"python",
"python-2.7",
"opencv",
"image-processing",
"transform"
] |
Decoding ASN1 UPER in Python
| 39,416,902
|
<p>I need to decode ASN1 message using python. I looked into the pyasn1 library but it doesn't support UPER. What can I use to decode ASN1 UPER in python</p>
| 0
|
2016-09-09T17:31:15Z
| 39,425,820
|
<p><strong>Got the Schema?</strong></p>
<p>Assuming you have the ASN.1 schema for the data you're trying to decode, you could start by taking a look at the <a href="http://taste.tuxfamily.org/wiki/index.php?title=ASN.1_generators" rel="nofollow">TASTE framework from the European Space Agency</a>. This is a large application development framework based on ASN.1 for spacecraft system.</p>
<p>The framework is irrelevant to you and your needs. However, lurking somewhere in the core of it as an ASN.1 schema compiler that supports Python code generation and uPER. You might best start by trying out their pre-built VM image that gives you a linux with everything already installed: <a href="http://taste.tuxfamily.org/wiki/index.php?title=Main_Page#Tool_availability" rel="nofollow">see here</a>. You'd use this to compile the schema into python source code that can then encode / decode uPER data from/to Python classes. As an aside, you could also do the same for C, C++, C#, Java, ADA. </p>
<p>I've not tried it out in much anger myself, but there's many an ESA spacecraft flying having been built using it, so it's probably all OK.</p>
<p><strong>Not Got the Schema?</strong></p>
<p>If you don't have the schema, well then you're going to have some problems. uPER cannot be decoded without the schema file. This is because the uPER data is sufficiently packed that there's little evidence of the data's structure left. You'd be reduced to guessing what the schema might have been, trying out a decode, see if it works on all your data, try again if not. </p>
<p>If it were known to be Cannonical PER encoded then you can decode it without the schema, but that's still a lot of effort.</p>
<p>This is in sharp contrast to BER encoded data, which does retain details of the data's structure by incorporating tag, type and value information for every encoded PDU field. But then BER encoded data is much larger that PER, so it's not used on radio systems or other bandwidth constrained transmission channels.</p>
<p>==EDIT==</p>
<p>Having just taken a look over there at TASTE I'm now not sure that it does generate Python code. Python is a dependency for the framework, but it's not claiming anywhere that it generates Python code. Looks like it's just C/C++ or ADA.</p>
<p>Regardless, the ASN.1 compiler seems to have ended up <a href="https://github.com/ttsiodras/asn1scc" rel="nofollow">here on GITHUB</a>. That will generate C code (and ADA, wow!), which you could call from your Python one way or another. It' won't be quite as tidy, but still better than nothing. </p>
<p><strong>Note</strong> This compiler is limited in what schema it will compile (it needs size constraints on arrays, etc, presumably to end up with static sized objects).</p>
<p>Your best bet might be to call C, C++, or Java or C# code generated by other ASN.1 compilers - there's commercial ones over at <a href="http://www.obj-sys.com/" rel="nofollow">Objective Systems</a> and <a href="http://www.oss.com/index.html" rel="nofollow">OSS Nokalva</a>.</p>
<p>==Yet Another Edit==</p>
<p><a href="https://www.thanassis.space/asn1.html" rel="nofollow">This page</a> talks about Python, ASN.1 uPER.</p>
<p>==Encore un Edit==</p>
<p>The <a href="http://pyasn1.sourceforge.net/" rel="nofollow">PyASN1</a> page refers to <a href="https://github.com/kimgr/asn1ate" rel="nofollow">asn1ate</a>, which is a code generator for Python. It is reported to be 'alpha quality', but for a simple schema it may be adequate. It's certainly worth a look.</p>
| 0
|
2016-09-10T11:56:34Z
|
[
"python",
"decode",
"asn.1"
] |
Regex capturing group within non-capturing group
| 39,416,911
|
<p>In Python, how do you capture a group within a non-capturing group? Put in another way, how do you repeat a non-capturing sub-pattern that contains a capturing group?</p>
<p>An example of this would be to capture all of the package names on an import string. E.g. the string:</p>
<blockquote>
<p>import pandas, os, sys</p>
</blockquote>
<p>Would return 'pandas', 'os', and 'sys'. The following pattern captures the first package and gets up to the second package:</p>
<pre><code>import\s+([a-zA-Z0=9]*),*\s*
</code></pre>
<p>From here, I would like to repeat the sub-pattern that captures the group and matches the following characters, i.e.<code>([a-zA-Z0=9]*),*\s*</code>. When I surround this sub-pattern with a non-capturing group and repeat it:</p>
<pre><code>import\s+(?:([a-zA-Z0=9]*),*\s*)*
</code></pre>
<p>It no longer captures the group inside.</p>
| 2
|
2016-09-09T17:32:13Z
| 39,417,275
|
<p>Your question is phrased strictly about regex, but if you're willing to use a <a href="https://en.wikipedia.org/wiki/Recursive_descent_parser" rel="nofollow">recursive descent parser</a> (e.g., <a href="http://pyparsing.wikispaces.com/" rel="nofollow"><code>pyparsing</code></a>), many things that require expertise in regex, become very simple.</p>
<p>E.g., here what you're asking becomes</p>
<pre><code>from pyparsing import *
p = Suppress(Literal('import')) + commaSeparatedList
>>> p.parseString('import pandas, os, sys').asList()
['pandas', 'os', 'sys']
>>> p.parseString('import pandas, os').asList()
['pandas', 'os']
</code></pre>
<hr>
<p>It might be a matter of personal taste, but to me, </p>
<pre><code>Suppress(Literal('import')) + commaSeparatedList
</code></pre>
<p>is also more intuitive than a regex.</p>
| 1
|
2016-09-09T17:59:28Z
|
[
"python",
"regex"
] |
Regex capturing group within non-capturing group
| 39,416,911
|
<p>In Python, how do you capture a group within a non-capturing group? Put in another way, how do you repeat a non-capturing sub-pattern that contains a capturing group?</p>
<p>An example of this would be to capture all of the package names on an import string. E.g. the string:</p>
<blockquote>
<p>import pandas, os, sys</p>
</blockquote>
<p>Would return 'pandas', 'os', and 'sys'. The following pattern captures the first package and gets up to the second package:</p>
<pre><code>import\s+([a-zA-Z0=9]*),*\s*
</code></pre>
<p>From here, I would like to repeat the sub-pattern that captures the group and matches the following characters, i.e.<code>([a-zA-Z0=9]*),*\s*</code>. When I surround this sub-pattern with a non-capturing group and repeat it:</p>
<pre><code>import\s+(?:([a-zA-Z0=9]*),*\s*)*
</code></pre>
<p>It no longer captures the group inside.</p>
| 2
|
2016-09-09T17:32:13Z
| 39,417,415
|
<p>A repeated capturing group will <em>only</em> capture the last iteration. This is why you need to restructure your regex to work with <code>re.findall</code>.</p>
<pre><code>\s*
(?:
(?:^from\s+
( # Base (from (base) import ...)
(?:[a-zA-Z_][a-zA-Z_0-9]* # Variable name
(?:\.[a-zA-Z_][a-zA-Z_0-9]*)* # Attribute (.attr)
)
)\s+import\s+
)
|
(?:^import\s|,)\s*
)
( # Name of imported module (import (this))
(?:[a-zA-Z_][a-zA-Z_0-9]* # Variable name
(?:\.[a-zA-Z_][a-zA-Z_0-9]*)* # Attribute (.attr)
)
)
(?:
\s+as\s+
( # Variable module is imported into (import foo as bar)
(?:[a-zA-Z_][a-zA-Z_0-9]* # Variable name
(?:\.[a-zA-Z_][a-zA-Z_0-9]*)* # Attribute (.attr)
)
)
)?
\s*
(?=,|$) # Ensure there is another thing being imported or it is the end of string
</code></pre>
<p><a href="https://regex101.com/r/jL7oQ4/2" rel="nofollow">Try it on regex101.com</a></p>
<p>Capture group 0 will be the <code>Base</code>, capture group 1 will be (What you're after) the name of the imported module, and capture group 2 will be the variable the module is in (<code>from (group 0) import (group 1) as (group 2)</code>)</p>
<pre><code>import re
regex = r"\s*(?:(?:^from\s+((?:[a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*))\s+import\s+)|(?:^import\s|,)\s*)((?:[a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*))(?:\s+as\s+((?:[a-zA-Z_][a-zA-Z_0-9]*(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*)))?\s*(?=,|$)"
print(re.findall(regex, "import pandas, os, sys"))
</code></pre>
<pre><code>[('', 'pandas', ''), ('', 'os', ''), ('', 'sys', '')]
</code></pre>
<p>You can remove the other two capturing groups if you don't care for them.</p>
| 0
|
2016-09-09T18:08:48Z
|
[
"python",
"regex"
] |
Regex capturing group within non-capturing group
| 39,416,911
|
<p>In Python, how do you capture a group within a non-capturing group? Put in another way, how do you repeat a non-capturing sub-pattern that contains a capturing group?</p>
<p>An example of this would be to capture all of the package names on an import string. E.g. the string:</p>
<blockquote>
<p>import pandas, os, sys</p>
</blockquote>
<p>Would return 'pandas', 'os', and 'sys'. The following pattern captures the first package and gets up to the second package:</p>
<pre><code>import\s+([a-zA-Z0=9]*),*\s*
</code></pre>
<p>From here, I would like to repeat the sub-pattern that captures the group and matches the following characters, i.e.<code>([a-zA-Z0=9]*),*\s*</code>. When I surround this sub-pattern with a non-capturing group and repeat it:</p>
<pre><code>import\s+(?:([a-zA-Z0=9]*),*\s*)*
</code></pre>
<p>It no longer captures the group inside.</p>
| 2
|
2016-09-09T17:32:13Z
| 39,418,673
|
<p>You can use your <code>import\s+(?:([a-zA-Z0-9=]+),*\s*)*</code> regex (I just fixed the <code>0-9</code> range to match any digit and included <code>=</code> to the end) and access the Group 1 capture stack using <a href="https://pypi.python.org/pypi/regex" rel="nofollow">PyPi regex module</a>:</p>
<pre><code>>>> import regex
>>> s = 'import pandas, os, sys'
>>> rx = regex.compile(r'^import\s+(?:([a-zA-Z0-9=]+),*\s*)*$')
>>> print([x.captures(1) for x in rx.finditer(s)])
[['pandas', 'os', 'sys']]
</code></pre>
| 0
|
2016-09-09T19:39:05Z
|
[
"python",
"regex"
] |
Python version of Arduino's Serial.available
| 39,416,966
|
<p>I'm trying to run an infinite loop in which the extension and movement of a linear actuator is controlled. The extension amount is controlled by user input with a value from 0 to 9, i.e. if I hit 9 and enter, the actuator will extend to maximum extension and if I hit 5 and enter, the actuator will go back to 50% extension.</p>
<p>I'm using a PINE A64+ with an MCP3008 connected to the Pi-2 bus and simply trying to replace a setup I had, with an Arduino + actuator, with a standalone embedded Linux setup.</p>
<p>I'm not sure how to go about having the program monitor raw_input consistently while running an infinite loop in the background. I was able to do this in my arduino code with the following:</p>
<pre><code>if (Serial.available() > 0) {
userInput = Serial.read()-48;
Serial.println(userInput);
}
</code></pre>
<p>How would I go about doing something like this in Python? I've tried using PySerial's inWaiting command but that doesn't give me the same result. Essentially I want the program to do either one of the two possibilites:</p>
<ol>
<li>Use an if statement within the loop to only assign a new value to
the variable used if there is user input, or </li>
<li>To monitor for input constantly, and when there is an input, to break the loop, assign anew value for the variable being used by the loop, and re-enter the loop.</li>
</ol>
<p>It would look something like this:</p>
<pre><code># begin loop w/ while True statement
# using if statement to enter only if there is user input, otherwise pass over
if Whatever:
Terminal[0] = user input
getVal = analogRead(0, PI2CLK, PI2MOSI, PI2MISO, PI2CS)
if (positionArray[Terminal[0]] - 10) < getVal < (positionArray[Terminal[0]] + 10):
PWM0A.stop()
PWM0B.stop()
elif getVal > positionArray[Terminal[0]]:
PWM0A.start(100)
PWM0B.stop()
elif getVal < positionArray[Terminal[0]]:
PWM0A.stop()
PWM0B.start(100)
# end loop
</code></pre>
<p>What's the best way of going about this? Thanks in advance :)</p>
| 0
|
2016-09-09T17:36:54Z
| 39,417,013
|
<p>From <a href="https://pythonhosted.org/pyserial/pyserial_api.html" rel="nofollow">the documentation</a>:</p>
<pre><code> in_waiting
Getter: Get the number of bytes in the input buffer
Type: int
Return the number of bytes in the receive buffer.
</code></pre>
| 0
|
2016-09-09T17:40:29Z
|
[
"python",
"embedded-linux",
"pyserial"
] |
Python version of Arduino's Serial.available
| 39,416,966
|
<p>I'm trying to run an infinite loop in which the extension and movement of a linear actuator is controlled. The extension amount is controlled by user input with a value from 0 to 9, i.e. if I hit 9 and enter, the actuator will extend to maximum extension and if I hit 5 and enter, the actuator will go back to 50% extension.</p>
<p>I'm using a PINE A64+ with an MCP3008 connected to the Pi-2 bus and simply trying to replace a setup I had, with an Arduino + actuator, with a standalone embedded Linux setup.</p>
<p>I'm not sure how to go about having the program monitor raw_input consistently while running an infinite loop in the background. I was able to do this in my arduino code with the following:</p>
<pre><code>if (Serial.available() > 0) {
userInput = Serial.read()-48;
Serial.println(userInput);
}
</code></pre>
<p>How would I go about doing something like this in Python? I've tried using PySerial's inWaiting command but that doesn't give me the same result. Essentially I want the program to do either one of the two possibilites:</p>
<ol>
<li>Use an if statement within the loop to only assign a new value to
the variable used if there is user input, or </li>
<li>To monitor for input constantly, and when there is an input, to break the loop, assign anew value for the variable being used by the loop, and re-enter the loop.</li>
</ol>
<p>It would look something like this:</p>
<pre><code># begin loop w/ while True statement
# using if statement to enter only if there is user input, otherwise pass over
if Whatever:
Terminal[0] = user input
getVal = analogRead(0, PI2CLK, PI2MOSI, PI2MISO, PI2CS)
if (positionArray[Terminal[0]] - 10) < getVal < (positionArray[Terminal[0]] + 10):
PWM0A.stop()
PWM0B.stop()
elif getVal > positionArray[Terminal[0]]:
PWM0A.start(100)
PWM0B.stop()
elif getVal < positionArray[Terminal[0]]:
PWM0A.stop()
PWM0B.start(100)
# end loop
</code></pre>
<p>What's the best way of going about this? Thanks in advance :)</p>
| 0
|
2016-09-09T17:36:54Z
| 39,417,258
|
<p>Answering my own question - I noticed I screwed up on the logic in my head a bit. I was trying to use the same internal serial port (the one I was using the execute the python script) to input information. Obviously this won't work. This is also why my inWaiting function was giving strange results.</p>
<p>Essentially, I opened a new COM port using serial.Serial (ttyS0), brought up a new terminal window to send data to ttyS0, then used the serial.inWaiting command to rerun the if statement each time a new value was entered. This time it was working correctly. Basically the same thing I did in my Arduino code. Doh :)</p>
| 0
|
2016-09-09T17:58:00Z
|
[
"python",
"embedded-linux",
"pyserial"
] |
Tkinter: why do both windows open?
| 39,417,091
|
<p>I started looking at some Tkinter tutorials. I always like to mess around with code before going on with the next chapter: for instance I tried to open more than one independent root.</p>
<pre><code>from Tkinter import *
def main():
root1, root2 = Tk(), Tk()
root1.title("First window")
root2.title("Second window")
root1.mainloop()
root2.mainloop()
main()
</code></pre>
<p>What I don't understand is why this code works (i.e. it shows two different windows at the same time).
If the Tk "mainloop" method is a loop, why do I see the second window? Shouldn't I see it only after closing the first window (i.e. after breaking the first while loop)?</p>
<p>Please, explain me how it works</p>
| 0
|
2016-09-09T17:45:16Z
| 39,417,968
|
<p><strong>EDIT: Removed incorrect answer, added answer below</strong></p>
<p>The short of why are confused is that the behavior of your code is undefined. Really, it isn't running as differently as you think. Try running this code:</p>
<pre><code>from Tkinter import *
def main():
root1, root2 = Tk(), Tk()
root1.title("First window")
root2.title("Second window")
root1.mainloop()
print 'root1.mainloop() has finished running.'
root2.mainloop()
print 'root2.mainloop() has finished running.'
main()
</code></pre>
<p>So the first <code>mainloop</code> doesn't actually continue on immediately. It hangs on <code>root1.mainloop()</code> (as you expected) until you close both of the windows, then it continues on. I am not sure exactly why running <code>root1.mainloop()</code> opens both windows as I don't have access to all of the source code but I think it would be a little bit like asking about the results of <code>0/0</code>. It just isn't supposed to happen. </p>
| 1
|
2016-09-09T18:46:15Z
|
[
"python",
"loops",
"methods",
"tkinter"
] |
SQLAlchemy automap - adding methods to automapped Model
| 39,417,143
|
<p>I have a preexisting database that I'm using with SQLAlchemy, so I'm using automap to get the Models from the database. What is the best way to add methods to these classes? For example, for a User class, I'd like to add methods such as verifying the password. Also, I'd like to add methods for flask-login (UserMixin) methods.</p>
| 1
|
2016-09-09T17:49:26Z
| 39,417,527
|
<p><a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html#specifying-classes-explicitly" rel="nofollow">Specify your classes explicitly</a> beforehand, and define your methods as you would normally:</p>
<pre><code>Base = automap_base()
class User(Base):
__tablename__ = 'user'
def verify_password(self, password):
...
Base.prepare(engine, reflect=True)
</code></pre>
<p>Now <code>Base.classes.User</code> and <code>User</code> are the same, with your additional methods. To make your <code>User</code> class flask-login compatible, implement the <a href="https://flask-login.readthedocs.io/en/latest/#your-user-class" rel="nofollow">listed attributes and methods</a>, or add the provided <a href="https://github.com/maxcountryman/flask-login/blob/master/flask_login/mixins.py#L12" rel="nofollow"><code>UserMixin</code></a> to your <code>User</code> class. The mixin seems to only expect the existence of an <code>id</code> attribute/column from your <code>User</code> class.</p>
| 0
|
2016-09-09T18:16:50Z
|
[
"python",
"flask",
"sqlalchemy",
"flask-sqlalchemy"
] |
How do I set up a login system in pyramid using mysql as database to store email and password?
| 39,417,217
|
<p>I have gone through this <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/authentication.html" rel="nofollow">http://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/authentication.html</a> but it does not give any clue how to add database to this to store email and password?</p>
| 1
|
2016-09-09T17:55:23Z
| 39,419,969
|
<p>The introduction to the Quick Tutorial describes its purpose and intended audience. Authentication and persistent storage are not covered in the same lesson, but in two different lessons.</p>
<p>Either you can combine learning from previous steps (not recommended) or you can take a stab at the <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/wiki2/index.html" rel="nofollow">SQLAlchemy + URL dispatch wiki tutorial</a> which covers a typical web application with authentication, authorization, hashing of passwords, and persistent storage in an SQL database.</p>
<p>Note however that it uses SQLite, not MySQL, as its SQL database, so you'll either have to use the provided one or swap it out for your preferred SQL database.</p>
| 3
|
2016-09-09T21:29:02Z
|
[
"python",
"authentication",
"pyramid"
] |
How do I set up a login system in pyramid using mysql as database to store email and password?
| 39,417,217
|
<p>I have gone through this <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/authentication.html" rel="nofollow">http://docs.pylonsproject.org/projects/pyramid/en/latest/quick_tutorial/authentication.html</a> but it does not give any clue how to add database to this to store email and password?</p>
| 1
|
2016-09-09T17:55:23Z
| 40,026,258
|
<p>Here are a few suggestions regarding switching from SQLite to MySQL. In your <code>development.ini</code> (and/or <code>production.ini</code>) file, change from SQLite to MySQL:</p>
<pre><code># sqlalchemy.url = sqlite:///%(here)s/MyProject.sqlite [comment out or remove this line]
sqlalchemy.url = mysql://MySQLUsername:MySQLPassword@localhost/MySQLdbName
</code></pre>
<p>Of course, you will need a MySQL database (<code>MySQLdbName</code> in the example above) and likely the knowledge and privileges to edit its metadata, for example, to add fields called <code>user_email</code> and <code>passwordhash</code> to the <code>users</code> table or create a <code>users</code> table if necessary.</p>
<p>In your <code>setup.py</code> file, you will require the <code>mysql-python</code> module to be imported. An example would be:</p>
<pre><code>requires = [
'bcrypt',
'pyramid',
'pyramid_jinja2',
'pyramid_debugtoolbar',
'pyramid_tm',
'SQLAlchemy',
'transaction',
'zope.sqlalchemy',
'waitress',
'mysql-python',
]
</code></pre>
<p>After specifying new module(s) in <code>setup.py</code>, be sure to run the following commands so your project recognizes the new module(s):</p>
<pre><code>cd $VENV/MyPyramidProject
sudo $VENV/bin/pip install -e .
</code></pre>
<p>By this point, your Pyramid project should be hooked up to MySQL. Now it is down to learning the details of Pyramid (and SQLAlchemy if this is your selected ORM). Much of the suggestions in the tutorials, partcularly the <a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/wiki2/index.html" rel="nofollow">SQLAlchemy + URL dispatch wiki tutorial</a> in your case, should work as they work with SQLite.</p>
| 0
|
2016-10-13T16:23:24Z
|
[
"python",
"authentication",
"pyramid"
] |
Why does Python default to ASCII encoding?
| 39,417,311
|
<p>I've run into lots of bugs in Python due to the default ASCII encoding. I always have to remember to switch it to utf8</p>
<p>I wanted to know, is there any reason or benefit to a default ASCII encoding? It seems strictly worse than utf8, and causes annoying bugs. Am I missing something by always switching to utf8?</p>
| 1
|
2016-09-09T18:01:59Z
| 39,417,340
|
<p>Because Python 2 Unicode was built (back in 1999-2000) before UTF-8 was ubiquitous. ASCII on the other hand was understood by almost all target platforms using 8-bit codecs.</p>
<p>If you look at the <a href="https://en.wikipedia.org/wiki/UTF-8" rel="nofollow">Wikipedia UTF-8 adoption graph</a>, you'll see that UTF-8 didn't really rise to popularity until 2006:</p>
<p><a href="http://i.stack.imgur.com/aZCCq.png" rel="nofollow"><img src="http://i.stack.imgur.com/aZCCq.png" alt="UTF-8 growth graph from Wikipedia"></a></p>
<p>Only with Python 3 was it possible to change this default; there implicit encoding and decoding is gone, and the default source code encoding has been changed to UTF-8 (the default for printing, file I/O and filesystem names is system dependent, as it is in Python 2).</p>
| 4
|
2016-09-09T18:04:36Z
|
[
"python",
"utf-8",
"character-encoding",
"ascii"
] |
Python 3.4.4 How to verify if a string is only made of 0 and 1
| 39,417,335
|
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>
<p>here's the program:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>hopefully someone can help me <3</p>
| 4
|
2016-09-09T18:04:04Z
| 39,417,373
|
<p>Follow the <a href="https://docs.python.org/3/glossary.html#term-eafp" rel="nofollow">EAFP approach</a>, try to convert it to decimal via <a href="https://docs.python.org/3/library/functions.html#int" rel="nofollow"><code>int()</code></a> and handle the <code>ValueError</code>:</p>
<pre><code>try:
int(binary, 2)
is_binary = True
except ValueError:
is_binary = False
</code></pre>
| 6
|
2016-09-09T18:06:30Z
|
[
"python"
] |
Python 3.4.4 How to verify if a string is only made of 0 and 1
| 39,417,335
|
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>
<p>here's the program:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>hopefully someone can help me <3</p>
| 4
|
2016-09-09T18:04:04Z
| 39,417,379
|
<p>Use <code>all()</code></p>
<pre><code> all(x in '10' for x in binary_string)
</code></pre>
| 2
|
2016-09-09T18:06:40Z
|
[
"python"
] |
Python 3.4.4 How to verify if a string is only made of 0 and 1
| 39,417,335
|
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>
<p>here's the program:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>hopefully someone can help me <3</p>
| 4
|
2016-09-09T18:04:04Z
| 39,417,383
|
<p>Maybe <code>all(x in "01" for x in binary)</code>.</p>
| 1
|
2016-09-09T18:07:01Z
|
[
"python"
] |
Python 3.4.4 How to verify if a string is only made of 0 and 1
| 39,417,335
|
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>
<p>here's the program:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>hopefully someone can help me <3</p>
| 4
|
2016-09-09T18:04:04Z
| 39,417,393
|
<p>If you <em>must</em> avoid using <code>int(binary, 2)</code> and handle the exception, you could use the <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>all()</code> function</a> with a <a href="https://docs.python.org/2/tutorial/classes.html#generator-expressions" rel="nofollow">generator expression</a>:</p>
<pre><code>all(c in '01' for c in binary)
</code></pre>
<p><code>all()</code> with a generator expression will bail out early and return <code>False</code> when a non-binary digit is found.</p>
<p>If you are already looping over all characters <em>anyway</em> you could just raise an exception in your loop:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
try:
while bit>0:
if binary[bit-1] not in '01':
raise ValueError('Not a binary string: %s' % binary)
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
except ValueError:
print('%s is not a binary string')
else:
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>Rather than use an index, your code could just loop over the reverse of the string, using numbers generated by <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate()</code></a> as the power:</p>
<pre><code>binary = input("Enter a binary number")
result = 0
try:
for power, bit in enumerate(reversed(binary)):
if bit not in '01':
raise ValueError('Not a binary string: %s' % binary)
result += int(bit) * 2 ** power
except ValueError:
print('%s is not a binary string')
else:
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
| 3
|
2016-09-09T18:07:30Z
|
[
"python"
] |
Python 3.4.4 How to verify if a string is only made of 0 and 1
| 39,417,335
|
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>
<p>here's the program:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>hopefully someone can help me <3</p>
| 4
|
2016-09-09T18:04:04Z
| 39,417,451
|
<p>Following is for 2.7.9, just look for a 3.4.4 parallel:</p>
<pre><code>import re
binary = raw_input("enter binary number")
if re.match("^[01]*$", binary):
print "ok"
</code></pre>
| 0
|
2016-09-09T18:11:45Z
|
[
"python"
] |
Python 3.4.4 How to verify if a string is only made of 0 and 1
| 39,417,335
|
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>
<p>here's the program:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>hopefully someone can help me <3</p>
| 4
|
2016-09-09T18:04:04Z
| 39,417,550
|
<p>You could check if the sum of occurrences of '0' and '1' is equal to the length of the string.</p>
<pre><code> binary.count('0') + binary.count('1') == len(binary)
</code></pre>
| 0
|
2016-09-09T18:18:45Z
|
[
"python"
] |
Python 3.4.4 How to verify if a string is only made of 0 and 1
| 39,417,335
|
<p>I'm doing a binary to decimal converter in python 3.4.4 and it's pretty much finished except for the fact that I would like to check that the binary number entered by the user is indeed a binary number (check if the string is only made of o and 1) but I'm unsure what to do.</p>
<p>here's the program:</p>
<pre><code>binary=input("Enter a binary number")
bit=len(binary)
result=0
power=0
while bit>0:
result=result+int(binary[bit-1])*2**power
bit=bit-1
power=power+1
print(binary, " in decimal is equal to ", result, sep="")
</code></pre>
<p>hopefully someone can help me <3</p>
| 4
|
2016-09-09T18:04:04Z
| 39,417,664
|
<p>I suppose checking the input string for correctness is best done with regular expressions. The code that would help you is the following:</p>
<pre><code>import re
binary = input("Enter a binary number")
len_bin = len(binary)
result = 0
if re.search("^[0-1]+$", binary) is not None:
for position in range(len_bin):
result += int(binary[position]) * 2 ** (len_bin - position - 1)
print(binary + " in decimal is equal to " + str(result))
else:
print("The input is not a binary number")
</code></pre>
<p>The regular expression determines whether the binary number only contains zeros and ones. Also, I took the opportunity to shorten the code a bit, using <code>result += ...</code>, which is equal to <code>result = result + ...</code>.</p>
| 0
|
2016-09-09T18:25:33Z
|
[
"python"
] |
OpenCV: getting error for resizing- 1428: error: (-215) ssize.area() > 0
| 39,417,407
|
<pre><code>while True:
ret, frame = cap.read()
frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
</code></pre>
<blockquote>
<p>1428: error: (-215) ssize.area() > 0</p>
</blockquote>
| -2
|
2016-09-09T18:08:31Z
| 39,422,937
|
<p>The error is suggesting that the <code>frame</code> you extracted from the camera has zero size. So it is recommended to check the size and data of <code>frame</code> from <code>cap.read()</code>
before doing any processing.</p>
| 1
|
2016-09-10T05:36:05Z
|
[
"python",
"opencv"
] |
numpy.where for 2+ specific values
| 39,417,419
|
<p>Can the numpy.where function be used for more than one specific value?</p>
<p>I can specify a specific value:</p>
<pre><code>>>> x = numpy.arange(5)
>>> numpy.where(x == 2)[0][0]
2
</code></pre>
<p>But I would like to do something like the following. It gives an error of course.</p>
<pre><code>>>> numpy.where(x in [3,4])[0][0]
[3,4]
</code></pre>
<p>Is there a way to do this without iterating through the list and combining the resulting arrays?</p>
<p><strong>EDIT:</strong> I also have a lists of lists of unknown lengths and unknown values so I cannot easily form the parameters of np.where() to search for multiple items. It would be much easier to pass a list.</p>
| 1
|
2016-09-09T18:09:09Z
| 39,417,516
|
<p>You can use the <code>numpy.in1d</code> function with <code>numpy.where</code>:</p>
<pre><code>import numpy
numpy.where(numpy.in1d(x, [2,3]))
# (array([2, 3]),)
</code></pre>
| 3
|
2016-09-09T18:16:10Z
|
[
"python",
"numpy"
] |
numpy.where for 2+ specific values
| 39,417,419
|
<p>Can the numpy.where function be used for more than one specific value?</p>
<p>I can specify a specific value:</p>
<pre><code>>>> x = numpy.arange(5)
>>> numpy.where(x == 2)[0][0]
2
</code></pre>
<p>But I would like to do something like the following. It gives an error of course.</p>
<pre><code>>>> numpy.where(x in [3,4])[0][0]
[3,4]
</code></pre>
<p>Is there a way to do this without iterating through the list and combining the resulting arrays?</p>
<p><strong>EDIT:</strong> I also have a lists of lists of unknown lengths and unknown values so I cannot easily form the parameters of np.where() to search for multiple items. It would be much easier to pass a list.</p>
| 1
|
2016-09-09T18:09:09Z
| 39,417,519
|
<p>I guess <code>np.ind1d</code> might help you, instead:</p>
<pre><code>>>> x = np.arange(5)
>>> np.in1d(x, [3,4])
array([False, False, False, True, True], dtype=bool)
>>> np.argwhere(_)
array([[3],
[4]])
</code></pre>
| 1
|
2016-09-09T18:16:29Z
|
[
"python",
"numpy"
] |
numpy.where for 2+ specific values
| 39,417,419
|
<p>Can the numpy.where function be used for more than one specific value?</p>
<p>I can specify a specific value:</p>
<pre><code>>>> x = numpy.arange(5)
>>> numpy.where(x == 2)[0][0]
2
</code></pre>
<p>But I would like to do something like the following. It gives an error of course.</p>
<pre><code>>>> numpy.where(x in [3,4])[0][0]
[3,4]
</code></pre>
<p>Is there a way to do this without iterating through the list and combining the resulting arrays?</p>
<p><strong>EDIT:</strong> I also have a lists of lists of unknown lengths and unknown values so I cannot easily form the parameters of np.where() to search for multiple items. It would be much easier to pass a list.</p>
| 1
|
2016-09-09T18:09:09Z
| 39,417,652
|
<p>If you only need to check for a few values you can:</p>
<pre><code>import numpy as np
x = np.arange(4)
ret_arr = np.where([x == 1, x == 2, x == 4, x == 0])[1]
print "Ret arr = ",ret_arr
</code></pre>
<p>Output:</p>
<pre><code>Ret arr = [1 2 0]
</code></pre>
| 1
|
2016-09-09T18:25:02Z
|
[
"python",
"numpy"
] |
Modifying string in a text file
| 39,417,479
|
<p>I am using a text file to store the last time data was pulled from an API.</p>
<p>After I check if new data should be pulled I am updating the last datapoint with this Python 2.7 code:</p>
<pre><code>if pullAgain == True:
# open last time again
lasttimedata = open('lasttimemultiple.txt', 'a+')
for item in splitData:
if item[0:2] == PullType:
#formats the data point
newTime = PullType + ':' + currenttime
#trying to write that data point to the spot of the old point.
lasttimedata.write(newTime)
print('We updated the last time')
lasttimedata.close() # close last time
</code></pre>
<p>I'm looking to replace the old point with the new point that this code generates. I can not figure out how to update the <code>splitdata[item]</code> position with a variable. Because <code>splitdata</code> is a list I can not reference this spot with anything but an integer. </p>
<p><strong>EDIT:</strong> </p>
<p>The goal of this code is to update the <code>splitdata[item]</code> value in the list <code>splitdata</code>. The issue is I can not use <code>item</code> as an index because <code>item</code> is not an integer.</p>
<p><strong>EDIT 2:</strong> </p>
<p>For example, </p>
<pre><code>splitdata = ['00:23:15:42','01:15:12:54','02:12:23:54']
</code></pre>
<p>I'm looking to replace the item with the newly generated point </p>
<p><strong>EDIT 3:</strong> </p>
<p>Here is the whole method:</p>
<pre><code>#Pull type is the piece of data being pulled,
# capability to Have 99 types, current default is 00.
def PullAgain(PullType):
# This is the variable that decides if the API is called
# again, True = pull data again.
pullAgain = False
# Calls the local time
s1=time.localtime()
#takes the hours, minutes and seconds out of the time
currenttime = str(s1[3])+':'+str(s1[4])+':'+str(s1[5])
#opens the file that contains the last time run
timefile = open('lasttimemultiple.txt','r+')
#reads the last time file
rawfile = timefile.read()
#splits the string into each individual row
splitData = string.split(rawfile,'\n')
#closes last time
timefile.close()
lasttime = "05:06:12"
for item in splitData:
if item[0:2] == PullType:
lasttime = str(item[3:])
print('We made it into the if statement')
print lasttime
#this is the time formatting
FMT = '%H:%M:%S'
#calculates the difference in times
delta = (
datetime.strptime(currenttime, FMT) -
datetime.strptime(lasttime, FMT))
#converts the difference into a string
tdelta = str(delta)
print 'this is tdelta before edit:',tdelta
if tdelta[0] =='-':
tdelta = tdelta[8:]
print 'tdelta time has been adjusted', tdelta
#if more than 0 hours apart
if int(tdelta[0])>0:
#Then call api again
pullAgain = True
elif int(tdelta[2])>=3:
#if time is greater than 29 sec call api again
pullAgain = True
else:
pullAgain = False
print('New data not pulled, the time elapsed since last pull was: '),tdelta
splitData2 = []
if pullAgain == True:
# open last time again
lasttimedata = open('lasttimemultiple.txt', 'a+')
for item in splitData:
if item[0:2] == PullType:
newTime = PullType + ':' + currenttime
splitData2.append(item)
lasttimedata.write(splitData2)
print('We updated the last time')
lasttimedata.close() # close last time
return pullAgain#return the decission to pull again or not
</code></pre>
| 0
|
2016-09-09T18:13:52Z
| 39,417,763
|
<h2>You were first asking for editing a list.</h2>
<p>There is two ways for doing that:</p>
<p><strong>Keep a counter to know witch element to edit:</strong></p>
<pre><code>for index, item in enumerate(splitData):
splitData[item] = new_value
</code></pre>
<p>But your are editing the list while iterating, and that is not always a great idea.</p>
<p><strong>Create an output list will the element you want:</strong></p>
<pre><code>output_list = []
for item in splitData:
if i_want_to_keep:
output_list.append(item)
else:
output_list.append(new_value)
</code></pre>
<h2>Then you are asking to put write that list in a file.</h2>
<p>I think that the best way of doing it is:</p>
<pre><code>with open(filename, 'w') as f:
for element in my_list:
f.write(element)
</code></pre>
<h2>To finish with your question.</h2>
<p>Please consider this code:</p>
<pre><code>splitData2 = []
if pullAgain == True:
# Change in splitData all the times that need to be update
for item in splitData:
newTime = PullType + ':' + currenttime
if item[0:2] == PullType:
splitData2.append(newTime)
print('We updated the last time')
# ReWrite the whole file with the whole data from splitData2
with open('lasttimemultiple.txt', 'w') as f:
for item in splitData2:
f.write(item)
</code></pre>
<ol>
<li>In the first part we create a new list that contain every non-changed and new values.</li>
<li>Then we write the content of this list in the file overwriting what was already there (the non-updates datas)</li>
</ol>
<p>I Hope that is going to help.</p>
| 1
|
2016-09-09T18:32:00Z
|
[
"python",
"python-2.7"
] |
How to make a list of lists in Python?
| 39,417,488
|
<p>Assume,</p>
<pre><code>range(len(column)) = 4
column = ['AAA', 'CTC', 'GTC', 'TTC']
for i in range(len(column)):
a = list(column[i])
</code></pre>
<p>Outside of this loop I want a variable,say x to be assigned such that it gives the following output. </p>
<pre><code> ['A', 'A', 'A']
['C', 'T', 'C']
['G', 'T', 'C']
['T', 'T', 'C']
</code></pre>
<hr>
<p>After doing this, here is what I should be able to do:
In the Next, I want to compare within x. Say x[2] to tell me if 'G' is different from 'T' and if 'G' is different from 'C' and if 'T' is different from 'C'</p>
| 1
|
2016-09-09T18:14:23Z
| 39,417,569
|
<p>I believe you are in need of a list of lists</p>
<p>Code:</p>
<pre><code>column = ['AAA', 'CTC', 'GTC', 'TTC']
x=[]
for i in range(len(column)):
a = list(column[i])
x.append(a)
print x
</code></pre>
<p>Output:</p>
<pre><code>[['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]
</code></pre>
| 2
|
2016-09-09T18:19:52Z
|
[
"python",
"python-2.7",
"for-loop",
"return"
] |
How to make a list of lists in Python?
| 39,417,488
|
<p>Assume,</p>
<pre><code>range(len(column)) = 4
column = ['AAA', 'CTC', 'GTC', 'TTC']
for i in range(len(column)):
a = list(column[i])
</code></pre>
<p>Outside of this loop I want a variable,say x to be assigned such that it gives the following output. </p>
<pre><code> ['A', 'A', 'A']
['C', 'T', 'C']
['G', 'T', 'C']
['T', 'T', 'C']
</code></pre>
<hr>
<p>After doing this, here is what I should be able to do:
In the Next, I want to compare within x. Say x[2] to tell me if 'G' is different from 'T' and if 'G' is different from 'C' and if 'T' is different from 'C'</p>
| 1
|
2016-09-09T18:14:23Z
| 39,417,576
|
<p>It's not completely clear what kind of comparison you want to do once you've formatted your data, but this is something </p>
<pre><code>import numpy as np
alt_col = [list(y) for y in column]
x = np.asarray(alt_col)
</code></pre>
<p>you can then compare whatever you want within the array</p>
<pre><code>print all(x[1, :] == x[2, :])
</code></pre>
| 1
|
2016-09-09T18:20:18Z
|
[
"python",
"python-2.7",
"for-loop",
"return"
] |
How to make a list of lists in Python?
| 39,417,488
|
<p>Assume,</p>
<pre><code>range(len(column)) = 4
column = ['AAA', 'CTC', 'GTC', 'TTC']
for i in range(len(column)):
a = list(column[i])
</code></pre>
<p>Outside of this loop I want a variable,say x to be assigned such that it gives the following output. </p>
<pre><code> ['A', 'A', 'A']
['C', 'T', 'C']
['G', 'T', 'C']
['T', 'T', 'C']
</code></pre>
<hr>
<p>After doing this, here is what I should be able to do:
In the Next, I want to compare within x. Say x[2] to tell me if 'G' is different from 'T' and if 'G' is different from 'C' and if 'T' is different from 'C'</p>
| 1
|
2016-09-09T18:14:23Z
| 39,417,832
|
<p>You can easily create <code>x</code> without using <code>numpy</code> or other external module:</p>
<pre><code>column = ['AAA', 'CTC', 'GTC', 'TTC']
x = [list(column[i]) for i in range(len(column))]
print(x)
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>[['A', 'A', 'A'], ['C', 'T', 'C'], ['G', 'T', 'C'], ['T', 'T', 'C']]
</code></pre>
<p>To use this you'll need to two indices: Which you can think of as the first representing the row and the second the column. For example the <code>'G'</code> is in <code>x[2][0]</code>. You can compare it to any other cell in <code>x</code> using the same notation.</p>
| 1
|
2016-09-09T18:37:44Z
|
[
"python",
"python-2.7",
"for-loop",
"return"
] |
How to make a list of lists in Python?
| 39,417,488
|
<p>Assume,</p>
<pre><code>range(len(column)) = 4
column = ['AAA', 'CTC', 'GTC', 'TTC']
for i in range(len(column)):
a = list(column[i])
</code></pre>
<p>Outside of this loop I want a variable,say x to be assigned such that it gives the following output. </p>
<pre><code> ['A', 'A', 'A']
['C', 'T', 'C']
['G', 'T', 'C']
['T', 'T', 'C']
</code></pre>
<hr>
<p>After doing this, here is what I should be able to do:
In the Next, I want to compare within x. Say x[2] to tell me if 'G' is different from 'T' and if 'G' is different from 'C' and if 'T' is different from 'C'</p>
| 1
|
2016-09-09T18:14:23Z
| 39,418,462
|
<pre><code>inputs = ['ABC','DEF','GHI'] # list of inputs
outputs = [] # creates an empty list to be populated
for i in range(len(inputs)): # steps through each item in the list
outputs.append([]) # adds a list into the output list, this is done for each item in the input list
for j in range(len(inputs[i])): # steps through each character in the strings in the input list
outputs[i].append(inputs[i][j]) # adds the character to the [i] position in the output list
outputs
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]
</code></pre>
<p>edit
added comments as to what each line is doing</p>
| 1
|
2016-09-09T19:25:06Z
|
[
"python",
"python-2.7",
"for-loop",
"return"
] |
running adb with python: executing a program and ending it
| 39,417,505
|
<p>I am trying to perform adb interactions through python code.
I have an endless executable on the android device which i would like to start and after 10 seconds kill it.
right now, i can get the program to start but cannot kill it other the manually pressing ctrl+c.</p>
<pre><code>procID = subprocess.Popen(["adb", "shell"], stdin=subprocess.PIPE,)
procID.communicate('su\n endless_program data/test 5\n')
time.sleep(5)
os.kill(procID, signal.SIGINT)
procID.kill()
</code></pre>
<p>i tried killing it with os.kill or procID.kill but both don't seem to work.</p>
<p>I have also trying using pexpect, but for some reason i cant get it to run adb.</p>
| -1
|
2016-09-09T18:15:34Z
| 39,417,632
|
<p>You are just killing the adb shell session, which won't kill the running application. If you would like to kill the running Android application, you have to stop the app over the adb shell. For details have a look at this <a href="https://stackoverflow.com/questions/17829606/android-adb-stop-application-command-like-force-stop-for-non-rooted-device#17829677">stackoverflow answer</a>.</p>
| 0
|
2016-09-09T18:23:53Z
|
[
"android",
"python",
"subprocess",
"adb",
"pexpect"
] |
convert string to other type in python
| 39,417,539
|
<p>Hi everyone I have a simple problem but I don't find the solution, I have a function that returns something like that</p>
<pre><code>[[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01'], [115, 'adr', 0, 0, 1, '2016-04-05T14:00:01'], [226, 'adr', 0, 0, 1, '2016-04-05T15:00:01'], [337, 'adr', 0, 0, 1, '2016-04-05T16:00:01']]
</code></pre>
<p>when I check de type of this variable <code>type(data)</code>say that is a string <code><type 'str'></code>
I want to create a loop to get each element like this </p>
<p>item 1 <code>[4, 'adr', 0, 0, 1, '2016-04-05T13:00:01']</code></p>
<p>item 2 <code>[115, 'adr', 0, 0, 1, '2016-04-05T14:00:01']</code></p>
<p>I try to convert the string in a list, a tuple... but nothing work, any idea how to change the string to any type that I can do a loop and get the items</p>
<p>when I try to convert in a tuple or string I have this result</p>
<pre><code>('[', '[', '4', ',', ' ', "'", 'a', 'd', 'r', "'", ',', ' ', '0', ',', ' ', '0', ',', ' ', '1', ',', ' ', "'", '2', '0', '1', '6', '-', '0', '4', '-', '0', '5', 'T', '1', '3', ':', '0', '0', ':', '0', '1', "'", ']', ',', ' ', '[', '1', '1', '5', ',', ' ', "'", 'a', 'd', 'r', "'", ',', ' ', '0', ',', ' ', '0', ',', ' ', '1', ',', ' ', "'", '2', '0', '1', '6', '-', '0', '4', '-', '0', '5', 'T', '1', '4', ':', '0', '0', ':', '0', '1', "'", ']', ',', ' ', '[', '2', '2', '6', ',', ' ', "'", 'a', 'd', 'r', "'", ',', ' ', '0', ',', ' ', '0', ',', ' ', '1', ',', ' ', "'", '2', '0', '1', '6', '-', '0', '4', '-', '0', '5', 'T', '1', '5', ':', '0', '0', ':', '0', '1', "'", ']', ',', ' ', '[', '3', '3', '7', ',', ' ', "'", 'a', 'd', 'r', "'", ',', ' ', '0', ',', ' ', '0', ',', ' ', '1', ',', ' ', "'", '2', '0', '1', '6', '-', '0', '4', '-', '0', '5', 'T', '1', '6', ':', '0', '0', ':', '0', '1', "'", ']', ']')
</code></pre>
| 0
|
2016-09-09T18:17:38Z
| 39,417,606
|
<p>The easiest, and most dangerous, solution would be to do</p>
<pre><code>eval( data )
</code></pre>
<p>Dangerous because you have to trust there is nothing malicious in that data.</p>
<p>You could write a regex to verify that the string/data is properly formatted; not knowing what that format is, I can't help with that.</p>
| 1
|
2016-09-09T18:22:13Z
|
[
"python",
"python-2.7"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.