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
Adding counter/index to a list of lists in Python
39,865,305
<p>I have a list of lists of strings:</p> <pre><code>listBefore = [['4', '5', '1', '1'], ['4', '6', '1', '1'], ['4', '7', '8', '1'], ['1', '2', '1', '1'], ['2', '3', '1', '1'], ['7', '8', '1', '1'], ['7', '9', '1', '1'], ['2', '4', '3', '1']] </code></pre> <p>and I would like to add a counter/index in the middle of each list so that the list looks like:</p> <pre><code>listAfter = [['4', '5', '1', '1', '1'], ['4', '6', '2', '1', '1'], ['4', '7', '3', '8', '1'], ['1', '2', '4', '1', '1'], ['2', '3', '5', '1', '1'], ['7', '8', '6', '1', '1'], ['7', '9', '7', '1', '1'], ['2', '4', '8', '3', '1']] </code></pre> <p>What would be the easiest way to do so? I could probably loop over the lists and add the index, but is there a cleaner way to do so?</p> <p>Cheers, Kate</p> <p>Edit: The code I wrote works for me:</p> <pre><code>item = 1 for list in listBefore: list.insert(2,str(item)) item = item + 1 print listBefore </code></pre> <p>I was wondering if there is another way to do so more efficiently or in one step.</p>
1
2016-10-05T04:10:15Z
39,865,457
<p>Iterate over the parent list with <code>enumerate()</code> to get counter (used as <code>i</code> in the below example) along with list element. In the sublist, insert the <code>i</code> at the middle of sublist using <code>list.insert(index, value)</code> method. <em>Note:</em> The value of counter i.e. <code>i</code> will be of <code>int</code> type, so you have to explicitly type cast it to <code>str</code> as <code>str(i)</code>before inserting. Below is the sample code:</p> <pre><code>for i, sub_list in enumerate(my_list, 1): # Here my_list is the list mentioned in question as 'listBefore' sub_list.insert(len(sub_list)/2, str(i)) # Value of 'my_list' # [['4', '5', '1', '1', '1'], # ['4', '6', '2', '1', '1'], # ['4', '7', '3', '8', '1'], # ['1', '2', '4', '1', '1'], # ['2', '3', '5', '1', '1'], # ['7', '8', '6', '1', '1'], # ['7', '9', '7', '1', '1'], # ['2', '4', '8', '3', '1']] </code></pre>
2
2016-10-05T04:28:49Z
[ "python", "list" ]
Adding counter/index to a list of lists in Python
39,865,305
<p>I have a list of lists of strings:</p> <pre><code>listBefore = [['4', '5', '1', '1'], ['4', '6', '1', '1'], ['4', '7', '8', '1'], ['1', '2', '1', '1'], ['2', '3', '1', '1'], ['7', '8', '1', '1'], ['7', '9', '1', '1'], ['2', '4', '3', '1']] </code></pre> <p>and I would like to add a counter/index in the middle of each list so that the list looks like:</p> <pre><code>listAfter = [['4', '5', '1', '1', '1'], ['4', '6', '2', '1', '1'], ['4', '7', '3', '8', '1'], ['1', '2', '4', '1', '1'], ['2', '3', '5', '1', '1'], ['7', '8', '6', '1', '1'], ['7', '9', '7', '1', '1'], ['2', '4', '8', '3', '1']] </code></pre> <p>What would be the easiest way to do so? I could probably loop over the lists and add the index, but is there a cleaner way to do so?</p> <p>Cheers, Kate</p> <p>Edit: The code I wrote works for me:</p> <pre><code>item = 1 for list in listBefore: list.insert(2,str(item)) item = item + 1 print listBefore </code></pre> <p>I was wondering if there is another way to do so more efficiently or in one step.</p>
1
2016-10-05T04:10:15Z
39,865,459
<p>You should learn about <code>enumerate</code>, it lets you iterate over the list with two iterators - one (<code>str_list</code> in this case<code>) holds the current item in the list, and the other (</code>i`) holds it's index in the list.</p> <pre><code>for i,str_list in enumerate(listBefore): listBefore[i] = str_list[:len(str_list)//2] + [str(i+1)] + str_list[len(str_list)//2:] </code></pre>
0
2016-10-05T04:29:01Z
[ "python", "list" ]
Adding counter/index to a list of lists in Python
39,865,305
<p>I have a list of lists of strings:</p> <pre><code>listBefore = [['4', '5', '1', '1'], ['4', '6', '1', '1'], ['4', '7', '8', '1'], ['1', '2', '1', '1'], ['2', '3', '1', '1'], ['7', '8', '1', '1'], ['7', '9', '1', '1'], ['2', '4', '3', '1']] </code></pre> <p>and I would like to add a counter/index in the middle of each list so that the list looks like:</p> <pre><code>listAfter = [['4', '5', '1', '1', '1'], ['4', '6', '2', '1', '1'], ['4', '7', '3', '8', '1'], ['1', '2', '4', '1', '1'], ['2', '3', '5', '1', '1'], ['7', '8', '6', '1', '1'], ['7', '9', '7', '1', '1'], ['2', '4', '8', '3', '1']] </code></pre> <p>What would be the easiest way to do so? I could probably loop over the lists and add the index, but is there a cleaner way to do so?</p> <p>Cheers, Kate</p> <p>Edit: The code I wrote works for me:</p> <pre><code>item = 1 for list in listBefore: list.insert(2,str(item)) item = item + 1 print listBefore </code></pre> <p>I was wondering if there is another way to do so more efficiently or in one step.</p>
1
2016-10-05T04:10:15Z
39,866,143
<pre><code>&gt;&gt;&gt; data = [['4', '5', '1', '1'], ['4', '6', '1', '1'], ['4', '7', '8', '1'], ['1', '2', '1', '1'], ['2', '3', '1', '1'], ['7', '8', '1', '1'], ['7', '9', '1', '1'], ['2', '4', '3', '1']] &gt;&gt;&gt; print [row[:len(row)//2] + [str(i)] + row[len(row)//2:] for i, row in enumerate(data, start=1)] [['4', '5', '1', '1', '1'], ['4', '6', '2', '1', '1'], ['4', '7', '3', '8', '1'], ['1', '2', '4', '1', '1'], ['2', '3', '5', '1', '1'], ['7', '8', '6', '1', '1'], ['7', '9', '7', '1', '1'], ['2', '4', '8', '3', '1']] </code></pre>
0
2016-10-05T05:37:01Z
[ "python", "list" ]
when using from file import function, how can the importing file be modified to give a desired output without modifying the imported file?
39,865,345
<p>File 1</p> <pre><code>def multiply(): x = raw_input('enter the number') y = x*4 </code></pre> <p>File 2</p> <pre><code>from file1 import multiply </code></pre> <p>how do i make the value of <code>x = 4</code> and hence the result <code>(4*4) = 16</code> without user input being implemented when running <code>file2</code>?</p>
0
2016-10-05T04:15:14Z
39,866,061
<p>There is a straightforward albeit hackey way of achieving what you want. I recommend against it. It is fundamentally a poor design choice, but here it is:</p> <pre><code>def multiply(): x = int(raw_input()) print x * 4 import sys import io def force_stdin(f, force_input): stdin = sys.stdin sys.stdin = io.StringIO(unicode(force_input)) f() sys.stdin = stdin force_stdin(multiply, '4') </code></pre> <p>Output:</p> <pre><code>16 </code></pre>
2
2016-10-05T05:30:41Z
[ "python", "python-2.7" ]
Django - 'RawQuerySet' object has no attribute 'all'
39,865,349
<p>I got this error message if i'm using SQL statement to populate data in dropdown.</p> <p>Error message</p> <pre><code>'RawQuerySet' object has no attribute 'all' </code></pre> <p>Model.py</p> <pre><code>@python_2_unicode_compatible # only if you need to support Python 2 class FacebookAccount(models.Model): user = models.ForeignKey(User) account_description = models.CharField(max_length=50) facebook_application_id = models.CharField(max_length=50) facebook_application_secret = models.CharField(max_length=50) ouath_token = models.CharField(max_length=500) status = models.BooleanField(default=False) def __str__(self): return self.account_description @python_2_unicode_compatible # only if you need to support Python 2 class FacebookFanPage(models.Model): facebook_account = models.ForeignKey(FacebookAccount) fan_page_description = models.CharField(max_length=50) fan_page_id = models.CharField(max_length=30) fan_page_access_token = models.CharField(max_length=500, null=True) def __str__(self): return self.fan_page_description class Campaign(models.Model): aList = ( ('1', 'Send replies to inbox messages'), ('2', 'Post replies to users comments') ) user = models.ForeignKey(User) campaign_name = models.CharField(max_length=50) autoresponder_type = models.CharField(max_length=10, choices=aList, null=True) facebook_account_to_use = models.ForeignKey(FacebookAccount) set_auto_reply_for_fan_page = models.ForeignKey(FacebookFanPage) message_list_to_use = models.ForeignKey(PredefinedMessage) #reply_only_in_this_hourly_interval reply_only_for_this_keyword = models.CharField(max_length=50, null=True) </code></pre> <p>View.py</p> <pre><code>def autoresponder_create(request, template_name='autoresponder/autoresponder_form.html'): if not request.user.is_authenticated(): return redirect('home') form = AutoresponderForm(request.POST or None) form.fields["set_auto_reply_for_fan_page"].query = FacebookFanPage.objects.raw('SELECT * ' 'FROM fbautoreply_facebookfanpage ' 'JOIN fbautoreply_facebookaccount ON fbautoreply_facebookfanpage.facebook_account_id = fbautoreply_facebookaccount.id ' 'WHERE fbautoreply_facebookaccount.user_id = %s ', [str(request.user.id)]) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.save() return redirect('autoresponder_list') return render(request, template_name, {'form':form}) </code></pre> <p>Please advice. Thank you.</p>
0
2016-10-05T04:15:39Z
39,866,120
<p>As the first comment says it seems like you are calling all() on queryset. You dont have to call .all() after executing raw sql queries, if you are assigning that to a variable since that variable already includes all objects fetched by your query. </p> <pre><code>In [6]: t = Team.objects.raw('SELECT * FROM core_team') In [7]: t Out[7]: &lt;RawQuerySet: SELECT * FROM core_team&gt; In [8]: t[0] Out[8]: &lt;Team: test&gt; In [9]: [x for x in t ] Out[9]: [&lt;Team: test&gt;, &lt;Team: team2&gt;, &lt;Team: adminTeam&gt;, &lt;Team: team4&gt;] </code></pre> <p>and if you call t.all()</p> <pre><code>In [11]: t.all() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-11-2ce0015f044f&gt; in &lt;module&gt;() ----&gt; 1 t.all() AttributeError: 'RawQuerySet' object has no attribute 'all' In [12]: </code></pre> <p>So it seems like you are calling <code>all()</code> on after executing a sql raw query. Remove that piece of code and it will be solved. You can refer <a href="https://docs.djangoproject.com/en/1.10/topics/db/sql/#executing-custom-sql-directly" rel="nofollow">to this section of django docs</a> if you want to use better ways to execute a sql query.</p> <h2>Edit</h2> <p>Try changing <code>form.fields["set_auto_reply_for_fan_page"].query</code> to <code>form.fields["set_auto_reply_for_fan_page"].queryset</code></p>
0
2016-10-05T05:35:30Z
[ "python", "django" ]
How to store aggregation pipeline in mongoDB?
39,865,416
<p>I am developing a rule engine using MongoDB and Python. I want to store Rules in MongoDB in a Rule database "myrulesdb" and want to use it to run aggregation pipeline on a different collection. Rule saved in MongoDB is</p> <pre><code>{ "_id" : ObjectId("57f46e843166d426a20d5e08"), "Rule" : "[{\"$match\":{\"Name.First\":\"Sunil\"}},{\"$limit\":5}]", "Description" : "You live long life" } </code></pre> <p>Python Code:</p> <pre><code>import pymongo from pymongo import MongoClient client = MongoClient('localhost', 27017) db = client['myDB'] coll = db['myColl'] ruledb = client['myrulesdb'] rulecoll = ruledb['myrules'] rule1 = rulecoll.find_one({}, {"Rule":1, "_id":0}) pipe = rule1['Rule'] print(pipe) data = coll.aggregate(pipeline=pipe) </code></pre> <p>I am getting correct string when i print pipe.</p> <pre><code>[{"$match":{"Name.First":"Sunil"}},{"$limit":5}] </code></pre> <p>But when i pass this to aggregate() function, it gives me following error:</p> <pre><code>data = coll.aggregate(pipeline=pipe) in aggregate raise TypeError("pipeline must be a list") TypeError: pipeline must be a list </code></pre> <p>After retrieving pipeline from database, how can i pass it to aggregate() function?</p>
1
2016-10-05T04:23:19Z
39,867,844
<p>I don't know why you are doing this but the culprit here is the value of the <code>Rule</code> field which is string. If you try a little debuging with the <code>print()</code> function your will see that <code>type(pipe)</code> yields <code>&lt;class 'str'&gt;</code></p> <p>You can fix this by loading the value using <a href="https://docs.python.org/3/library/json.html#json.loads" rel="nofollow"><code>json.loads</code></a> like this:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; r = {"Rule" : "[{\"$match\":{\"Name.First\":\"Sunil\"}},{\"$limit\":5}]"} &gt;&gt;&gt; pipe = json.loads(r['Rule']) &gt;&gt;&gt; pipe [{'$match': {'Name.First': 'Sunil'}}, {'$limit': 5}] &gt;&gt;&gt; type(pipe) &lt;class 'list'&gt; </code></pre>
0
2016-10-05T07:27:44Z
[ "python", "mongodb", "rule-engine" ]
Setting value of Select in html
39,865,542
<p>I am generating this html from python and 2% is the value of the field so it is what should be shown but I am baffled as to why it doesn't work as I expect. I have tried so many permutations and figure it is something so simple. Please Help. I don't necessarily want to use the selected option in the <code>&lt;option&gt;</code> tag.</p> <pre><code> &lt;select name="discount" value="2%"&gt; &lt;option&gt;10%&lt;/option&gt; &lt;option&gt;9%&lt;/option&gt; &lt;option&gt;8%&lt;/option&gt; &lt;option&gt;7%&lt;/option&gt; &lt;option&gt;6%&lt;/option&gt; &lt;option&gt;5%&lt;/option&gt; &lt;option&gt;4%&lt;/option&gt; &lt;option&gt;3%&lt;/option&gt; &lt;option&gt;2%&lt;/option&gt; &lt;option&gt;1%&lt;/option&gt; &lt;option"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
1
2016-10-05T04:39:07Z
39,865,564
<p>Are you mean this? put your value on <code>&lt;option&gt;</code>, not <code>&lt;select&gt;</code>. And see whats double quote on last <code>&lt;option&gt;</code></p> <pre><code> &lt;select name="discount"&gt; &lt;option value="10%"&gt;10%&lt;/option&gt; &lt;option value="9%"&gt;9%&lt;/option&gt; &lt;option value="8%"&gt;8%&lt;/option&gt; &lt;option value="7%"&gt;7%&lt;/option&gt; &lt;option value="6%"&gt;6%&lt;/option&gt; &lt;option value="5%"&gt;5%&lt;/option&gt; &lt;option value="4%"&gt;4%&lt;/option&gt; &lt;option value="3%"&gt;3%&lt;/option&gt; &lt;option value="2%"&gt;2%&lt;/option&gt; &lt;option value="1%"&gt;1%&lt;/option&gt; &lt;option value="0%"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
1
2016-10-05T04:42:20Z
[ "python", "html" ]
Setting value of Select in html
39,865,542
<p>I am generating this html from python and 2% is the value of the field so it is what should be shown but I am baffled as to why it doesn't work as I expect. I have tried so many permutations and figure it is something so simple. Please Help. I don't necessarily want to use the selected option in the <code>&lt;option&gt;</code> tag.</p> <pre><code> &lt;select name="discount" value="2%"&gt; &lt;option&gt;10%&lt;/option&gt; &lt;option&gt;9%&lt;/option&gt; &lt;option&gt;8%&lt;/option&gt; &lt;option&gt;7%&lt;/option&gt; &lt;option&gt;6%&lt;/option&gt; &lt;option&gt;5%&lt;/option&gt; &lt;option&gt;4%&lt;/option&gt; &lt;option&gt;3%&lt;/option&gt; &lt;option&gt;2%&lt;/option&gt; &lt;option&gt;1%&lt;/option&gt; &lt;option"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
1
2016-10-05T04:39:07Z
39,865,603
<p>If you want to selected 2% value then your dropdown should be like this : </p> <pre><code>&lt;select name="discount"&gt; &lt;option value="10%"&gt;10%&lt;/option&gt; &lt;option value="9%"&gt;9%&lt;/option&gt; &lt;option value="8%"&gt;8%&lt;/option&gt; &lt;option value="7%"&gt;7%&lt;/option&gt; &lt;option value="6%"&gt;6%&lt;/option&gt; &lt;option value="5%"&gt;5%&lt;/option&gt; &lt;option value="4%"&gt;4%&lt;/option&gt; &lt;option value="3%"&gt;3%&lt;/option&gt; &lt;option selected value="2%"&gt;2%&lt;/option&gt; &lt;option value="1%"&gt;1%&lt;/option&gt; &lt;option value="0%"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre> <p>try with it.</p>
2
2016-10-05T04:45:35Z
[ "python", "html" ]
Setting value of Select in html
39,865,542
<p>I am generating this html from python and 2% is the value of the field so it is what should be shown but I am baffled as to why it doesn't work as I expect. I have tried so many permutations and figure it is something so simple. Please Help. I don't necessarily want to use the selected option in the <code>&lt;option&gt;</code> tag.</p> <pre><code> &lt;select name="discount" value="2%"&gt; &lt;option&gt;10%&lt;/option&gt; &lt;option&gt;9%&lt;/option&gt; &lt;option&gt;8%&lt;/option&gt; &lt;option&gt;7%&lt;/option&gt; &lt;option&gt;6%&lt;/option&gt; &lt;option&gt;5%&lt;/option&gt; &lt;option&gt;4%&lt;/option&gt; &lt;option&gt;3%&lt;/option&gt; &lt;option&gt;2%&lt;/option&gt; &lt;option&gt;1%&lt;/option&gt; &lt;option"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
1
2016-10-05T04:39:07Z
39,865,621
<p>Add a selected attribute to the item. You also had a stray quotation mark on the last <code>&lt;option&gt;</code></p> <pre><code>&lt;select name="discount"&gt; &lt;option&gt;10%&lt;/option&gt; &lt;option&gt;9%&lt;/option&gt; &lt;option&gt;8%&lt;/option&gt; &lt;option&gt;7%&lt;/option&gt; &lt;option&gt;6%&lt;/option&gt; &lt;option&gt;5%&lt;/option&gt; &lt;option&gt;4%&lt;/option&gt; &lt;option&gt;3%&lt;/option&gt; &lt;option selected&gt;2%&lt;/option&gt; &lt;option&gt;1%&lt;/option&gt; &lt;option&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre> <p><strong>Alternatively you can use JavaScript to set the option:</strong></p> <pre><code>document.getElementsByName('discount')[0].selectedIndex = 8 </code></pre> <p><strong>or as you've suggested in the comments if all values are unique you may be able to just set the value</strong> the only caveat to this method is if two options have the same value but different text the incorrect option may be selected</p> <pre><code>document.getElementsByName('discount')[0].value = "2%" </code></pre> <p>Either of these scripts should be able to be run inlined anywhere after the select box or onload.</p>
1
2016-10-05T04:47:43Z
[ "python", "html" ]
Setting value of Select in html
39,865,542
<p>I am generating this html from python and 2% is the value of the field so it is what should be shown but I am baffled as to why it doesn't work as I expect. I have tried so many permutations and figure it is something so simple. Please Help. I don't necessarily want to use the selected option in the <code>&lt;option&gt;</code> tag.</p> <pre><code> &lt;select name="discount" value="2%"&gt; &lt;option&gt;10%&lt;/option&gt; &lt;option&gt;9%&lt;/option&gt; &lt;option&gt;8%&lt;/option&gt; &lt;option&gt;7%&lt;/option&gt; &lt;option&gt;6%&lt;/option&gt; &lt;option&gt;5%&lt;/option&gt; &lt;option&gt;4%&lt;/option&gt; &lt;option&gt;3%&lt;/option&gt; &lt;option&gt;2%&lt;/option&gt; &lt;option&gt;1%&lt;/option&gt; &lt;option"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
1
2016-10-05T04:39:07Z
39,865,636
<p><strong>Description</strong> Use the following HTML for your query. </p> <pre><code> &lt;select name="discount"&gt; &lt;option value="10%"&gt;10%&lt;/option&gt; &lt;option value="9%"&gt;9%&lt;/option&gt; &lt;option value="8%"&gt;8%&lt;/option&gt; &lt;option value="7%"&gt;7%&lt;/option&gt; &lt;option value="6%"&gt;6%&lt;/option&gt; &lt;option value="5%"&gt;5%&lt;/option&gt; &lt;option value="4%"&gt;4%&lt;/option&gt; &lt;option value="3%"&gt;3%&lt;/option&gt; &lt;option value="2%" selected&gt;2%&lt;/option&gt; &lt;option value="1%"&gt;1%&lt;/option&gt; &lt;option value="0%"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
0
2016-10-05T04:49:17Z
[ "python", "html" ]
Setting value of Select in html
39,865,542
<p>I am generating this html from python and 2% is the value of the field so it is what should be shown but I am baffled as to why it doesn't work as I expect. I have tried so many permutations and figure it is something so simple. Please Help. I don't necessarily want to use the selected option in the <code>&lt;option&gt;</code> tag.</p> <pre><code> &lt;select name="discount" value="2%"&gt; &lt;option&gt;10%&lt;/option&gt; &lt;option&gt;9%&lt;/option&gt; &lt;option&gt;8%&lt;/option&gt; &lt;option&gt;7%&lt;/option&gt; &lt;option&gt;6%&lt;/option&gt; &lt;option&gt;5%&lt;/option&gt; &lt;option&gt;4%&lt;/option&gt; &lt;option&gt;3%&lt;/option&gt; &lt;option&gt;2%&lt;/option&gt; &lt;option&gt;1%&lt;/option&gt; &lt;option"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
1
2016-10-05T04:39:07Z
39,871,369
<p>Here is what worked for me and thanks to Brian</p> <pre><code> &lt;body onload="myfield=document.getElementsByName('discount')[0].value='2%'"&gt; &lt;select name="discount"&gt; &lt;option value="10%"&gt;10%&lt;/option&gt; &lt;option value="9%"&gt;9%&lt;/option&gt; &lt;option value="8%"&gt;8%&lt;/option&gt; &lt;option value="7%"&gt;7%&lt;/option&gt; &lt;option value="6%"&gt;6%&lt;/option&gt; &lt;option value="5%"&gt;5%&lt;/option&gt; &lt;option value="4%"&gt;4%&lt;/option&gt; &lt;option value="3%"&gt;3%&lt;/option&gt; &lt;option value="2%"&gt;2%&lt;/option&gt; &lt;option value="1%"&gt;1%&lt;/option&gt; &lt;option value="0%"&gt;0%&lt;/option&gt; &lt;/select&gt; </code></pre>
0
2016-10-05T10:20:17Z
[ "python", "html" ]
sentiment analysis joint list
39,865,557
<p>im doing the sentiment analysis with scikit-learn python, now I'm using the nltk to do the words lemmatization in order to increase processing speed, for example:</p> <p>I get the following arrays after nltk processing:</p> <pre><code>array([ ['Really', 'a', 'terrible', 'course', u'lecture', u'be', 'so', 'boring', 'i', u'contemplate', 'suicide', 'on', 'numerous', u'occasion', 'and', 'the', 'tutes', u'go', 'for', 'two', u'hour', 'and', u'be', 'completely'], ['Management', 'accounting', u'require', 'sufficient', 'practice', 'to', 'get', 'a', 'hang', 'of', 'Made', 'easier', 'with', 'a', 'great', 'lecturer']], dtype=object) </code></pre> <p>but the scklearn require the array is </p> <pre><code>array([ 'Really a terrible course lectures were so boring i contemplated suicide on numerous occasions and the tutes went for two hours and were completely ', 'Management accounting requires sufficient practice to get a hang of Made easier with a great lecturer '],dtype=object) </code></pre> <p>so what is the best way to convert this array into the right form? I try to use <a href="http://i.stack.imgur.com/h9g4z.png" rel="nofollow">joint list</a> but the result is strange</p>
1
2016-10-05T04:41:04Z
39,869,881
<p>You would do:</p> <pre><code>second_array = [' '.join(each) for each in first_array] </code></pre> <p>Alternatively you can tell <code>sklearn.CountVectorizer</code> to just use your tokens:</p> <pre><code>vect = CountVectorizer(preprocessor=lambda x: x, tokenizer=lambda x: x) X = vect.fit_transform(first_array) </code></pre>
0
2016-10-05T09:12:24Z
[ "python", "arrays", "scikit-learn" ]
variables formatting using python script
39,865,625
<p>I'm having issues formatting my variables. My PORT1 and PORT2 are not working properly. I'm getting syntax errors. What I'm doing wrong. Thank you for the inputs.</p> <pre><code>import socket import os import netifaces NICS = netifaces.interfaces() PORT1 = NICS[1] PORT2 = NICS[2] os.system("nmcli con add type team-slave con-name team0-port1 ifname {}".format(PORT1)) master team0) os.system("nmcli con add type team-slave con-name team0-port2 ifname {}".format(PORT2)) master team0) </code></pre> <p>Error:</p> <pre><code>os.system("nmcli con add type team-slave con-name team0-port1 ifname {}".format(PORT1)) + master team0) ^ SyntaxError: invalid syntax </code></pre>
-1
2016-10-05T04:48:18Z
39,865,651
<p>Your problem that you are trying to append string <code>master team0</code> but you didn't wrap that in quotes also there one more closing bracket than opening ones</p> <p>I thin this is what it should be</p> <pre><code>os.system("nmcli con add type team-slave con-name team0-port1 ifname {} master team0".format(PORT1)) </code></pre>
2
2016-10-05T04:50:42Z
[ "python" ]
WxPython's ScrolledWindow element collapses to minimum size
39,865,870
<p>I am using a Panel within a Frame to display images (the GUI need to switch between multiple panels and hence the hierarchy). As images should be displayed in native size I used ScrolledWindow as the panel parent. The scrolls do appear and work, but it causes the Panel to collapse to minimum size and it needs to be resized using drag&amp;drop every time. Is there a way around this?</p> <p>Below is a reduced version of the code, which shows the problem:</p> <pre><code>import os import wx from wx.lib.pubsub import pub class Edit_Panel(wx.PyScrolledWindow): def __init__(self, parent): super(Edit_Panel, self).__init__(parent) # Display size width, height = wx.DisplaySize() self.photoMaxSize = height - 500 # Loaded image self.loaded_image = None # Icons self.open_icon_id = 500 # Generate panel self.layout() def layout(self): self.main_sizer = wx.BoxSizer(wx.VERTICAL) divider = wx.StaticLine(self, -1, style = wx.LI_HORIZONTAL) self.main_sizer.Add(divider, 0, wx.ALL | wx.EXPAND) self.toolbar = self.init_toolbar() self.main_sizer.Add(self.toolbar, 0, wx.ALL) img = wx.EmptyImage(self.photoMaxSize, self.photoMaxSize) self.image_control = wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(img)) self.main_sizer.Add(self.image_control, 0, wx.ALL | wx.CENTER, 5) self.image_label = wx.StaticText(self, -1, style = wx.ALIGN_CENTRE) self.main_sizer.Add(self.image_label, 0, wx.ALL | wx.ALIGN_CENTRE, 5) self.SetSizer(self.main_sizer) fontsz = wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT).GetPixelSize() self.SetScrollRate(fontsz.x, fontsz.y) self.EnableScrolling(True, True) def init_toolbar(self): toolbar = wx.ToolBar(self) toolbar.SetToolBitmapSize((16, 16)) open_ico = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, (16, 16)) open_tool = toolbar.AddSimpleTool(self.open_icon_id, open_ico, "Open", "Open an Image Directory") handler = self.on_open_reference self.Bind(event = wx.EVT_MENU, handler = handler, source = open_tool) toolbar.Realize() return toolbar def on_open_reference(self, event, wildcard = None): if wildcard is None: wildcard = self.get_wildcard() defaultDir = '~/' dbox = wx.FileDialog(self, "Choose an image to display", defaultDir = defaultDir, wildcard = wildcard, style = wx.OPEN) if dbox.ShowModal() == wx.ID_OK: file_name = dbox.GetPath() # load image self.load_image(image = file_name) dbox.Destroy() def get_wildcard(self): wildcard = 'Image files (*.jpg;*.png;*.bmp)|*.png;*.bmp;*.jpg;*.jpeg' return wildcard def load_image(self, image): self.loaded_image = image # Load image img = wx.Image(image, wx.BITMAP_TYPE_ANY) # Label image name image_name = os.path.basename(image) self.image_label.SetLabel(image_name) # scale the image, preserving the aspect ratio scale_image = True if scale_image: W = img.GetWidth() H = img.GetHeight() if W &gt; H: NewW = self.photoMaxSize NewH = self.photoMaxSize * H / W else: NewH = self.photoMaxSize NewW = self.photoMaxSize * W / H img = img.Scale(NewW, NewH) self.image_control.SetBitmap(wx.BitmapFromImage(img)) # Render self.main_sizer.Layout() self.main_sizer.Fit(self) self.Refresh() pub.sendMessage("resize", msg = "") class Viewer_Frame(wx.Frame): def __init__(self, parent, id, title): super(Viewer_Frame, self).__init__(parent = parent, id = id, title = title) # Edit panel self.edit_panel = Edit_Panel(self) # Default panel self.main_panel = self.edit_panel # Render frame self.render_frame() # Subscription to re-render pub.subscribe(self.resize_frame, ("resize")) def render_frame(self): # Main Sizer self.main_sizer = wx.BoxSizer(wx.VERTICAL) # Add default sizer self.main_sizer.Add(self.main_panel, 1, wx.EXPAND) # Render self.SetSizer(self.main_sizer) self.Show() self.main_sizer.Fit(self) self.Center() def resize_frame(self, msg): self.main_sizer.Fit(self) if __name__ == "__main__": app = wx.App(False) frame = Viewer_Frame(parent = None, id = -1, title = 'Toolkit') app.MainLoop() </code></pre>
0
2016-10-05T05:13:05Z
39,871,909
<p>You're calling <code>Fit()</code>, so you're explicitly asking the panel to fit its contents, but you don't specify the min/best size of this contents anywhere (AFAICS, there is a lot of code here, so I could be missing something).</p> <p>If you want to use some minimal size for the panel, just set it using <code>SetMinSize()</code>.</p>
1
2016-10-05T10:47:09Z
[ "python", "wxpython", "wxwidgets" ]
pattern.match with regex not working
39,865,885
<pre><code>import re def test(stest): pattern = re.compile(r'/product\/(.*?)/i') result = pattern.match(stest) if result: print result.group() else: print "Doesn't match" test('product/WKSGGPC104/GGPC-The-Paladin') </code></pre> <p>When I run the coding as the above, I will get "Doesn't match" for the result instead of 'product/'.</p> <p>Could someone help me out? I have tested regular expression by using the online tool, it shows fine and matches the string that I am going to test. </p> <p>Thank you for your help.</p>
1
2016-10-05T05:14:29Z
39,865,962
<p>A couple of issues with your code.<br> First, there was no <code>/</code> in the beginning, second, you provide the modifiers <strong>after</strong> the call:</p> <pre><code>import re def test(stest): pattern = re.compile(r'product/([^/]+)'. re.IGNORECASE) result = pattern.match(stest) if result: print(result.group()) else: print("Doesn't match") test('product/WKSGGPC104/GGPC-The-Paladin') </code></pre> <p>See <a href="http://ideone.com/TBgQMN" rel="nofollow"><strong>a demo on regex101.com</strong></a>.</p>
1
2016-10-05T05:21:54Z
[ "python", "regex" ]
pattern.match with regex not working
39,865,885
<pre><code>import re def test(stest): pattern = re.compile(r'/product\/(.*?)/i') result = pattern.match(stest) if result: print result.group() else: print "Doesn't match" test('product/WKSGGPC104/GGPC-The-Paladin') </code></pre> <p>When I run the coding as the above, I will get "Doesn't match" for the result instead of 'product/'.</p> <p>Could someone help me out? I have tested regular expression by using the online tool, it shows fine and matches the string that I am going to test. </p> <p>Thank you for your help.</p>
1
2016-10-05T05:14:29Z
39,866,133
<p>You are using string literals but still escaping the \ in your string.</p>
0
2016-10-05T05:36:32Z
[ "python", "regex" ]
How to understand numpy's combined slicing and indexing example
39,866,043
<p>I am trying to understand numpy's combined slicing and indexing concept, however I am not sure how to correctly get the below results from numpy's output (by hand so that we can understand how numpy process combined slicing and indexing, which one will be process first?):</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a=np.arange(12).reshape(3,4) &gt;&gt;&gt; a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) &gt;&gt;&gt; i=np.array([[0,1],[2,2]]) &gt;&gt;&gt; a[i,:] array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [ 8, 9, 10, 11]]]) &gt;&gt;&gt; j=np.array([[2,1],[3,3]]) &gt;&gt;&gt; a[:,j] array([[[ 2, 1], [ 3, 3]], [[ 6, 5], [ 7, 7]], [[10, 9], [11, 11]]]) &gt;&gt;&gt; aj=a[:,j] &gt;&gt;&gt; aj.shape (3L, 2L, 2L) </code></pre> <p>I am bit confused about how aj's shape becomes (3,2,2) with the above output, any detailed explanations are very appreciated, thanks!</p>
0
2016-10-05T05:29:20Z
39,866,514
<p><code>a[:,j][0]</code> is equivalent to <code>a[0,j]</code> or <code>[0, 1, 2, 3][j]</code> which gives you <code>[[2, 1], [3, 3]])</code></p> <p><code>a[:,j][1]</code> is equivalent to <code>a[1,j]</code> or <code>[4, 5, 6, 7][j]</code> which gives you <code>[[6, 5], [7, 7]])</code></p> <p><code>a[:,j][2]</code> is equivalent to <code>a[2,j]</code> or <code>[8, 9, 10, 11][j]</code> which gives you <code>[[10, 9], [11, 11]])</code></p>
0
2016-10-05T06:06:56Z
[ "python", "arrays", "numpy", "indexing" ]
How to understand numpy's combined slicing and indexing example
39,866,043
<p>I am trying to understand numpy's combined slicing and indexing concept, however I am not sure how to correctly get the below results from numpy's output (by hand so that we can understand how numpy process combined slicing and indexing, which one will be process first?):</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a=np.arange(12).reshape(3,4) &gt;&gt;&gt; a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) &gt;&gt;&gt; i=np.array([[0,1],[2,2]]) &gt;&gt;&gt; a[i,:] array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7]], [[ 8, 9, 10, 11], [ 8, 9, 10, 11]]]) &gt;&gt;&gt; j=np.array([[2,1],[3,3]]) &gt;&gt;&gt; a[:,j] array([[[ 2, 1], [ 3, 3]], [[ 6, 5], [ 7, 7]], [[10, 9], [11, 11]]]) &gt;&gt;&gt; aj=a[:,j] &gt;&gt;&gt; aj.shape (3L, 2L, 2L) </code></pre> <p>I am bit confused about how aj's shape becomes (3,2,2) with the above output, any detailed explanations are very appreciated, thanks!</p>
0
2016-10-05T05:29:20Z
39,866,515
<p>Whenever you use an array of indices, the result has the <em>same shape as the indices</em>; for example:</p> <pre><code>&gt;&gt;&gt; x = np.ones(5) &gt;&gt;&gt; i = np.array([[0, 1], [1, 0]]) &gt;&gt;&gt; x[i] array([[ 1., 1.], [ 1., 1.]]) </code></pre> <p>We've indexed with a 2x2 array, and the result is a 2x2 array. When combined with a slice, the size of the slice is preserved. For example:</p> <pre><code>&gt;&gt;&gt; x = np.ones((5, 3)) &gt;&gt;&gt; x[i, :].shape (2, 2, 3) </code></pre> <p>Where the first example was a 2x2 array of items, this example is a 2x2 array of (length-3) rows.</p> <p>The same is true when you switch the order of the slice:</p> <pre><code>&gt;&gt;&gt; x = np.ones((5, 3)) &gt;&gt;&gt; x[:, i].shape (5, 2, 2) </code></pre> <p>This can be thought of as a list of five 2x2 arrays.</p> <p>Just remember: when any dimension is indexed with a list or array, the result has the shape of the <em>indices</em>, not the shape of the input.</p>
1
2016-10-05T06:07:04Z
[ "python", "arrays", "numpy", "indexing" ]
sympy - symbolically solve equations with float power
39,866,051
<p>Using sympy, I define the symbols,</p> <pre><code>a, b, c = sympy.symbols(['a', 'b', 'c']) </code></pre> <p>Then, when I try to solve the following system of equations,</p> <pre><code>sympy.solve([sympy.Eq(b - a**2.552 - c), sympy.Eq(a, 2)]) </code></pre> <p>I get the solution,</p> <pre><code>[{b: c + 5.86446702875684, a: 2.00000000000000}] </code></pre> <p>But, when I try to solve,</p> <pre><code>sympy.solve([sympy.Eq(b - a**2.552 - c), sympy.Eq(b, 2)]) </code></pre> <p>It just seems to keep running (for ~4hrs), with no solution. Any help would be appreciated!</p>
3
2016-10-05T05:30:01Z
39,866,932
<p>I don't know why but <code>rational=False</code> helps</p> <pre><code>sympy.solve([sympy.Eq(b - a**2.552 - c), sympy.Eq(b, 2)], rational=False) </code></pre> <p>see: <a href="http://stackoverflow.com/questions/17087629/sympy-hangs-when-trying-to-solve-a-simple-algebraic-equation">sympy hangs when trying to solve a simple algebraic equation</a></p>
4
2016-10-05T06:34:06Z
[ "python", "sympy" ]
Django admin login returns Forbidden 403 CSRF verification failed. Request aborted
39,866,056
<p>Pretty new to Django. Working through a second project following the Polls tutorial on Django website. Previous effort went well, albeit simple. This time around encountering problems accessing admin login.</p> <p>I have created a superuser and using those credentials, when I try to login to <code>http://127.0.0.1:8000/admin/login/?next=/admin/</code> I get the following error:</p> <pre><code>Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF cookie not set. </code></pre> <p>Looking at <a href="http://stackoverflow.com/questions/3678238/why-is-django-admin-login-giving-me-403-csrf-error">this</a> and <a href="http://stackoverflow.com/questions/29573163/django-admin-login-suddenly-demanding-csrf-token">this</a>, most answers either detail clearing browser cookies (did that), include <code>'django.middleware.csrf.CsrfViewMiddleware'</code> in your middleware (which I do), or creating an exemption or workaround. </p> <p>1) My question is why the admin portal does not seem to work now, but it did for my previous project and I am following the same steps?</p> <p>2) Shouldn't the properties for the admin panel be inherited through the project initiation?</p> <p>3) How would I set the CSRF for admin when <a href="https://docs.djangoproject.com/en/1.9/ref/csrf/" rel="nofollow">the documentation</a> appears to state that the CSRF middleware is activated by default?</p> <p>Thanks for any help.</p> <p><strong>settings.py</strong></p> <pre><code>""" Django settings for aptly project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import dj_database_url from .secret_settings import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_DIR = os.path.join(PROJECT_ROOT,'../search') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'aptly.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'aptly.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "db_name", "USER": "me", "PASSWORD": "", "HOST": "localhost", "PORT": "", } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'static'), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' #DATABASES['default'] = dj_database_url.config() </code></pre> <p><strong>urls.py</strong></p> <pre><code>from django.conf.urls import patterns, include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), ] </code></pre> <p><strong>Directory</strong></p> <pre><code>project -aptly --settings.py --urls.py --wsgi.py -search --templates ---index.html --models.py --urls.py --views.py manage.py </code></pre>
0
2016-10-05T05:30:24Z
39,866,348
<p>You are setting <code>SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')</code> Remove this line and see if that solves your issue. If you are enabling https <code>csrf will work only as per the specifications of https</code>. There is a possibility that you are enabling https and serving your website from a non-https server. Also, Have you tried in another browser after clearing cookies or in private/incognito mode? Sometimes this error occurs because <code>csrf cookie is not set correctly</code>. Try <code>inspecting your request/response headers</code> from browser console.</p>
0
2016-10-05T05:54:50Z
[ "python", "django" ]
Django admin login returns Forbidden 403 CSRF verification failed. Request aborted
39,866,056
<p>Pretty new to Django. Working through a second project following the Polls tutorial on Django website. Previous effort went well, albeit simple. This time around encountering problems accessing admin login.</p> <p>I have created a superuser and using those credentials, when I try to login to <code>http://127.0.0.1:8000/admin/login/?next=/admin/</code> I get the following error:</p> <pre><code>Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF cookie not set. </code></pre> <p>Looking at <a href="http://stackoverflow.com/questions/3678238/why-is-django-admin-login-giving-me-403-csrf-error">this</a> and <a href="http://stackoverflow.com/questions/29573163/django-admin-login-suddenly-demanding-csrf-token">this</a>, most answers either detail clearing browser cookies (did that), include <code>'django.middleware.csrf.CsrfViewMiddleware'</code> in your middleware (which I do), or creating an exemption or workaround. </p> <p>1) My question is why the admin portal does not seem to work now, but it did for my previous project and I am following the same steps?</p> <p>2) Shouldn't the properties for the admin panel be inherited through the project initiation?</p> <p>3) How would I set the CSRF for admin when <a href="https://docs.djangoproject.com/en/1.9/ref/csrf/" rel="nofollow">the documentation</a> appears to state that the CSRF middleware is activated by default?</p> <p>Thanks for any help.</p> <p><strong>settings.py</strong></p> <pre><code>""" Django settings for aptly project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import dj_database_url from .secret_settings import * # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) PROJECT_DIR = os.path.join(PROJECT_ROOT,'../search') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'search', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'aptly.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'aptly.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": "db_name", "USER": "me", "PASSWORD": "", "HOST": "localhost", "PORT": "", } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'static'), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' #DATABASES['default'] = dj_database_url.config() </code></pre> <p><strong>urls.py</strong></p> <pre><code>from django.conf.urls import patterns, include, url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^admin/', admin.site.urls), ] </code></pre> <p><strong>Directory</strong></p> <pre><code>project -aptly --settings.py --urls.py --wsgi.py -search --templates ---index.html --models.py --urls.py --views.py manage.py </code></pre>
0
2016-10-05T05:30:24Z
39,880,781
<p>I have no clue why this is the answer, but I went in and updated my Django to the current release. For whatever reason this solved the problem...</p> <pre><code>pip install --upgrade django==1.10.2 </code></pre>
0
2016-10-05T17:59:15Z
[ "python", "django" ]
Programmatically enable/disable Bluetooth profiles
39,866,179
<p>I'm running Rasbian Jessie Lite on Raspberry Pi 3 with a USB/Bluetooth dongle (blueZ) 5.4.</p> <p>The <code>/etc/bluetooth/main.conf</code> has Class = 0x0c0408. I have a Qt5 application which enables the Bluetooth device and accepts any incoming pairing requests.</p> <p>I can successfully connect from my smartphone to all enabled Bluetooth profiles: A2DP and HFP.</p> <p>Now I want to let the users select which profile(s) should be enabled. Thus I'm looking for a way to enable/disable on-the-fly A2DP and HFP. It's ok from C++, bash or python script.</p> <p>I can't just change the Class value because I cannot restart the bluetooth service - I MUST keep running the GATT server.</p> <p>Any thought about?</p>
0
2016-10-05T05:40:24Z
40,034,928
<p>Enabling and disabling any profile/service in Bluez can be done using sdptool command. If you want to enable any profile/service you can use:</p> <p><code>sdptool add A2SRC</code></p> <p>In the same way to disable any service/profile you can use:</p> <pre><code>sdptool del A2SRC </code></pre> <p>More info can be found using help of sdptool</p> <pre><code> sdptool - SDP tool v5.37 Usage: sdptool [options] &lt;command&gt; [command parameters] Options: -h Display help -i Specify source interface Commands: search Search for a service browse Browse all available services records Request all records add Add local service del Delete local service get Get local service setattr Set/Add attribute to a SDP record setseq Set/Add attribute sequence to a SDP record Services: DID SP DUN LAN FAX OPUSH FTP PRINT HS HSAG HF HFAG SAP PBAP MAP NAP GN PANU HCRP HID KEYB WIIMOTE CIP CTP A2SRC A2SNK AVRCT AVRTG UDIUE UDITE SEMCHLA SR1 SYNCML SYNCMLSERV ACTIVESYNC HOTSYNC PALMOS NOKID PCSUITE NFTP NSYNCML NGAGE APPLE IAP ISYNC GATT </code></pre> <p>Now, this is how you can enable and disable any profile/services. </p> <p>Moving to your second question, how to remotely let the user of smartphone to enable and disable the profile. This you can achieve through the serial port profile(SPP) in Bluetooth. Just to brief you, SPP is serial port emulation over Bluetooth. It is based on RFcomm protocol and can be used in parallel with A2DP and HFP. </p> <p>So here the idea is to create SPP connection from smartphone to RSP and then send command to enable and disable profiles. SPP can be used from command line using rfcomm command available with Bluez. More info on how to use the command can be found here: </p> <blockquote> <p><a href="http://unix.stackexchange.com/questions/92255/how-do-i-connect-and-send-data-to-a-bluetooth-serial-port-on-linux">http://unix.stackexchange.com/questions/92255/how-do-i-connect-and-send-data-to-a-bluetooth-serial-port-on-linux</a></p> </blockquote> <p>Let me know if any further clarification you need on this. </p>
1
2016-10-14T04:28:22Z
[ "python", "linux", "bluetooth", "a2dp", "hfp" ]
django makemigrations to rename field without user input
39,866,339
<p>I have a model with CharField named <em>oldName</em>. I want to rename the field to <em>newName</em>. </p> <p>When I run <em>python manage.py makemigrations</em>, I get a confirmation request <strong>"Did you rename model.oldName to model.newName (a CharField)? [y/N]"</strong></p> <p>However, I want to run the whole thing inside a docker container and there is no provision to provide the user input. Is there a way to force the migration without need for user input?</p> <p><strong>PS:</strong> I tried <strong>--noinput</strong> option with makemigrations. In this case migrations are not getting applied.</p>
0
2016-10-05T05:54:01Z
39,866,780
<p>Use </p> <pre><code>script_or_command &lt; &lt;(yes y) </code></pre> <p>But I'm not sure this will work for multiple input prompts.</p>
0
2016-10-05T06:24:27Z
[ "python", "django", "rename", "makemigrations" ]
In Python, is it possible to skip a certain part of a for loop?
39,866,378
<p>so I attempted to add some code to my working product(A triangle maker) where you can add some text to the middle of the triangle if the program allows so. So far I've added the text with the correct amount of x's and indents but the program still outputs the original middle line of x's. For example Triangle(3, "M") would output</p> <pre><code> x xxx xMx xxxxx </code></pre> <p>instead of </p> <pre><code> x xMx xxxxx </code></pre> <p>which is what I would like. I have tried using break when x == textrow - 1 but that did not seem to work and I think what I would have to do is somehow break the loop, print the user's text with the x's skip the part where the computer would normally print the xxx's and keep going. But I have no idea on how to do that. Here is my code, the only really relevant parts are under the "if x > 1" (I know that it is probably the most inefficient thing you have ever seen, but I'm a beginner and I would do what I understand.)</p> <pre><code>def Triangle(height, text): text1 = str(text) number_of_x2 = (height - len(text)) / 2 if height % 2 == 0: print "Please enter a height that is odd" else: stringTriangle = "x" HT = "" for x in range(height + height - 1): HT += "x" length_of_HT = len(HT) length_of_HT = int(length_of_HT) length_of_HT = len(HT) / 2 length_of_HT = int(length_of_HT) indent_text_length = length_of_HT / 2 for x in range(height): #should be height change later if x == 1: stringTriangle = " " * length_of_HT + stringTriangle print stringTriangle if x &gt; 1: textrow = height / 2 for x in range(height): if stringTriangle == HT: break if len(text) == len(stringTriangle): break if x == textrow: text = "" text = " " * number_of_x2 for x in range(number_of_x2): text+="x" text = text + text1 for x in range(number_of_x2): text+="x" print text stringTriangle += "xx" stringTriangle = stringTriangle[1:] print stringTriangle </code></pre> <p>Thank you!</p>
0
2016-10-05T05:57:17Z
39,867,065
<p>I am not sure of how how your code works, but I tweaked it until it returned the result I expected. Also, I made small changes to parts that were a bit ugly. This should do what you want:</p> <pre><code>def Triangle(height, text): number_of_x2 = (height - len(text)) / 2 if not height % 2: print "Please enter a height that is odd" else: string_triangle = "x" ht = "x" * (2 * height - 1) length_of_ht = len(ht) / 2 indent_text_length = length_of_ht / 2 text_row = height / 2 # should be height change later for x in range(height): if x == 1: string_triangle = " " * length_of_ht + string_triangle print string_triangle if x &gt; 1: for x in range(height): if x == text_row - 1: string_triangle += "xx" string_triangle = string_triangle[1:] continue if x == textrow: special_line = " " * (number_of_x2 + len(text) / 2) + "x" * number_of_x2 + text + "x" * number_of_x2 if not len(text) % 2: special_line += "x" print special_line if string_triangle == ht or len(text) == len(string_triangle): break string_triangle += "xx" string_triangle = string_triangle[1:] print string_triangle </code></pre>
0
2016-10-05T06:42:48Z
[ "python", "loops" ]
From JSON file to Numpy Array
39,866,713
<p>I have a MongoDB collection, which, when imported to Python via PyMongo, is a dictionnary in Python. I am looking to transform it into a Numpy Array.</p> <p>For instance, if the JSON file looks like this :</p> <pre><code>{ "_id" : ObjectId("57065024c3d1132426c4dd53"), "B" : { "BA" : 14, "BB" : 23, "BC" : 32, "BD" : 41 "A" : 50, } { "_id" : ObjectId("57065024c3d1132426c4dd53"), "A" : 1 "B" : { "BA" : 1, "BB" : 2, "BC" : 3, "BD" : 4 </code></pre> <p>}</p> <p>I'd like to get in return this 5*2 Numpy Array : np.array([[50,14,23,32,41], [1,1,2,3,4]]) In that case, the first column corresponds to "A", the second one to "BA", the third one to "BB", etc. Notice that keys are not always sorted in the same order.</p> <p>My code, which does not work at all (and does not do what I want yet) looks like this :</p> <pre><code>from pymongo import MongoClient uri = "mongodb://localhost/test" client = MongoClient(uri) db=client.recodb collection=db.recos list1=list(collection.find()) array2=np.vstack([[product[key] for key in product.keys()] for product in list1]) </code></pre>
0
2016-10-05T06:20:17Z
39,870,755
<p>The <a href="https://pypi.python.org/pypi/flatdict" rel="nofollow">flatdict</a> module can sometimes be useful when working with mongodb data structures. It will handle flattening the nested dictionary structure for you:</p> <pre><code>columns = [] for d in data: flat = flatdict.FlatDict(d) del flat['_id'] columns.append([item[1] for item in sorted(flat.items(), key=lambda item: item[0])]) np.vstack(columns) </code></pre> <p>Of course this can be solved without flatdict too.</p>
1
2016-10-05T09:50:54Z
[ "python", "arrays", "json", "mongodb", "numpy" ]
From JSON file to Numpy Array
39,866,713
<p>I have a MongoDB collection, which, when imported to Python via PyMongo, is a dictionnary in Python. I am looking to transform it into a Numpy Array.</p> <p>For instance, if the JSON file looks like this :</p> <pre><code>{ "_id" : ObjectId("57065024c3d1132426c4dd53"), "B" : { "BA" : 14, "BB" : 23, "BC" : 32, "BD" : 41 "A" : 50, } { "_id" : ObjectId("57065024c3d1132426c4dd53"), "A" : 1 "B" : { "BA" : 1, "BB" : 2, "BC" : 3, "BD" : 4 </code></pre> <p>}</p> <p>I'd like to get in return this 5*2 Numpy Array : np.array([[50,14,23,32,41], [1,1,2,3,4]]) In that case, the first column corresponds to "A", the second one to "BA", the third one to "BB", etc. Notice that keys are not always sorted in the same order.</p> <p>My code, which does not work at all (and does not do what I want yet) looks like this :</p> <pre><code>from pymongo import MongoClient uri = "mongodb://localhost/test" client = MongoClient(uri) db=client.recodb collection=db.recos list1=list(collection.find()) array2=np.vstack([[product[key] for key in product.keys()] for product in list1]) </code></pre>
0
2016-10-05T06:20:17Z
39,870,771
<p>Assuming you've successfully loaded that JSON into Python, here's one way to create the Numpy array you want. My code has a minimal definition of <code>ObjectId</code> so that it won't raise a NameError on <code>ObjectId</code> entries. </p> <pre><code>sorted(d["B"].items())] </code></pre> <p>produces a list of (key, value) tuples from the contents of a "B" dictionary, sorted by key. We then extract just the values from those tuples into a list, and append that list to a list containing the value from the "A" item.</p> <pre><code>import numpy as np class ObjectId(object): def __init__(self, objectid): self.objectid = objectid def __repr__(self): return 'ObjectId("{}")'.format(self.objectid) data = [ { "_id" : ObjectId("57065024c3d1132426c4dd53"), "B" : { "BA" : 14, "BB" : 23, "BC" : 32, "BD" : 41 }, "A" : 50 }, { "_id" : ObjectId("57065024c3d1132426c4dd53"), "A" : 1, "B" : { "BA" : 1, "BB" : 2, "BC" : 3, "BD" : 4 } } ] array2 = np.array([[d["A"]] + [v for _, v in sorted(d["B"].items())] for d in data]) print(array2) </code></pre> <p><strong>output</strong></p> <pre><code>[[50 14 23 32 41] [ 1 1 2 3 4]] </code></pre>
1
2016-10-05T09:51:33Z
[ "python", "arrays", "json", "mongodb", "numpy" ]
TypeError at /myapp/hello/ hello() takes exactly 2 arguments (1 given)
39,866,858
<p>ecomstore/settings.py</p> <pre><code>INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploader', 'myapp', ) </code></pre> <p>ecomstore/urls.py</p> <pre><code>from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'ecomstore.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^catalog/$', 'ecomstore.views.catalog'), url(r'^myapp/', include(myapp.urls)), url(r'^upload/$', 'uploader.views.home', name = 'imageupload'), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) </code></pre> <p>myapp/urls.py</p> <pre><code>from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name = 'hello'), ) </code></pre> <p>myapp/views.py</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse # Create your views here. def hello(request, number): text = "&lt;h1&gt;welcome to my app number %s!&lt;/h1&gt;"% number return render(request, "myapp/template/hello.html", {}) return HttpResponse(text) </code></pre> <p>after changing url(r'^myapp/', include('myapp.urls') when i put in url localhost:8000/myapp/hello/ it's throwing TypeError at /myapp/hello/</p> <p><em>hello() takes exactly 2 arguments (1 given)</em></p> <p>please guide me </p> <p>Thanks.</p>
0
2016-10-05T06:29:43Z
39,866,949
<p>You're missing quotes it should be:</p> <pre><code>include('myapp.urls') </code></pre> <p>That or import myapp (which is not imported on your urls.py)</p>
0
2016-10-05T06:35:11Z
[ "python", "django" ]
Python: Insert into a postGreSQL table using python by passing parameters
39,866,900
<p>I have two lists:</p> <pre><code>columns = ['id','name','address'] data = ['1,'John','LA'','2,'Jessica','TX''] </code></pre> <p>I have a table schema with the same columns as above and I am unable to insert data into the table using psycopg2 connections when I pass the values and column names as parameters.</p> <pre><code>cursor_r.execute("insert into test %s values %s ",tuple(column_names),tuple(values))) </code></pre> <p>I get the error as </p> <pre><code>psycopg2.ProgrammingError: syntax error at or near "'id'" </code></pre> <p>I really am unable to figure what I'm doing wrong and would really appreciate any kind of help. Thank you in advance for trying to help me out. EDIT: I tried typing in this query:</p> <pre><code>cursor_r.execute("insert into test (%s) values (%s) ", ((x for x in column_names),(str(y).replace("(","").replace(")","") for y in values))) </code></pre> <p>It now gives me the error that it cannot adapt to a type 'generator'</p> <p>EDIT 2: I'm now getting the error that 'generator' object doesn't support indexing. Someone help me out</p>
0
2016-10-05T06:32:10Z
39,866,986
<p><code>INSERT</code> needs columns and values in <code>()</code> so you need <code>INSERT INTO test (%s) VALUES (%s)</code></p> <p>see: <a href="http://www.w3schools.com/sql/sql_insert.asp" rel="nofollow">http://www.w3schools.com/sql/sql_insert.asp</a></p>
0
2016-10-05T06:37:48Z
[ "python", "sql", "insert", "psycopg2" ]
Python PyInstaller Tkinter Button Tied to Messagebox Does Nothing
39,866,976
<p>I have a tiny button with a question mark in my app. When clicked, it displays the doc string from a function in my app which helps to explain what the app does.</p> <p>The problem is, I build a single .exe using pyinstaller and this question mark button does nothing when clicked.</p> <p><strong>Recreation Steps</strong></p> <ol> <li>save the file below as run.py</li> <li>open command-prompt</li> <li>paste <code>pyinstaller.exe --onefile --windowed run.py</code></li> <li>go to <code>dist</code> folder and run single exe</li> <li>click <code>?</code> button and notice it does nothing</li> </ol> <p>run.py below</p> <pre><code>import tkinter as tk from tkinter import ttk ''' pyinstaller.exe --onefile --windowed run.py ''' def someotherfunction(): ''' This is some message that I want to appear but it currently doesn\'t seem to work when I put try to launch a messagebox showinfo window... ''' pass def showhelpwindow(): return tk.messagebox.showinfo(title='How to use this tool', message=someotherfunction.__doc__) root = tk.Tk() helpbutton = ttk.Button(root, text='?', command=showhelpwindow, width=2) helpbutton.grid(row=0, column=3, sticky='e') root.mainloop() </code></pre> <p>My setup:</p> <ul> <li>PyInstaller 3.2</li> <li>Windows 7</li> <li>Python 3.4.2</li> </ul> <p>I tried adding <a href="http://stackoverflow.com/questions/28349359/pyinstaller-single-file-executable-doesnt-run"><code>--noupx</code></a> option but that didn't fix it.</p> <p>EDIT:</p> <p>I removed <code>--windowed</code> option this time and the console is now showing me an error when I click this button.</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "tkinter\__init__.py", line 1533, in __call__ File "run.py", line 156, in showhelpwindow AttributeError: 'module' object has no attribute 'messagebox' </code></pre>
2
2016-10-05T06:37:14Z
39,877,519
<p>Line 3 below is the solution. I needed to import the <code>tkinter.messagebox</code> module explicitly.</p> <pre><code>import tkinter as tk from tkinter import ttk import tkinter.messagebox ''' pyinstaller.exe --onefile --windowed run.py ''' def someotherfunction(): ''' This is some message that I want to appear but it currently doesn\'t seem to work when I put try to launch a messagebox showinfo window... ''' pass def showhelpwindow(): return tk.messagebox.showinfo(title='How to use this tool', message=someotherfunction.__doc__) root = tk.Tk() helpbutton = ttk.Button(root, text='?', command=showhelpwindow, width=2) helpbutton.grid(row=0, column=3, sticky='e') root.mainloop() </code></pre>
0
2016-10-05T15:01:23Z
[ "python", "tkinter", "messagebox", "pyinstaller" ]
Pandas: get first 10 elements of a series
39,867,061
<p>I have a data frame with a column <code>tfidf_sorted</code> as follows:</p> <pre><code> tfidf_sorted 0 [(morrell, 45.9736796), (football, 25.58352014... 1 [(melatonin, 48.0010051405), (lewy, 27.5842077... 2 [(blues, 36.5746634797), (harpdog, 20.58669641... 3 [(lem, 35.1570832476), (rottensteiner, 30.8800... 4 [(genka, 51.4667410433), (legendaarne, 30.8800... </code></pre> <p>The <code>type(df.tfidf_sorted)</code> returns <code>pandas.core.series.Series</code>.</p> <p>This column was created as follows:</p> <pre><code>df['tfidf_sorted'] = df['tfidf'].apply(lambda y: sorted(y.items(), key=lambda x: x[1], reverse=True)) </code></pre> <p>where <code>tfidf</code> is a dictionary.</p> <p>How do I get the first 10 key-value pairs from <code>tfidf_sorted</code>?</p>
3
2016-10-05T06:42:42Z
39,867,338
<p>IIUC you can use:</p> <pre><code>from itertools import chain #flat nested lists a = list(chain.from_iterable(df['tfidf_sorted'])) #sorting a.sort(key=lambda x: x[1], reverse=True) #get 10 top print (a[:10]) </code></pre> <p>Or if need top 10 per row add <code>[:10]</code>:</p> <pre><code>df['tfidf_sorted'] = df['tfidf'].apply(lambda y: (sorted(y.items(), key=lambda x: x[1], reverse=True))[:10]) </code></pre>
1
2016-10-05T06:59:19Z
[ "python", "list", "python-2.7", "pandas", "indexing" ]
Codenvy. "The system is out of resources. Please contact your system admin."
39,867,141
<p><img src="http://i.stack.imgur.com/8dkRU.jpg" alt="enter image description here"></p> <p>Don't understand this error, while creating python slack.</p>
-1
2016-10-05T06:47:48Z
39,867,188
<p>Someone seem to have had a similar question and got some help here: <a href="https://groups.google.com/a/codenvy.com/forum/#!topic/codenvy/N1OE5BgfZNk" rel="nofollow">https://groups.google.com/a/codenvy.com/forum/#!topic/codenvy/N1OE5BgfZNk</a></p> <blockquote> <p>"Can you run the following please?</p> </blockquote> <p><code>docker rm $(docker ps -a -q)</code></p> <blockquote> <p>And then try creating a new workspace again." "Did you run this command as a root? It should work. As to why it happens, Swarm reserves resources for stopped containers as well and the current version of Codenvy does not delete them after a workspace is stopped. This is fixed in the new version."</p> </blockquote>
0
2016-10-05T06:50:35Z
[ "python", "codenvy" ]
Codenvy. "The system is out of resources. Please contact your system admin."
39,867,141
<p><img src="http://i.stack.imgur.com/8dkRU.jpg" alt="enter image description here"></p> <p>Don't understand this error, while creating python slack.</p>
-1
2016-10-05T06:47:48Z
39,894,018
<p>Is this happening at beta.codenvy.com? Or on your own downloaded Codenvy system? You can also file an issue at <a href="https://github.com/codenvy/codenvy/issues" rel="nofollow">https://github.com/codenvy/codenvy/issues</a> where support and engineers hang out.</p>
0
2016-10-06T10:50:00Z
[ "python", "codenvy" ]
Codenvy. "The system is out of resources. Please contact your system admin."
39,867,141
<p><img src="http://i.stack.imgur.com/8dkRU.jpg" alt="enter image description here"></p> <p>Don't understand this error, while creating python slack.</p>
-1
2016-10-05T06:47:48Z
39,897,308
<p>This particular issue happens when you are running your own private Codenvy system and the underlying hardware is out of memory / CPU to give to users. So while the user gets this message, its an indication that the system administrator needs to add additional physical nodes to the cluster. I am going to open an issue as I believe we have implemented capabilities to prevent new workspaces from being started for the user if the underlying system is out of resources. So you may be running an old version - can you upgrade to 5.0.0-M4 please?</p>
0
2016-10-06T13:26:05Z
[ "python", "codenvy" ]
Need to mock a non test method in Django
39,867,259
<p>I have a test class just like the one below: </p> <pre><code>@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async') class SortAPITestCase(APITestCase): def hit_scan("""some args"""): scan_uri = 'some url' data = 'some data' resp = self.client.post(scan_uri, data=data) id = resp.data['id'] self.assertEqual(resp.status_code, 201) return data, id def setUp(self): super(SortAPITestCase, self).setUp() self.scan_data, self.id = self.hit_scan() def test_1(self, mock_obj): ..... def test_2(self, mock_obj): ..... </code></pre> <p>In <code>myapp.apps.mytask1.views</code>, there is the Scan API, where there is <code>post</code> method which calls a celery task like:</p> <pre><code>def post("""some args"""): """ here there is a celery task that gets called""" image_processing.apply_async( args=[img_data], queue='image', countdown=10 ) </code></pre> <p><em>The celery task prints out a message when it is called somewhat like below</em></p> <pre><code>@shared_task def image_processing(img_data): if os.isfile(img_file): print "File Not Present" </code></pre> <p>So, whenever <code>img_file</code> is not present it prints out <code>File Not Present</code>. When the test fucntions(with mock) post to the Scan API, this print message is not printed on the console because of mock. But the <code>hit_scan()</code> method when posts to Scan API, then this message gets printed as the celery task is not getting mocked. Can I mock the celery task in <code>hit_scan</code>??</p> <p>So, Is there way to prevent the print statement from coming up in the console when I run the test??</p> <p>By the way, all the test cases pass. There is no problem from that point of view. I just wanted the console to look better with only <code>....</code> instead of the print statements from celery task also showing up.</p> <p><strong>Edit</strong>: Solved the problem. Here is what I did</p> <pre><code>@mock.patch('myapp.apps.mytask1.views.image_processing.apply_async') def hit_scan(self, mock_obj, """some args"""): </code></pre>
1
2016-10-05T06:55:10Z
39,867,949
<p>This has nothing to do with the method being outside of the test; Python makes no such distinction. However your syntax for mocking is consult wrong: you need to reference the thing you want to mock via a Python module path, not a file path.</p> <pre><code> @mock.patch('path.something.file.apply_async') </code></pre>
0
2016-10-05T07:32:29Z
[ "python", "django", "unit-testing", "celery", "django-celery" ]
Celery - [Errno 111] Connection refused when celery task is triggered using delay()
39,867,380
<p>I have two application servers(both having the django application). Both have celery worker running. RabbitMQ server is set up on a third different server.</p> <p>When any of the test task is being executed from any of the two application's servers through shell using <code>delay()</code>, they get executed fine. </p> <p>If the same task is triggered from server1 from the browser (through ajax) it works fine again. </p> <p>But in case of server2 (having the same config and code as server1), when the same task is triggered from the browser it gives [Error 111] Connection refused error.</p> <p>Some of the installed packages on server1 or server2 are:</p> <pre><code>celery 3.1.18 amqp 1.4.9 django 1.8.5 </code></pre> <p>Can anybody help me out with this? Thanks!</p> <p>The error trace is as follows:</p> <pre> File "../lib/python2.7/site-packages/celery/app/task.py" in delay 453. return self.apply_async(args, kwargs) File "../lib/python2.7/site-packages/celery/app/task.py" in apply_async 559. **dict(self._get_exec_options(), **options) File "../lib/python2.7/site-packages/celery/app/base.py" in send_task 353. reply_to=reply_to or self.oid, **options File "../lib/python2.7/site-packages/celery/app/amqp.py" in publish_task 305. **kwargs File "../lib/python2.7/site-packages/kombu/messaging.py" in publish 172. routing_key, mandatory, immediate, exchange, declare) File "../lib/python2.7/site-packages/kombu/connection.py" in _ensured 457. interval_max) File "../lib/python2.7/site-packages/kombu/connection.py" in ensure_connection 369. interval_start, interval_step, interval_max, callback) File "../lib/python2.7/site-packages/kombu/utils/__init__.py" in retry_over_time 246. return fun(*args, **kwargs) File "../local/lib/python2.7/site-packages/kombu/connection.py" in connect 237. return self.connection File "../lib/python2.7/site-packages/kombu/connection.py" in connection 742. self._connection = self._establish_connection() File "../lib/python2.7/site-packages/kombu/connection.py" in _establish_connection 697. conn = self.transport.establish_connection() File "../lib/python2.7/site-packages/kombu/transport/pyamqp.py" in establish_connection 116. conn = self.Connection(**opts) File "../lib/python2.7/site-packages/amqp/connection.py" in __init__ 165. self.transport = self.Transport(host, connect_timeout, ssl) File "../lib/python2.7/site-packages/amqp/connection.py" in Transport 186. return create_transport(host, connect_timeout, ssl) File "../lib/python2.7/site-packages/amqp/transport.py" in create_transport 299. return TCPTransport(host, connect_timeout) File "../lib/python2.7/site-packages/amqp/transport.py" in __init__ 95. raise socket.error(last_err) </pre>
0
2016-10-05T07:01:37Z
39,884,285
<p>I'd say start adding some extra logging calls before calling delay on server2 just to make sure your celery config is correct when running it as a webserver (as opposed to the manage.py shell instance). It sounds like some startup script for gunicorn / uwsgi / apache / magic isn't loading some variable needed to actually configure the celery correctly. Or it's just being overridden somehow in that context.</p> <p>Really horrible method is run your webserver on server2 as manage.py runserver and put a PDB in there right before your call to <code>.delay()</code> and poke around. Not exactly something you want open to the general internet while you're doing that but when all else fails...</p>
0
2016-10-05T21:51:22Z
[ "python", "django", "python-2.7", "rabbitmq", "celery" ]
Parsing Weather XML with Python
39,867,385
<p>I'm a beginner but with a lot of effort I'm trying to parse some data about the weather from an .xml file called "weather.xml" which looks like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Weather&gt; &lt;locality name="Rome" alt="21"&gt; &lt;situation temperature="18°C" temperatureF="64,4°F" humidity="77%" pression="1016 mb" wind="5 SSW km/h" windKN="2,9 SSW kn"&gt; &lt;description&gt;clear sky&lt;/description&gt; &lt;lastUpdate&gt;17:45&lt;/lastUpdate&gt; /&gt; &lt;/situation&gt; &lt;sun sunrise="6:57" sunset="18:36" /&gt; &lt;/locality&gt; </code></pre> <p>I parsed some data from this XML and this is how my Python code looks now:</p> <pre><code>#!/usr/bin/python from xml.dom import minidom xmldoc = minidom.parse('weather.xml') entry_situation = xmldoc.getElementsByTagName('situation') entry_locality = xmldoc.getElementsByTagName('locality') print entry_locality[0].attributes['name'].value print "Temperature: "+entry_situation[0].attributes['temperature'].value print "Humidity: "+entry_situation[0].attributes['humidity'].value print "Pression: "+entry_situation[0].attributes['pression'].value </code></pre> <p>It's working fine but if I try to parse data from "description" or "lastUpdate" node with the same method, I get an error, so this way must be wrong for those nodes which actually I can see they are differents.</p> <p>I'm also trying to write output into a log file with no success, the most I get is an empty file.</p> <p>Thank you for your time reading this.</p>
1
2016-10-05T07:01:56Z
39,868,130
<p>It is because "description" and "lastUpdate" are not attributes but child nodes of the "situation" node.</p> <p>Try:</p> <pre><code>d = entry_situation[0].getElementsByTagName("description")[0] print "Description: %s" % d.firstChild.nodeValue </code></pre> <p>You should use the same method to access the "situation" node from its parent "locality".</p> <p>By the way you should take a look at the <a href="http://lxml.de/" rel="nofollow" title="lxml">lxml</a> module, especially the objectify API as yegorich said. It is easier to use.</p>
1
2016-10-05T07:43:11Z
[ "python", "xml", "minidom" ]
Assign Jinja2 block variable from for loop in view
39,867,462
<p>How would I replace the the hard coded '<code>python</code>' with <code>snippet['language']</code> from a for loop in my view?</p> <pre><code>{% highlight 'python', lineno='inline' -%} {{snippet['code']}} {% endhighlight %} </code></pre>
0
2016-10-05T07:05:53Z
39,869,400
<p>You can simply put your variable in place of the hardcoded string like this:</p> <pre><code>{% set lang = 'python' %} {% highlight lang %} from fridge import Beer glass = Beer(lt=500) glass.drink() {% endhighlight %} </code></pre> <p>You haven't showed us your for-loop, but in principle you can do the same thing in the for-loop too:</p> <pre><code>{% for lang in ['python', 'ruby', 'scheme'] %} {% highlight lang %} from fridge import Beer {% endhighlight %} {% endfor %} </code></pre>
0
2016-10-05T08:50:15Z
[ "python", "flask", "jinja2" ]
How to enable a button when some text is entered in tkinter entry widget?
39,867,526
<p>Currently i have a scenario where buttons are disabled.Now i want to enable the buttons when some input is entered by the user in tkinter entry widget.</p> <p>Please suggest.</p> <p>Thanks!</p>
-2
2016-10-05T07:08:58Z
39,867,661
<p>You can <code>bind()</code> function to <code>Entry</code> which will be executed when user press <code>&lt;Key&gt;</code>.</p> <p>See <code>bind()</code> and <code>&lt;Key&gt;</code> in <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">Events and Binding</a></p>
2
2016-10-05T07:16:20Z
[ "python", "tkinter" ]
How to enable a button when some text is entered in tkinter entry widget?
39,867,526
<p>Currently i have a scenario where buttons are disabled.Now i want to enable the buttons when some input is entered by the user in tkinter entry widget.</p> <p>Please suggest.</p> <p>Thanks!</p>
-2
2016-10-05T07:08:58Z
39,868,465
<p>You can follow this <a href="http://stackoverflow.com/questions/19148242/tkinter-entry-widget-is-detecting-input-text-possible">question</a> and as @Furas said you can bind function to Entry, something like this</p> <pre><code>from Tkinter import Tk, Entry root = Tk() frame = Frame(root) #"frame" represents the parent window, where the entry widget should be placed. frame.pack() #GUI widgets entry = Entry(frame, width=80) #The syntax of an entry widget entry.pack(side='right') #callbacks def enableEntry(): entry.configure(state="normal") entry.update() def disableEntry(): entry.configure(state="disabled") entry.update() def click(key): #print the key that was pressed print key.char var = StringVar() disableEnButton = Radiobutton(frame, text="Disable", variable=var, value="0", command=disableEntry) disableEnButton.pack(anchor=W) enableEnButton = Radiobutton(frame, text="Enable", variable=var, value="1", command=enableEntry) enableEnButton.pack(anchor=W) #Bind entry to any keypress entry.bind("&lt;Key&gt;", click) root.mainloop() #This is necessary for the event loop to service events such as button clicks </code></pre>
0
2016-10-05T08:01:07Z
[ "python", "tkinter" ]
How to test a FileField in Django REST Framework
39,867,672
<p>I have this serializer which I am trying to test:</p> <pre><code>class AttachmentSerializer(CustomModelSerializer): order = serializers.PrimaryKeyRelatedField() file = FileField() class Meta: model = Attachment fields = ( 'id', 'order', 'name', 'file_type', 'file', 'created_at', ) </code></pre> <p>My test simply checks whether it is valid or not:</p> <pre><code> def test_serializer_create(self): self.data = { 'order': self.order.pk, 'name': 'sample_name', 'file_type': 'image', 'created_at': datetime.now(), 'file': open(self.image_path, 'rb').read() } serializer = AttachmentSerializer(data=self.data) self.assertTrue(serializer.is_valid()) </code></pre> <p>And I am constantly getting this error:</p> <pre><code>{'file': ['No file was submitted. Check the encoding type on the form.']} </code></pre> <p>I tried to create a file in a number of different ways, such as with StringIO/BytesIO, File and etc. to no avail.</p> <p>What might be wrong?</p>
0
2016-10-05T07:17:02Z
39,869,073
<p>The thing is that you pass an opened file to the APIClient / APIRequestFactory, not to the view itself. The Django request will wraps the file to an <a href="https://docs.djangoproject.com/en/1.10/ref/files/uploads/#uploaded-files" rel="nofollow"><code>UploadedFile</code></a> which is what you should use.</p>
0
2016-10-05T08:35:16Z
[ "python", "django", "serialization", "django-rest-framework" ]
Embed a file line by line in Combo Box in Python Qt
39,867,697
<p>I am having a situation in which I have to fill <code>Combo Box</code> with data available in a file. Mine approach is</p> <pre><code>self.cmbBusListBox.addItem("Select ..") lines = [line.rstrip('\n') for line in open('i2coutput.cfg')] for line in lines: self.cmbBusListBox.addItem(line) self.cmbBusListBox.currentIndexChanged.connect(self.selectBusChange) </code></pre> <p>This process giving me error:</p> <pre><code>Traceback (most recent call last): File "I2CMain.py", line 3, in &lt;module&gt; from Py4 import QtGui, QtCore ImportError: No module named Py4 </code></pre> <p>In any file handling process for data populating from file in <code>Combo Box</code> giving same error. Please guide me. Thanks in advance. </p>
0
2016-10-05T07:18:35Z
39,867,982
<p><code>No module named Py4</code> but there is one named <code>PyQt4</code>:</p> <pre><code>from PyQt4 import QtGui, QtCore </code></pre> <p>It's just a typo in import statement and has nothing with combobox populating.</p>
0
2016-10-05T07:34:13Z
[ "python", "linux", "pyqt4" ]
Getting good accuracy but very low precision for classification task on an unbalanced dataset
39,867,753
<p>I have an unbalanced dataset , where the positive class is about 10,000 entries and the negative class is some 8,00,000 entries. I am trying a simple scikit's LogisticRegression model as a base line model, with class_weight='balanced' (hopefully unbalanced problem should be solved?).</p> <p>However, I am getting an accuracy score of 0.83, but a precision score of 0.03. What could be the issue? Do I need to handle the unbalanced part separately?</p> <p>This is my current code:</p> <pre><code>&gt;&gt;&gt; train = [] &gt;&gt;&gt; target = [] &gt;&gt;&gt; len(posList) ... 10214 &gt;&gt;&gt; len(negList) ... 831134 &gt;&gt;&gt; for entry in posList: ... train.append(entry) ... target.append(1) ... &gt;&gt;&gt; for entry in negList: ... train.append(entry) ... target.append(-1) ... &gt;&gt;&gt; train = np.array(train) &gt;&gt;&gt; target = np.array(target) &gt;&gt;&gt; &gt;&gt;&gt; X_train, X_test, y_train, y_test = train_test_split(train, target, test_size=0.3, random_state=42) &gt;&gt;&gt; &gt;&gt;&gt; model = LogisticRegression(class_weight='balanced') &gt;&gt;&gt; model.fit(X_train, y_train) LogisticRegression(C=1.0, class_weight='balanced', dual=False, fit_intercept=True, intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1, penalty='l2', random_state=None, solver='liblinear', tol=0.0001, verbose=0, warm_start=False) &gt;&gt;&gt; &gt;&gt;&gt; predicted = model.predict(X_test) &gt;&gt;&gt; &gt;&gt;&gt; metrics.accuracy_score(y_test, predicted) 0.835596671213 &gt;&gt;&gt; &gt;&gt;&gt; metrics.precision_score(y_test, predicted, average='weighted') /usr/local/lib/python2.7/dist-packages/sklearn/metrics/classification.py:976: DeprecationWarning: From version 0.18, binary input will not be handled specially when using averaged precision/recall/F-score. Please use average='binary' to report only the positive class performance. 'positive class performance.', DeprecationWarning) 0.033512518766 </code></pre>
0
2016-10-05T07:22:11Z
39,871,424
<p>I think I understand what is going on.</p> <p>Consider a dummy classifier that would return the majority class for each sample of your data set. For an unbalanced set like yours it seems pretty fair (let's call your positive class <em>class 1</em> and the negative one <em>class 0</em>). The classifier would have an accuracy of : <code>831134/(831134+10214.0) = 0.987859958067292</code>. Yes, <strong>an accuracy of 99%</strong>, but it doesn't give a good representation of your classifier. Instead, we'd better look at its <strong>precision</strong>. So since your data is really unbalanced (ratio <code>1:80</code>) the Logistic Regression performs poorly, but as for the dummy classifier, it has a high accuracy.</p> <p><strong>Precision</strong> is defined as the ratio of <em>true positives</em> and the sum of <em>true positives</em> and <em>false positives</em>. In other words, it is the proportion of <em>elements truly belonging to class 1</em> amongst <em>all the elements detected as belonging to class 1</em>.</p> <p>The accuracy of your LinearRegression classifier is <code>acc = 0.835596671213</code>. Thus, their is a difference of accuracy between the dummy classifier and the logistic regression of : <code>diff = 0.987859958067292 - 0.835596671213 = 0.15226328685429202</code>. So <strong>15%</strong> of the data has been <strong>misclassified</strong> by the dummy classifier, which corresponds to almost <code>n_misclass = 0.15*(831134+10214.0)=126202.2</code> samples. Thus, the Logistic regression classifies <strong>126202</strong> samples as being from <em>class 1</em> while they are only <strong>10214</strong>.</p> <p>The <strong>precision that Logistic Regression</strong> might then be something like : <code>prec = 10214/126202.0 = 0.081</code>.</p> <p>In your case it seems that it performs less good in terms of accuracy than what we've seen above. But that was roughly to give you a clue about what might be going on.</p>
0
2016-10-05T10:22:58Z
[ "python", "python-2.7", "scikit-learn" ]
How to replace a value in specific cell of a csv file?
39,868,100
<p>I want to make a python script which has a counter that replaces the current value of a specific cell in a CSV file. </p> <p>My code is : </p> <pre><code>with open(ctlLst[-1], 'rb') as csvfile: csvReader = csv.reader(csvfile) csvReader.next() for row in csvReader: if row[6]&gt;counter: newCTLcount=int(row[6])-counter #need to replace cell row[6] </code></pre> <p>The file looks like this: </p> <pre><code> InterfaceCode InterfaceSeqID OperatorCode CreationDateTime MintransactionDateTime MaxtransactionDateTime NoOfRows ControlFileName DataFileName 201 1170 30 20161005 04:30:27 20161004 06:55:56 20161005 03:08:37 8696 CTL_TripEventAndAlert_30_20161004.CSV TripEventAndAlert_30_20161004.CSV </code></pre> <p>In this example I need to replace the value of 8696 (on row 2 cell 6) with a new value (newCTLcount).</p>
1
2016-10-05T07:41:10Z
39,871,965
<p>Most probably it's a good idea to write while reading/parsing to save memory</p> <pre><code>with open('out.csv', 'wb') as outfile: with open(ctlLst[-1], 'rb') as csvfile: csvReader = csv.reader(csvfile) csvWriter = csv.writer(outfile) csvReader.next() for row in csvReader: row[6] = int(row[6]) # assumed as int if row[6] &gt; counter: row[6] -= counter outfile.writerow(row) </code></pre> <p>For Python 2 see <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> </p>
0
2016-10-05T10:49:45Z
[ "python", "csv" ]
How to replace a value in specific cell of a csv file?
39,868,100
<p>I want to make a python script which has a counter that replaces the current value of a specific cell in a CSV file. </p> <p>My code is : </p> <pre><code>with open(ctlLst[-1], 'rb') as csvfile: csvReader = csv.reader(csvfile) csvReader.next() for row in csvReader: if row[6]&gt;counter: newCTLcount=int(row[6])-counter #need to replace cell row[6] </code></pre> <p>The file looks like this: </p> <pre><code> InterfaceCode InterfaceSeqID OperatorCode CreationDateTime MintransactionDateTime MaxtransactionDateTime NoOfRows ControlFileName DataFileName 201 1170 30 20161005 04:30:27 20161004 06:55:56 20161005 03:08:37 8696 CTL_TripEventAndAlert_30_20161004.CSV TripEventAndAlert_30_20161004.CSV </code></pre> <p>In this example I need to replace the value of 8696 (on row 2 cell 6) with a new value (newCTLcount).</p>
1
2016-10-05T07:41:10Z
39,872,398
<p>got it...</p> <pre><code> rowData=[] with open(ctlLst[-1], 'rb') as csvfile: csvReader = csv.reader(csvfile) for row in csvReader: rowData.append(row) rowData[1][6]=int(rowData[1][6])-counter print ("new Row data count is " + str(rowData[1][6])) </code></pre> <p>thank's </p>
-1
2016-10-05T11:11:59Z
[ "python", "csv" ]
How to git fetch using gitpython?
39,868,114
<p>I am looking for a equivalent way to fetch in gitpython</p> <pre><code>git fetch --quiet --all </code></pre> <p>How can I perform git fetch in python?</p>
1
2016-10-05T07:42:14Z
39,868,183
<p>The <a href="http://gitpython.readthedocs.io/en/stable/reference.html?highlight=Fetch#module-git.remote" rel="nofollow"><code>fetch</code> method</a> is equivalent to issuing <code>git fetch</code>. Accordingly, you can fetch all your remotes by iterating and fetching each individually:</p> <pre><code>repo = git.Repo('name_of_repo') for remote in repo.remotes: remote.fetch() </code></pre>
3
2016-10-05T07:46:02Z
[ "python", "git", "gitpython" ]
How to plot a task schedule with matplotlib
39,868,191
<p>I have three lists of tuples containing start time, finish time and column allocation for different tasks. I want to plot these lists into a schedule in the following way: <a href="http://i.stack.imgur.com/hIBjR.png" rel="nofollow"><img src="http://i.stack.imgur.com/hIBjR.png" alt="enter image description here"></a> </p> <p>Here is the data:</p> <pre><code>time_start = [('a', 0), ('b', 1), ('c', 1), ('d', 3), ('e', 3), ('f', 3), ('g', 4)] time_finish = [('a', 1), ('b', 3), ('c', 3), ('d', 4), ('e', 4), ('f', 4), ('g', 6)] column_allocation = [('a', 'p1'), ('d', 'p1'), ('b', 'p1'), ('g', 'p1'), ('e', 'p2'), ('c', 'p2'), ('f', 'p3')] </code></pre> <p>Is this possible?</p>
0
2016-10-05T07:46:24Z
39,870,178
<p><a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.bar" rel="nofollow"><code>axes.bar</code></a> allows you to specify left position, height, and bottom coordinates of each bar, as well as a common width for all bars. Seems like a good fit for your problem.</p>
0
2016-10-05T09:25:40Z
[ "python", "python-2.7", "matplotlib", "plot" ]
Cpp compilation from python fail but not in the shell
39,868,209
<p>I have a <code>cpp</code> file that compiles fine with <code>g++</code> by using the shell:</p> <pre><code>extern "C"{ #include &lt;quadmath.h&gt; } inline char* print( const __float128&amp; val) { char* buffer = new char[128]; quadmath_snprintf(buffer,128,"%+.34Qe", val); return buffer; } int main(){ __float128 a = 1.0; print(a); return 0; } </code></pre> <p>However, when I try to compile it via a <code>python</code> scrit, it fails with the following error:</p> <blockquote> <p>"undefined reference to quadmath_snprintf"</p> </blockquote> <p>Here the code of the <code>python</code> script:</p> <pre><code>import commands import string import os (status, output) = commands.getstatusoutput("(g++ test/*.c -O3 -lquadmath -m64)") </code></pre> <p>Any idea how to solve this? Thanks.</p>
3
2016-10-05T07:47:38Z
39,868,750
<p>When you open a shell a whole of stuff is silently initialized for you, and most important for your issue, environment variables are set. What you most likely miss is the definition of <code>LIBRARY_PATH</code>, which is the variable used by the linker to look for libraries matching the ones you instruct it to link using the <code>-lNAME</code> flags. </p> <p>What the linker needs is a list of directories where it will search for files matching <code>libNAME.{a,so}</code>. You can also pass these directories directly using the <code>-L</code> flag, but in general, you should probably try to use a program like CMake, Make or any other build tool.</p> <p>This will give you access to commands like <code>find_package</code> and <code>target_link_libraries</code> (CMake), to find, respectively add libraries to your build targets, instead of having to maintain your python to compile your stuff.</p>
3
2016-10-05T08:16:44Z
[ "python", "c++", "g++" ]
scikit-learn package successfully updated, but continues to use/show old version
39,868,413
<p>I just got access to a new server which has Python 2.7 and some packages already installed. However, I need the newest version of scikit-learn (0.18.0). </p> <p>I tried to pip-upgrade the package, which returns the following affirmative message <code>Successfully installed scikit-learn Cleaning up...</code></p> <p>I used the following command, which worked for upgrading other packages (e.g. scipy):</p> <pre><code>OPENBLAS=/cluster/apps/openblas/0.2.13_seq/x86_64/gcc_5.2.0/lib python -m pip install --user --upgrade scikit-learn </code></pre> <p>When checking the version with <code>pip freeze</code> and <code>python -c 'import sklearn; print sklearn.__version__'</code> it continues to show the old version (0.17.1). In my home directory (I don't have root access) a folder named 'scikit_learn-0.18-py2.7.egg-info' was created.</p> <p>Can someone point out what I'm doing wrong?</p> <p>Edit: I'm on Centos 6 and packages like numpy and scipy worked just fine</p>
0
2016-10-05T07:58:12Z
39,879,221
<p>Hi I was in the same situation as you, in order to get the correct version of sklearn, before importing it, I added this line to my code:</p> <pre><code>import sys sys.path.insert(0, '/home/your_user_name/.local/lib/python2.7/site-packages/') </code></pre> <p>I am not quite sure about the path part, but basically I think it is</p> <pre><code>sys.path.insert(0, '$HOME/.local/lib/python2.7/site-packages/') </code></pre> <p>Hope this helps.</p>
1
2016-10-05T16:24:26Z
[ "python", "scikit-learn", "pip" ]
How to merge key values within dictionaries if they have a common key-value pair?
39,868,437
<p>I have a list of dictionaries,</p> <pre><code>list = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] </code></pre> <p>How do I make it so that the output looks like this:</p> <pre><code>outputList = [ { 'hostname': 'a', 'ipaddr': ['abcde', 'fghijkl', 'bbbbbb'] }, { 'hostname': 'b', 'ipaddr':'xxxx' } ] </code></pre> <hr> <p><strong>Edit</strong>: Before this step, I have filtered a JSON list of selected hostnames </p> <pre><code>['hostname1', 'hostname2', 'hostname3', 'hostname4' ......] </code></pre> <p>Then, given a huge JSON list of dictionaries (called "list" above), I have to sieve out the respective hostnames and ipaddresses, preferably grouped according to hostnames so that I can parse it elsewhere easily. </p>
0
2016-10-05T07:59:38Z
39,868,866
<pre><code>lists = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] hostnames = set([d['hostname'] for d in lists]) outputlist= list() for hostname in hostnames: od = { 'hostname': hostname, 'ipaddr': [] } for d in lists: if d['hostname'] == hostname: od['ipaddr'].append(d['ipaddr']) outputlist.append(od) </code></pre> <p>This solution assumes that all the dictionaries inside <code>lists</code> will contain the key <code>'hostname'</code>.</p>
2
2016-10-05T08:23:27Z
[ "python", "list", "dictionary", "merge" ]
How to merge key values within dictionaries if they have a common key-value pair?
39,868,437
<p>I have a list of dictionaries,</p> <pre><code>list = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] </code></pre> <p>How do I make it so that the output looks like this:</p> <pre><code>outputList = [ { 'hostname': 'a', 'ipaddr': ['abcde', 'fghijkl', 'bbbbbb'] }, { 'hostname': 'b', 'ipaddr':'xxxx' } ] </code></pre> <hr> <p><strong>Edit</strong>: Before this step, I have filtered a JSON list of selected hostnames </p> <pre><code>['hostname1', 'hostname2', 'hostname3', 'hostname4' ......] </code></pre> <p>Then, given a huge JSON list of dictionaries (called "list" above), I have to sieve out the respective hostnames and ipaddresses, preferably grouped according to hostnames so that I can parse it elsewhere easily. </p>
0
2016-10-05T07:59:38Z
39,868,914
<p>Here is one way:</p> <pre><code>inputList = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] outputList = {} for d in inputList: od = outputList.setdefault(d['hostname'], {}) od.setdefault('hostname', d['hostname']) od.setdefault('ipaddr', []).append(d['ipaddr']) outputList = sorted(outputList.values(), key=lambda x: x['hostname']) assert outputList == [ { 'hostname': 'a', 'ipaddr': ['abcde', 'fghijkl', 'bbbbbb'] }, { 'hostname': 'b', 'ipaddr':['xxxx'] } ] </code></pre>
1
2016-10-05T08:26:05Z
[ "python", "list", "dictionary", "merge" ]
How to merge key values within dictionaries if they have a common key-value pair?
39,868,437
<p>I have a list of dictionaries,</p> <pre><code>list = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] </code></pre> <p>How do I make it so that the output looks like this:</p> <pre><code>outputList = [ { 'hostname': 'a', 'ipaddr': ['abcde', 'fghijkl', 'bbbbbb'] }, { 'hostname': 'b', 'ipaddr':'xxxx' } ] </code></pre> <hr> <p><strong>Edit</strong>: Before this step, I have filtered a JSON list of selected hostnames </p> <pre><code>['hostname1', 'hostname2', 'hostname3', 'hostname4' ......] </code></pre> <p>Then, given a huge JSON list of dictionaries (called "list" above), I have to sieve out the respective hostnames and ipaddresses, preferably grouped according to hostnames so that I can parse it elsewhere easily. </p>
0
2016-10-05T07:59:38Z
39,868,998
<p>You can use below code:</p> <pre><code>list_1 = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] out_list = [] for each_dict in list_1: if out_list: for out_dict in out_list: if out_dict['hostname']==each_dict['hostname']: out_dict['ipaddr'].append(each_dict['ipaddr']) else: temp_dict = {} temp_dict['hostname']=each_dict['hostname'] temp_dict['ipaddr']=[each_dict['ipaddr'],] out_list.append(temp_dict) else: temp_dict = {} temp_dict['hostname']=each_dict['hostname'] temp_dict['ipaddr']=[each_dict['ipaddr'],] out_list.append(temp_dict) print out_list </code></pre>
0
2016-10-05T08:30:36Z
[ "python", "list", "dictionary", "merge" ]
How to merge key values within dictionaries if they have a common key-value pair?
39,868,437
<p>I have a list of dictionaries,</p> <pre><code>list = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] </code></pre> <p>How do I make it so that the output looks like this:</p> <pre><code>outputList = [ { 'hostname': 'a', 'ipaddr': ['abcde', 'fghijkl', 'bbbbbb'] }, { 'hostname': 'b', 'ipaddr':'xxxx' } ] </code></pre> <hr> <p><strong>Edit</strong>: Before this step, I have filtered a JSON list of selected hostnames </p> <pre><code>['hostname1', 'hostname2', 'hostname3', 'hostname4' ......] </code></pre> <p>Then, given a huge JSON list of dictionaries (called "list" above), I have to sieve out the respective hostnames and ipaddresses, preferably grouped according to hostnames so that I can parse it elsewhere easily. </p>
0
2016-10-05T07:59:38Z
39,869,020
<pre><code>from collections import defaultdict lst = [ {'hostname': 'a', 'ipaddr':'abcde'}, {'hostname': 'a', 'ipaddr':'fghijkl'}, {'hostname': 'a', 'ipaddr':'bbbbbb'}, {'hostname': 'b', 'ipaddr':'xxxx'} ] d = defaultdict(list) for item in lst: d[item['hostname']].append(item['ipaddr']) output = [dict(zip(['hostname', 'ipaddr'], item)) for item in d.items()] </code></pre>
0
2016-10-05T08:32:06Z
[ "python", "list", "dictionary", "merge" ]
Combining elements of a list if condition is met
39,868,527
<p>I have some python code, with its final output being a list:</p> <pre><code>['JAVS P 0 060107084657.30', '59.41 0 S', ' CEY P 0 060107084659.39', '03.10 0 S', 'CADS P 0 060107084703.67', 'VISS P 0 060107084704.14'] </code></pre> <p>Now, I would like to join the lines, that do not start with sta (JAVS, CEY, CADS, VISS,...) with the previous one. I get this element of the list with:</p> <pre><code>if not element.startswith(sta): print element </code></pre> <p>How to proceed with joining the elements?</p> <p>Final output should be like this:</p> <pre><code>[u'JAVS P 0 060107084657.30 59.41 0 S'] [u' CEY P 0 060107084659.39 03.10 0 S'] [u'CADS P 0 060107084703.67'] [u'VISS P 0 060107084704.14'] </code></pre> <p>Full code:</p> <pre><code>import glob from obspy import read_events import itertools ####### Definitions def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return itertools.izip(a, b) ####### Script #write_file = open("hypoell", "w") path = 'events/' event_files = glob.glob(path + '*.hyp') fmt_p = '%s %s %s %s' fmt_s = '%s %s %s' for event_file in event_files: cat = read_events(event_file) event = cat[0] lines = [] for pick in event.picks: sta = pick.waveform_id.station_code if len(sta) &lt;= 3: sta = " "+sta else: sta=sta phase = pick.phase_hint year = pick.time.year month = pick.time.month day = pick.time.day hh = pick.time.hour minute = pick.time.minute sec = pick.time.second ms = pick.time.microsecond p_time = pick.time.strftime("%Y%m%d%H%M%S.%f") p_time = p_time[2:-4] s_time = pick.time.strftime("%Y%m%d%H%M%S.%f") s_time = s_time[12:-4] if phase == "P": p_line = fmt_p %(sta, phase, 0, p_time) lines.append(str(p_line)) if phase == "S": s_line = fmt_s %(s_time, 0, "S") lines.append(str(s_line)) ######################################################################## print lines prefixes = ('JAVS', ' CEY', 'CADS', 'VISS') for a, b in pairwise(lines): if a[0].startswith(prefixes): if not b[0].startswith(prefixes): print a + b else: print a </code></pre>
2
2016-10-05T08:05:07Z
39,868,748
<p>You can use the <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>pairwise</code> recipe from <code>itertools</code></a> to itertate through your data in pairs.</p> <pre><code>import itertools mydata = [ [u'JAVS P 0 060107084657.30'], ['59.41 0 S'], [u' CEY P 0 060107084659.39'], ['03.10 0 S'], [u'CADS P 0 060107084703.67'], [u'VISS P 0 060107084704.14'], ] def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return itertools.izip(a, b) prefixes = ('JAVS', ' CEY', 'CADS', 'VISS') for a, b in pairwise(mydata): if a[0].startswith(prefixes): if not b[0].startswith(prefixes): print a + b else: print a </code></pre>
0
2016-10-05T08:16:40Z
[ "python" ]
Combining elements of a list if condition is met
39,868,527
<p>I have some python code, with its final output being a list:</p> <pre><code>['JAVS P 0 060107084657.30', '59.41 0 S', ' CEY P 0 060107084659.39', '03.10 0 S', 'CADS P 0 060107084703.67', 'VISS P 0 060107084704.14'] </code></pre> <p>Now, I would like to join the lines, that do not start with sta (JAVS, CEY, CADS, VISS,...) with the previous one. I get this element of the list with:</p> <pre><code>if not element.startswith(sta): print element </code></pre> <p>How to proceed with joining the elements?</p> <p>Final output should be like this:</p> <pre><code>[u'JAVS P 0 060107084657.30 59.41 0 S'] [u' CEY P 0 060107084659.39 03.10 0 S'] [u'CADS P 0 060107084703.67'] [u'VISS P 0 060107084704.14'] </code></pre> <p>Full code:</p> <pre><code>import glob from obspy import read_events import itertools ####### Definitions def pairwise(iterable): "s -&gt; (s0,s1), (s1,s2), (s2, s3), ..." a, b = itertools.tee(iterable) next(b, None) return itertools.izip(a, b) ####### Script #write_file = open("hypoell", "w") path = 'events/' event_files = glob.glob(path + '*.hyp') fmt_p = '%s %s %s %s' fmt_s = '%s %s %s' for event_file in event_files: cat = read_events(event_file) event = cat[0] lines = [] for pick in event.picks: sta = pick.waveform_id.station_code if len(sta) &lt;= 3: sta = " "+sta else: sta=sta phase = pick.phase_hint year = pick.time.year month = pick.time.month day = pick.time.day hh = pick.time.hour minute = pick.time.minute sec = pick.time.second ms = pick.time.microsecond p_time = pick.time.strftime("%Y%m%d%H%M%S.%f") p_time = p_time[2:-4] s_time = pick.time.strftime("%Y%m%d%H%M%S.%f") s_time = s_time[12:-4] if phase == "P": p_line = fmt_p %(sta, phase, 0, p_time) lines.append(str(p_line)) if phase == "S": s_line = fmt_s %(s_time, 0, "S") lines.append(str(s_line)) ######################################################################## print lines prefixes = ('JAVS', ' CEY', 'CADS', 'VISS') for a, b in pairwise(lines): if a[0].startswith(prefixes): if not b[0].startswith(prefixes): print a + b else: print a </code></pre>
2
2016-10-05T08:05:07Z
39,870,031
<p>Here is a simple loop assuming <code>mydata</code> is non-empty.</p> <pre><code>#!/usr/bin/env python mydata = [ [u'JAVS P 0 060107084657.30'], ['59.41 0 S'], [u' CEY P 0 060107084659.39'], ['03.10 0 S'], [u'CADS P 0 060107084703.67'], [u'VISS P 0 060107084704.14'], ] prefixes = (u'JAVS', u' CEY', u'CADS', u'VISS') a = [u''] for b in mydata: if a[0].startswith(prefixes): if not b[0].startswith(prefixes): print([a[0] + " " + b[0]]) else: print([a[0]]) a = b print([a[0]]) </code></pre> <p>with output </p> <pre><code>['JAVS P 0 060107084657.30 59.41 0 S'] [' CEY P 0 060107084659.39 03.10 0 S'] ['CADS P 0 060107084703.67'] ['VISS P 0 060107084704.14'] </code></pre>
0
2016-10-05T09:18:45Z
[ "python" ]
How to calculate metrics for one particular column from other columns in Pandas?
39,868,547
<p>I have a dataset where I need to calculate metrics related to each person on a dataset. For example, I have a dataframe with data that looks like this</p> <pre><code>id name age task_date task_venue money_earned 1 John 25 2016-05-01 A 100 2 Jane 28 2016-05-12 A 120 1 John 25 2016-05-03 B 150 3 Suse 21 2016-05-30 B 200 ... </code></pre> <p>So, what I need to do is calculate metrics for each person <code>John, Jane, Suse</code> etc., such as <code>Time Since Last Task</code>, <code>Average Earnings</code>, <code>Total Earnings</code>, <code>Total Tasks Done</code> and so on. </p> <p>The real dataset is large (around 1M rows and has a lot more columns ~50 and ~75K persons), but this explains essentially what I need to do. </p> <p>What would be the most efficient way to take this dataframe and do those calculations? I'd prefer do use pandas functions but pure python would also work as long as I can save the result in another dataframe?</p>
0
2016-10-05T08:06:12Z
39,868,627
<p>You need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.aggregate.html" rel="nofollow"><code>aggregate</code></a> metrics like for column <code>money_earned</code> <code>mean</code> and <code>sum</code>, for column <code>task_venue</code> <code>size</code> and so on:</p> <pre><code>print (df.groupby('name').agg({'money_earned':['mean', sum], 'task_venue': len})) task_venue money_earned len mean sum name Jane 1 120 120 John 2 125 250 Suse 1 200 200 </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation" rel="nofollow">Aggregation in pandas documentation</a>.</p> <hr> <p>After aggregation you get <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.html" rel="nofollow"><code>MultiIndex</code></a> in columns, you can flat it by <code>list comprehension</code>:</p> <pre><code>df1 = df.groupby('name').agg({'money_earned':['mean', sum], 'task_venue': len}) df1.columns = ['_'.join(col) for col in df1.columns] print (df1) task_venue_len money_earned_mean money_earned_sum name Jane 1 120 120 John 2 125 250 Suse 1 200 200 </code></pre> <hr> <p>If need aggregate custom function use:</p> <pre><code>df.task_date = pd.to_datetime(df.task_date) def f(x): #print (x) return x.min() + pd.Timedelta('3d') df1 = df.groupby('name').agg({'money_earned':['mean',sum], 'task_venue': len, 'task_date':f}) df1.columns = ['_'.join(col) for col in df1.columns] print (df1) task_venue_len task_date_f money_earned_mean money_earned_sum name Jane 1 2016-05-15 120 120 John 2 2016-05-04 125 250 Suse 1 2016-06-02 200 200 </code></pre> <hr> <p>If aggregation is slow, because big <code>DataFrame</code>, I suggest <a href="http://dask.pydata.org/en/latest/dataframe-api.html#dask.dataframe.DataFrame.reduction" rel="nofollow"><code>dask.dataframe.DataFrame.reduction</code></a>.</p>
2
2016-10-05T08:10:50Z
[ "python", "pandas", "optimization", "data-analysis", "data-science" ]
scrapy xpath can't get values
39,868,615
<p>I have a website and i would like to save two span element value.</p> <p>This is the relevant part of my html code:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="box-search-product-filter-row"&gt; &lt;span class="result-numbers" sth-bind="model.navigationSettings.showFilter"&gt; &lt;span class="number" sth-bind="span1"&gt;&lt;/span&gt; &lt;span class="result" sth-bind="span2"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>I create a spider:</p> <pre><code>from scrapy.spiders import Spider from scrapy.selector import Selector class MySpdier(Spider): name = "list" allowed_domains = ["example.com"] start_urls = [ "https://www.example.com"] def parse(self, response): sel = Selector(response) divs = sel.xpath("//div[@class='box-search-product-filter-row']") for div in divs: sth = div.xpath("/span[class='result']/text()").extract() print sth </code></pre> <p>When I crawl the spider, it prints only this:</p> <p><code>[]</code></p> <p>Can anybody help me how can I get the values from my two (class number, and class result) span element?</p>
0
2016-10-05T08:10:03Z
39,869,333
<p>You forgot <code>@</code> in your xpath <code>"/span[class='result']/text()"</code>. Furthermore the span you are looking for is not a 1st level child so you need to use <code>.//</code> instead of <code>/</code>. See: <a href="http://i.stack.imgur.com/xPxff.png" rel="nofollow"><img src="http://i.stack.imgur.com/xPxff.png" alt="enter image description here"></a> Source: <a href="http://www.w3schools.com/xsl/xpath_syntax.asp" rel="nofollow">http://www.w3schools.com/xsl/xpath_syntax.asp</a></p> <p>Complete and correct xpath would be: <code>".//span[@class='result']"</code> + '/text()' if you want to select only the text, but the nodes in your example have no text so it wouldn't work here.</p>
1
2016-10-05T08:46:49Z
[ "python", "xpath", "scrapy", "scrapy-spider" ]
scrapy xpath can't get values
39,868,615
<p>I have a website and i would like to save two span element value.</p> <p>This is the relevant part of my html code:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="box-search-product-filter-row"&gt; &lt;span class="result-numbers" sth-bind="model.navigationSettings.showFilter"&gt; &lt;span class="number" sth-bind="span1"&gt;&lt;/span&gt; &lt;span class="result" sth-bind="span2"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; </code></pre> <p>I create a spider:</p> <pre><code>from scrapy.spiders import Spider from scrapy.selector import Selector class MySpdier(Spider): name = "list" allowed_domains = ["example.com"] start_urls = [ "https://www.example.com"] def parse(self, response): sel = Selector(response) divs = sel.xpath("//div[@class='box-search-product-filter-row']") for div in divs: sth = div.xpath("/span[class='result']/text()").extract() print sth </code></pre> <p>When I crawl the spider, it prints only this:</p> <p><code>[]</code></p> <p>Can anybody help me how can I get the values from my two (class number, and class result) span element?</p>
0
2016-10-05T08:10:03Z
39,869,427
<p>This will work for you </p> <p><strong>EDIT:</strong></p> <pre><code>from scrapy.spiders import Spider from scrapy.selector import Selector class MySpdier(Spider): name = "list" allowed_domains = ["example.com"] start_urls = [ "https://www.example.com"] def parse(self, response): sel = Selector(response) divs = sel.xpath("//div[@class='box-search-product-filter-row']") for div in divs: sth = div.xpath(".//span[@class='result']/text()").extract() print sth </code></pre>
0
2016-10-05T08:51:37Z
[ "python", "xpath", "scrapy", "scrapy-spider" ]
How to add sqlalchemy.exc.IntegrityError as side effect to mock objects?
39,868,682
<p>I am testing a function that needs a mock object. This object might raise IntegrityError so I am adding this error as side effect to the mock object </p> <pre><code>def test_(self, mock_object): mock_object.side_effect = IntegrityError </code></pre> <p>This is somehow not correct as it raises an exception saying <code>__init__() takes at least 4 arguments (1 given)</code> What is the correct way of doing this?</p>
0
2016-10-05T08:13:27Z
39,868,889
<p>Just build a one-line function raising an integrity error, and adds that as the side-effect:</p> <pre><code>x = Mock() def b(): raise IntegrityError('Mock', 'mock', 'mock') x.side_effect = b x() </code></pre>
1
2016-10-05T08:24:52Z
[ "python", "unit-testing", "python-mock" ]
Concatenate list Object to cypher
39,868,743
<p>I am using Neo4j Bolt Driver and executing few queries where I have to check the node in a list of id's.</p> <p>Query:</p> <pre><code>MATCH (n)-[r]-&gt;(m) WHERE ID(n) in [1,2,3,4] RETURN n,r,m </code></pre> <p>Doing the same with python fails:</p> <pre><code>l = [1,2,3,4] query = 'MATCH (n)-[r]-&gt;(m) WHERE ID(n) in '+list+' RETURN n,r,m' </code></pre> <p>The execution fails with this error:</p> <pre><code>query = 'MATCH (n)-[r]-&gt;(m) WHERE ID(n)' in '+list+' RETURN n,r,m' TypeError: cannot concatenate 'str' and 'int' objects </code></pre> <p>How can we achieve this?</p>
1
2016-10-05T08:16:27Z
39,868,919
<p>Your <code>list</code> is not of type String (str). As there is no natural way of concatenation of <code>int</code> and <code>str</code>, you're getting this error.</p> <p>Making <code>list</code> string like <code>list = '[1,2,3,4]'</code> would help.</p> <p>Btw <code>list</code> is a reserved keyword in python. You should use a different name.</p>
1
2016-10-05T08:26:16Z
[ "python", "neo4j", "cypher" ]
Concatenate list Object to cypher
39,868,743
<p>I am using Neo4j Bolt Driver and executing few queries where I have to check the node in a list of id's.</p> <p>Query:</p> <pre><code>MATCH (n)-[r]-&gt;(m) WHERE ID(n) in [1,2,3,4] RETURN n,r,m </code></pre> <p>Doing the same with python fails:</p> <pre><code>l = [1,2,3,4] query = 'MATCH (n)-[r]-&gt;(m) WHERE ID(n) in '+list+' RETURN n,r,m' </code></pre> <p>The execution fails with this error:</p> <pre><code>query = 'MATCH (n)-[r]-&gt;(m) WHERE ID(n)' in '+list+' RETURN n,r,m' TypeError: cannot concatenate 'str' and 'int' objects </code></pre> <p>How can we achieve this?</p>
1
2016-10-05T08:16:27Z
39,876,915
<p>If you're using a driver, you should be using a parameter for this, which avoids all of the string mangling and stringification problems (which are explicitly recommended against):</p> <pre><code>query = 'MATCH (n)-[r]-&gt;(m) WHERE ID(n) in {id_list} RETURN n,r,m' params = {'id_list': [1, 2, 3, 4]} session.run(statement=query, parameters=params) </code></pre> <p>There are several components (labels, relationship types) that cannot be parameterized, but it makes your queries much faster and cleaner to use this feature when possible. Check out <a href="http://neo4j.com/docs/developer-manual/3.0/cypher/#cypher-parameters" rel="nofollow">the docs</a> for more about them.</p>
1
2016-10-05T14:36:25Z
[ "python", "neo4j", "cypher" ]
Minimizing the sum of 3 variables subject to equality and integrality constraints
39,868,762
<p>I am working on a programming (using Python) problem where I have to solve the following type of linear equation in 3 variables:</p> <p>x, y, z are all integers.</p> <p>Equation example: <code>2x + 5y + 8z = 14</code></p> <p>Condition: <code>Minimize x + y + z</code></p> <p>I have been trying to search for an algorithm for finding a solution to this, in an optimum way. If anybody has any idea please guide me through algorithm or code-sources.</p> <p>I am just curious, what can be done if this problem is extrapolated to n variables? </p> <p>I don't want to use hit &amp; trial loops to keep checking for values. Also, there may be a scenario that equation has no solution. </p> <p><strong>UPDATE</strong></p> <p>Adding lower bounds condition:</p> <pre><code>x, y, z &gt;= 0 x, y, z are natural </code></pre>
3
2016-10-05T08:17:09Z
39,868,807
<p>Any triple <em>(x, y, z)</em>, with <em>z = (14 - 2x - 5y) / 8</em>, satisfies your constraint. </p> <p>Note that <em>x + y + (14 - 2x - 5y) / 8</em> is unbounded from below. This function decreases when each of <em>x</em> and <em>y</em> decrease, with no finite minimum.</p>
3
2016-10-05T08:20:05Z
[ "python", "algorithm", "linear-programming", "integer-programming" ]
Minimizing the sum of 3 variables subject to equality and integrality constraints
39,868,762
<p>I am working on a programming (using Python) problem where I have to solve the following type of linear equation in 3 variables:</p> <p>x, y, z are all integers.</p> <p>Equation example: <code>2x + 5y + 8z = 14</code></p> <p>Condition: <code>Minimize x + y + z</code></p> <p>I have been trying to search for an algorithm for finding a solution to this, in an optimum way. If anybody has any idea please guide me through algorithm or code-sources.</p> <p>I am just curious, what can be done if this problem is extrapolated to n variables? </p> <p>I don't want to use hit &amp; trial loops to keep checking for values. Also, there may be a scenario that equation has no solution. </p> <p><strong>UPDATE</strong></p> <p>Adding lower bounds condition:</p> <pre><code>x, y, z &gt;= 0 x, y, z are natural </code></pre>
3
2016-10-05T08:17:09Z
39,869,034
<p>From your first equation:</p> <p>x = (14 - 5y - 8x) / 2</p> <p>so, you now only need to minimize</p> <p>(14 - 5y - 8z) / 2 + y + z</p> <p>which is</p> <p>(14 - 3y - 6z) / 2</p> <p>But we can ignore the ' / 2' part for minimization purposes.</p> <p>Presumably, there must be some other constraints on your problem, since as described the solution is that both y and z may grow without bound.</p>
0
2016-10-05T08:33:03Z
[ "python", "algorithm", "linear-programming", "integer-programming" ]
Minimizing the sum of 3 variables subject to equality and integrality constraints
39,868,762
<p>I am working on a programming (using Python) problem where I have to solve the following type of linear equation in 3 variables:</p> <p>x, y, z are all integers.</p> <p>Equation example: <code>2x + 5y + 8z = 14</code></p> <p>Condition: <code>Minimize x + y + z</code></p> <p>I have been trying to search for an algorithm for finding a solution to this, in an optimum way. If anybody has any idea please guide me through algorithm or code-sources.</p> <p>I am just curious, what can be done if this problem is extrapolated to n variables? </p> <p>I don't want to use hit &amp; trial loops to keep checking for values. Also, there may be a scenario that equation has no solution. </p> <p><strong>UPDATE</strong></p> <p>Adding lower bounds condition:</p> <pre><code>x, y, z &gt;= 0 x, y, z are natural </code></pre>
3
2016-10-05T08:17:09Z
39,869,597
<p>I do not know any general fast solution for n variables, or not using hit &amp; trail loops. But for the given specific equation <code>2x + 5y + 8z = 14</code>, there maybe some shortcut based on observation.</p> <p>Notice that the range is very small for any possible solutions: </p> <p><code>0&lt;=x&lt;=7</code>, <code>0&lt;=y&lt;=2</code>, <code>0&lt;=z&lt;=1</code></p> <p>Also other than x = 7, you have at least to use 2 variables. <strong>(x+y+z = 7 for this case)</strong></p> <hr> <p>Let's find what we got if using only 2 variables:</p> <p>If you choose to use (x,z) or (y,z), as <code>z</code> can only be 1, <code>x</code> or <code>y</code> is trivial. </p> <p><strong>(x+y+z = 4 for (x,z), no solution for (y,z))</strong></p> <p>If you choose to use (x,y), as <code>x</code>'s coefficient is even and <code>y</code>'s coefficient is odd, you must choose even number of <code>y</code> to achieve an even R.H.S. (14). Which means <code>y</code> must be 2, <code>x</code> is then trivial.</p> <p><strong>(x+y+z = 4 for this case)</strong></p> <hr> <p>Let's find what we got if using all 3 variables:</p> <p>Similarly, <code>z</code> must be 1, so basically it's using 2 variables (x,y) to achieve 14-8 = 6 which is even.</p> <p>Again we use similar argument, so we must choose even number of <code>y</code> which is 2, however at this point 2y + 1z > 14 already, which means there is <strong>no solution using all 3 variables</strong>.</p> <hr> <p>Therefore simply by logic, reduce the equation by using 1 or 2 variables, we can find that <strong>minimum x+y+z is 4</strong> to achieve 14 <strong>(x=3,y=0,z=1 or x=2,y=2,z=0)</strong></p>
0
2016-10-05T09:00:03Z
[ "python", "algorithm", "linear-programming", "integer-programming" ]
Minimizing the sum of 3 variables subject to equality and integrality constraints
39,868,762
<p>I am working on a programming (using Python) problem where I have to solve the following type of linear equation in 3 variables:</p> <p>x, y, z are all integers.</p> <p>Equation example: <code>2x + 5y + 8z = 14</code></p> <p>Condition: <code>Minimize x + y + z</code></p> <p>I have been trying to search for an algorithm for finding a solution to this, in an optimum way. If anybody has any idea please guide me through algorithm or code-sources.</p> <p>I am just curious, what can be done if this problem is extrapolated to n variables? </p> <p>I don't want to use hit &amp; trial loops to keep checking for values. Also, there may be a scenario that equation has no solution. </p> <p><strong>UPDATE</strong></p> <p>Adding lower bounds condition:</p> <pre><code>x, y, z &gt;= 0 x, y, z are natural </code></pre>
3
2016-10-05T08:17:09Z
39,888,287
<p>Another tool to solve this type of problems is <a href="http://scip.zib.de" rel="nofollow">SCIP</a>. There is also an easy to use Python interface available on GitHub: <a href="https://github.com/SCIP-Interfaces/PySCIPOpt" rel="nofollow">PySCIPOpt</a>.</p> <p>In general (mixed) integer programming problems are very hard to solve (NP complexity) and often even simple looking instances with only a few variables and constraints can take hours to prove the optimal solution.</p>
0
2016-10-06T05:38:45Z
[ "python", "algorithm", "linear-programming", "integer-programming" ]
Increment slice object?
39,868,870
<p>Is it possible to change the values in a python slice object?</p> <p>For example, if I have </p> <pre><code>slice(0,1,None) </code></pre> <p>How would I, in effect, add 1 to the start and end values and so convert this to:</p> <pre><code>slice(1,2,None) </code></pre>
1
2016-10-05T08:23:41Z
39,868,968
<p>Not exactly elegant, but it works:</p> <pre><code>&gt;&gt;&gt; s1 = slice(0,1,None) &gt;&gt;&gt; s2 = slice(s1.start + 1, s1.stop + 1, s1.step) &gt;&gt;&gt; s2 slice(1, 2, None) &gt;&gt;&gt; </code></pre>
3
2016-10-05T08:29:12Z
[ "python", "slice" ]
Is there a way to get the labels of running GTK applications?
39,868,883
<p>I am trying to extract labels of widgets of running GTK applications. I tried using GtkParasite but I have no idea how to get it working in my python program.</p> <p>I want to be able to get the widgets and their labels of a gtk application that is running on my computer. It means that if I run gedit on my system then i want to get the labels of the widgets at run time. I hope this makes sense.</p> <p>Is there a way to use the C library of GTK to get an instance of a running GTK application?</p> <p>Thanks in advance.</p>
2
2016-10-05T08:24:34Z
39,870,918
<p>You probably should use accessibility libraries - those are tools that allow eg. screen readers to read GUI labels for visually impaired users. On Linux, <a href="https://en.wikipedia.org/wiki/Assistive_Technology_Service_Provider_Interface">at-spi2</a> seems to be the de-facto standard.</p> <p>For Python, take look at at-spi examples: <a href="https://github.com/infapi00/at-spi2-examples">https://github.com/infapi00/at-spi2-examples</a></p>
5
2016-10-05T09:58:18Z
[ "python", "python-2.7", "gtk", "pygtk", "gtk3" ]
Unlucky number 13
39,868,990
<p>I came accorss this problem <a href="http://qa.geeksforgeeks.org/4344/the-unlucky-13" rel="nofollow">Unlucky number 13! </a> recently but could not think of efficient solution this.</p> <h3>Problem statement :</h3> <p>N is taken as input. </p> <blockquote> <p>N can be very large 0&lt;= N &lt;= 1000000009</p> </blockquote> <p>Find total number of such strings that are made of exactly N characters which don't include "13". The strings may contain any integer from 0-9, repeated any number of times.</p> <pre><code># Example: # N = 2 : # output : 99 (0-99 without 13 number) # N =1 : # output : 10 (0-9 without 13 number) </code></pre> <p>My solution:</p> <pre><code>N = int(raw_input()) if N &lt; 2: print 10 else: without_13 = 10 for i in range(10, int('9' * N)+1): string = str(i) if string.count("13") &gt;= 1: continue without_13 += 1 print without_13 </code></pre> <h2>Output</h2> <p>The output file should contain answer to each query in a new line modulo 1000000009.</p> <p>Any other efficient way to solve this ? My solution gives time limit exceeded on coding site.</p>
5
2016-10-05T08:30:24Z
39,869,632
<p>I get the feeling that this question is designed with the expectation that you would initially instinctively do it the way you have. However, I believe there's a slightly different approach that would be faster.</p> <p>You can produce all the numbers that contain the number 13 yourself, without having to loop through all the numbers in between. For example:</p> <p>2 digits: 13</p> <p>3 digits position 1: 113 213 313 etc.</p> <p>3 digits position 2: 131 132 133 etc.</p> <p>Therefore, you don't have to check all the number from 0 to n*9. You simply count all the numbers with 13 in them until the length is larger than N.</p> <p>This may not be the fastest solution (in fact I'd be surprised if this couldn't be solved efficiently by using some mathematics trickery) but I believe it will be more efficient than the approach you have currently taken.</p>
5
2016-10-05T09:01:52Z
[ "python" ]
Unlucky number 13
39,868,990
<p>I came accorss this problem <a href="http://qa.geeksforgeeks.org/4344/the-unlucky-13" rel="nofollow">Unlucky number 13! </a> recently but could not think of efficient solution this.</p> <h3>Problem statement :</h3> <p>N is taken as input. </p> <blockquote> <p>N can be very large 0&lt;= N &lt;= 1000000009</p> </blockquote> <p>Find total number of such strings that are made of exactly N characters which don't include "13". The strings may contain any integer from 0-9, repeated any number of times.</p> <pre><code># Example: # N = 2 : # output : 99 (0-99 without 13 number) # N =1 : # output : 10 (0-9 without 13 number) </code></pre> <p>My solution:</p> <pre><code>N = int(raw_input()) if N &lt; 2: print 10 else: without_13 = 10 for i in range(10, int('9' * N)+1): string = str(i) if string.count("13") &gt;= 1: continue without_13 += 1 print without_13 </code></pre> <h2>Output</h2> <p>The output file should contain answer to each query in a new line modulo 1000000009.</p> <p>Any other efficient way to solve this ? My solution gives time limit exceeded on coding site.</p>
5
2016-10-05T08:30:24Z
39,869,693
<p>I think this can be solved via recursion:</p> <pre><code>ans(n) = { ans([n/2])^2 - ans([n/2]-1)^2 }, if n is even ans(n) = { ans([n/2]+1)*ans([n/2]) - ans([n/2])*ans([n/2]-1) }, if n is odd </code></pre> <p>Base Cases:</p> <ul> <li><code>ans(0)</code> = 1</li> <li><code>ans(1)</code> = 10</li> </ul> <p>It's implementation is running quite fast even for larger inputs like <code>10^9</code> ( which is expected as its complexity is <code>O(log[n])</code> instead of <code>O(n)</code> like the other answers ): </p> <pre><code>cache = {} mod = 1000000009 def ans(n): if cache.has_key(n): return cache[n] if n == 0: cache[n] = 1 return cache[n] if n == 1: cache[n] = 10 return cache[n] temp1 = ans(n/2) temp2 = ans(n/2-1) if (n &amp; 1) == 0: cache[n] = (temp1*temp1 - temp2*temp2) % mod else: temp3 = ans(n/2 + 1) cache[n] = (temp1 * (temp3 - temp2)) % mod return cache[n] print ans(1000000000) </code></pre> <p><a href="http://ideone.com/TNqxJw" rel="nofollow">Online Demo</a></p> <p><strong>Explanation:</strong></p> <p>Let a string <code>s</code> have even number of digits 'n'.<br> Let <code>ans(n)</code> be the answer for the input <code>n</code>, i.e. the number of strings without the substring <code>13</code> in them.<br> Therefore, the answer for string <code>s</code> having length <code>n</code> can be written as the multiplication of the answer for the first half of the string (<code>ans([n/2])</code>) and the answer for the second half of the string (<code>ans([n/2])</code>), minus the number of cases where the string <code>13</code> appears in the middle of the number <code>n</code>, i.e. when the last digit of the first half is <code>1</code> and the first digit of the second half is <code>3</code>.</p> <p>This can expressed mathematically as: </p> <pre><code>ans(n) = ans([n/2])^2 - ans([n/2]-1)*2 </code></pre> <p>Similarly for the cases where the input number <code>n</code> is odd, we can derive the following equation: </p> <pre><code>ans(n) = ans([n/2]+1)*ans([n/2]) - ans([n/2])*ans([n/2]-1) </code></pre>
4
2016-10-05T09:04:17Z
[ "python" ]
Unlucky number 13
39,868,990
<p>I came accorss this problem <a href="http://qa.geeksforgeeks.org/4344/the-unlucky-13" rel="nofollow">Unlucky number 13! </a> recently but could not think of efficient solution this.</p> <h3>Problem statement :</h3> <p>N is taken as input. </p> <blockquote> <p>N can be very large 0&lt;= N &lt;= 1000000009</p> </blockquote> <p>Find total number of such strings that are made of exactly N characters which don't include "13". The strings may contain any integer from 0-9, repeated any number of times.</p> <pre><code># Example: # N = 2 : # output : 99 (0-99 without 13 number) # N =1 : # output : 10 (0-9 without 13 number) </code></pre> <p>My solution:</p> <pre><code>N = int(raw_input()) if N &lt; 2: print 10 else: without_13 = 10 for i in range(10, int('9' * N)+1): string = str(i) if string.count("13") &gt;= 1: continue without_13 += 1 print without_13 </code></pre> <h2>Output</h2> <p>The output file should contain answer to each query in a new line modulo 1000000009.</p> <p>Any other efficient way to solve this ? My solution gives time limit exceeded on coding site.</p>
5
2016-10-05T08:30:24Z
39,869,878
<p>This a P&amp;C problem. I'm going to assume 0 is valid string and so is 00, 000 and so on, each being treated distinct from the other.</p> <p>The total number of strings not containing 13, of length N, is unsurprisingly given by:</p> <pre><code>(Total Number of strings of length N) - (Total number of strings of length N that have 13 in them) </code></pre> <p>Now, the Total number of strings of length N is easy, you have 10 digits and N slots to put them in: <code>10^N</code>.</p> <p>The number of strings of length N with 13 in them is a little trickier. You'd think you can do something like this:</p> <pre><code>=&gt; (N-1)C1 * 10^(N-2) =&gt; (N-1) * 10^(N-2) </code></pre> <p>But you'd be wrong, or more accurately, you'd be over counting certain strings. For example, you'd be over counting the set of string that have two or more 13s in them.</p> <p>What you really need to do is apply the <a href="https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle" rel="nofollow">inclusion-exclusion principle</a> to count the number of strings with 13 in them, so that they're all included once.</p> <p>If you look at this problem as a set counting problem, you have quite a few sets:</p> <pre><code>S(0,N): Set of all strings of Length N. S(1,N): Set of all strings of Length N, with at least one '13' in it. S(2,N): Set of all strings of Length N, with at least two '13's in it. ... S(N/2,N): Set of all strings of Length N, with at least floor(N/2) '13's in it. </code></pre> <p>You want the set of all strings with 13 in them, but counted at most once. You can use the inclusion-exclusion principle for computing that set.</p>
3
2016-10-05T09:12:20Z
[ "python" ]
Unlucky number 13
39,868,990
<p>I came accorss this problem <a href="http://qa.geeksforgeeks.org/4344/the-unlucky-13" rel="nofollow">Unlucky number 13! </a> recently but could not think of efficient solution this.</p> <h3>Problem statement :</h3> <p>N is taken as input. </p> <blockquote> <p>N can be very large 0&lt;= N &lt;= 1000000009</p> </blockquote> <p>Find total number of such strings that are made of exactly N characters which don't include "13". The strings may contain any integer from 0-9, repeated any number of times.</p> <pre><code># Example: # N = 2 : # output : 99 (0-99 without 13 number) # N =1 : # output : 10 (0-9 without 13 number) </code></pre> <p>My solution:</p> <pre><code>N = int(raw_input()) if N &lt; 2: print 10 else: without_13 = 10 for i in range(10, int('9' * N)+1): string = str(i) if string.count("13") &gt;= 1: continue without_13 += 1 print without_13 </code></pre> <h2>Output</h2> <p>The output file should contain answer to each query in a new line modulo 1000000009.</p> <p>Any other efficient way to solve this ? My solution gives time limit exceeded on coding site.</p>
5
2016-10-05T08:30:24Z
39,870,385
<p>In fact this question is more about math than about python. For N figures there is 10^N possible unique strings. To get the answer to the problem we need to subtract the number of string containing "13". If string starts from "13" we have 10^(N-2) possible unique strings. If we have 13 at the second possition (e.i. a string like x13...), we again have 10^(N-2) possibilities. But we can't continue this logic further as this will lead us to double calculation of string which have 13 at different possitions. For example for N=4 there will be a string "1313" which we will calculate twice. To avoid this we should calculate only those strings which we haven't calculated before. So for "13" on possition <code>p</code> (counting from 0) we should find the number of unique string which don't have "13" on the left side from <code>p</code>, that is for each p number_of_strings_for_13_at_p = total_number_of_strings_without_13(N=p-1) * 10^(N-p-2) So we recursevily define the total_number_of_strings_without_13 function.</p> <p>Here is the idea in the code:</p> <pre><code>def number_of_strings_without_13(N): sum_numbers_with_13 = 0 for p in range(N-1): if p &lt; 2: sum_numbers_with_13 += 10**(N-2) else: sum_numbers_with_13 += number_of_strings_without_13(p) * 10**(N-p-2) return 10**N - sum_numbers_with_13 </code></pre> <p>I should say that <code>10**N</code> means 10 in the power of N. All the other is described above. The functions also has a surprisingly pleasent ability to give correct answers for N=1 and N=2.</p> <p>To test this works correct I've rewritten your code into function and refactored a little bit:</p> <pre><code>def number_of_strings_without_13_bruteforce(N): without_13 = 0 for i in range(10**N): if str(i).count("13"): continue without_13 += 1 return without_13 for N in range(1, 7): print(number_of_strings_without_13(N), number_of_strings_without_13_bruteforce(N)) </code></pre> <p>They gave the same answers. With bigger N bruteforce is very slow. But for very large N recursive function also gets mush slower. There is a well known solution for that: as we use the value of <code>number_of_strings_without_13</code> with parameters smaller than N multiple times, we should remember the answers and not recalculate them each time. It's quite simple to do like this:</p> <pre><code>def number_of_strings_without_13(N, answers=dict()): if N in answers: return answers[N] sum_numbers_with_13 = 0 for p in range(N-1): if p &lt; 2: sum_numbers_with_13 += 10**(N-2) else: sum_numbers_with_13 += number_of_strings_without_13(p) * 10**(N-p-2) result = 10**N - sum_numbers_with_13 answers[N] = result return result </code></pre>
2
2016-10-05T09:34:14Z
[ "python" ]
Unlucky number 13
39,868,990
<p>I came accorss this problem <a href="http://qa.geeksforgeeks.org/4344/the-unlucky-13" rel="nofollow">Unlucky number 13! </a> recently but could not think of efficient solution this.</p> <h3>Problem statement :</h3> <p>N is taken as input. </p> <blockquote> <p>N can be very large 0&lt;= N &lt;= 1000000009</p> </blockquote> <p>Find total number of such strings that are made of exactly N characters which don't include "13". The strings may contain any integer from 0-9, repeated any number of times.</p> <pre><code># Example: # N = 2 : # output : 99 (0-99 without 13 number) # N =1 : # output : 10 (0-9 without 13 number) </code></pre> <p>My solution:</p> <pre><code>N = int(raw_input()) if N &lt; 2: print 10 else: without_13 = 10 for i in range(10, int('9' * N)+1): string = str(i) if string.count("13") &gt;= 1: continue without_13 += 1 print without_13 </code></pre> <h2>Output</h2> <p>The output file should contain answer to each query in a new line modulo 1000000009.</p> <p>Any other efficient way to solve this ? My solution gives time limit exceeded on coding site.</p>
5
2016-10-05T08:30:24Z
39,871,874
<p>Let <code>f(n)</code> be the number of sequences of length n that have no "13" in them, and <code>g(n)</code> be the number of sequences of length n that have "13" in them.</p> <p>Then <code>f(n) = 10^n - g(n)</code> (in mathematical notation), because it's the number of possible sequences (<code>10^n</code>) minus the ones that contain "13".</p> <p>Base cases:</p> <pre><code>f(0) = 1 g(0) = 0 f(1) = 10 g(1) = 0 </code></pre> <p>When looking for the sequences <em>with</em> "13", a sequence can have a "13" at the beginning. That will account for <code>10^(n-2)</code> possible sequences with "13" in them. It could also have a "13" in the second position, again accounting for <code>10^(n-2)</code> possible sequences. But if it has a "13" in the <em>third</em> position, and we'd assume there would also be <code>10^(n-2)</code> possible sequences, we could those twice that already had a "13" in the first position. So we have to substract them. Instead, we count <code>10^(n-4)</code> times <code>f(2)</code> (because those are exactly the combinations in the first two positions that don't have "13" in them).</p> <p>E.g. for g(5):</p> <pre><code>g(5) = 10^(n-2) + 10^(n-2) + f(2)*10^(n-4) + f(3)*10^(n-5) </code></pre> <p>We can rewrite that to look the same everywhere:</p> <pre><code>g(5) = f(0)*10^(n-2) + f(1)*10^(n-3) + f(2)*10^(n-4) + f(3)*10^(n-5) </code></pre> <p>Or simply the sum of <code>f(i)*10^(n-(i+2))</code> with <code>i</code> ranging from <code>0</code> to <code>n-2</code>.</p> <p>In Python:</p> <pre><code>from functools import lru_cache @lru_cache(maxsize=1024) def f(n): return 10**n - g(n) @lru_cache(maxsize=1024) def g(n): return sum(f(i)*10**(n-(i+2)) for i in range(n-1)) # range is exclusive </code></pre> <p>The <code>lru_cache</code> is optional, but often a good idea when working with recursion.</p> <hr> <pre><code>&gt;&gt;&gt; [f(n) for n in range(10)] [1, 10, 99, 980, 9701, 96030, 950599, 9409960, 93149001, 922080050] </code></pre> <p>The results are instant and <s>it works for very large numbers</s>.</p>
2
2016-10-05T10:45:03Z
[ "python" ]
Unlucky number 13
39,868,990
<p>I came accorss this problem <a href="http://qa.geeksforgeeks.org/4344/the-unlucky-13" rel="nofollow">Unlucky number 13! </a> recently but could not think of efficient solution this.</p> <h3>Problem statement :</h3> <p>N is taken as input. </p> <blockquote> <p>N can be very large 0&lt;= N &lt;= 1000000009</p> </blockquote> <p>Find total number of such strings that are made of exactly N characters which don't include "13". The strings may contain any integer from 0-9, repeated any number of times.</p> <pre><code># Example: # N = 2 : # output : 99 (0-99 without 13 number) # N =1 : # output : 10 (0-9 without 13 number) </code></pre> <p>My solution:</p> <pre><code>N = int(raw_input()) if N &lt; 2: print 10 else: without_13 = 10 for i in range(10, int('9' * N)+1): string = str(i) if string.count("13") &gt;= 1: continue without_13 += 1 print without_13 </code></pre> <h2>Output</h2> <p>The output file should contain answer to each query in a new line modulo 1000000009.</p> <p>Any other efficient way to solve this ? My solution gives time limit exceeded on coding site.</p>
5
2016-10-05T08:30:24Z
39,879,256
<p>Thanks to L3viathan's comment now it is clear. The logic is beautiful.</p> <p>Let's assume <code>a(n)</code> is a number of strings of <code>n</code> digits without "13" in it. If we know all the good strings for <code>n-1</code>, we can add one more digit to the left of each string and calculate <code>a(n)</code>. As we can combine previous digits with any of 10 new, we will get <code>10*a(n-1)</code> different strings. But we must subtract the number of strings, which now starts with "13" which we wrongly summed like OK at previous step. There is <code>a(n-2)</code> of such wrongly adde strings. So <code>a(n+1) = 10*a(n-1) - a(n-2)</code>. That is it. Such simple.</p> <p>What is even more interesting is that this sequence can be calculated without iterations with a formula <a href="https://oeis.org/A004189" rel="nofollow">https://oeis.org/A004189</a> But practically that doesn't helps much, as the formula requires floating point calculations which will lead to rounding and would not work for big n (will give answer with some mistake).</p> <p>Nevertheless the original sequence is quite easy to calculate and it doesn't need to store all the previous values, just the last two. So here is the code</p> <pre><code>def number_of_strings(n): result = 0 result1 = 99 result2 = 10 if n == 1: return result2 if n == 2: return result1 for i in range(3, n+1): result = 10*result1 - result2 result2 = result1 result1 = result return result </code></pre> <p>This one is several orders faster than my previous suggestion. And memory consumption is now just O(n)</p> <p>P.S. If you run this with Python2, you'd better change <code>range</code> to <code>xrange</code></p>
2
2016-10-05T16:26:24Z
[ "python" ]
\MongoDB\BSON\Regex in aggregation pipeline - Convert regex from Python to PHP
39,868,993
<p>I'm trying to match some input parameters in my API call using the newer Regex library in PHP, but it's not working so far. I'm using string interpolation to achieve this, but its returning any results. Here is my code:</p> <pre><code>$regex = new \MongoDB\BSON\Regex ("^{$this-&gt;device_id}:", 'i'); $pipeline = [ [ '$match' =&gt; [ '_id' =&gt; $regex, ]] </code></pre> <p>My document _id are of the type <code>'london_10:2016-10-05 09'</code> which is the <code>device_id:datehour</code>.</p> <p>When I var_dump the (string)$regex I get the following, which appears to be working:</p> <pre><code>string(15) "/^london_10:/i" </code></pre> <p>The issue is that when adding this to the pipeline, it returns an empty collection. I have equivalent code which is confirmed working but written in Python, and I need to rewrite it in PHP:</p> <pre><code> pipeline = [ { '$match': { "_id": re.compile("^%s:" %(self.device_id) ) } } ] </code></pre>
0
2016-10-05T08:30:29Z
39,869,209
<p>The original code in the question is actually correct - I found that the problem wasn't in this part of my pipeline, but further downstream.</p>
0
2016-10-05T08:41:29Z
[ "php", "python", "regex", "mongodb", "aggregate" ]
re.sub: non-greedy doesn't work as expected
39,869,136
<p>I have the following code in ipython. I expect it to remove the beginning "ab" since .*? is a non-greedy one. But why it remove all the way up to the last b?</p> <pre><code> In [15]: b="abcabcabc" In [16]: re.sub(".*?b","",b) Out[16]: 'c' </code></pre>
1
2016-10-05T08:37:58Z
39,869,265
<p>That is because, by default, <code>re.sub()</code> will search and replace all occurrences </p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; b="abcabcabc" &gt;&gt;&gt; re.sub(".*?b","",b) 'c' &gt;&gt;&gt; re.sub("^.*?b","",b) 'cabcabc' &gt;&gt;&gt; re.sub(".*?b","",b, count=1) 'cabcabc' &gt;&gt;&gt; re.sub(".*?b","",b, count=2) 'cabc' </code></pre> <p><br> From <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow">doc</a></p> <pre><code>re.sub(pattern, repl, string, count=0, flags=0) </code></pre>
3
2016-10-05T08:44:06Z
[ "python", "regex" ]
re.sub: non-greedy doesn't work as expected
39,869,136
<p>I have the following code in ipython. I expect it to remove the beginning "ab" since .*? is a non-greedy one. But why it remove all the way up to the last b?</p> <pre><code> In [15]: b="abcabcabc" In [16]: re.sub(".*?b","",b) Out[16]: 'c' </code></pre>
1
2016-10-05T08:37:58Z
39,869,413
<p>The <em>python</em> <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow">docs</a> says:</p> <blockquote> <p>The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, <strong>all occurrences will be replaced</strong></p> </blockquote> <p>So, you can call <code>re.sub</code> with <code>count=1</code> to get your desired result:</p> <pre><code>re.sub(".*?b", "", b, 1) #output 'cabcabc' </code></pre>
1
2016-10-05T08:51:06Z
[ "python", "regex" ]
Error Capturing specific bounds
39,869,219
<p>hello python comunity,</p> <p>How do I stop this from looping?</p> <pre><code>error33 = int(2) while error33 &gt; 1: while True: try: survivalrateforjuveniles = float(input("Please enter the survival rate for poomen"))##Float input is being used as break except ValueError: print("Please enter a number between 0 and 1") continue else: break </code></pre> <p>Many Thanks</p>
-1
2016-10-05T08:41:45Z
39,869,517
<p>This works...</p> <pre><code>error33 = 2 while error33 &gt; 1: while True: try: survivalrateforjuveniles = float(input("Please enter the survival rate for poomen\n")) break except ValueError: print("Please enter a number between 0 and 1") continue else: error33 = 0 break </code></pre> <p>I do not know exactly what you are doing... but I think I would use somehting similar to this:</p> <pre><code>error33 = 2 survivalrateforjuveniles = -1.0 while error33 &gt; 1: while not (0 &lt; survivalrateforjuveniles &lt; 1): survivalrateforjuveniles = input("Please enter the survival rate for poomen\n") try: survivalrateforjuveniles = float(survivalrateforjuveniles) except ValueError: survivalrateforjuveniles = -1 print("Please enter a number between 0 and 1") print('do what you want') error33 =0 </code></pre> <p>Not so much different from your solution but you don't need the <code>break</code> and looks more robust. However, creating a function to read the <code>survivalrate...</code> and the other inputs (which I guess you have) would be much better since you would not use the same lines of code more than once (which is one of the basic practice to write good software).</p>
-2
2016-10-05T08:55:45Z
[ "python", "error-handling" ]
iItertools.product with variable validation
39,869,423
<p>I have this form of list</p> <pre><code>data = [ [ {'name': 's11', 'class': 'c1'}, {'name': 's12', 'class': 'c2'} ], [ {'name': 's21', 'class': 'c2'}, {'name': 's22', 'class': 'c2'} ], [ {'name': 's31', 'class': 'c1'}, {'name': 's32', 'class': 'c1'} ] ] </code></pre> <p>by using the <code>itertools.product(data)</code> I receive all the possible combinations needed by taking one element from each list in the main list data. What I want to do, I want to skip if the element in the first sublist have a different class in the second or third sublist.</p> <p>Does itertools.product provide any validation options for such case ?</p> <p>The expected results should be:</p> <pre><code>({'name': 's11', 'class': 'c1'},{'name': 's31', 'class': 'c1'}), ( {'name': 's11', 'class': 'c1'}, {'name': 's32', 'class': 'c1'}), ({'name': 's12', 'class': 'c2'},{'name': 's21', 'class': 'c2'}), ({'name': 's12', 'class': 'c2'},{'name': 's22', 'class': 'c2'}), </code></pre>
0
2016-10-05T08:51:33Z
39,869,749
<pre><code>from itertools import chain, combinations, product result = [ (a, b) for a, b in chain.from_iterable(product(*l) for l in combinations(data, 2)) if a['class'] == b['class'] ] </code></pre>
1
2016-10-05T09:06:59Z
[ "python", "list", "dictionary", "itertools" ]
iItertools.product with variable validation
39,869,423
<p>I have this form of list</p> <pre><code>data = [ [ {'name': 's11', 'class': 'c1'}, {'name': 's12', 'class': 'c2'} ], [ {'name': 's21', 'class': 'c2'}, {'name': 's22', 'class': 'c2'} ], [ {'name': 's31', 'class': 'c1'}, {'name': 's32', 'class': 'c1'} ] ] </code></pre> <p>by using the <code>itertools.product(data)</code> I receive all the possible combinations needed by taking one element from each list in the main list data. What I want to do, I want to skip if the element in the first sublist have a different class in the second or third sublist.</p> <p>Does itertools.product provide any validation options for such case ?</p> <p>The expected results should be:</p> <pre><code>({'name': 's11', 'class': 'c1'},{'name': 's31', 'class': 'c1'}), ( {'name': 's11', 'class': 'c1'}, {'name': 's32', 'class': 'c1'}), ({'name': 's12', 'class': 'c2'},{'name': 's21', 'class': 'c2'}), ({'name': 's12', 'class': 'c2'},{'name': 's22', 'class': 'c2'}), </code></pre>
0
2016-10-05T08:51:33Z
39,869,825
<p>Almost the same as @skovorodkin posted.</p> <pre><code>from itertools import product, chain data = [ [{'name': 's11', 'class': 'c1'}, {'name': 's12', 'class': 'c2'}], [{'name': 's21', 'class': 'c2'}, {'name': 's22', 'class': 'c2'}], [{'name': 's31', 'class': 'c1'}, {'name': 's32', 'class': 'c1'}] ] output = [i for i in product(data[0], chain.from_iterable(data[1:])) if i[0]['class'] == i[1]['class']] output </code></pre> <p>Output:</p> <pre><code>[({'class': 'c1', 'name': 's11'}, {'class': 'c1', 'name': 's31'}), ({'class': 'c1', 'name': 's11'}, {'class': 'c1', 'name': 's32'}), ({'class': 'c2', 'name': 's12'}, {'class': 'c2', 'name': 's21'}), ({'class': 'c2', 'name': 's12'}, {'class': 'c2', 'name': 's22'})] </code></pre> <p><strong>UPDATE</strong></p> <p>Just a little comparison. I just used the default data and the time results are the following:</p> <p>@skovorodkin answer:</p> <pre><code>&gt;&gt;&gt; %timeit result = [(a, b) for a, b in chain.from_iterable(product(*l) for l in combinations(data, 2)) if a['class'] == b['class']] The slowest run took 8.56 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 3.69 µs per loop </code></pre> <p>My answer:</p> <pre><code>&gt;&gt;&gt; %timeit output = [i for i in product(data[0], chain.from_iterable(data[1:])) if i[0]['class'] == i[1]['class']] The slowest run took 10.37 times longer than the fastest. This could mean that an intermediate result is being cached. 100000 loops, best of 3: 2.43 µs per loop </code></pre>
0
2016-10-05T09:10:26Z
[ "python", "list", "dictionary", "itertools" ]
update numpy array where not masked
39,869,524
<p>My question is twofolded</p> <p>First, lets say I've two numpy arrays, that are partially masked</p> <pre><code>array_old [[-- -- -- --] [10 11 -- --] [12 14 -- --] [-- -- 17 --]] array_update [[-- 5 -- --] [-- -- 9 --] [-- 15 8 13] [-- -- 19 16]] </code></pre> <p>How to get create a new array, where all non-masked values are updated or ammended, like:</p> <pre><code>array_new [[-- 5 -- --] [10 11 9 --] [12 15 8 13] [-- -- 19 16]] </code></pre> <p>Secondly, If possible, how to do above in a 3d numpy array?</p> <p><strong>UPDATE:</strong></p> <p>For the second part, now I use a for loop, using <a href="https://stackoverflow.com/a/39869892/2459096">@freidrichen</a> method as follows:</p> <pre><code>array = np.ma.masked_equal([[[0, 0, 0, 0], [10, 11, 0, 0], [12, 14, 0, 0], [0, 0, 17, 0]],[[0, 5, 0, 0], [0, 0, 9, 0], [0, 15, 8, 13], [0, 0, 19, 16]],[[0, 0, 0, 0], [5, 0, 0, 13], [8, 14, 0, 0], [0, 0, 17, 0]],[[6, 7, 8, 9], [0, 0, 0, 0], [0, 0, 0, 21], [0, 0, 0, 0]]], 0) a = array[0,::] for ix in range(array.shape[0] - 1): b = array[ix,::] c = array[ix+1,::] b[~c.mask] = c.compressed() a[~b.mask] = b.compressed() </code></pre> <p>Not sure if that's the best solution</p>
2
2016-10-05T08:56:17Z
39,869,892
<p>Use <code>a[~b.mask] = b.compressed()</code>.</p> <p><code>a[~b.mask]</code> selects all the values in <code>a</code> where <code>b</code> is not masked. <code>b.compressed()</code> is a flattened array with all the non-masked values in <code>b</code>.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; a = np.ma.masked_equal([[0, 0, 0, 0], [10, 11, 0, 0], [12, 14, 0, 0], [0, 0, 17, 0]], 0) &gt;&gt;&gt; b = np.ma.masked_equal([[0, 5, 0, 0], [0, 0, 9, 0], [0, 15, 8, 13], [0, 0, 19, 16]], 0) &gt;&gt;&gt; a[~b.mask] = b.compressed() &gt;&gt;&gt; a [[-- 5 -- --] [10 11 9 --] [12 15 8 13] [-- -- 19 16]] </code></pre> <p>This should work with 3d arrays too.</p>
5
2016-10-05T09:12:45Z
[ "python", "arrays", "numpy" ]
AxesSubplot' object has no attribute 'get_xdata' error when plotting OHLC matplotlib chart
39,869,546
<p>I am trying to make a OHLC graph plotted with matplotlib interactive upon the user clicking on a valid point. The data is stored as a pandas dataframe of the form</p> <pre><code>index PX_BID PX_ASK PX_LAST PX_OPEN PX_HIGH PX_LOW 2016-07-01 1.1136 1.1137 1.1136 1.1106 1.1169 1.1072 2016-07-04 1.1154 1.1155 1.1154 1.1143 1.1160 1.1098 2016-07-05 1.1076 1.1077 1.1076 1.1154 1.1186 1.1062 2016-07-06 1.1100 1.1101 1.1100 1.1076 1.1112 1.1029 2016-07-07 1.1062 1.1063 1.1063 1.1100 1.1107 1.1053 </code></pre> <p>I am plotting it with matplotlib's candlestick function:</p> <pre><code>candlestick2_ohlc(ax1, df['PX_OPEN'],df['PX_HIGH'],df['PX_LOW'],df['PX_LAST'],width=1) </code></pre> <p>When plotted it looks somthing like this:</p> <p><a href="http://i.stack.imgur.com/EC0oX.png" rel="nofollow"><img src="http://i.stack.imgur.com/EC0oX.png" alt=""></a></p> <p>I want the console to print out the value of the point clicked, the date and whether it is an open, high low or close. So far I have something like:</p> <pre><code>fig, ax1 = plt.subplots() ax1.set_picker(True) ax1.set_title('click on points', picker=True) ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red')) line = candlestick2_ohlc(ax1, df['PX_OPEN'],df['PX_HIGH'],df['PX_LOW'],df['PX_LAST'],width=0.4) def onpick1(event): if isinstance(event.artist, (lineCollection, barCollection)): thisline = event.artist xdata = thisline.get_xdata() ydata = thisline.get_ydata() ind = event.ind #points = tuple(zip(xdata[ind], ydata[ind])) #print('onpick points:', points) print( 'X='+str(np.take(xdata, ind)[0]) ) # Print X point print( 'Y='+str(np.take(ydata, ind)[0]) ) # Print Y point fig.canvas.mpl_connect('pick_event', onpick1) plt.show() </code></pre> <p>When I run this the graph appears however upon clicking anywhere on the graph it gives error: </p> <p>AttributeError: 'AxesSubplot' object has no attribute 'get_xdata'. Does the candlestick2_ohlc not support this? </p> <p>Additionally, what is the instance type of matplotlibs candlestick2_ohlc so I can check if the user has clicked on an actual point?</p> <p>For example for a line graph one could use check for</p> <pre><code>isinstance(event.artist,Line2D) </code></pre>
0
2016-10-05T08:57:32Z
39,875,387
<p>First of all, <code>candlestick2_ohlc</code> appears to create and return a tuple of a <code>matplotlib.collections.LineCollection</code> instance, and a <code>matplotlib.collections.PolyCollection</code> instance. </p> <p>We need to make each of these instances pickable, before we do anything else. </p> <p>If you grab those instances as they are returned from <code>candlestick2_ohlc</code>, this is an easy using <code>set_picker</code>:</p> <pre><code>linecoll, polycoll = candlestick2_ohlc(ax1, df['PX_OPEN'],df['PX_HIGH'],df['PX_LOW'],df['PX_LAST'],width=0.4) linecoll.set_picker(True) polycoll.set_picker(True) </code></pre> <p>They are what we need to check for in the <code>onpick1</code> function:</p> <pre><code>import matplotlib.collections as collections def onpick1(event): # Check we have clicked on one of the collections created by candlestick2_ohlc if isinstance(event.artist, (collections.LineCollection, collections.PolyCollection)): thiscollection = event.artist # Find which box or line we have clicked on ind = event.ind[0] # Find the vertices of the object verts = thiscollection.get_paths()[ind].vertices if isinstance(event.artist, collections.LineCollection): print "Errorbar line dimensions" elif isinstance(event.artist, collections.PolyCollection): print "Box dimensions" # Print the minimum and maximum extent of the object in x and y print( "X = {}, {}".format(verts[:, 0].min(), verts[:, 0].max()) ) print( "Y = {}, {}".format(verts[:, 1].min(), verts[:, 1].max()) ) </code></pre>
0
2016-10-05T13:31:02Z
[ "python", "pandas", "matplotlib", "graph", "interactive" ]
Reportlab + SimpleDocTemplate + Table - create QR code with text - multiple pages
39,869,671
<p>I'm using Reportlab to create a pdf file that can span across multiple pages with the following format:</p> <p>QR code + h1 paragraph + 2-3 lines of text</p> <p>We need to support a dynamic number of elements with the format I described above.</p> <p>I was thinking of using a Table inside a SimpleDocTemplate but couldn't find a way to support dynamic number of elements than can span over multiple pages.</p> <p>How would you tackle this challenge?</p>
0
2016-10-05T09:03:25Z
39,873,267
<p>This snippet is not fully working, but it could help you, for start </p> <pre><code>class StandardReport: def __init__(self,): self.doc = BaseDocTemplate(destinationPath , showBoundary = 0, leftMargin=0.7*cm, rightMargin=0.7*cm, topMargin=0.7*cm, bottomMargin=0.7*cm, pagesize=A4) self.simpleFrame = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height - 5*cm, id='normal') def createPdf(self): templates = []; self.doc.totalPages = 0; self.fill_sample(); templates.append(SamplePageTempalte(self)); self.doc.totalPages = self.doc.totalPages + 1; self.doc.addPageTemplates(templates); self.doc.build(self.Elements) class SamplePageTempalte (PageTemplate): def __init__ (self, context): self.context = context self.largeur = self.context.doc.pagesize[0] self.hauteur = self.context.doc.pagesize[1] self.simpleFrame = Frame( self.context.doc.leftMargin, self.context.doc.bottomMargin, self.context.doc.width, self.context.doc.height - 3*cm, id='normal') PageTemplate.__init__ (self, id="GraphStatPageTemplateMonth", frames = [self.simpleFrame], pagesize=A4, onPage = self.context.footerAndHeader) </code></pre>
0
2016-10-05T11:54:51Z
[ "python", "barcode", "reportlab" ]
Disable checkbox in django admin if already checked
39,869,681
<p>I have a simple but problematic question for me. How can I disable checkbox, if input is already filled/checked? I must disable some fields after first filling them. Thank you for all your ideas.</p> <p>Sierran</p>
0
2016-10-05T09:03:50Z
39,869,931
<p>There is no built-in solution to this problem, if you want the fields to display dynamically you will always need a custom javascript/ajax solution! You might be able to hack the admin view and template to conditionally show/not show widgets for a field, but if you want to do it dynamically based on user behaviors in the admin, you'll be using javascript.</p> <p>It's not so terrible, though. At least the Django admin templates have model- and instance-specific ids to give you granular control over your show/hide behavior.</p>
0
2016-10-05T09:14:44Z
[ "python", "django", "django-admin" ]
sqlalchemy need back_populates?
39,869,793
<p>When I try SQLAlchemy Relation Example following this guide: <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/basic_relationships.html#one-to-many" rel="nofollow">Basic Relationship Patterns</a></p> <p>I have this code</p> <pre><code>#!/usr/bin/env python # encoding: utf-8 from sqlalchemy import create_engine from sqlalchemy import Table, Column, Integer, ForeignKey from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///:memory:', echo=True) Session = sessionmaker(bind=engine) session = Session() Base = declarative_base(bind=engine) class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent") Base.metadata.create_all() p = Parent() session.add(p) session.commit() c = Child(parent_id=p.id) session.add(c) session.commit() print "children: {}".format(p.children[0].id) print "parent: {}".format(c.parent.id) </code></pre> <p>It works well, but in the guide, it says the model should be:</p> <pre><code>class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) **children = relationship("Child", back_populates="parent")** class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) **parent = relationship("Parent", back_populates="children")** </code></pre> <p>Why don't I need <code>back_populates</code> or <code>backref</code> in my example? When should I use one or the other?</p>
1
2016-10-05T09:08:57Z
39,870,250
<p>If you use <code>backref</code> you don't need to declare the relationship on the second table.</p> <pre><code>class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", backref="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) </code></pre> <p>If you're <em>not</em> using <code>backref</code>, and defining the <code>relationship</code>'s separately, then if you don't use <code>back_populates</code>, sqlalchemy won't know to connect the relationships, so that modifying one also modifies the other.</p> <p>So, in your example, where you've defined the <code>relationship</code>'s separately, but didn't provide a <code>back_populates</code> argument, modifying one field wouldn't automatically update the other in your transaction.</p> <pre><code>&gt;&gt;&gt; parent = Parent() &gt;&gt;&gt; child = Child() &gt;&gt;&gt; child.parent = parent &gt;&gt;&gt; print parent.children [] </code></pre> <p>See how it didn't automatically fill out the <code>children</code> field? </p> <p>Now, if you supply a <code>back_populates</code> argument, sqlalchemy will connect the fields.</p> <pre><code>class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent", back_populates="children") </code></pre> <p>So now we get</p> <pre><code>&gt;&gt;&gt; parent = Parent() &gt;&gt;&gt; child = Child() &gt;&gt;&gt; child.parent = parent &gt;&gt;&gt; print parent.children [Child(...)] </code></pre> <p>Sqlalchemy knows these two fields are related now, and will update each as the other is updated. It's worth noting that using <code>backref</code> will do this, too. Using <code>back_populates</code> is nice if you want to define the relationships on every class, so it's easy to see all the fields just be glancing at the model class, instead of having to look at other classes that define fields via backref.</p>
0
2016-10-05T09:28:53Z
[ "python", "sqlalchemy" ]
Add content to iframe with BeautifulSoup
39,869,888
<p>Let say I have the following iframe</p> <pre><code> s="""" &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;iframe src="http://www.w3schools.com"&gt; &lt;p&gt;Your browser does not support iframes.&lt;/p&gt; &lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; """ </code></pre> <p>I want to replace all content with this string 'this is the replacement' If I use</p> <pre><code>dom = BeatifulSoup(s, 'html.parser') f = dom.find('iframe') f.contents[0].replace_with('this is the replacement') </code></pre> <p>Then instead of replacing all the content I will replace only the first character, which in this case is a newline. Also this does not work if the iframe is completely empty because f.contents[0] is out of index</p>
2
2016-10-05T09:12:37Z
39,873,342
<p>This will work for you to replace the <code>iframe</code> tag content.</p> <pre><code>s=""" &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;iframe src="http://www.w3schools.com"&gt; &lt;p&gt;Your browser does not support iframes.&lt;/p&gt; &lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; """ from BeautifulSoup import BeautifulSoup from HTMLParser import HTMLParser soup = BeautifulSoup(s, convertEntities=BeautifulSoup.HTML_ENTITIES) show= soup.findAll('iframe')[0] show.replaceWith('&lt;iframe src="http://www.w3schools.com"&gt;this is the replacement&lt;/iframe&gt;'.encode('utf-8')) html = HTMLParser() print html.unescape(str(soup.prettify())) </code></pre> <p>Output:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;iframe src="http://www.w3schools.com"&gt;my text&lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
2016-10-05T11:58:27Z
[ "python", "iframe", "beautifulsoup" ]
Add content to iframe with BeautifulSoup
39,869,888
<p>Let say I have the following iframe</p> <pre><code> s="""" &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;iframe src="http://www.w3schools.com"&gt; &lt;p&gt;Your browser does not support iframes.&lt;/p&gt; &lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; """ </code></pre> <p>I want to replace all content with this string 'this is the replacement' If I use</p> <pre><code>dom = BeatifulSoup(s, 'html.parser') f = dom.find('iframe') f.contents[0].replace_with('this is the replacement') </code></pre> <p>Then instead of replacing all the content I will replace only the first character, which in this case is a newline. Also this does not work if the iframe is completely empty because f.contents[0] is out of index</p>
2
2016-10-05T09:12:37Z
39,875,046
<p>Simply set the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string" rel="nofollow"><code>.string</code> property</a>:</p> <pre><code>from bs4 import BeautifulSoup data = """ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;iframe src="http://www.w3schools.com"&gt; &lt;p&gt;Your browser does not support iframes.&lt;/p&gt; &lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; """ soup = BeautifulSoup(data, "html.parser") frame = soup.iframe frame.string = 'this is the replacement' print(soup.prettify()) </code></pre> <p>Prints:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;iframe src="http://www.w3schools.com"&gt; this is the replacement &lt;/iframe&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
2016-10-05T13:16:56Z
[ "python", "iframe", "beautifulsoup" ]
Python equivalence of R's match() for indexing
39,869,958
<p>So i essentially want to implement the equivalent of R's match() function in Python, using Pandas dataframes - without using a for-loop. </p> <p>In R match() returns a vector of the positions of (first) matches of its first argument in its second. </p> <p>Let's say that I have two df A and B, of which both include the column C. Where </p> <pre><code>A$C = c('a','b') B$C = c('c','c','b','b','c','b','a','a') </code></pre> <p>In R we would get</p> <pre><code>match(A$C,B$C) = c(7,3) </code></pre> <p>What is an equivalent method in Python for columns in pandas data frames, that doesn't require looping through the values.</p>
2
2016-10-05T09:15:46Z
39,870,277
<p>You can use first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop_duplicates.html" rel="nofollow"><code>drop_duplicates</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a>.</p> <p>Python counts from <code>0</code>, so for same output add <code>1</code>.</p> <pre><code>A = pd.DataFrame({'c':['a','b']}) B = pd.DataFrame({'c':['c','c','b','b','c','b','a','a']}) B = B.drop_duplicates('c') print (B) c 0 c 2 b 6 a print (B[B.c.isin(A.c)]) c 2 b 6 a print (B[B.c.isin(A.c)].index) Int64Index([2, 6], dtype='int64') </code></pre> <hr> <pre><code>print (pd.merge(B.reset_index(), A)) index c 0 2 b 1 6 a print (pd.merge(B.reset_index(), A)['index']) 0 2 1 6 Name: index, dtype: int64 </code></pre>
2
2016-10-05T09:30:01Z
[ "python", "pandas", "indexing", "match" ]
Python equivalence of R's match() for indexing
39,869,958
<p>So i essentially want to implement the equivalent of R's match() function in Python, using Pandas dataframes - without using a for-loop. </p> <p>In R match() returns a vector of the positions of (first) matches of its first argument in its second. </p> <p>Let's say that I have two df A and B, of which both include the column C. Where </p> <pre><code>A$C = c('a','b') B$C = c('c','c','b','b','c','b','a','a') </code></pre> <p>In R we would get</p> <pre><code>match(A$C,B$C) = c(7,3) </code></pre> <p>What is an equivalent method in Python for columns in pandas data frames, that doesn't require looping through the values.</p>
2
2016-10-05T09:15:46Z
39,870,451
<p>This gives all the indices that are matched (with python's 0 based indexing):</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'C': ['a','b']}) print df1 C 0 a 1 b df2 = pd.DataFrame({'C': ['c','c','b','b','c','b','a','a']}) print df2 C 0 c 1 c 2 b 3 b 4 c 5 b 6 a 7 a match = df2['C'].isin(df1['C']) print [i for i in range(match.shape[0]) if match[i]] #[2, 3, 5, 6, 7] </code></pre>
1
2016-10-05T09:37:56Z
[ "python", "pandas", "indexing", "match" ]
Python equivalence of R's match() for indexing
39,869,958
<p>So i essentially want to implement the equivalent of R's match() function in Python, using Pandas dataframes - without using a for-loop. </p> <p>In R match() returns a vector of the positions of (first) matches of its first argument in its second. </p> <p>Let's say that I have two df A and B, of which both include the column C. Where </p> <pre><code>A$C = c('a','b') B$C = c('c','c','b','b','c','b','a','a') </code></pre> <p>In R we would get</p> <pre><code>match(A$C,B$C) = c(7,3) </code></pre> <p>What is an equivalent method in Python for columns in pandas data frames, that doesn't require looping through the values.</p>
2
2016-10-05T09:15:46Z
39,871,039
<p>You can also simulate the same behavior using <a href="http://pandas.pydata.org/pandas-docs/stable/comparison_with_r.html#match" rel="nofollow"><code>pd.match</code></a>:</p> <pre><code>s1 = A['C'] print(s1) #0 a #1 b #Name: C, dtype: object s2 = B['C'] print(s2) #0 c #1 c #2 b #3 b #4 c #5 b #6 a #7 a #Name: C, dtype: object s = pd.Series(pd.match(s2, s1, np.nan)) print(s) #0 NaN #1 NaN #2 1.0 #3 1.0 #4 NaN #5 1.0 #6 0.0 #7 0.0 #dtype: float64 </code></pre> <p>Then, take unique elements and drop the <code>NaN</code> values and return indices of the values remaining:</p> <pre><code>arr, idx = np.unique(s, return_index=True) idx[~np.isnan(arr)] ## array([6, 2], dtype=int64) </code></pre> <p>To get the array to be the same as the one obtained in R, simply shift the series by one position downwards to suppress the zero-based indexing problem:</p> <pre><code>arr, idx = np.unique(s.shift(), return_index=True) idx[~np.isnan(arr)] ## array([7, 3], dtype=int64) </code></pre>
0
2016-10-05T10:03:34Z
[ "python", "pandas", "indexing", "match" ]
Django filter queryset by timedelta
39,870,014
<p>What could be nice way to filter devices which response was later than, for example, 500 seconds?</p> <p>So assume my model:</p> <pre><code>class Device(models.Model): last_response = models.DateTimeField(null=True, blank=True) </code></pre> <p>My best move was:</p> <pre><code>from django.utils import timezone for d in Device.objects.all(): now = timezone.now() if d.last_response and (now - d.last_response).seconds &lt; 500: # Do something </code></pre> <p>But I don't want to query all database for this. How can I make it work with filter, like <code>for d in Device.objects.filter(..some arguments..):</code> ?</p>
0
2016-10-05T09:18:03Z
39,870,114
<pre><code>from django.utils import timezone from datetime import timedelta Device.objects.filter(last_response__lte=timezone.now()-timedelta(seconds=500)) </code></pre>
2
2016-10-05T09:22:26Z
[ "python", "django" ]
Splitting strings - for a calculation
39,870,251
<p>I want to create a calculator with several functions. When the user inputs something such as "ADD3, DIVIDE4" it will output the answer. So I believe I will have to split the string to work on each part individually. So far all I can find is</p> <pre><code> numb= input("What is your first numb") calc = input("What is your calculation") calc.split(', ') </code></pre> <p>But I don't know how to work on each section once it has been split. So for example if the first is numb = 5 and then its 'calc = ADD3, SUB4' the program will output 4. But then so when it gets more complicated with more calculations and things like DIVIDE it will still work. Thank you</p>
-2
2016-10-05T09:28:56Z
39,870,328
<p>Loop through calc Items. In the loop use a Switch case to find out the Operation and do the calculation. </p> <p>edit: refer to this <a href="https://www.pydanny.com/why-doesnt-python-have-switch-case.html" rel="nofollow">link</a> for switch case implementation in python.</p>
1
2016-10-05T09:31:52Z
[ "python", "string", "split" ]
Splitting strings - for a calculation
39,870,251
<p>I want to create a calculator with several functions. When the user inputs something such as "ADD3, DIVIDE4" it will output the answer. So I believe I will have to split the string to work on each part individually. So far all I can find is</p> <pre><code> numb= input("What is your first numb") calc = input("What is your calculation") calc.split(', ') </code></pre> <p>But I don't know how to work on each section once it has been split. So for example if the first is numb = 5 and then its 'calc = ADD3, SUB4' the program will output 4. But then so when it gets more complicated with more calculations and things like DIVIDE it will still work. Thank you</p>
-2
2016-10-05T09:28:56Z
39,870,508
<p>You could do something like this:</p> <pre><code>numb = input("What is your first numb") calc = input("What is your calculation") ops = calc.split(', ') for op in ops: if op.lower().startswith('add'): number = float(op[3:]) numb += number elif op.lower().startswith('sub'): number = float(op[3:]) numb -= number elif op.lower().startswith('divide'): number = float(op[6:]) numb /= number print(numb) </code></pre> <p>So what you do here is the following:</p> <ul> <li>Determine the operation ( op.lower().startswith(operation) ), .lower() makes it case insensitive</li> <li>Find the number by selecting the rest of the string using string slicing (op[3:] or op[6:] )</li> <li>Perform the operation on numb</li> </ul> <p>Note: This does the operations in the order they are inputted, not in the PEMDAS order of operations!</p>
0
2016-10-05T09:40:22Z
[ "python", "string", "split" ]
How to strip line breaks from BeautifulSoup get text method
39,870,290
<p>I have a following output after scraping a web page</p> <pre><code> text Out[50]: ['\nAbsolute FreeBSD, 2nd Edition\n', '\nAbsolute OpenBSD, 2nd Edition\n', '\nAndroid Security Internals\n', '\nApple Confidential 2.0\n', '\nArduino Playground\n', '\nArduino Project Handbook\n', '\nArduino Workshop\n', '\nArt of Assembly Language, 2nd Edition\n', '\nArt of Debugging\n', '\nArt of Interactive Design\n',] </code></pre> <p>I need to strip \n from above list while iterating over it. Following is my code</p> <pre><code>text = [] for name in web_text: a = name.get_text() text.append(a) </code></pre>
-2
2016-10-05T09:30:29Z
39,870,343
<p>Just like you would <a href="https://docs.python.org/3/library/stdtypes.html#str.strip" rel="nofollow"><code>strip</code></a> any other string:</p> <pre><code>text = [] for name in web_text: a = name.get_text().strip() text.append(a) </code></pre>
1
2016-10-05T09:32:38Z
[ "python", "beautifulsoup" ]
How to strip line breaks from BeautifulSoup get text method
39,870,290
<p>I have a following output after scraping a web page</p> <pre><code> text Out[50]: ['\nAbsolute FreeBSD, 2nd Edition\n', '\nAbsolute OpenBSD, 2nd Edition\n', '\nAndroid Security Internals\n', '\nApple Confidential 2.0\n', '\nArduino Playground\n', '\nArduino Project Handbook\n', '\nArduino Workshop\n', '\nArt of Assembly Language, 2nd Edition\n', '\nArt of Debugging\n', '\nArt of Interactive Design\n',] </code></pre> <p>I need to strip \n from above list while iterating over it. Following is my code</p> <pre><code>text = [] for name in web_text: a = name.get_text() text.append(a) </code></pre>
-2
2016-10-05T09:30:29Z
39,870,364
<p>You can use <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201610050931583559832">list comprehension</a>:</p> <pre><code>stripedText = [ t.strip() for t in text ] </code></pre> <p>Which outputs:</p> <pre><code>&gt;&gt;&gt; stripedText ['Absolute FreeBSD, 2nd Edition', 'Absolute OpenBSD, 2nd Edition', 'Android Security Internals', 'Apple Confidential 2.0', 'Arduino Playground', 'Arduino Project Handbook', 'Arduino Workshop', 'Art of Assembly Language, 2nd Edition', 'Art of Debugging', 'Art of Interactive Design'] </code></pre>
0
2016-10-05T09:33:29Z
[ "python", "beautifulsoup" ]
How to strip line breaks from BeautifulSoup get text method
39,870,290
<p>I have a following output after scraping a web page</p> <pre><code> text Out[50]: ['\nAbsolute FreeBSD, 2nd Edition\n', '\nAbsolute OpenBSD, 2nd Edition\n', '\nAndroid Security Internals\n', '\nApple Confidential 2.0\n', '\nArduino Playground\n', '\nArduino Project Handbook\n', '\nArduino Workshop\n', '\nArt of Assembly Language, 2nd Edition\n', '\nArt of Debugging\n', '\nArt of Interactive Design\n',] </code></pre> <p>I need to strip \n from above list while iterating over it. Following is my code</p> <pre><code>text = [] for name in web_text: a = name.get_text() text.append(a) </code></pre>
-2
2016-10-05T09:30:29Z
39,874,799
<p>Rather than calling <code>.strip()</code> explicitly, use the <code>strip</code> argument:</p> <pre><code>a = name.get_text(strip=True) </code></pre> <p>This would also remove the extra whitespace and newline characters in the children texts if any.</p>
0
2016-10-05T13:05:32Z
[ "python", "beautifulsoup" ]
MQTT Paho Python Client subscriber, how subscribe forever?
39,870,394
<p>Try to simple subscribe without disconnect to a Mosquitto broker to get all messages from devices that are publishing data in a specific topic, save them in a BD and Post them to a php that do "staff".</p> <p>Here is my subscribe.py</p> <pre><code>import paho.mqtt.client as mqtt from mqtt_myapp import * topic="topic/#" # MQTT broker topic myclient="my-paho-client" # MQTT broker My Client user="user" # MQTT broker user pw="pass" # MQTT broker password host="localhost" # MQTT broker host port=1883 # MQTT broker port value="123" # somethin i need for myapp def on_connect(mqttc, userdata, rc): print('connected...rc=' + str(rc)) mqttc.subscribe(topic, qos=0) def on_disconnect(mqttc, userdata, rc): print('disconnected...rc=' + str(rc)) def on_message(mqttc, userdata, msg): print('message received...') print('topic: ' + msg.topic + ', qos: ' + str(msg.qos) + ', message: ' + str(msg.payload)) save_to_db(msg) post_data(msg.payload,value) def on_subscribe(mqttc, userdata, mid, granted_qos): print('subscribed (qos=' + str(granted_qos) + ')') def on_unsubscribe(mqttc, userdata, mid, granted_qos): print('unsubscribed (qos=' + str(granted_qos) + ')') mqttc = mqtt.Client(myclient) mqttc.on_connect = on_connect mqttc.on_disconnect = on_disconnect mqttc.on_message = on_message mqttc.on_subscribe = on_subscribe mqttc.on_unsubscribe = on_unsubscribe mqttc.username_pw_set(user,pw) mqttc.connect(host, port, 60) mqttc.loop_forever() </code></pre> <p>Here is my mqtt_myapp.py:</p> <pre><code>import MySQLdb import requests # pip install requests url = "mydomain/data_from_broker.php" def save_to_db(msg): with db: cursor = db.cursor() try: cursor.execute("INSERT INTO MQTT_LOGS (topic, payload) VALUES (%s,%s)", (msg.topic, msg.payload)) except (MySQLdb.Error, MySQLdb.Warning) as e: print('excepttion BD ' + e) return None def post_data(payload,value): datos = {'VALUE': value,'data-from-broker': payload} r = requests.post(url, datos) r.status_code print('response POST' + str(r.status_code)) db = MySQLdb.connect("localhost","user_db","pass_db","db" ) </code></pre> <p>When I run my python script on background with <code>python -t mqtt_subscribe.py &amp;</code> I get messages publish for other clients, but <strong>after some hours of my subscribe.py script running, socket error happens.</strong></p> <p>Mosquito.log:</p> <pre><code> ... 1475614815: Received PINGREQ from my-paho-client 1475614815: Sending PINGRESP to my-paho-client 1475614872: New connection from xxx.xxx.xxx.xxx on port 1883. 1475614872: Client device1 disconnected. 1475614872: New client connected from xxx.xxx.xxx.xxx as device1(c0, k0, u'user1'). 1475614872: Sending CONNACK to device1(0, 0) 1475614873: Received PUBLISH from device1(d0, q1, r0, m1, 'topic/data', ... (33 bytes)) 1475614873: Sending PUBACK to device1 (Mid: 1) 1475614873: Sending PUBLISH to my-paho-client (d0, q0, r0, m0, 'topic/data', ... (33 bytes)) 1475614874: Received DISCONNECT from device1 1475614874: Client device1 disconnected. ... 1475625566: Received PINGREQ from my-paho-client 1475625566: Sending PINGRESP to my-paho-client 1475625626: Received PINGREQ from my-paho-client 1475625626: Sending PINGRESP to my-paho-client 1475625675: New connection from xxx.xxx.xxx.xxx on port 1883. 1475625675: Client device1 disconnected. 1475625675: New client connected from xxx.xxx.xxx.xxx as device1 (c0, k0, u'user1'). 1475625675: Sending CONNACK to device1 (0, 0) 1475625677: Received PUBLISH from device1 (d0, q1, r0, m1, 'topic/data', ... (33 bytes)) 1475625677: Sending PUBACK to device1 (Mid: 1) 1475625677: Sending PUBLISH to my-paho-client (d0, q0, r0, m0, 'topic/data', ... (33 bytes)) 1475625677: Socket error on client my-paho-client, disconnecting. 1475625677: Received DISCONNECT from device1 ... </code></pre> <p>What could be the problem? Any idea or suggestion?</p> <p>Thanks in advance</p>
0
2016-10-05T09:34:43Z
39,874,223
<p>If your code in the method "on_message" throws an exception and you do not catch it, you will be disconnected. Try uncommenting all statements except the print statements. Probably one of the following statements is throwing an exception.</p> <pre><code> save_to_db(msg) post_data(msg.payload,value) </code></pre>
0
2016-10-05T12:39:18Z
[ "python", "mqtt", "mosquitto", "paho" ]
Django Factory Boy iterate over related parent
39,870,398
<p>I have a project with Clients, Draftschedules, LineItems and Servers.</p> <ul> <li><p>Each client has a single DraftSchedule, each Draftschedule has many Lineitems</p></li> <li><p>Each Client has many Servers</p></li> <li><p>Each LineItem has a Single Server</p></li> </ul> <p><a href="http://i.stack.imgur.com/JPRI1.png" rel="nofollow"><img src="http://i.stack.imgur.com/JPRI1.png" alt="enter image description here"></a></p> <p>I have some code to generate LineItems for each DraftSchedule with random data. However the resulting LineItems contain Servers not actually owned by the Draftschedule Client</p> <pre><code>class LineItemFactory(factory.django.DjangoModelFactory): class Meta: model = LineItem line_item_type = factory.Iterator(LineItemType.objects.all()) draftschedule = factory.Iterator(DraftSchedule.objects.all()) servers = factory.Iterator(Server.objects.all()) # &lt;----- Problem line cost = factory.LazyAttribute(lambda x: faker.pydecimal(2, 2, positive=True)) detail = factory.LazyAttribute(lambda x: faker.sentence()) ... </code></pre> <p>I'd like to restrict the server choice set to be only those servers owned by the parent client of the Draftschedule the Lineitem is being created for.</p> <p>So that when I call <code>LineItemFactory()</code> it returns a new LineItem object and I can garantee that the Server on the LineItem is actually owned by the Client associated with the DraftSchedule</p> <p>I've tried the following:</p> <pre><code>servers = factory.Iterator(lambda x: x.draftschedule.client.servers.all()) </code></pre> <p>where <code>client.servers</code> is the related name, but the function isn't iterable so I'm a bit stuck</p> <p>Is this possible or should I approach the problem from a different angle?</p>
0
2016-10-05T09:35:05Z
39,870,916
<p>You could try using a <a href="http://factoryboy.readthedocs.io/en/latest/reference.html#id6" rel="nofollow">lazy_attribute_sequence</a> :</p> <pre><code>@factory.lazy_attribute_sequence def servers(obj, seq): all_servers = obj.draftschedule.client.servers.all() nb_servers = all_servers.count() return all_servers[seq % nb_servers] </code></pre>
1
2016-10-05T09:58:15Z
[ "python", "django", "fixtures", "factory-boy" ]
PyQt wake main thread from non-QThread
39,870,577
<p>I have a PyQt application that receives information from an external source via callbacks that are called from threads that are not under my control and which are not <code>QThread</code>. What is the correct way to pass such information to the main thread, without polling? Particularly, I want to emit a Qt signal such that I can wake the main thread (or another <code>QThread</code>) upon arrival of new data.</p>
1
2016-10-05T09:42:38Z
39,882,191
<p>I would handle it the same way I would if you were just polling an external device or library. Create a separate worker thread that handles the callback, and emits an signal to the main GUI thread.</p> <pre><code>class Worker(QObject): data_ready = pyqtSignal(object, object) def callback(self, *args, **kwargs): self.data_ready.emit(args, kwargs) class Window(...) def __init__(self): ... self.worker = Worker(self) # Connect worker callback function to your external library library.register_callback(self.worker.callback) #?? ... # Mover worker to thread and connect signal self.thread = QThread(self) self.worker.data_ready.connect(self.handle_data) self.worker.moveToThread(self.thread) self.thread.start() @pyqtSlot(object, object) def handle_data(self, args, kwargs): # do something with data </code></pre>
0
2016-10-05T19:30:46Z
[ "python", "multithreading", "qt", "pyqt", "qthread" ]
PyQt wake main thread from non-QThread
39,870,577
<p>I have a PyQt application that receives information from an external source via callbacks that are called from threads that are not under my control and which are not <code>QThread</code>. What is the correct way to pass such information to the main thread, without polling? Particularly, I want to emit a Qt signal such that I can wake the main thread (or another <code>QThread</code>) upon arrival of new data.</p>
1
2016-10-05T09:42:38Z
39,901,464
<p>The default connection type for signals is <a href="http://doc.qt.io/qt-4.8/qt.html#ConnectionType-enum" rel="nofollow">Qt.AutoConnection</a>, which the docs describe thus:</p> <blockquote> <p>If the signal is emitted from a different thread than the receiving object, the signal is queued, behaving as Qt::QueuedConnection. Otherwise, the slot is invoked directly, behaving as Qt::DirectConnection. The type of connection is determined when the signal is emitted.</p> </blockquote> <p>So before emitting a signal, Qt simply compares the <strong>current</strong> thread affinity of the sender and receiver before deciding whether to queue it or not. It does not matter <em>how</em> the underlying threads were originally started.</p> <p>Here is a simple demo using a python worker thread:</p> <pre><code>import sys, time, threading from PyQt4 import QtCore, QtGui class Worker(object): def __init__(self, callback): self._callback = callback self._thread = None def active(self): return self._thread is not None and self._thread.is_alive() def start(self): self._thread = threading.Thread(target=self.work, name='Worker') self._thread.start() def work(self): print('work: [%s]' % threading.current_thread().name) for x in range(5): time.sleep(1) self._callback(str(x)) class Window(QtGui.QPushButton): dataReceived = QtCore.pyqtSignal(str) def __init__(self): super(Window, self).__init__('Start') self.clicked.connect(self.start) self.dataReceived.connect(self.receive) self.worker = Worker(self.callback) def receive(self, data): print('received: %s [%s]' % (data, threading.current_thread().name)) def callback(self, data): print('callback: %s [%s]' % (data, threading.current_thread().name)) self.dataReceived.emit(data) def start(self): if self.worker.active(): print('still active...') else: print('start: [%s]' % threading.current_thread().name) self.worker.start() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) window = Window() window.show() print('show: [%s]' % threading.current_thread().name) sys.exit(app.exec_()) </code></pre> <p>Typical output:</p> <pre><code>$ python test.py show: [MainThread] start: [MainThread] work: [Worker] callback: 0 [Worker] received: 0 [MainThread] still active... callback: 1 [Worker] received: 1 [MainThread] still active... callback: 2 [Worker] received: 2 [MainThread] still active... callback: 3 [Worker] received: 3 [MainThread] callback: 4 [Worker] received: 4 [MainThread] </code></pre>
1
2016-10-06T16:42:21Z
[ "python", "multithreading", "qt", "pyqt", "qthread" ]
Matplotlib - How to plot a high resolution graph?
39,870,642
<p>I've used matplotlib for plotting some experimental results (discussed it in here: <a href="http://stackoverflow.com/questions/39676294/looping-over-files-and-plotting-python/" title="Looping over files and plotting &#40;Python&#41;">Looping over files and plotting</a>. However, saving the picture by clicking right to the image gives very bad quality / low resolution images.</p> <pre><code>from glob import glob import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl # loop over all files in the current directory ending with .txt for fname in glob("./*.txt"): # read file, skip header (1 line) and unpack into 3 variables WL, ABS, T = np.genfromtxt(fname, skip_header=1, unpack=True) # first plot plt.plot(WL, T, label='BN', color='blue') plt.xlabel('Wavelength (nm)') plt.xlim(200,1000) plt.ylim(0,100) plt.ylabel('Transmittance, %') mpl.rcParams.update({'font.size': 14}) #plt.legend(loc='lower center') plt.title('') plt.show() plt.clf() # second plot plt.plot(WL, ABS, label='BN', color='red') plt.xlabel('Wavelength (nm)') plt.xlim(200,1000) plt.ylabel('Absorbance, A') mpl.rcParams.update({'font.size': 14}) #plt.legend() plt.title('') plt.show() plt.clf() </code></pre> <p>Example graph of what I'm looking for: <a href="http://i.stack.imgur.com/CNSoO.png" rel="nofollow">example graph</a></p>
2
2016-10-05T09:45:40Z
39,870,740
<p>You can use <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.savefig" rel="nofollow"><code>savfig()</code></a> to export to an image file:</p> <pre><code>plt.savefig('filename.png') </code></pre> <p>In adittion, you can specify the <code>dpi</code> arg to some scalar value, for example:</p> <pre><code>plt.savefig('filename.png', dpi = 300) </code></pre>
0
2016-10-05T09:50:20Z
[ "python", "matplotlib" ]
Matplotlib - How to plot a high resolution graph?
39,870,642
<p>I've used matplotlib for plotting some experimental results (discussed it in here: <a href="http://stackoverflow.com/questions/39676294/looping-over-files-and-plotting-python/" title="Looping over files and plotting &#40;Python&#41;">Looping over files and plotting</a>. However, saving the picture by clicking right to the image gives very bad quality / low resolution images.</p> <pre><code>from glob import glob import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl # loop over all files in the current directory ending with .txt for fname in glob("./*.txt"): # read file, skip header (1 line) and unpack into 3 variables WL, ABS, T = np.genfromtxt(fname, skip_header=1, unpack=True) # first plot plt.plot(WL, T, label='BN', color='blue') plt.xlabel('Wavelength (nm)') plt.xlim(200,1000) plt.ylim(0,100) plt.ylabel('Transmittance, %') mpl.rcParams.update({'font.size': 14}) #plt.legend(loc='lower center') plt.title('') plt.show() plt.clf() # second plot plt.plot(WL, ABS, label='BN', color='red') plt.xlabel('Wavelength (nm)') plt.xlim(200,1000) plt.ylabel('Absorbance, A') mpl.rcParams.update({'font.size': 14}) #plt.legend() plt.title('') plt.show() plt.clf() </code></pre> <p>Example graph of what I'm looking for: <a href="http://i.stack.imgur.com/CNSoO.png" rel="nofollow">example graph</a></p>
2
2016-10-05T09:45:40Z
39,870,761
<p>You can save your graph as svg for a lossless quality:</p> <pre><code>import matplotlib.pylab as plt x = range(10) plt.figure() plt.plot(x,x) plt.savefig("graph.svg") </code></pre>
1
2016-10-05T09:51:12Z
[ "python", "matplotlib" ]