title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Repeat each elements based on a list of values
38,758,708
<p>Is there a Python builtin that repeats each element of a list based on the corresponding value in another list? For example <code>A</code> in list <code>x</code> position 0 is repeated 2 times because of the value <code>2</code> at position 0 in the list <code>y</code>.</p> <pre><code>&gt;&gt;&gt; x = ['A', 'B', 'C'] &gt;&gt;&gt; y = [2, 1, 3] &gt;&gt;&gt; f(x, y) ['A', 'A', 'B', 'C', 'C', 'C'] </code></pre> <p>Or to put it another way, what is the fastest way to achieve this operation?</p>
2
2016-08-04T04:52:24Z
38,758,795
<p>Just use a simple list comprehension:</p> <pre><code>&gt;&gt;&gt; x = ['A', 'B', 'C'] &gt;&gt;&gt; y = [2, 1, 3] &gt;&gt;&gt; [x[i] for i in range(len(x)) for j in range(y[i])] ['A', 'A', 'B', 'C', 'C', 'C'] &gt;&gt;&gt; </code></pre>
3
2016-08-04T05:01:14Z
[ "python", "list" ]
Django model on_update=models.CASCADE related object reference
38,758,723
<p>I have looked for <code>django</code> doc in their official site but i can't find the article about the <code>on_update</code> model function here in <a href="https://docs.djangoproject.com/ja/1.9/ref/models/relations/" rel="nofollow">Related objects reference</a> except for <code>on_delete</code>.</p> <p>Here is an example code:</p> <pre><code>from django.db import models class Reporter(models.Model): # ... pass class Article(models.Model): reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) </code></pre> <p>Is there any version of <code>on_update</code>?</p> <p>I have visited this <a href="http://stackoverflow.com/questions/7295417/cascade-on-update-and-delete-wih-django">Cascade on update and delete wih django</a> but there is not a clear answer about the <code>on_update</code> </p> <p>I am using <code>mysql</code> and define the relationship in the <code>ERD</code> and sync it to the db and tried running the <code>python manage.py inspectdb</code> to generate the <code>django-model</code> but it shows only <code>models.DO_NOTHING</code>.</p> <p>Is there a better way to achieve this, if any?</p>
0
2016-08-04T04:53:32Z
38,793,704
<p>It's normally adviseable to completely leave the primary key alone when setting up your Django models, as these are used by Django in a number of ways to maintain relationships between objects. Django will set them up and use them automatically.</p> <p>Instead, create a separate field in your model to keep track of unique data:</p> <pre><code>class Reporter(models.Model): emp_id = models.CharField(unique=True) </code></pre> <p>This way you can obtain the <code>emp_id</code> with <code>reporter_object.emp_id</code> and if you need it, you can still get the pk with <code>reporter_object.id</code>.</p> <p>You can read about how it works it in the <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#unique" rel="nofollow">Django 1.9 Documentation</a></p>
1
2016-08-05T16:15:25Z
[ "python", "mysql", "django" ]
How to remove pattern from items in an array
38,758,763
<p>I'm trying to make a new array from an already existing array, where all the items in the array has a pattern in it. </p> <p>For example</p> <pre><code>my_array=['A_1.gi.kl','BC_1.gi.kl','FGKX_1.gi.kl'] </code></pre> <p>What I want is a function that can automatically make </p> <pre><code>my_new_array=['A','BC','FGKX'] </code></pre> <p>How can I do this easily? The resulting items in the array don't have an identical length.</p>
0
2016-08-04T04:58:08Z
38,758,792
<p>Use <code>split</code> with a comprehension:</p> <pre><code>my_array = ['A_1.gi.kl', 'BC_1.gi.kl', 'FGKX_1.gi.kl'] my_new_array = [item.split('_')[0] for item in my_array] </code></pre>
2
2016-08-04T05:01:02Z
[ "python", "list", "python-3.x" ]
How to remove pattern from items in an array
38,758,763
<p>I'm trying to make a new array from an already existing array, where all the items in the array has a pattern in it. </p> <p>For example</p> <pre><code>my_array=['A_1.gi.kl','BC_1.gi.kl','FGKX_1.gi.kl'] </code></pre> <p>What I want is a function that can automatically make </p> <pre><code>my_new_array=['A','BC','FGKX'] </code></pre> <p>How can I do this easily? The resulting items in the array don't have an identical length.</p>
0
2016-08-04T04:58:08Z
38,758,813
<p>Define the suffix:</p> <pre><code>&gt;&gt;&gt; suffix = '_1.gi.kl' </code></pre> <p>Then just split by the suffix:</p> <pre><code>&gt;&gt;&gt; [item.split(suffix)[0] for item in my_array] ['A', 'BC', 'FGKX'] &gt;&gt;&gt; </code></pre>
0
2016-08-04T05:03:04Z
[ "python", "list", "python-3.x" ]
How to remove pattern from items in an array
38,758,763
<p>I'm trying to make a new array from an already existing array, where all the items in the array has a pattern in it. </p> <p>For example</p> <pre><code>my_array=['A_1.gi.kl','BC_1.gi.kl','FGKX_1.gi.kl'] </code></pre> <p>What I want is a function that can automatically make </p> <pre><code>my_new_array=['A','BC','FGKX'] </code></pre> <p>How can I do this easily? The resulting items in the array don't have an identical length.</p>
0
2016-08-04T04:58:08Z
38,758,876
<p>You can get element up to certain character by using <code>list.index</code> if all of your elements have that character( as you have mentioned)</p> <pre><code>[v[:v.index('_')] for v in my_array] ['A', 'BC', 'FGKX'] </code></pre>
1
2016-08-04T05:07:48Z
[ "python", "list", "python-3.x" ]
Python: subprocess call doesn't recognize * wildcard character?
38,758,830
<p>I want to remove all the *.ts in file. <code>os.remove</code> didn't work.</p> <p>And this doesn't expand <code>*</code></p> <pre><code>&gt;&gt;&gt; args = ['rm', '*.ts'] &gt;&gt;&gt; p = subprocess.call(args) rm: *.ts No such file or directory </code></pre>
0
2016-08-04T05:05:02Z
38,758,859
<p>The <code>rm</code> program takes a list of filenames, but <code>*.ts</code> isn't a list of filenames, it's a pattern for matching filenames. You have to name the actual files for <code>rm</code>. When you use a shell, the shell (but not <code>rm</code>!) will expand patterns like <code>*.ts</code> for you. In Python, you have to explicitly ask for it.</p> <pre><code>import glob import subprocess subprocess.check_call(['rm', '--'] + glob.glob('*.ts')) # ^^^^ this makes things much safer, by the way </code></pre> <p>Of course, why bother with <code>subprocess</code>?</p> <pre><code>import glob import os for path in glob.glob('*.ts'): os.remove(path) </code></pre>
8
2016-08-04T05:06:59Z
[ "python", "linux", "shell", "subprocess" ]
Looking for a regex matching apostrophe only within string
38,758,873
<p>I'm looking for a Python regex that can match <code>'didn't'</code> and returns only the character that is immediately preceded by an apostrophe, like <code>'t</code>, but not the <code>'d</code> or <code>t'</code> at the beginning and end.</p> <p>I have tried <code>(?=.*\w)^(\w|')+$</code> but it only matches the apostrophe at the beginning.</p> <p>Some more examples:</p> <p><code>'I'm'</code> should only match <code>'m</code> and not <code>'I</code></p> <p><code>'Erick's'</code> should only return <code>'s</code> and not <code>'E</code></p> <p>The text will always start and end with an apostrophe and can include apostrophes within the text.</p>
-2
2016-08-04T05:07:42Z
38,866,676
<p>Here is a <a href="https://ideone.com/LDVyia" rel="nofollow">bunch of possible solutions</a>:</p> <pre><code>import re s = "'didn't'" print(s.strip("'")[s.strip("'").find("'")+1]) print(re.search(r'\b\'(\w)', s).group(1)) print(re.search(r'\b\'([^\W\d_])', s).group(1)) print(re.search(r'\b\'([a-z])', s, flags=re.I).group(1)) print(re.findall(r'\b\'([a-z])', "'didn't know I'm a student'", flags=re.I)) </code></pre> <p>The <code>s.strip("'")[s.strip("'").find("'")+1]</code> gets the character after the first <code>'</code> after stripping the leading/trailing apostrophes.</p> <p>The <code>re.search(r'\b\'(\w)', s).group(1)</code> solution gets the <em>word</em> (i.e. <code>[a-zA-Z0-9_]</code>, can be adjusted from here) char after a <code>'</code> that is preceded with a word char (due to the <code>\b</code> word boundary).</p> <p>The <code>re.search(r'\b\'([^\W\d_])', s).group(1)</code> is almost identical to the above solution, it only fetches a <em>letter</em> character as <code>[^\W\d_]</code> matches any char other than a non-word, digit and <code>_</code>. </p> <p>Note that the <code>re.search(r'\b\'([a-z])', s, flags=re.I).group(1)</code> solution is next to identical to the above one, but you cannot make it Unicode aware with <code>re.UNICODE</code>.</p> <p>The last <code>re.findall(r'\b\'([a-z])', "'didn't know I'm a student'", flags=re.I)</code> just shows how to fetch multiple letter chars from a string input.</p>
1
2016-08-10T07:20:24Z
[ "python", "regex" ]
Lists and pop() not working as I'd expect
38,758,884
<p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or chest again.</p> <p>In pseudocode, the system should work something like this:</p> <pre><code>if potions: if there are still potions in the list: drink potion potions.pop() else: print "There are no potions left." else: print "There are no potions to drink." </code></pre> <p>I think what is happening is when I pop the potion from the list, <code>if potions</code> doesn't compute to being true, and it automatically goes to the else block, but I'm not sure why it does that, nor am I sure why when I come back to the room the list resets itself.</p> <p>It's very possible that I'm not fully understanding how lists or the pop method works so if anybody could clarify that would be great. Thank you!</p> <p><strong>Edit real code from OP's link</strong></p> <pre><code>if room.potions: if len(room.potions) &gt; 0: # if there are potions left if hasattr(room.potions[0], 'explode'): # if the potion is a bomb room.potions[0].explode(You) # explode using zeroeth item from the list room.potions[0].pop # remove zeroeth item from the list` else: room.potions[0].heal(You) # heal using zeroeth potion from the list room.potions.pop(0) # remove zeroeth item from the list else: print "There are no more potions to drink" else: print "There are no potions to drink" </code></pre> <p><strong>EDIT: SOLVED</strong></p> <p>My problem was that when I put the parameters in for the lexicon, I put the entire room as one of them, thinking I would be able to use everything in it just fine. But each time I did that it would set the room up with the <strong>init</strong>, thus effectively ruining what I was trying to do. I added separate parameters for the potions and chest and it is now working perfectly. Thank you @Bernie for the helpful advice that allowed me to see the error. Also thank you @Everybody for your suggestions and tips.</p>
0
2016-08-04T05:08:38Z
38,759,108
<p>What you could do is when they drink it do this</p> <pre><code>potions = 1 if potions &gt; 0: drink potion potions = potions - 1 else: print "There are no potions left." </code></pre>
1
2016-08-04T05:29:23Z
[ "python", "list", "pop" ]
Lists and pop() not working as I'd expect
38,758,884
<p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or chest again.</p> <p>In pseudocode, the system should work something like this:</p> <pre><code>if potions: if there are still potions in the list: drink potion potions.pop() else: print "There are no potions left." else: print "There are no potions to drink." </code></pre> <p>I think what is happening is when I pop the potion from the list, <code>if potions</code> doesn't compute to being true, and it automatically goes to the else block, but I'm not sure why it does that, nor am I sure why when I come back to the room the list resets itself.</p> <p>It's very possible that I'm not fully understanding how lists or the pop method works so if anybody could clarify that would be great. Thank you!</p> <p><strong>Edit real code from OP's link</strong></p> <pre><code>if room.potions: if len(room.potions) &gt; 0: # if there are potions left if hasattr(room.potions[0], 'explode'): # if the potion is a bomb room.potions[0].explode(You) # explode using zeroeth item from the list room.potions[0].pop # remove zeroeth item from the list` else: room.potions[0].heal(You) # heal using zeroeth potion from the list room.potions.pop(0) # remove zeroeth item from the list else: print "There are no more potions to drink" else: print "There are no potions to drink" </code></pre> <p><strong>EDIT: SOLVED</strong></p> <p>My problem was that when I put the parameters in for the lexicon, I put the entire room as one of them, thinking I would be able to use everything in it just fine. But each time I did that it would set the room up with the <strong>init</strong>, thus effectively ruining what I was trying to do. I added separate parameters for the potions and chest and it is now working perfectly. Thank you @Bernie for the helpful advice that allowed me to see the error. Also thank you @Everybody for your suggestions and tips.</p>
0
2016-08-04T05:08:38Z
38,759,155
<p>You can simply write your code as follows:</p> <pre><code>if potions: # same as len(potions) &gt; 0 # drink potion potions.pop() else: print "There are no potions to drink." </code></pre> <p>So check if any potion is left, if it is left drink it and remove from list otherwise show there is no potion left.</p>
0
2016-08-04T05:33:30Z
[ "python", "list", "pop" ]
Lists and pop() not working as I'd expect
38,758,884
<p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or chest again.</p> <p>In pseudocode, the system should work something like this:</p> <pre><code>if potions: if there are still potions in the list: drink potion potions.pop() else: print "There are no potions left." else: print "There are no potions to drink." </code></pre> <p>I think what is happening is when I pop the potion from the list, <code>if potions</code> doesn't compute to being true, and it automatically goes to the else block, but I'm not sure why it does that, nor am I sure why when I come back to the room the list resets itself.</p> <p>It's very possible that I'm not fully understanding how lists or the pop method works so if anybody could clarify that would be great. Thank you!</p> <p><strong>Edit real code from OP's link</strong></p> <pre><code>if room.potions: if len(room.potions) &gt; 0: # if there are potions left if hasattr(room.potions[0], 'explode'): # if the potion is a bomb room.potions[0].explode(You) # explode using zeroeth item from the list room.potions[0].pop # remove zeroeth item from the list` else: room.potions[0].heal(You) # heal using zeroeth potion from the list room.potions.pop(0) # remove zeroeth item from the list else: print "There are no more potions to drink" else: print "There are no potions to drink" </code></pre> <p><strong>EDIT: SOLVED</strong></p> <p>My problem was that when I put the parameters in for the lexicon, I put the entire room as one of them, thinking I would be able to use everything in it just fine. But each time I did that it would set the room up with the <strong>init</strong>, thus effectively ruining what I was trying to do. I added separate parameters for the potions and chest and it is now working perfectly. Thank you @Bernie for the helpful advice that allowed me to see the error. Also thank you @Everybody for your suggestions and tips.</p>
0
2016-08-04T05:08:38Z
38,759,828
<p><a href="https://docs.python.org/2/glossary.html" rel="nofollow">EAFP</a> approach:</p> <pre><code>try: potions.pop() except IndexError: print "No potion left" </code></pre> <blockquote> <p>Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.</p> </blockquote>
0
2016-08-04T06:20:13Z
[ "python", "list", "pop" ]
Lists and pop() not working as I'd expect
38,758,884
<p>My program is an adventure game with potions and chests. I've set these up in lists so when the user drinks a potion or opens a chest, I can use <code>pop()</code> to remove it from the list. This works fine while the user is in the same room, but if they come back to the room they are able to use that potion or chest again.</p> <p>In pseudocode, the system should work something like this:</p> <pre><code>if potions: if there are still potions in the list: drink potion potions.pop() else: print "There are no potions left." else: print "There are no potions to drink." </code></pre> <p>I think what is happening is when I pop the potion from the list, <code>if potions</code> doesn't compute to being true, and it automatically goes to the else block, but I'm not sure why it does that, nor am I sure why when I come back to the room the list resets itself.</p> <p>It's very possible that I'm not fully understanding how lists or the pop method works so if anybody could clarify that would be great. Thank you!</p> <p><strong>Edit real code from OP's link</strong></p> <pre><code>if room.potions: if len(room.potions) &gt; 0: # if there are potions left if hasattr(room.potions[0], 'explode'): # if the potion is a bomb room.potions[0].explode(You) # explode using zeroeth item from the list room.potions[0].pop # remove zeroeth item from the list` else: room.potions[0].heal(You) # heal using zeroeth potion from the list room.potions.pop(0) # remove zeroeth item from the list else: print "There are no more potions to drink" else: print "There are no potions to drink" </code></pre> <p><strong>EDIT: SOLVED</strong></p> <p>My problem was that when I put the parameters in for the lexicon, I put the entire room as one of them, thinking I would be able to use everything in it just fine. But each time I did that it would set the room up with the <strong>init</strong>, thus effectively ruining what I was trying to do. I added separate parameters for the potions and chest and it is now working perfectly. Thank you @Bernie for the helpful advice that allowed me to see the error. Also thank you @Everybody for your suggestions and tips.</p>
0
2016-08-04T05:08:38Z
38,760,911
<p>OK. I was tempted... :) Of course, should exist a hierarchy of potions and the <code>print()</code> method could be a message to the 'world'. And so forth...</p> <pre><code>import random class Potion: """Define the Potion class. Could be explosive and provoke a damage""" def __init__(self, explosive=None, damage=None): if explosive == None: self.__explosive = bool(random.getrandbits(1)) else: self.__explosive = explosive if self.__explosive: if damage == None: self.__damage = random.randint(1,5) else: self.__damage = damage else: self.__damage = 0 def isExplosive(self): return self.__explosive def explode(self): if self.isExplosive(): return self.__damage else: return 0 def __str__(self): if self.isExplosive(): res = "explosive potion" else: res = "simple potion" return res class Hero: """Simple Hero class""" def __init__(self, name): self.__name = name self.__hp = 100 self.__potions = [] def receiveDamage(self, damage): self.__hp = self.__hp - damage if self.__hp &lt;= 0: print("I'm dead!") def isAlive(self): return self.__hp &gt; 0 def getPotion(self, room): """ Get the first potion in the room.If the potion is explosive, explode and receive some damage TODO: Trapped potions? """ potion = room.getFirstPotion() print("%s take a %s" % (self.__name, potion)) if potion.isExplosive(): damage = potion.explode() print("%s received %d hp of damage!!" % (self.__name, damage)) self.receiveDamage(damage) else: self.__potions.append(potion) def __str__(self): res = "%s have %d HP and %d potions." % (self.__name, self.__hp, len(self.__potions)) return res class Room: def __init__(self, potions): """Create a room with some potions""" self.__potions = potions def getFirstPotion(self): """Return the first potion """ if self.__potions: potion = self.__potions.pop() else: potion = None return potion def havePotions(self): return len(self.__potions) &gt; 0 @property def potions(self): return self.__potions def __str__(self): return "This room have %s potions" % len(self.__potions) peter = Hero('Peter') room = Room(potions=[Potion() for i in range(5)]) print(room) print(peter) while room.havePotions(): print("___________") peter.getPotion(room) print(room) print(peter) </code></pre> <p><strong>Output:</strong><br></p> <blockquote> <p>This room have 5 potions<br> Peter have 100 HP and 0 potions.<br> ___________<br> Peter take a simple potion<br> This room have 4 potions<br> Peter have 100 HP and 1 potions.<br> ___________<br> Peter take a explosive potion<br> Peter received 3 hp of damage!!<br> This room have 3 potions<br> Peter have 97 HP and 1 potions.<br> ___________<br> Peter take a explosive potion<br> Peter received 3 hp of damage!!<br> This room have 2 potions<br> Peter have 94 HP and 1 potions.<br> ___________<br> Peter take a explosive potion<br> Peter received 5 hp of damage!!<br> This room have 1 potions<br> Peter have 89 HP and 1 potions.<br> ___________<br> Peter take a explosive potion<br> Peter received 1 hp of damage!!<br> This room have 0 potions<br> Peter have 88 HP and 1 potions.<br></p> </blockquote>
0
2016-08-04T07:22:10Z
[ "python", "list", "pop" ]
Pass a scoring function from sklearn.metrics to GridSearchCV
38,758,925
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html" rel="nofollow">GridSearchCV's documentations</a> states that I can pass a scoring function.</p> <blockquote> <p>scoring : string, callable or None, default=None</p> </blockquote> <p>I would like to use a native <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html" rel="nofollow">accuracy_score</a> as a scoring function.</p> <p>So here is my attempt. Imports and some data:</p> <pre><code>import numpy as np from sklearn.cross_validation import KFold, cross_val_score from sklearn.grid_search import GridSearchCV from sklearn.metrics import accuracy_score from sklearn import neighbors X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) Y = np.array([0, 1, 0, 0, 0, 1]) </code></pre> <p>Now when I use just k-fold cross-validation without my scoring function, everything works as intended:</p> <pre><code>parameters = { 'n_neighbors': [2, 3, 4], 'weights':['uniform', 'distance'], 'p': [1, 2, 3] } model = neighbors.KNeighborsClassifier() k_fold = KFold(len(Y), n_folds=6, shuffle=True, random_state=0) clf = GridSearchCV(model, parameters, cv=k_fold) # TODO will change clf.fit(X, Y) print clf.best_score_ </code></pre> <p>But when I change the line to</p> <pre><code>clf = GridSearchCV(model, parameters, cv=k_fold, scoring=accuracy_score) # or accuracy_score() </code></pre> <p>I get the error: <code>ValueError: Cannot have number of folds n_folds=10 greater than the number of samples: 6.</code> which in my opinion does not represent the real problem.</p> <p>In my opinion the problem is that <code>accuracy_score</code> does not follow the signature <code>scorer(estimator, X, y)</code>, which is written in the documentation</p> <hr> <p>So how can I fix this problem?</p>
0
2016-08-04T05:12:20Z
38,759,297
<p>It will work if you change <code>scoring=accuracy_score</code> to <code>scoring='accuracy'</code> (see the doco at <a href="http://scikit-learn.org/stable/modules/model_evaluation.html" rel="nofollow">http://scikit-learn.org/stable/modules/model_evaluation.html</a> for the full list of scorers you can use by name in this way).</p> <p>In theory you should be able to pass custom scoring functions like you're trying, but my guess is that you're right and <code>accuracy_score</code> doesn't have the right API.</p>
2
2016-08-04T05:45:33Z
[ "python", "scikit-learn", "grid-search" ]
smtplib: Why do the recipients in "To" field receive the mail twice?
38,758,956
<p>I searched about this quite a lot, but could not fix the issue in my script. So finally, I decided to post it here.</p> <p>Here's the code snippet:</p> <pre><code>fromaddr = "someValidAddress@xyz.com" cc = ['SomeEmailAlias@xyz.com'] toaddr = "" msg = MIMEMultipart() toaddrlist = list(toaddr.split(',')) #As sendmail() accepts the list of recipients only in list form. toaddrlist += (cc,) msg['From'] = fromaddr msg['To'] = toaddr msg['Cc'] = ', '.join(cc) msg['Date'] = formatdate(localtime=True) msgHtml = MIMEText(html, 'html') msg.attach(msgHtml) msg['Subject'] = "Test mail" server = "someMailServer.xyz.com" smtp = smtplib.SMTP(server, 25) smtp.sendmail(fromaddr, toaddrlist, msg.as_string()) smtp.close() #Close the SMTP server connection. </code></pre> <p>I'm aware and I've ensured that msg['To'] accepts a string value (toaddr), whereas toaddrlist in sendmail() should be a list.</p> <p>Catch: If I remove the line <code>toaddrlist += (cc,)</code>, then the mail does not get delivered twice to the recipients in "To" field, but the mail does not get delivered to the Cc alias.</p> <p>Please help.</p>
0
2016-08-04T05:15:05Z
38,765,645
<p>When the line <code>toaddrlist += (cc,)</code> is evaluated, the value of <code>toaddrlist</code> in your case is : </p> <pre><code>["", ["SomeEmailAlias@xyz.com"]] </code></pre> <p>and it's wrong because <code>toaddrlist</code> must be a list of strings not a list containing some lists.</p> <p>So the solution is to change :</p> <pre><code> toaddrlist += (cc,) </code></pre> <p>to </p> <pre><code>toaddrlist += cc </code></pre> <p>or the recommended form (the pythonic way) :</p> <pre><code>toaddrlist.extend(cc) </code></pre>
0
2016-08-04T11:06:57Z
[ "python", "sendmail", "smtplib" ]
python list value make a list
38,758,958
<p>I want to make my list value as list.</p> <p>example : </p> <pre><code>abc = [1,2,3,4] </code></pre> <p>result : </p> <pre><code>abc = [[1], [2], [3], [4]] </code></pre> <p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
0
2016-08-04T05:15:12Z
38,758,983
<p>I don't think you need numpy. A list comprehension should do.</p> <pre><code>abc = [[x] for x in abc] </code></pre>
8
2016-08-04T05:17:13Z
[ "python", "list", "numpy" ]
python list value make a list
38,758,958
<p>I want to make my list value as list.</p> <p>example : </p> <pre><code>abc = [1,2,3,4] </code></pre> <p>result : </p> <pre><code>abc = [[1], [2], [3], [4]] </code></pre> <p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
0
2016-08-04T05:15:12Z
38,759,029
<p>Try This:-</p> <pre><code>abc = map(lambda x:[x], abc) </code></pre>
2
2016-08-04T05:22:09Z
[ "python", "list", "numpy" ]
python list value make a list
38,758,958
<p>I want to make my list value as list.</p> <p>example : </p> <pre><code>abc = [1,2,3,4] </code></pre> <p>result : </p> <pre><code>abc = [[1], [2], [3], [4]] </code></pre> <p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
0
2016-08-04T05:15:12Z
38,759,067
<p>A non <code>list comprehension</code> or <code>lambda function</code> version would be </p> <pre><code>abc = [1,2,3] arr = [] for x in abc: arr.append([x]) print arr </code></pre> <p>I believe this is more intuitive for beginners but less pythonic.</p>
1
2016-08-04T05:25:47Z
[ "python", "list", "numpy" ]
python list value make a list
38,758,958
<p>I want to make my list value as list.</p> <p>example : </p> <pre><code>abc = [1,2,3,4] </code></pre> <p>result : </p> <pre><code>abc = [[1], [2], [3], [4]] </code></pre> <p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
0
2016-08-04T05:15:12Z
38,759,087
<p>With numpy, you can add a new axis:</p> <pre><code>import numpy as np np.array(abc)[:, np.newaxis] Out: array([[1], [2], [3], [4]]) </code></pre>
1
2016-08-04T05:27:31Z
[ "python", "list", "numpy" ]
python list value make a list
38,758,958
<p>I want to make my list value as list.</p> <p>example : </p> <pre><code>abc = [1,2,3,4] </code></pre> <p>result : </p> <pre><code>abc = [[1], [2], [3], [4]] </code></pre> <p>I found that <code>numpy</code> library is needed. however I don't know how to change that. Who know the solution?</p>
0
2016-08-04T05:15:12Z
38,761,704
<pre><code>import numpy as np arr = np.array([[x] for x in abc]) </code></pre>
0
2016-08-04T08:02:12Z
[ "python", "list", "numpy" ]
Expanding sys.path via __init__.py
38,758,965
<p>There're a lot of threads on importing modules from sibling directories, and majority recommends to either simply add <strong>init</strong>.py to source tree, or modify sys.path from inside those init files.</p> <p>Suppose I have following project structure:</p> <pre><code>project_root/ __init__.py wrappers/ __init__.py wrapper1.py wrapper2.py samples/ __init__.py sample1.py sample2.py </code></pre> <p>All <strong>init</strong>.py files contain code which inserts absolute path to project_root/ directory into the sys.path. I get "No module names x", no matter how I'm trying to import wrapperX modules into sampleX. And when I try to print sys.path from sampleX, it appears that it does not contain path to project_root. </p> <p>So how do I use <strong>init</strong>.py correctly to set up project environment variables?</p>
0
2016-08-04T05:15:43Z
38,759,254
<p>Do not run <code>sampleX.py</code> directly, execute as module instead:</p> <pre><code># (in project root directory) python -m samples.sample1 </code></pre> <p>This way you do not need to fiddle with <code>sys.path</code> at all (which is generally discouraged). It also makes it much easier to use the samples/ package as a library later on.</p> <p>Oh, and <strong>init</strong>.py is not run because it only gets run/imported (which is more or less the same thing) if you import the samples package, not if you run an individual file as script.</p>
1
2016-08-04T05:41:18Z
[ "python" ]
What are the best ways to write a derived query to Apache SOLR core through python ?
38,759,111
<p>I am using solrpy to access the core and indices in the SOLR server. I wanted to build some some queries. i.e example to find all companies which have an average sales of particular product less than/ more than some amount? </p> <p>What are the ways in which i can pass such query to solr server using python ? </p>
0
2016-08-04T05:29:47Z
38,761,193
<p>The documentation is always the best place to look for examples. <a href="https://cwiki.apache.org/confluence/display/solr/Using+Python" rel="nofollow">Here</a> you can find examples for simple Python and Python with JSON that is more robust.</p>
0
2016-08-04T07:35:44Z
[ "python", "apache", "solr" ]
Updating metadata for gridfs file object
38,759,131
<p>I use GridFS as follows:</p> <pre><code>connection = MongoClient(host='localhost') db = connection.gridfs_example fs = gridfs.GridFS(db) fileId = fs.put("Contents of my file", key='s1') </code></pre> <p>After files are originally stored in GridFS, I have a process that computes additional metadata respective to the contents of the file. </p> <pre><code>def qcFile(fileId): #DO QC return "QC PASSED" qcResult = qcFile(fileId) </code></pre> <p>It would have been great if I could do:</p> <pre><code>fs.update(fileId, QC_RESULT = qcResult) </code></pre> <p>But that option does not appear to exist within the documentation. I found <a href="http://stackoverflow.com/questions/29515327/how-to-perform-update-operations-in-gridfs-using-java">here</a> (the question updated with solution) that the Java driver appears to offer an option to do something like this but can't find its equivalent in python gridfs.</p> <p>So, how do I use pymongo to tag my file with the newly computed metadata value <code>qcResult</code>? I can't find it within the <a href="http://api.mongodb.com/python/current/api/gridfs/" rel="nofollow">documentation</a>.</p>
0
2016-08-04T05:31:35Z
38,760,294
<p>GridFS stores files in two collections: 1. files collection: store files' metadata 2. chunks collection: store files' binary data</p> <p>You can hack into the files collection. The name of the files collection is 'fs.files' where 'fs' is the default bucket name.</p> <p>So, to update the QC result, you can do like this:</p> <p><code>db.fs.files.update({'_id': fileId}, {'$set': {'QC_RESULT': qcResult}})</code></p>
2
2016-08-04T06:49:24Z
[ "python", "mongodb", "pymongo", "gridfs" ]
select doesn't work for pipe in python?
38,759,184
<p>When using <code>check_parent_select</code>, after the reader side is closed, exception list is not filled.</p> <p>But using <code>check_parent_poll</code>, after the reader side is closed, it can detects the pipe disconnection.</p> <p>Does someone know the root cause?</p> <pre><code>#!/usr/bin/python2.7 import select import sys import os log=open("./test.log","w") (reader, writer) = os.pipe() def check_parent_select(fh): (rlist, wlist, xlist) = select.select([], [], [fh], 1) if fh in xlist: print "parent exit" else: print "parent OK" def check_parent_poll(fh): poller = select.poll() EVENTS = select.POLLERR poller.register(fh) events = poller.poll() for fd, flag in events: if flag &amp; select.POLLERR: print "parent exit" else: print "parent OK" open_file = os.fdopen(writer, "w") check_parent_select(open_file) os.close(reader) check_parent_select(open_file) </code></pre> <p>Used strace to trace select function, select can't detect the pipe close.</p> <blockquote> <p><strong>pipe([4, 5]) = 0</strong></p> <p><strong>select(6, [], [], [5], {1, 0}) = 0 (Timeout)</strong></p> <p>write(1, "parent OK\n", 10parent OK</p> <p><strong>close(4) = 0</strong></p> <p><strong>select(6, [], [], [5], {1, 0}) = 0 (Timeout)</strong></p> </blockquote>
3
2016-08-04T05:35:36Z
38,761,046
<p>It is somewhat hidden, but if you follow <a href="http://pubs.opengroup.org/onlinepubs/007908799/xsh/select.html" rel="nofollow">the documentation</a>, it becomes clearer: <code>select()</code> checks for <em>pending error conditions</em>, i.e. error conditions that make the file descriptor unusable, but only after the error has occurred.</p> <p>After closing the read end, you haven't done any operation on the pipe yet, that causes an error condition. There are still valid operations for the <code>writer</code>: For example, you can close the fd. The pipe thus isn't yet in an error state. </p> <p>The problem is more easily discerned when closing the writer side: Even after the close there could be readable data in the pipe's buffer, that hasn't been consumed yet. In such cases, you want <code>read()</code> to return <code>0</code> on <code>EOF</code>, not <code>-1</code> for error. The other side behaves similarly, even though you really cannot write to a pipe whose read end is already closed.</p> <p>The behavior is the same with <code>socket.socketpair()</code> (or actual sockets): As long as haven't done anything invalid yet, there's no error condition.</p> <pre><code>log=open("./test.log","w") (reader, writer) = socket.socketpair() def check_parent_select(fh): (rlist, wlist, xlist) = select.select([], [], [fh], 1) if fh in xlist: print "parent exit" else: print "parent OK" def check_parent_poll(fh): poller = select.poll() EVENTS = select.POLLERR poller.register(fh) events = poller.poll() for fd, flag in events: if flag &amp; select.POLLERR: print "parent exit" else: print "parent OK" check_parent_select(writer) reader.close() check_parent_select(writer) </code></pre>
1
2016-08-04T07:29:02Z
[ "python", "linux" ]
select doesn't work for pipe in python?
38,759,184
<p>When using <code>check_parent_select</code>, after the reader side is closed, exception list is not filled.</p> <p>But using <code>check_parent_poll</code>, after the reader side is closed, it can detects the pipe disconnection.</p> <p>Does someone know the root cause?</p> <pre><code>#!/usr/bin/python2.7 import select import sys import os log=open("./test.log","w") (reader, writer) = os.pipe() def check_parent_select(fh): (rlist, wlist, xlist) = select.select([], [], [fh], 1) if fh in xlist: print "parent exit" else: print "parent OK" def check_parent_poll(fh): poller = select.poll() EVENTS = select.POLLERR poller.register(fh) events = poller.poll() for fd, flag in events: if flag &amp; select.POLLERR: print "parent exit" else: print "parent OK" open_file = os.fdopen(writer, "w") check_parent_select(open_file) os.close(reader) check_parent_select(open_file) </code></pre> <p>Used strace to trace select function, select can't detect the pipe close.</p> <blockquote> <p><strong>pipe([4, 5]) = 0</strong></p> <p><strong>select(6, [], [], [5], {1, 0}) = 0 (Timeout)</strong></p> <p>write(1, "parent OK\n", 10parent OK</p> <p><strong>close(4) = 0</strong></p> <p><strong>select(6, [], [], [5], {1, 0}) = 0 (Timeout)</strong></p> </blockquote>
3
2016-08-04T05:35:36Z
38,761,387
<p>A quick fix for mitigating this unexpected result is to listen for read events in the writer. A better fix would be to use pselect() and listen for SIG_PIPE as well but afaik python doesn't have a pselect()</p> <p>I call it "unexpected" because the first thing which comes to your mind is that the closing of the read end will be signaled as an exception for the writer. From the point of view of the writer it may be indeed an exceptional case as long as it still has something to write. But, from the point of view of the OS, this is just a simple close() of a file descriptor.</p> <p>If you read the manpage for poll() system call you will find that the closing of a file descriptor will be signaled by marking the POLLHUP bit in the read events list. select() has the same behavior only that it doesn't have specific bits to set for identifying the close() call.</p> <pre><code>#!/usr/bin/python2.7 import select import sys import os import time log=open("./test.log","w") (reader, writer) = os.pipe() def check_parent_select(fh): (rlist, wlist, xlist) = select.select([fh], [fh], [fh], 1) print(rlist, wlist, xlist) if fh in rlist: print "oh i'm just writing. error" if fh in xlist: print "parent exit" else: print "parent OK" def check_parent_poll(fh): poller = select.poll() EVENTS = select.POLLERR poller.register(fh) events = poller.poll() for fd, flag in events: if flag &amp; select.POLLERR: print "parent exit" else: print "parent OK" #open_file = os.fdopen(writer, "w") check_parent_select(writer) os.close(reader) #time.sleep(3) check_parent_select(writer) </code></pre> <p>so when the pipe is closed you'll get a read event in the writer:</p> <pre><code> python2 t1.py ([], [5], []) parent OK ([5], [5], []) oh i'm just writing. error parent OK </code></pre>
0
2016-08-04T07:46:05Z
[ "python", "linux" ]
RecursionError in Project Euler #5
38,759,256
<p>I'm receiving a "maximum recursion depth exceeded" error when executing my program to solve this problem. Project Euler's <a href="https://projecteuler.net/problem=5" rel="nofollow">question #5</a> asks to find:</p> <blockquote> <p>The smallest positive number that is evenly divisible by all of the numbers from 1 to 10.</p> </blockquote> <p>I've tried to write a program that recursively checks if <code>x</code> is divisible by each integer 1-10, and if it doesn't then we call it again with <code>x</code> incremented by 1 and repeat until <code>x</code> is found. (In this case the answer is 2520, which is why I added the if statement.)</p> <pre><code>def euler5(x): if x &lt; 2521: for i in range(1, 11): if x % i == 0: print(x) else: euler5(x+1) else: print(x) x = 2 print(euler5(x)) </code></pre>
0
2016-08-04T05:41:22Z
38,759,317
<p>In you defined function, you could you a loop even if you do not know math functions. However, your code is not efficient as program has to keep checking the values to see if it matches the condition. Recursion is not recommended as it should be flexible to be used with other values not just for this question. Euler questions are meant to train your coding practices. </p> <p>A better method can be used to simplify your code:</p> <pre><code>from functools import reduce from fractions import gcd def lcm(a,b): return a*b//gcd(a,b) #gcd is greatest common divisor AKA HCF print (reduce(lcm, range(1, 20+1))) </code></pre>
-1
2016-08-04T05:46:50Z
[ "python", "recursion" ]
RecursionError in Project Euler #5
38,759,256
<p>I'm receiving a "maximum recursion depth exceeded" error when executing my program to solve this problem. Project Euler's <a href="https://projecteuler.net/problem=5" rel="nofollow">question #5</a> asks to find:</p> <blockquote> <p>The smallest positive number that is evenly divisible by all of the numbers from 1 to 10.</p> </blockquote> <p>I've tried to write a program that recursively checks if <code>x</code> is divisible by each integer 1-10, and if it doesn't then we call it again with <code>x</code> incremented by 1 and repeat until <code>x</code> is found. (In this case the answer is 2520, which is why I added the if statement.)</p> <pre><code>def euler5(x): if x &lt; 2521: for i in range(1, 11): if x % i == 0: print(x) else: euler5(x+1) else: print(x) x = 2 print(euler5(x)) </code></pre>
0
2016-08-04T05:41:22Z
38,759,451
<p>The reason for this is that Python (or CPython, at least) has a limited stack size and no tail call optimization. So you cannot use unbounded recursion in Python, unlike Scheme (for example).</p> <p>The solution is to use a regular loop:</p> <pre><code>x = 0 while True: x += 1 # Put loop body here </code></pre>
4
2016-08-04T05:55:10Z
[ "python", "recursion" ]
create index based on condition in python
38,759,357
<p>I have data of <strong>5 weeks(35 days)</strong> with me where the <strong>start_date</strong> (1-AUG-2016) is the first date of first week and end_date( ) is the last date on the 5th week. Also i have the hourly data from (say <strong>0 - 23</strong>). </p> <pre><code>day date(dd-mm-yyyy) hour 1 01-01-2016 0 1 01-01-2016 1 1 01-01-2016 2 1 01-01-2016 3 1 01-01-2016 4 1 01-01-2016 5 1 01-01-2016 6 . . 1 01-01-2016 23 . . 35 04-02-2016 0 35 04-02-2016 1 . . </code></pre> <p>And i want to create and index that it counts up till my selected hours (say 3 - 5) and adds 1 to the next index. But the moment it hits non selected hours it should retain its last value. something like this. </p> <pre><code>day date(dd-mm-yyyy) hour Index 1 01-01-2016 0 1 1 01-01-2016 1 1 1 01-01-2016 2 1 1 01-01-2016 3 2 1 01-01-2016 4 3 1 01-01-2016 5 4 1 01-01-2016 6 5 1 01-01-2016 7 5 1 01-01-2016 8 5 . . 1 01-01-2016 23 5 2 02-01-2016 0 5 2 02-01-2016 1 5 2 02-01-2016 2 5 2 02-01-2016 3 6 . 35 04-02-2016 0 35 04-02-2016 1 . . </code></pre> <p>Can we do this in python using loops. we might need to sort the data by day,date and hour. I know this is simple but i am stuck. can we also create a lookup for sequence of date?</p>
1
2016-08-04T05:49:50Z
38,759,645
<p>You can do a counter that should look like this, depending on how your data is structured. I would assume that you have made a list of the hours?</p> <pre> hours = [0,1,2,3,4,5...,23] </pre> <p>You could make a list of what you want to find like this</p> <pre> select = [3,4,5] //This is your selection list.</pre> <p>Then run a for loop through the select list.</p> <pre> count = 0 for i in select: if i in hours: count+=1 </pre> <p><em>So if you want to count for the rest of the weeks, you can multiply by the total number of days, which I assume would be number of days in a week multiplied by the number of weeks.</em></p> <pre> count = count*7*5 </pre> <p>Im sorry if this answer does not meet your requirements, I cannot add comments yet! But this is the best I can give</p>
0
2016-08-04T06:08:32Z
[ "python", "loops", "python-3.x", "pandas" ]
create index based on condition in python
38,759,357
<p>I have data of <strong>5 weeks(35 days)</strong> with me where the <strong>start_date</strong> (1-AUG-2016) is the first date of first week and end_date( ) is the last date on the 5th week. Also i have the hourly data from (say <strong>0 - 23</strong>). </p> <pre><code>day date(dd-mm-yyyy) hour 1 01-01-2016 0 1 01-01-2016 1 1 01-01-2016 2 1 01-01-2016 3 1 01-01-2016 4 1 01-01-2016 5 1 01-01-2016 6 . . 1 01-01-2016 23 . . 35 04-02-2016 0 35 04-02-2016 1 . . </code></pre> <p>And i want to create and index that it counts up till my selected hours (say 3 - 5) and adds 1 to the next index. But the moment it hits non selected hours it should retain its last value. something like this. </p> <pre><code>day date(dd-mm-yyyy) hour Index 1 01-01-2016 0 1 1 01-01-2016 1 1 1 01-01-2016 2 1 1 01-01-2016 3 2 1 01-01-2016 4 3 1 01-01-2016 5 4 1 01-01-2016 6 5 1 01-01-2016 7 5 1 01-01-2016 8 5 . . 1 01-01-2016 23 5 2 02-01-2016 0 5 2 02-01-2016 1 5 2 02-01-2016 2 5 2 02-01-2016 3 6 . 35 04-02-2016 0 35 04-02-2016 1 . . </code></pre> <p>Can we do this in python using loops. we might need to sort the data by day,date and hour. I know this is simple but i am stuck. can we also create a lookup for sequence of date?</p>
1
2016-08-04T05:49:50Z
38,759,999
<p>IIUC you can use:</p> <pre><code>print (df) day date(dd-mm-yyyy) hour 0 1 01-01-2016 0 1 1 01-01-2016 1 2 1 01-01-2016 2 3 1 01-01-2016 3 4 1 01-01-2016 4 5 1 01-01-2016 5 6 1 01-01-2016 6 7 1 01-01-2016 23 8 35 04-02-2016 0 9 35 04-02-2016 1 10 35 04-02-2016 2 11 35 04-02-2016 3 12 35 04-02-2016 4 13 35 04-02-2016 5 14 35 04-02-2016 6 15 35 04-02-2016 7 </code></pre> <pre><code>#create list for lookup hours = [3,4,5] hours = hours + [hours[-1] + 1] print (hours) [3, 4, 5, 6] </code></pre> <p>Check values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow"><code>cumsum</code></a>:</p> <pre><code>print (df.hour.isin(hours)) 0 False 1 False 2 False 3 True 4 True 5 True 6 True 7 False 8 False 9 False 10 False 11 True 12 True 13 True 14 True 15 False Name: hour, dtype: bool </code></pre> <pre><code>df['Index'] = df.hour.isin(hours).cumsum() + 1 print (df) day date(dd-mm-yyyy) hour Index 0 1 01-01-2016 0 1 1 1 01-01-2016 1 1 2 1 01-01-2016 2 1 3 1 01-01-2016 3 2 4 1 01-01-2016 4 3 5 1 01-01-2016 5 4 6 1 01-01-2016 6 5 7 1 01-01-2016 23 5 8 35 04-02-2016 0 5 9 35 04-02-2016 1 5 10 35 04-02-2016 2 5 11 35 04-02-2016 3 6 12 35 04-02-2016 4 7 13 35 04-02-2016 5 8 14 35 04-02-2016 6 9 15 35 04-02-2016 7 9 </code></pre>
1
2016-08-04T06:31:55Z
[ "python", "loops", "python-3.x", "pandas" ]
Python pickle's data can't update in tkinter
38,759,422
<p>here's a part of my code from recent game i've try to make</p> <p>i'm confused about the data loaded from [pickle] cannot apply to the Label in [tkinter]</p> <p>it works when i'm saving and loading the data</p> <pre><code>from tkinter import * import pickle Prvs_controll = [3,3,3,3,3] Prvs_size = [1,1,1,1,1] GameData= [Prvs_controll, Prvs_size] class MainGame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): global canvas self.parent.title('PythonEuropaGame') self.pack(fill=BOTH, expand=1) tkframe = Frame(self) canvas = Canvas(self) canvas.pack(fill = BOTH, expand = 1) canvas.update() def save(): global GameData with open('Save_01.pickle', 'wb') as handle: pickle.dump(GameData, handle) print(GameData) def load(): global canvas global GameData with open('Save_01.pickle', 'rb') as handle: GameData = pickle.load(handle) Label_size_b.configure(text = Prvs_size[0]) print(GameData) def change_controll(): global GameData GameData[0] = [9,9,9,9,9] def change_size(): global GameData GameData[1][0] += 150 Label_size_b.configure(text = Prvs_size[0]) root = Tk() ex = MainGame(root) root.geometry('900x650') Label_size_a = Label(root, text = 'Size') Label_size_b = Label(root, text = '---') Label_size_a.place(x = 700, y = 195) Label_size_b.place(x = 750, y = 195) Button_save = Button(root, text = 'Save', command = save) Button_load = Button(root, text = 'Load', command = load) Button_size_add = Button(root, text = 'Upgrade', command = change_size) Button_save.place(x = 700, y = 500) Button_load.place(x = 750, y = 500) Button_size_add.place(x = 800, y = 225) </code></pre> <p>At first, I called change_size() and save(), </p> <p>it printed "[3, 3, 3, 3, 3], [151, 1, 1, 1, 1]]" </p> <p>and the label[Label_size_b] had showed the change in size(it printed "151) and it is saved.</p> <p>However when I restart the module and call load(), it still print the data above "[3, 3, 3, 3, 3], [151, 1, 1, 1, 1]]" .</p> <p>But the main problem is label[Label_size_b] is printed as "1" but not "151" that mean I changed something and load it, but the Label still print the Original data!(see the top on code)</p> <p>I guess it may be the "global" problem but I can't find any way to correct it.</p>
0
2016-08-04T05:53:39Z
38,759,681
<p>The problem is this line in the <code>load()</code> function:</p> <pre><code>Label_size_b.configure(text = Prvs_size[0]) </code></pre> <p>Here <code>Prvs_size</code> refers to the global variable that is initialised to <code>[1,1,1,1,1]</code> when the script starts, and is never updated. You need to access the values loaded from the pickle file into <code>GameData</code> like this:</p> <pre><code>Label_size_b.configure(text = GameData[1][0]) </code></pre> <p>This accesses the first element of the second list in the <code>GameData</code> list as loaded from the pickled data.</p> <p>There is a similar problem in the <code>change_size()</code> function.</p>
2
2016-08-04T06:11:17Z
[ "python", "tkinter", "label", "pickle" ]
Efficiently find the n-ring of every node in a graph in python
38,759,462
<p>I have a numpy array of M edge definitions that is Mx2 and contains node indexes. For every node, I would like to find edges inside the n-ring (in my case 3-ring) of the node. I have N=250K nodes from a medium dense computational mesh for a numercial model, so I'm looking for something appropriately efficient and sparse.</p>
-3
2016-08-04T05:56:08Z
38,765,016
<pre><code>import numpy as np import networkx as nx G = nx.dorogovtsev_goltsev_mendes_graph(4) edges_list = G.edges() edges_list = np.array(edges_list) one_ring = [] for n in G.nodes(): first = edges_list[edges_list[:, 0] == n, 1] second = edges_list[edges_list[:, 1] == n, 0] one_ring.append(np.hstack([first, second])) N = 3 n_ring = [] def find_n_ring(root, node, i): if i &gt;= N: return node for node2 in one_ring[node]: n_ring_node = find_n_ring(root, node2, i + 1) if n_ring_node is not None and n_ring_node not in n_ring[root]: n_ring[root].append(n_ring_node) for root in G.nodes(): n_ring.append([]) find_n_ring(root, root, 0) print(n_ring) </code></pre>
0
2016-08-04T10:37:05Z
[ "python", "numpy", "graph" ]
converting char to list in R
38,760,090
<p>I wrote a python script for reading mails' content and append to list and calling this python script in R. The problem is R is considering the list as one instead of two elements in it.</p> <p>Here is my python script:</p> <pre><code>{ import sys import string import glob def parseOutText(f): f.seek(0) all_text = f.read() ### split off metadata content = all_text.split("Bcc:") return content def main(): path = "D:/Hadoop/practice/machine_learning/mails/*.txt" files = glob.glob(path) file_list = [] for each_file in files: ff = open(each_file, "r") text = parseOutText(ff) #text = sys.stdout.write(ff.read()) file_list.append(text) ff.close() print(file_list) print(len(file_list)) } </code></pre> <p>and the output for this.</p> <blockquote> <p>[['From: xxx@xxx.com\nTo: xyz@xxx.com\nSubject: Hi\nCc: abc@xxx.com\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n', ' test@xxx.com\n\nHi,\n\nYour problem is resolved. \n\nPlease reply to this email and let us know if it is not working.\n\nThank you \nCCD.'], ['From: abc@xxx.com\nTo: test2@xxx.com\nSubject: Hi\nCc: xyz@xxx.com\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n', ' test@xxx.com\n\nHi,\n\nThis will not work out unless and until you work harder.\n\nThank you \nCCD.']] 2</p> </blockquote> <p>R code:</p> <pre><code>#setting the working directory to the mails folder setwd("D:/Hadoop/practice/machine_learning/mails") command = "python" output = as.list(system2(command, args = "D:/Hadoop/practice/machine_learning/mails/testR.py", stdout = TRUE)) print(output) print(length(output)) print(str(output)) str(command) </code></pre> <p>R output:</p> <blockquote> <p>[[1]] [1] "[['From: xxx@xxx.com\nTo: xyz@xxx.com\nSubject: Hi\nCc: abc@xxx.com\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n', ' test@xxx.com\n\nHi,\n\nYour problem is resolved. \n\nPlease reply to this email and let us know if it is not working.\n\nThank you \nCCD.'], ['From: abc@xxx.com\nTo: test2@xxx.com\nSubject: Hi\nCc: xyz@xxx.com\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\n', ' test@xxx.com\n\nHi,\n\nThis will not work out unless and until you work harder.\n\nThank you \nCCD.']]"</p> <p>print(length(output)) [1] 1</p> </blockquote> <p>How can I get two mails as two elements in the same list?</p> <p>mails:</p> <pre><code>From: xxx@xxx.com To: xyz@xxx.com Subject: Hi Cc: abc@xxx.com Mime-Version: 1.0 Content-Transfer-Encoding: 7bit Bcc: test@xxx.com Hi, Your problem is resolved. Please reply to this email and let us know if it is not working. Thank you CCD. </code></pre> <p>2nd mail:</p> <pre><code>From: abc@xxx.com To: test2@xxx.com Subject: Hi Cc: xyz@xxx.com Mime-Version: 1.0 Content-Transfer-Encoding: 7bit Bcc: test@xxx.com Hi, This will not work out unless and until you work harder. Thank you CCD. </code></pre>
1
2016-08-04T06:36:56Z
38,760,295
<pre><code>l = as.list(cbind(text1, text2)) </code></pre> <p>Gives me the following output:</p> <pre><code>[[1]] [1] " From: xxx@xxx.com\nTo: xyz@xxx.com\nSubject: Hi\nCc: abc@xxx.com\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\nBcc: test@xxx.com\n\nHi,\n\nYour problem is resolved. \n\nPlease reply to this email and let us know if it is not working.\n\nThank you \nCCD." [[2]] [1] "From: abc@xxx.com\nTo: test2@xxx.com\nSubject: Hi\nCc: xyz@xxx.com\nMime-Version: 1.0\nContent-Transfer-Encoding: 7bit\nBcc: test@xxx.com\n\nHi,\n\nThis will not work out unless and until you work harder.\n\nThank you \nCCD." </code></pre>
0
2016-08-04T06:49:25Z
[ "python", "list", "email" ]
place python script in chef cookbook
38,760,128
<p>I have a python script which deploys ear file on a server, how do I execute this script using chef to bootstrap a linux node?</p> <p>Tried a recipe like below, but it couldn't identify my python script which is present inside "mycookbook\files\default\deploy.py" folder of my cookbook.</p> <pre><code>execute 'executeFile' do command "python #{'deploy.py'}" end </code></pre> <p>Tried giving full file path still it didn't recognise the file. How to execute a python script inside a cookbook using execute resource of chef?</p>
0
2016-08-04T06:39:23Z
38,760,995
<p>Using the <code>poise-python</code> cookbook's <code>python_execute</code> resource:</p> <pre><code>cookbook_file "/root/deploy.py" do source "deploy.py" end python_execute "/root/deploy.py" </code></pre> <p>You could also use a normal <code>execute</code> resource if you tweak the command line. The important bit is you need to use <code>cookbook_file</code> to actually copy out the file from the cookbook to somewhere on the node.</p>
2
2016-08-04T07:26:43Z
[ "python", "chef", "chef-recipe" ]
Need help understanding index_col in read_excel (pandas)
38,760,429
<p>I have an excel file where the first column is "ID" and the items are of the form IDXXX. </p> <p>This code</p> <pre><code>s = pd.read_excel('error4.xlsx', keep_default_na = False, index_col = 0) </code></pre> <p>Comes up with the error</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#324&gt;", line 1, in &lt;module&gt; shit = pd.read_excel('error4.xlsx', keep_default_na = False, index_col = 0) File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 170, in read_excel io = ExcelFile(io, engine=engine) File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 438, in _parse_excel if not com.is_list_like(header): File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 740, in read if fallback_reason: File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 1601, in read self._make_reader(f) File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 910, in _make_index File "C:\Python27\lib\site-packages\pandas\io\parsers.py", line 1002, in _agg_index % ','.join([str(x) for x in self.header]) TypeError: unsupported operand type(s) for |: 'list' and 'set' </code></pre> <p>I have tried reading the documentation but I don't get it. It works fine if I remove <code>index_col = 0</code>. <code>index_col = 'ID'</code> doesn't work either.</p>
0
2016-08-04T06:56:32Z
38,761,274
<p>The error is coming due to the option:</p> <pre><code>keep_default_na = False </code></pre> <p>According to the documentation:</p> <pre><code>na_values : str or list-like or dict, default None Additional strings to recognize as NA/NaN. If dict passed, specific per-column NA values. By default the following values are interpreted as NaN: ‘’, ‘#N/A’, ‘#N/A N/A’, ‘#NA’, ‘-1.#IND’, ‘-1.#QNAN’, ‘-NaN’, ‘-nan’, ‘1.#IND’, ‘1.#QNAN’, ‘N/A’, ‘NA’, ‘NULL’, ‘NaN’, ‘nan’. keep_default_na : bool, default True If na_values are specified and keep_default_na is False the default NaN values are overridden, otherwise they’re appended to. </code></pre> <p>So if you have no specified any new values that are to be converted to NaN why do you need this option</p> <h1>EDIT</h1> <p>If you have a file with a single column,say i have a file output2.csv with a single column :</p> <pre><code> cmfa -0.0019 -0.0018 -0.0033 </code></pre> <p>if you use the following command `</p> <pre><code>s = pd.read_csv('output2.csv',keep_default_na = False,index_col=0) </code></pre> <p>it will throw out an error saying <code>TypeError: unsupported operand type(s) for |: 'list' and 'set'</code></p> <p>Because the dataset does not have any columns to operate on and retain NaN values as you are trying with the keep_default_na statement. It just has an index determined by your column.</p> <p>However the following works as expected <code>s = pd.read_csv('output2.csv',index_col=0)</code> </p> <p>and gives an output (Note there are no columns)</p> <pre><code>print s Empty DataFrame Columns: [] Index: [-0.0019, -0.0018, -0.0033] </code></pre> <p>If you do want to keep an <code>keep_default_na=False</code> statement then you have to do away with <code>index_col=0</code> option since the statement needs some values to operate on and let the dataframe have the default indexing of 0,1,2,3 etc.</p> <h1>EDIT2</h1> <p>It seems pandas does not work when you club the <code>index_col</code> and <code>keep_default_na = False</code> statement, that being said as per the documentation it also does not expect the <code>keep_default_na = False</code> to be specified without specifying <code>na_values</code></p> <p>So use the following in your case :</p> <pre><code>s = pd.read_csv('output.csv',na_values=[],keep_default_na = False,index_col=0) </code></pre> <p>If you are not specifying <code>na_values</code>, <code>keep_default_na=False</code> works standalone if <code>index_col = None or False</code> else it will throw out an error for any other value of <code>index_col</code>. So a good programming practice is to use the <code>na_values</code> option in such cases, although I do agree there should be better error handling in pandas regarding this.</p>
0
2016-08-04T07:40:01Z
[ "python", "pandas" ]
Why template path is different and rendered content is different in mezzanine?
38,760,510
<p>I have two free themes in mezzanine - <code>solid &amp; moderna</code> taken from - <a href="https://github.com/thecodinghouse/mezzanine-themes" rel="nofollow">HERE</a>.</p> <p>I simply want to run the <code>HOST_THEMES</code> feature of <code>mezzanine</code>. So I went ahead and loaded both the themes in my <code>INSTALLED_APPS</code> like this - </p> <pre><code>INSTALLED_APPS = ( "moderna", "solid", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.redirects", "django.contrib.sessions", "django.contrib.sites", "django.contrib.sitemaps", "django.contrib.staticfiles", "mezzanine.boot", "mezzanine.conf", "mezzanine.core", "mezzanine.generic", "mezzanine.pages", "mezzanine.blog", "mezzanine.forms", "mezzanine.galleries", "mezzanine.twitter", 'mezzanine_api', 'rest_framework', 'rest_framework_swagger', 'oauth2_provider', # "mezzanine.accounts", # "mezzanine.mobile", ) </code></pre> <p>AFter that I configured my code and ran on <code>0.0.0.0:8000</code>. Then I made two hosts in my <code>HOST_THEMES</code> settings like this</p> <pre><code>HOST_THEMES = [("localhost:8000", "solid"), ("192.168.1.130:8000", "moderna")] </code></pre> <p>Everyone wondering why the <code>:8000</code> in my hosts because of this line in code - <code>Line 25</code></p> <pre><code>if host.lower() == domain.lower(): </code></pre> <p>if I don't set my host with the ports the equality fails.</p> <p>So after this I am debugging step by step for which templates are picking up. <a href="http://i.stack.imgur.com/S8Uz9.png" rel="nofollow"><img src="http://i.stack.imgur.com/S8Uz9.png" alt="Host and themes match here clearly"></a></p> <p>And the template directory is also correctly selected: <a href="http://i.stack.imgur.com/lAzgX.png" rel="nofollow"><img src="http://i.stack.imgur.com/lAzgX.png" alt="solid theme being picked up from my directory"></a></p> <p><a href="http://i.stack.imgur.com/LcbHx.png" rel="nofollow"><img src="http://i.stack.imgur.com/LcbHx.png" alt="As you can see in the &lt;code&gt;rendered_content&lt;/code&gt; you will find moderna being rendered always because its on top and &lt;code&gt;template_name&lt;/code&gt; being the template from &lt;code&gt;solid&lt;/code&gt; directory"></a></p> <p>What exactly I am doing wrong?</p>
0
2016-08-04T07:01:30Z
38,764,690
<p>Hey Guys I was able to solve this by - 1. Making custom <code>Hosts</code> in <code>/etc/hosts</code></p> <p>Made two custom hosts and bind them to my IP and voila it worked</p> <p>I don't know why this doesn't work with <code>localhost</code> or <code>127.0.0.1</code></p>
0
2016-08-04T10:20:56Z
[ "python", "django", "multi-tenant", "mezzanine", "django-sites" ]
imap not allowing use of gmail folders - mail.select folder other than 'inbox'
38,760,698
<p>Basically as stated in the title, I'm using</p> <pre><code>mail.select("inbox") result, data = mail.search(None, "ALL") ids = data[0] # data is a list. id_list = ids.split() # ids is a space separated string latest_email_id = id_list[-1] # get the latest </code></pre> <p>To get the most recent email from the inbox. Theoretically you can change 'inbox' to another label or folder in gmail (my labels and folders showed up using mail.list() just fine). I want to use my label "Server Status/Leviathan" but it throws the error</p> <pre><code>Traceback (most recent call last): File "E:\False Apparition\Desktop\test3.py", line 18, in &lt;module&gt; mail.select("Server Status/Leviathan") File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 737, in select typ, dat = self._simple_command(name, mailbox) File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1188, in _simple_command return self._command_complete(name, self._command(name, *args)) File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1019, in _command_complete raise self.error('%s command error: %s %s' % (name, typ, data)) imaplib.error: SELECT command error: BAD [b'Could not parse command'] </code></pre> <p>Which is different than if the label doesn't exist on gmail...</p> <pre><code>Traceback (most recent call last): File "E:\False Apparition\Desktop\test3.py", line 20, in &lt;module&gt; result, data = mail.search(None, "ALL") File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 715, in search typ, dat = self._simple_command(name, *criteria) File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 1188, in _simple_command return self._command_complete(name, self._command(name, *args)) File "C:\Users\Ancient Abysswalker\AppData\Local\Programs\Python\Python36-32\lib\imaplib.py", line 936, in _command ', '.join(Commands[name]))) imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED </code></pre> <p>Am I missing something? A library perhaps?</p>
1
2016-08-04T07:12:09Z
38,811,028
<p>Add quotes around your folder name. Imaplib should do this for you, but it doesn't: <code>mail.select('"folder with space"')</code></p>
0
2016-08-07T05:01:25Z
[ "python", "email", "gmail", "imap" ]
How Apache manages HTTP request when it is python which is going to response? it is thread based or process based?
38,760,716
<p>What i mean is when some one makes a http request, does it like apache spawn a <strong>new process or thread</strong>. My configuration is <code>apache + python with wsgi module</code>. </p>
0
2016-08-04T07:13:01Z
38,760,814
<p>Neither. Requests will be handled by the already running single thread, or a thread from a preallocated thread pool. For more information about how it works with mod_wsgi read:</p> <ul> <li><a href="http://modwsgi.readthedocs.io/en/develop/user-guides/processes-and-threading.html" rel="nofollow">http://modwsgi.readthedocs.io/en/develop/user-guides/processes-and-threading.html</a></li> </ul> <p>Be aware that it is better to use daemon mode of mod_wsgi and disable Python inside the main Apache processes altogether. For details of that see:</p> <ul> <li><a href="http://blog.dscpl.com.au/2012/10/why-are-you-using-embedded-mode-of.html" rel="nofollow">http://blog.dscpl.com.au/2012/10/why-are-you-using-embedded-mode-of.html</a></li> <li><a href="http://blog.dscpl.com.au/2009/11/save-on-memory-with-modwsgi-30.html" rel="nofollow">http://blog.dscpl.com.au/2009/11/save-on-memory-with-modwsgi-30.html</a></li> </ul>
1
2016-08-04T07:17:35Z
[ "python", "multithreading", "apache", "process", "wsgi" ]
How to index a Cartesian product
38,760,783
<p>Suppose that the variables <code>x</code> and <code>theta</code> can take the possible values <code>[0, 1, 2]</code> and <code>[0, 1, 2, 3]</code>, respectively.</p> <p>Let's say that in one realization, <code>x = 1</code> and <code>theta = 3</code>. The natural way to represent this is by a tuple <code>(1,3)</code>. However, I'd like to instead label the state <code>(1,3)</code> by a single index. A 'brute-force' method of doing this is to form the Cartesian product of all the possible ordered pairs <code>(x,theta)</code> and look it up:</p> <pre><code>import numpy as np import itertools N_x = 3 N_theta = 4 np.random.seed(seed = 1) x = np.random.choice(range(N_x)) theta = np.random.choice(range(N_theta)) def get_box(x, N_x, theta, N_theta): states = list(itertools.product(range(N_x),range(N_theta))) inds = [i for i in range(len(states)) if states[i]==(x,theta)] return inds[0] print (x, theta) box = get_box(x, N_x, theta, N_theta) print box </code></pre> <p>This gives <code>(x, theta) = (1,3)</code> and <code>box = 7</code>, which makes sense if we look it up in the <code>states</code> list:</p> <p><code>[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]</code></p> <p>However, this 'brute-force' approach seems inefficient, as it should be possible to determine the index beforehand without looking it up. Is there any general way to do this? (The number of states <code>N_x</code> and <code>N_theta</code> may vary in the actual application, and there might be more variables in the Cartesian product).</p>
0
2016-08-04T07:16:30Z
38,760,928
<p>If you always store your <code>states</code> lexicographically and the possible values for <code>x</code> and <code>theta</code> are always the complete range from <code>0</code> to some maximum as your examples suggests, you can use the formula</p> <pre><code>index = x * N_theta + theta </code></pre> <p>where <code>(x, theta)</code> is one of your tuples.</p> <p>This generalizes in the following way to higher dimensional tuples: If <code>N</code> is a list or tuple representing the ranges of the variables (so <code>N[0]</code> is the number of possible values for the first variable, etc.) and <code>p</code> is a tuple, you get the index into a lexicographically sorted list of all possible tuples using the following snippet:</p> <pre><code>index = 0 skip = 1 for dimension in reversed(range(len(N))): index += skip * p[dimension] skip *= N[dimension] </code></pre> <p>This might not be the most Pythonic way to do it but it shows what is going on: You think of your tuples as a hypercube where you can only go along one dimension, but if you reach the edge, your coordinate in the "next" dimension increases and your traveling coordinate resets. The reader is advised to draw some pictures. ;)</p>
3
2016-08-04T07:23:18Z
[ "python" ]
How to index a Cartesian product
38,760,783
<p>Suppose that the variables <code>x</code> and <code>theta</code> can take the possible values <code>[0, 1, 2]</code> and <code>[0, 1, 2, 3]</code>, respectively.</p> <p>Let's say that in one realization, <code>x = 1</code> and <code>theta = 3</code>. The natural way to represent this is by a tuple <code>(1,3)</code>. However, I'd like to instead label the state <code>(1,3)</code> by a single index. A 'brute-force' method of doing this is to form the Cartesian product of all the possible ordered pairs <code>(x,theta)</code> and look it up:</p> <pre><code>import numpy as np import itertools N_x = 3 N_theta = 4 np.random.seed(seed = 1) x = np.random.choice(range(N_x)) theta = np.random.choice(range(N_theta)) def get_box(x, N_x, theta, N_theta): states = list(itertools.product(range(N_x),range(N_theta))) inds = [i for i in range(len(states)) if states[i]==(x,theta)] return inds[0] print (x, theta) box = get_box(x, N_x, theta, N_theta) print box </code></pre> <p>This gives <code>(x, theta) = (1,3)</code> and <code>box = 7</code>, which makes sense if we look it up in the <code>states</code> list:</p> <p><code>[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]</code></p> <p>However, this 'brute-force' approach seems inefficient, as it should be possible to determine the index beforehand without looking it up. Is there any general way to do this? (The number of states <code>N_x</code> and <code>N_theta</code> may vary in the actual application, and there might be more variables in the Cartesian product).</p>
0
2016-08-04T07:16:30Z
38,762,634
<p>I think it depends on the data you have. If they are sparse, the best solution is a dictionary. And works for any tuple's dimension. <br></p> <pre><code>import itertools import random n = 100 m = 100 l1 = [i for i in range(n)] l2 = [i for i in range(m)] a = {} prod = [element for element in itertools.product(l1, l2)] for i in prod: a[i] = random.randint(1, 100) </code></pre> <p>A very good source about the performance is in <a href="http://stackoverflow.com/questions/513882/python-list-vs-dict-for-look-up-table">this discution</a>.</p>
0
2016-08-04T08:48:09Z
[ "python" ]
How to index a Cartesian product
38,760,783
<p>Suppose that the variables <code>x</code> and <code>theta</code> can take the possible values <code>[0, 1, 2]</code> and <code>[0, 1, 2, 3]</code>, respectively.</p> <p>Let's say that in one realization, <code>x = 1</code> and <code>theta = 3</code>. The natural way to represent this is by a tuple <code>(1,3)</code>. However, I'd like to instead label the state <code>(1,3)</code> by a single index. A 'brute-force' method of doing this is to form the Cartesian product of all the possible ordered pairs <code>(x,theta)</code> and look it up:</p> <pre><code>import numpy as np import itertools N_x = 3 N_theta = 4 np.random.seed(seed = 1) x = np.random.choice(range(N_x)) theta = np.random.choice(range(N_theta)) def get_box(x, N_x, theta, N_theta): states = list(itertools.product(range(N_x),range(N_theta))) inds = [i for i in range(len(states)) if states[i]==(x,theta)] return inds[0] print (x, theta) box = get_box(x, N_x, theta, N_theta) print box </code></pre> <p>This gives <code>(x, theta) = (1,3)</code> and <code>box = 7</code>, which makes sense if we look it up in the <code>states</code> list:</p> <p><code>[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 1), (1, 2), (1, 3), (2, 0), (2, 1), (2, 2), (2, 3)]</code></p> <p>However, this 'brute-force' approach seems inefficient, as it should be possible to determine the index beforehand without looking it up. Is there any general way to do this? (The number of states <code>N_x</code> and <code>N_theta</code> may vary in the actual application, and there might be more variables in the Cartesian product).</p>
0
2016-08-04T07:16:30Z
38,765,852
<p>For the sake of completeness I'll include my implementation of Julian Kniephoff's solution, <code>get_box3</code>, with a slightly adapted version of the original implementation, <code>get_box2</code>:</p> <pre><code># 'Brute-force' method def get_box2(p, N): states = list(itertools.product(*[range(n) for n in N])) return states.index(p) # 'Analytic' method def get_box3(p, N): index = 0 skip = 1 for dimension in reversed(range(len(N))): index += skip * p[dimension] skip *= N[dimension] return index p = (1,3,2) # Tuple characterizing the total state of the system N = [3,4,3] # List of the number of possible values for each state variable print "Brute-force method yields %s" % get_box2(p, N) print "Analytical method yields %s" % get_box3(p, N) </code></pre> <p>Both the 'brute-force' and 'analytic' method yield the same result:</p> <pre><code>Brute-force method yields 23 Analytical method yields 23 </code></pre> <p>but I expect the 'analytic' method to be faster. I've changed the representation to <code>p</code> and <code>N</code> as suggested by Julian.</p>
0
2016-08-04T11:16:00Z
[ "python" ]
How do you transpose a dask dataframe (convert columns to rows) to approach tidy data principles
38,760,864
<p><strong>TLDR</strong>: I created a dask dataframe from a dask bag. The dask dataframe treats every observation (event) as a column. So, instead of having rows of data for each event, I have a column for each event. The goal is to transpose the columns to rows in the same way that pandas can transpose a dataframe using df.T.</p> <p><strong>Details</strong>: I have <a href="https://s3.amazonaws.com/lc3-static/sampleTwitter.json" rel="nofollow">sample twitter data from my timeline here</a>. To get to my starting point, here is the code to read a json from disk into a <code>dask.bag</code> and then convert that into a <code>dask.dataframe</code></p> <pre class="lang-py prettyprint-override"><code>import dask.bag as db import dask.dataframe as dd import json b = db.read_text('./sampleTwitter.json').map(json.loads) df = b.to_dataframe() df.head() </code></pre> <p><strong>The Problem</strong> All my individual events (i.e. tweets) are recorded as columns vice rows. In keeping with <code>tidy</code> principles, I would like to have rows for each event. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.transpose.html" rel="nofollow"><code>pandas</code> has a transpose method for dataframes</a> and dask.array has a transpose method for arrays. My goal is to do the same transpose operation, but on a dask dataframe. How would I do that?</p> <ol> <li>Convert rows to columns</li> </ol> <h1>Edit for solution</h1> <p>This code resolves the original transpose problem, cleans Twitter json files by defining the columns you want to keep and dropping the rest, and creates a new column by applying a function to a Series. Then, we write a MUCH smaller, cleaned file to disk. </p> <pre class="lang-py prettyprint-override"><code>import dask.dataframe as dd from dask.delayed import delayed import dask.bag as db from dask.diagnostics import ProgressBar,Profiler, ResourceProfiler, CacheProfiler import pandas as pd import json import glob # pull in all files.. filenames = glob.glob('~/sampleTwitter*.json') # df = ... # do work with dask.dataframe dfs = [delayed(pd.read_json)(fn, 'records') for fn in filenames] df = dd.from_delayed(dfs) # see all the fields of the dataframe fields = list(df.columns) # identify the fields we want to keep keepers = ['coordinates','id','user','created_at','lang'] # remove the fields i don't want from column list for f in keepers: if f in fields: fields.remove(f) # drop the fields i don't want and only keep whats necessary df = df.drop(fields,axis=1) clean = df.coordinates.apply(lambda x: (x['coordinates'][0],x['coordinates'][1]), meta= ('coords',tuple)) df['coords'] = clean # making new filenames from old filenames to save cleaned files import re newfilenames = [] for l in filenames: newfilenames.append(re.search('(?&lt;=\/).+?(?=\.)',l).group()+'cleaned.json') #newfilenames # custom saver function for dataframes using newfilenames def saver(frame,filename): return frame.to_json('./'+filename) # converting back to a delayed object dfs = df.to_delayed() writes = [(delayed((saver)(df, fn))) for df, fn in zip(dfs, newfilenames)] # writing the cleaned, MUCH smaller objects back to disk dd.compute(*writes) </code></pre>
1
2016-08-04T07:19:40Z
38,799,815
<p>I think you can get the result you want by bypassing bag altogether, with code like</p> <pre><code>import glob import pandas as pd import dask.dataframe as dd from dask.delayed import delayed filenames = glob.glob('sampleTwitter*.json') dfs = [delayed(pd.read_json)(fn, 'records') for fn in filenames] ddf = dd.from_delayed(dfs) </code></pre>
1
2016-08-06T01:41:54Z
[ "python", "twitter", "dataframe", "transpose", "dask" ]
Cannot create entry
38,760,988
<p>Django version 1.10, python version 3.4</p> <p>I type and execute this code in manage.py shell:</p> <pre><code>from tweet.models import Tweet tweet = Tweet("Parse JSON like a boss", "Admin") tweet.save() </code></pre> <p>and receive message with error:</p> <blockquote> <p>invalid literal for int() with base 10: 'Parse JSON like a Boss'</p> </blockquote> <p>models.py:</p> <pre><code>class Tweet(models.Model): text = models.TextField() pub_time = models.DateTimeField(auto_now_add=True) author = models.CharField(max_length=100) class Meta: ordering = ['-pub_time'] </code></pre>
2
2016-08-04T07:26:22Z
38,761,016
<p>When you are not specifying values for all the fields in a model, you should send in the values that you do have as name value pairs.</p> <pre><code>Tweet(text="Parse JSON like a boss", author="admin") </code></pre> <p>in fact, it's a best practice to do this all the time so that changes to the model in the future do not break your code elsewhere. Also it's the recommended way in the <a href="https://docs.djangoproject.com/en/1.9/ref/models/instances/" rel="nofollow">manual</a>:</p> <blockquote> <p>To create a new instance of a model, just instantiate it like any other Python class:</p> <p>class Model(**kwargs)[source]¶ The keyword arguments are simply the names of the fields you’ve defined on your model. Note that instantiating a model in no way touches your database; for that, you need to save().</p> </blockquote>
4
2016-08-04T07:27:41Z
[ "python", "django", "sqlite" ]
Cannot create entry
38,760,988
<p>Django version 1.10, python version 3.4</p> <p>I type and execute this code in manage.py shell:</p> <pre><code>from tweet.models import Tweet tweet = Tweet("Parse JSON like a boss", "Admin") tweet.save() </code></pre> <p>and receive message with error:</p> <blockquote> <p>invalid literal for int() with base 10: 'Parse JSON like a Boss'</p> </blockquote> <p>models.py:</p> <pre><code>class Tweet(models.Model): text = models.TextField() pub_time = models.DateTimeField(auto_now_add=True) author = models.CharField(max_length=100) class Meta: ordering = ['-pub_time'] </code></pre>
2
2016-08-04T07:26:22Z
38,761,102
<p>If you're not using kwargs, then django iterates over the args you provide in the same order that the fields are inside the internal fields dictionary (<a href="https://github.com/django/django/blob/master/django/db/models/base.py#L478" rel="nofollow">Source Code</a>),</p> <p>What it appears to be doing is trying to assign your text to the id parameter, which only accepts integers.</p> <p>So yes, as e4c5 shows, you are much better off using kwargs.</p>
0
2016-08-04T07:31:43Z
[ "python", "django", "sqlite" ]
Get source code containing all information in google feedback box?
38,761,009
<p>I want to parse all the text in Google feedback cards using BeautifulSoup. </p> <p>For query "<em>define apple</em>" Google shows info card with a <a href="http://i.stack.imgur.com/xCbTZ.png" rel="nofollow">drop down menu</a>. I want to parse all the text in <a href="http://i.stack.imgur.com/69QIH.png" rel="nofollow">there</a>. </p> <p>The similar questions is <a href="http://stackoverflow.com/questions/37381946/how-can-i-get-the-contents-of-the-feedback-box-from-google-searches">here</a> but the solution doesn't parses the full box (after drop down) because the source code fetch by <code>requests.get(url)</code> doesn't contain that information. </p> <p>Is there a way that I can get the whole source code without <strong>selenium</strong>.</p>
0
2016-08-04T07:27:31Z
38,764,542
<p>You do get all the source back using <em>requests</em>, the only issue you may have is some of the output are images:</p> <pre><code>headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36", } soup = BeautifulSoup(requests.get("https://www.google.ie/search?q=define+apple", headers=headers).content, "lxml") div = soup.select("div.lr_dct_ent span") desc = "\n".join(sp.text.strip("; ") for sp in div) img = soup.select_one("div.lr_dct_ent").find_next("img") print(desc) print(img["src"]) print "\n".join(d.text for d in soup.select("div.vk_sh.vk_gy")) </code></pre> <p>Which gives you:</p> <pre><code>apple ˈap(ə)l/ ˈap(ə)l noun noun: apple plural noun: apples noun: apple tree plural noun: apple trees the round fruit of a tree of the rose family, which typically has thin green or red skin and crisp flesh. used in names of unrelated fruits or other plant growths that resemble apples in some way, e.g. custard apple, oak apple. the tree bearing apples, with hard pale timber that is used in carpentry and to smoke food. Old English æppel, of Germanic origin; related to Dutch appel and German Apfel . data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== Origin Use over time for: apple </code></pre>
0
2016-08-04T10:14:48Z
[ "python", "beautifulsoup", "python-requests" ]
How to pass current directory as argument to a script?
38,761,013
<p>Is this possible in Python? I'm working on linux so I'm wondering if there is a way to combine bash commands when invoking the script (something like pwd).</p>
0
2016-08-04T07:27:35Z
38,761,070
<p>To get the current working directory, you can use:</p> <pre><code>import os os.getcwd() </code></pre> <p>If you want to run bash commands, @DeepSpace notes that <code>subprocess</code> is preferred to <code>os.system</code>, syntax like this:</p> <pre><code>import subprocess subprocess.call("pwd") </code></pre> <p><code>os.system</code> is still functional though, you can do something like this:</p> <pre><code>import os os.system("pwd") </code></pre>
3
2016-08-04T07:30:14Z
[ "python", "arguments" ]
How to pass current directory as argument to a script?
38,761,013
<p>Is this possible in Python? I'm working on linux so I'm wondering if there is a way to combine bash commands when invoking the script (something like pwd).</p>
0
2016-08-04T07:27:35Z
38,761,087
<p>Yes. You can use <a href="https://docs.python.org/3.5/library/os.html#os.curdir" rel="nofollow">os.curdir</a>, combined with <a href="https://docs.python.org/3.5/library/os.path.html#os.path.abspath" rel="nofollow">os.path.abspath</a></p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.path.abspath(os.path.curdir) '/home/msvalkon' </code></pre>
3
2016-08-04T07:31:00Z
[ "python", "arguments" ]
boost python list get item causing error when i use operator[]
38,761,141
<p>i use boost 1.57 and boost python. here is my code example:</p> <pre><code>list records = call_method&lt;list&gt;(...); object attr = records.attr("__len__")(); int n = extract&lt;long&gt;(attr); for (int i = 0; i &lt; n; ++i) { records[i]; }//here cause error </code></pre> <p>in this list i have stored some tuples contained strings from python. it seems that records[i] out of this scope will call Py_DECREF and cause error. , so how should i do to get data from item?</p>
3
2016-08-04T07:33:28Z
38,783,690
<p>It seems that some operator[] may cause these phenomenon, so I have to avoid it and use following solution:</p> <pre><code>#include &lt;boost/python/stl_iterator.hpp&gt; list records = call_method&lt;list&gt;(...); stl_input_iterator&lt;tuple&gt; end; for (stl_input_iterator&lt;tuple&gt; itr(records); itr != end;++itr) { auto record = *itr; std::string tick = call_method&lt;std::string&gt;(record.ptr(), "__getitem__", 0); ... } </code></pre>
0
2016-08-05T07:36:51Z
[ "python", "c++", "list", "boost" ]
How to update all rows in particular column of pandas dataframe in python?
38,761,142
<p>I want to read a csv file and store this file in pandas data-frame, after that I want to check one column value is equal to constant variable and that equal rows should be kept in separate data-frame.</p> <p>Next step is to update one column from the separate data-frame. In this step I'm iterating through whole data-frame and updating all the rows of particular column, so it will take too much time because my data-frame is has thousands of rows.</p> <p><strong>Input.csv-</strong></p> <pre><code>line_no,time 205,1467099122677889 205,1467099122677889 206,1467099363719028 207,1467099363818373 207,1467099363918360 208,1467099363818373 210,1467099363958749 </code></pre> <p><strong>Program-</strong></p> <pre><code>import pandas as pd if __name__ == "__main__": file_path = 'Input.csv' input_line_no = 205 pd_dataframe = pd.read_csv(file_path,delimiter=',',keep_default_na=False) match_df = pd.DataFrame(pd_dataframe.loc[pd_dataframe['line_no'] == int(input_line_no)]) if match_df.empty: print 'Given line no is not present in dataframe.' sys.exit(1) match_df = match_df.applymap(str) for index in range(0,len(match_df.index)): epoch_time = match_df.iloc[index]['time'] stamp = int(str(epoch_time)+'0') date = datetime.datetime.fromtimestamp(stamp / 10000000.0).strftime('%H:%M:%S %f')[:-3] match_df['time'].apply(str) match_df.iloc[index]['time'] = date print match_df.to_csv(index=False) </code></pre> <p>This time column is in epoch time I want to convert it into the human readable timestamp so logic is for that purpose only. </p> <p>But I'm facing execution time issue regarding to this task. Is there any other way to update the existing data-frame's column in the faster manner?</p>
1
2016-08-04T07:33:29Z
38,761,685
<p>IIUC you can use first:</p> <pre><code>match_df = pd_dataframe[pd_dataframe['line_no'] == int(input_line_no)].copy() print (match_df) line_no time 0 205 1467099122677889 1 205 1467099122677889 </code></pre> <p>You can use <code>apply</code>, because <a href="http://pandas.pydata.org/pandas-docs/stable/timeseries.html#timestamp-limitations" rel="nofollow">timestamp limitations</a>: </p> <blockquote> <p>In [55]: pd.Timestamp.max<br> Out[55]: Timestamp('2262-04-11 23:47:16.854775807') </p> </blockquote> <pre><code>match_df['time'] = match_df.time .apply(lambda x: datetime.datetime.fromtimestamp(int(str(x)+'0') / 10000000.0)) print (match_df) line_no time 0 205 2016-06-28 09:32:02.677889 1 205 2016-06-28 09:32:02.677889 </code></pre> <p>And then:</p> <pre><code>match_df['time'] = match_df.time .apply(lambda x: datetime.datetime.fromtimestamp(int(str(x)+'0') / 10000000.0).strftime('%H:%M:%S %f')[:-3]) print (match_df) line_no time 0 205 09:32:02 677 1 205 09:32:02 677 </code></pre>
1
2016-08-04T08:01:03Z
[ "python", "csv", "pandas", "indexing", "dataframe" ]
SSL bad Handshake Error 10054 "WSAECONNRESET"
38,761,166
<p><strong>Notes:</strong></p> <pre><code>versions Python 2.7.11 and my requests version is '2.10.0' 'OpenSSL 1.0.2d 9 Jul 2015' Please read the below comment by Martijn Pieters before reproducing </code></pre> <p>Initially I tried to get pdf from <code>https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx</code> using code as below</p> <p><strong>code1:</strong></p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; requests.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx",verify=False) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 67, in get return request('get', url, params=params, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESE T')",) </code></pre> <p>After googling and searching I found that you have use SSL verification and using session with adapters can solve the problem. But I still got error's please find the code and error's below</p> <p><strong>Code2:</strong> </p> <pre><code>import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager import ssl import traceback class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1) s = requests.Session() s.mount('https://', MyAdapter()) print "Mounted " r = s.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx", stream=True, timeout=120) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 480, in get return self.request('GET', url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESET')",) </code></pre>
10
2016-08-04T07:34:30Z
38,827,932
<p>I use python 2.7.6 and this simple example still working on my ubuntu 14.04</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) with open('out.docx', 'wb') as h : r = requests.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx", verify=False, stream=True) for block in r.iter_content(1024): h.write(block) </code></pre>
0
2016-08-08T11:21:36Z
[ "python", "python-2.7", "ssl", "python-requests" ]
SSL bad Handshake Error 10054 "WSAECONNRESET"
38,761,166
<p><strong>Notes:</strong></p> <pre><code>versions Python 2.7.11 and my requests version is '2.10.0' 'OpenSSL 1.0.2d 9 Jul 2015' Please read the below comment by Martijn Pieters before reproducing </code></pre> <p>Initially I tried to get pdf from <code>https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx</code> using code as below</p> <p><strong>code1:</strong></p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; requests.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx",verify=False) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 67, in get return request('get', url, params=params, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESE T')",) </code></pre> <p>After googling and searching I found that you have use SSL verification and using session with adapters can solve the problem. But I still got error's please find the code and error's below</p> <p><strong>Code2:</strong> </p> <pre><code>import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager import ssl import traceback class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1) s = requests.Session() s.mount('https://', MyAdapter()) print "Mounted " r = s.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx", stream=True, timeout=120) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 480, in get return self.request('GET', url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESET')",) </code></pre>
10
2016-08-04T07:34:30Z
38,883,759
<p>This snippet works for me (py2.7.11 64bits + requests==2.10.0) on windows7:</p> <pre><code>import requests import ssl import traceback import shutil from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1) if __name__ == "__main__": s = requests.Session() s.mount('https://', MyAdapter()) print "Mounted " filename = "N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx" r = s.get( "https://www.neco.navy.mil/necoattach/{0}".format(filename), verify=False, stream=True, timeout=120) if r.status_code == 200: with open(filename, 'wb') as f: r.raw.decode_content = True shutil.copyfileobj(r.raw, f) </code></pre>
1
2016-08-10T21:19:21Z
[ "python", "python-2.7", "ssl", "python-requests" ]
SSL bad Handshake Error 10054 "WSAECONNRESET"
38,761,166
<p><strong>Notes:</strong></p> <pre><code>versions Python 2.7.11 and my requests version is '2.10.0' 'OpenSSL 1.0.2d 9 Jul 2015' Please read the below comment by Martijn Pieters before reproducing </code></pre> <p>Initially I tried to get pdf from <code>https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx</code> using code as below</p> <p><strong>code1:</strong></p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; requests.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx",verify=False) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 67, in get return request('get', url, params=params, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\api.py", line 53, in request return session.request(method=method, url=url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESE T')",) </code></pre> <p>After googling and searching I found that you have use SSL verification and using session with adapters can solve the problem. But I still got error's please find the code and error's below</p> <p><strong>Code2:</strong> </p> <pre><code>import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.poolmanager import PoolManager import ssl import traceback class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1) s = requests.Session() s.mount('https://', MyAdapter()) print "Mounted " r = s.get("https://www.neco.navy.mil/necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx", stream=True, timeout=120) </code></pre> <p><strong>Error:</strong></p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 480, in get return self.request('GET', url, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 468, in request resp = self.send(prep, **send_kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\sessions.py", line 576, in send r = adapter.send(request, **kwargs) File "C:\Users\mob140003207\AppData\Local\Enthought\Canopy\User\lib\site-packa ges\requests\adapters.py", line 447, in send raise SSLError(e, request=request) requests.exceptions.SSLError: ("bad handshake: SysCallError(10054, 'WSAECONNRESET')",) </code></pre>
10
2016-08-04T07:34:30Z
38,884,883
<p>First of all, I confirm that the host, <code>www.neco.navy.mil</code>, is not accessible from everywhere. From some networks (geography) it works*, from others connection just hangs:</p> <pre><code>$ curl www.neco.navy.mil curl: (7) couldn't connect to host $ curl https://www.neco.navy.mil curl: (7) couldn't connect to host </code></pre> <p>Second, when connection can be established there is an certificate problem:</p> <pre><code>$ curl -v https://www.neco.navy.mil * Rebuilt URL to: https://www.neco.navy.mil/ * Hostname was NOT found in DNS cache * Trying 205.85.2.133... * Connected to www.neco.navy.mil (205.85.2.133) port 443 (#0) * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * SSLv3, TLS handshake, Client hello (1): * SSLv3, TLS handshake, Server hello (2): * SSLv3, TLS handshake, CERT (11): * SSLv3, TLS alert, Server hello (2): * SSL certificate problem: unable to get local issuer certificate * Closing connection 0 curl: (60) SSL certificate problem: unable to get local issuer certificate More details here: http://curl.haxx.se/docs/sslcerts.html curl performs SSL certificate verification by default, using a "bundle" of Certificate Authority (CA) public keys (CA certs). If the default bundle file isn't adequate, you can specify an alternate file using the --cacert option. If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL). If you'd like to turn off curl's verification of the certificate, use the -k (or --insecure) option. </code></pre> <p>To make sure, you just feed it to <a href="https://www.ssllabs.com/ssltest/analyze.html?d=www.neco.navy.mil" rel="nofollow">Qualys SSL tester</a>: <a href="http://i.stack.imgur.com/HG9bV.png" rel="nofollow"><img src="http://i.stack.imgur.com/HG9bV.png" alt="enter image description here"></a></p> <p>The CA (<em>DoD Root CA 2</em>) is not trusted. Moreover it's not in the chain. Note that <a href="https://www.openssl.org/docs/manmaster/apps/verify.html" rel="nofollow">OpenSSL validation process needs whole chain</a>:</p> <blockquote> <p>Firstly a certificate chain is built up starting from the supplied certificate and ending in the root CA. It is an error if the whole chain cannot be built up.</p> </blockquote> <p>But there's only <em>www.neco.navy.mil</em> -> <em>DODCA-28</em>. It may be related to the TLD and extra security measure, but C grade alone isn't much anyway ;-)</p> <p>On they Python side it won't be much different. If you don't have access to the CA, you can only disable certificate validation entirely (after you have connectivity problem solved, of course). If you have it, you can use <code>cafile</code>.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import ssl ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE r = urllib2.urlopen('https://www.neco.navy.mil/' 'necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx', timeout = 5, context = ctx) print(len(r.read())) r = urllib2.urlopen('https://www.neco.navy.mil/' 'necoattach/N6945016R0626_2016-06-20__INFO_NAS_Pensacola_Base_Access.docx', timeout = 5, cafile = '/path/to/DODCA-28_and_DoD_Root_CA_2.pem') print(len(r.read())) </code></pre> <p>To reproduce with certain version of Python, use simple Dockerfile like follows:</p> <pre><code>FROM python:2.7.11 WORKDIR /opt ADD . ./ CMD dpkg -s openssl | grep Version &amp;&amp; ./app.py </code></pre> <p>Then run:</p> <pre><code>docker build -t ssl-test . docker run --rm ssl-test </code></pre>
4
2016-08-10T23:00:31Z
[ "python", "python-2.7", "ssl", "python-requests" ]
Boxplots from count table in Python
38,761,192
<p>I have a count table as dataframe in Python and I want to plot my distribution as a boxplot. E.g.:</p> <pre><code>df=pandas.DataFrame.from_items([('Quality',[29,30,31,32,33,34,35,36,37,38,39,40]), ('Count', [3,38,512,2646,9523,23151,43140,69250,107597,179374,840596,38243])]) </code></pre> <p>I 'solved' it by repeating my quality value by its count. But I dont think its a good way and my dataframe is getting very very big.</p> <p>In R there its a one liner:</p> <pre><code>ggplot(df, aes(x=1,y=Quality,weight=Count)) + geom_boxplot() </code></pre> <p>This will output:<a href="http://i.stack.imgur.com/N5hUf.png" rel="nofollow">!Boxplot from R<a href="http://i.stack.imgur.com/N5hUf.png" rel="nofollow">1</a></a></p> <p>My aim is to compare the distribution of different groups and it should look like <a href="http://i.stack.imgur.com/H1QRu.png" rel="nofollow"><img src="http://i.stack.imgur.com/H1QRu.png" alt="this"></a> Can Python solve it like this too?</p>
2
2016-08-04T07:35:39Z
38,762,768
<p>What are you trying to look at here? The boxplot hereunder will return the following figure.</p> <p><a href="http://i.stack.imgur.com/elcbo.png" rel="nofollow"><img src="http://i.stack.imgur.com/elcbo.png" alt="enter image description here"></a></p> <pre><code>import matplotlib.pyplot as plt import pandas as pd %matplotlib inline df=pd.DataFrame.from_items([('Quality',[29,30,31,32,33,34,35,36,37,38,39,40]), ('Count', [3,38,512,2646,9523,23151,43140,69250,107597,179374,840596,38243])]) plt.figure() df_box = df.boxplot(column='Quality', by='Count',return_type='axes') </code></pre> <p>If you want to look at your Quality distibution weighted on Count, you can try plotting an histogramme:</p> <pre><code>plt.figure() df_hist = plt.hist(df.Quality, bins=10, range=None, normed=False, weights=df.Count) </code></pre> <p><a href="http://i.stack.imgur.com/2mySC.png" rel="nofollow"><img src="http://i.stack.imgur.com/2mySC.png" alt="Histogramme"></a></p>
0
2016-08-04T08:53:49Z
[ "python", "python-3.x", "pandas", "matplotlib", "ggplot2" ]
I want to perform some task whenever the install button is pressed in Odoo 9 for a module
38,761,244
<p>I tried overriding the <code>button_install()</code> method of the model <code>ir.module.module</code></p> <pre><code>class module(models.Model): _inherit = 'ir.module.module' @api.multi def button_install(self): raise Warning("----Cannot Install---") </code></pre> <p>But the above method does not execute.</p> <p>Can anyone help? </p>
1
2016-08-04T07:38:14Z
38,761,749
<p>On the module formular <code>button_immediate_install()</code> is used, try to override this method.</p>
0
2016-08-04T08:04:07Z
[ "python", "openerp", "odoo-9" ]
Pandas - printing limited rows based on a value in one column
38,761,357
<p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p> <p>For instance:</p> <pre><code>Column1, Column2, Column3 aaa, bbb, ccc none, ddd, ggg </code></pre> <p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p> <p>Here is my code:</p> <pre><code>for v in df: if 'none' in df['2nd_prize']: print v </code></pre>
1
2016-08-04T07:44:07Z
38,761,412
<pre><code>for row in table: if row[0] is none: print row </code></pre>
1
2016-08-04T07:47:14Z
[ "python", "csv", "pandas", "indexing", "dataframe" ]
Pandas - printing limited rows based on a value in one column
38,761,357
<p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p> <p>For instance:</p> <pre><code>Column1, Column2, Column3 aaa, bbb, ccc none, ddd, ggg </code></pre> <p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p> <p>Here is my code:</p> <pre><code>for v in df: if 'none' in df['2nd_prize']: print v </code></pre>
1
2016-08-04T07:44:07Z
38,761,660
<p>You could subset the rows of the dataframe using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> to restrict rows containing <code>"none"</code> in <code>Column 1</code> as shown:</p> <p><strong>Data Preparation</strong></p> <pre><code>In [1]: import pandas as pd ...: from io import StringIO ...: In [2]: df = pd.read_csv(StringIO( ...: ''' ...: Column1, Column2, Column3 ...: aaa, bbb, ccc ...: none, ddd, ggg ...: kkk, jjj, ppp ...: none, eee, fff ...: ''')) </code></pre> <p><strong>Operations</strong></p> <pre><code>In [3]: df.loc[df['Column1'] == "none"] Out[3]: Column1 Column2 Column3 1 none ddd ggg 3 none eee fff </code></pre>
1
2016-08-04T07:59:35Z
[ "python", "csv", "pandas", "indexing", "dataframe" ]
Pandas - printing limited rows based on a value in one column
38,761,357
<p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p> <p>For instance:</p> <pre><code>Column1, Column2, Column3 aaa, bbb, ccc none, ddd, ggg </code></pre> <p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p> <p>Here is my code:</p> <pre><code>for v in df: if 'none' in df['2nd_prize']: print v </code></pre>
1
2016-08-04T07:44:07Z
38,761,721
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with mask:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Column2': {0: 'bbb', 1: 'ddd'}, 'Column1': {0: 'aaa', 1: 'none'}, 'Column3': {0: 'ccc', 1: 'ggg'}}) print (df) Column1 Column2 Column3 0 aaa bbb ccc 1 none ddd ggg print (df['Column1'] == "none") 0 False 1 True Name: Column1, dtype: bool print (df[df['Column1'] == "none"]) Column1 Column2 Column3 1 none ddd ggg </code></pre> <p>If values contains whitespaces in start of strings, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a>:</p> <pre><code>import pandas as pd df = pd.DataFrame({'Column2': {0: ' bbb', 1: ' ddd'}, 'Column1': {0: ' aaa', 1: ' none'}, 'Column3': {0: ' ccc', 1: ' ggg'}}) print (df) Column1 Column2 Column3 0 aaa bbb ccc 1 none ddd ggg print (df['Column1'].str.strip() == "none") 0 False 1 True Name: Column1, dtype: bool print (df[df['Column1'].str.strip() == "none"]) Column1 Column2 Column3 1 none ddd ggg </code></pre>
1
2016-08-04T08:03:13Z
[ "python", "csv", "pandas", "indexing", "dataframe" ]
Pandas - printing limited rows based on a value in one column
38,761,357
<p>I wanted to limit the rows being printed by selecting rows based on a value in a specific column.</p> <p>For instance:</p> <pre><code>Column1, Column2, Column3 aaa, bbb, ccc none, ddd, ggg </code></pre> <p>I just want to print the row where <code>Column1</code> value is <code>none</code>.</p> <p>Here is my code:</p> <pre><code>for v in df: if 'none' in df['2nd_prize']: print v </code></pre>
1
2016-08-04T07:44:07Z
38,762,117
<p>Here is one additional approach which first manually strips out the whitespace, and then feeds the processed file contents to pandas.</p> <pre><code>import pandas as pd from io import StringIO # First strip out the whitespace contents = open('Input.txt').read().splitlines() contents = "\n".join([",".join([x.strip() for x in y.split(",")]) for y in contents]) # Convert to a stringIO to feed to pandas df = pd.read_csv(StringIO(unicode(contents, 'utf-8'))) print df[df['Column1'] == "none"] </code></pre>
1
2016-08-04T08:22:59Z
[ "python", "csv", "pandas", "indexing", "dataframe" ]
add json objects to specific index - python
38,761,414
<p>Today, I started with json an Python 3.x... So there are sill some problems. This is now my first important problem I have. </p> <p>I'm looking for a fuction wich can insert (for example) this:</p> <pre><code>{ 'Current': '3A', 'Voltage': '11V' } </code></pre> <p>In to here:</p> <pre><code>{ 'Measure': [ {'Current': '2A', 'Voltage': '11V'} ] } </code></pre> <p>...so that my result is:</p> <pre><code>{ 'Measure': [ {'Current': '2A', 'Voltage': '11V'}, {'Current': '3A', 'Voltage': '11V'} ] } </code></pre> <p>I only found functions in javascript to solve my problem, in python not. Till now, I saw only a hierarchical creation methode for json and nothing like a class and instance build up.</p> <p>I hope, there are opportunity to done it. ;) Any ideas?</p>
0
2016-08-04T07:47:19Z
38,761,499
<p>Did you mean to something like this?</p> <pre><code>&gt;&gt;&gt; measureDict = {'Measure': []} &gt;&gt;&gt; measureDict['Measure'].append({'Current': '2A', 'Voltage': '11V'}) &gt;&gt;&gt; measureDict['Measure'].append({'Current': '3A', 'Voltage': '11V'}) &gt;&gt;&gt; measureDict {'Measure': [{'Current': '2A', 'Voltage': '11V'}, {'Current': '3A', 'Voltage': '11V'}]} &gt;&gt;&gt; import json &gt;&gt;&gt; json.dumps(measureDict) '{"Measure": [{"Current": "2A", "Voltage": "11V"}, {"Current": "3A", "Voltage": "11V"}]}' &gt;&gt;&gt; </code></pre>
0
2016-08-04T07:52:14Z
[ "python", "json" ]
add json objects to specific index - python
38,761,414
<p>Today, I started with json an Python 3.x... So there are sill some problems. This is now my first important problem I have. </p> <p>I'm looking for a fuction wich can insert (for example) this:</p> <pre><code>{ 'Current': '3A', 'Voltage': '11V' } </code></pre> <p>In to here:</p> <pre><code>{ 'Measure': [ {'Current': '2A', 'Voltage': '11V'} ] } </code></pre> <p>...so that my result is:</p> <pre><code>{ 'Measure': [ {'Current': '2A', 'Voltage': '11V'}, {'Current': '3A', 'Voltage': '11V'} ] } </code></pre> <p>I only found functions in javascript to solve my problem, in python not. Till now, I saw only a hierarchical creation methode for json and nothing like a class and instance build up.</p> <p>I hope, there are opportunity to done it. ;) Any ideas?</p>
0
2016-08-04T07:47:19Z
38,762,113
<p>My solution for your problem is to Keep the data as Python- Dictionary then do operations on it, later you can get JSON Objects.</p> <pre><code>import json j = {'Measure': [ {'Current': '2A', 'Voltage': '11V'}]} d = {'Current': '3A', 'Voltage': '11V'} j['Measure'].append(d) # as it is list use append otherwise update json.dumps(j) </code></pre> <p>Output:</p> <pre><code>'{"Measure": [ {"Current": "2A", "Voltage": "11V"}, {"Current": "3A", "Voltage": "11V"} ]}' </code></pre> <p><strong>EDIT-1:</strong> </p> <p>First append data to child dictionary then use dict.update to parent dictionary Hence solved. </p> <p><strong>EDIT-2</strong></p> <p>Exact answer is </p> <p><code>j['Device']['Measure'].append({'Current': '3A', 'Voltage': '11V'})</code></p> <p>it has to work.</p> <p>Hope it is helpful ..!!</p>
0
2016-08-04T08:22:45Z
[ "python", "json" ]
Markup ending without empty line. But markup is only thing in comment
38,761,546
<p>When documenting my python code I have a decorator to mark functions deprecated that also updates the docstring. This works fine if the function has documentation but when it doesn't sphinx complains and the documentation for <code>deprecated</code> does not look correct.</p> <p>I have narrowed the problem down to the equivalent code:</p> <pre><code>def func(): """.. deprecated:: 0.1.0 Please use :func:`func_new` """ </code></pre> <p>These are all variations I have tried without success:</p> <pre><code>def func(): """.. deprecated:: 0.1.0 Please use :func:`func_new` """ def func(): """ .. deprecated:: 0.1.0 Please use :func:`func_new` """ </code></pre> <p>In this case Sphinx complains with <code>WARNING: Explicit markup ends without a blank line; unexpected unindent.</code>. It does not matter how many empty lines I have at the end or if the lines have some spaces in front of it.</p> <p>I would not care about the warning if the documentation was ok but instead of producing</p> <pre><code>Module.func(): Deprecated since version 0.1.0: Please use :func:`func_new` </code></pre> <p>the output is </p> <pre><code>Module.func(): Deprecated since version 0.1.0. Please use :func:`func_new` </code></pre> <p>How can I fix this without having to add any (visible) text to the docstring?</p>
0
2016-08-04T07:54:08Z
38,762,633
<p>jonrsharpe pointed me to the right direction with the dedent.</p> <p>The documentation string must be exactly like this:</p> <pre><code>def func(): """ .. deprecated:: 0.1.0 Please use :func:`func_new` """ </code></pre> <p>Two spaces in the next line, and <code>.. deprecated</code> must be aligned with the starting <code>"""</code> block. It cannot start in the same line as the <code>"""</code>.</p> <p>Dedenting the docstring and adding a <code>\n</code> before <code>.. deprecated</code> fixed my problem.</p>
0
2016-08-04T08:48:09Z
[ "python", "python-2.7", "python-sphinx" ]
Can`t load files for pygame project using pyqt resource system
38,761,578
<p>I have .qrc file:</p> <pre><code>&lt;!DOCTYPE RCC&gt; &lt;RCC version="1.0"&gt; &lt;qresource prefix="/data"&gt; &lt;file alias="key.png"&gt;resources/blocks/key.png&lt;/file&gt; &lt;/qresource&gt; &lt;/RCC&gt; </code></pre> <p>I generate resources_rc.py by pyrcc5, than in my main script:</p> <pre><code>import resources_rc.py key = pygame.image.load(':/data/key.png').convert_alpha() </code></pre> <p>I get an error:</p> <pre><code>File "E:/Python game/main.py", line 137, in main key = pygame.image.load(':/data/key.png').convert_alpha() pygame.error: Couldn't open :/data/key.png </code></pre> <p>What am I doing wrong?</p>
0
2016-08-04T07:55:40Z
38,763,223
<p>The <code>:/foo/bar</code> filenames are special filenames used by Qt's (and thus PyQt's) ressource system.</p> <p>pygame is not PyQt- you won't be able to do that outside of Qt.</p>
0
2016-08-04T09:15:12Z
[ "python", "pyqt", "pygame" ]
Indexing a large 3D HDF5 dataset for subsetting based on 2D condition
38,761,878
<p>I have a large 3D HDF5 dataset that represents location (X,Y) and time for a certain variable. Next, I have a 2D numpy array containing a classification for the same (X,Y) location. What I would like to achieve is that I can extract all time series from the 3D HDF5 dataset that fall under a certain class in the 2D array.</p> <p>Here's my example:</p> <pre><code>import numpy as np import h5py # Open the HDF5 dataset NDVI_file = 'NDVI_values.hdf5' f_NDVI = h5py.File(NDVI_file,'r') NDVI_data = f_NDVI["NDVI"] # See what's in the dataset NDVI_data &lt;HDF5 dataset "NDVI": shape (1319, 2063, 53), type "&lt;f4"&gt; # Let's make a random 1319 x 2063 classification containing class numbers 0-4 classification = np.random.randint(5, size=(1319, 2063)) </code></pre> <p>Now we have our 3D HDF5 dataset and a 2D classification. Let's look for pixels that fall under class number '3'</p> <pre><code># Look for the X,Y locations that have class number '3' idx = np.where(classification == 3) </code></pre> <p>This returns me a tuple of size 2 that contains the X,Y pairs that match the condition, and in my random example the amount of pairs is 544433. How should I use now this <code>idx</code> variable to create a 2D array of size (544433,53) that contains the 544433 time series of the pixels that have classification class number '3'?</p> <p>I did some testing with fancy indexing and pure 3D numpy arrays and this example would work just fine:</p> <pre><code>subset = 3D_numpy_array[idx[0],idx[1],:] </code></pre> <p>However, the HDF5 dataset is too large to convert to a numpy array; when I'm trying to use the same indexing method directly on the HDF5 dataset:</p> <pre><code># Try to use fancy indexing directly on HDF5 dataset NDVI_subset = np.array(NDVI_data[idx[0],idx[1],:]) </code></pre> <p>It throws me an error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "h5py\_objects.pyx", line 54, in h5py._objects.with_phil.wrapper (C:\aroot\work\h5py\_objects.c:2584) File "h5py\_objects.pyx", line 55, in h5py._objects.with_phil.wrapper (C:\aroot\work\h5py\_objects.c:2543) File "C:\Users\vtrichtk\AppData\Local\Continuum\Anaconda2\lib\site-packages\h5py\_hl\dataset.py", line 431, in __getitem__ selection = sel.select(self.shape, args, dsid=self.id) File "C:\Users\vtrichtk\AppData\Local\Continuum\Anaconda2\lib\site-packages\h5py\_hl\selections.py", line 95, in select sel[args] File "C:\Users\vtrichtk\AppData\Local\Continuum\Anaconda2\lib\site-packages\h5py\_hl\selections.py", line 429, in __getitem__ raise TypeError("Indexing elements must be in increasing order") TypeError: Indexing elements must be in increasing order </code></pre> <p>Another thing I tried is to <code>np.repeat</code> the classification array in the 3rd dimension to create a 3D array that matches the shape of the HDF5 dataset. The <code>idx</code> variable than gets a tuple of size 3:</p> <pre><code>classification_3D = np.repeat(np.reshape(classification,(1319,2063,1)),53,axis=2) idx = np.where(classification == 3) </code></pre> <p>But the following statement than throws the exact same error:</p> <pre><code>NDVI_subset = np.array(NDVI_data[idx]) </code></pre> <p>Is this because the HDF5 dataset works differently compared to a pure numpy array? The documentation does say "Selection coordinates must be given in increasing order"</p> <p>Does anyone in that case have a suggestion on how I could get this to work without having to read in the full HDF5 dataset into memory (which does not work)? Thank you very much!</p>
1
2016-08-04T08:11:07Z
38,775,157
<p>Advanced/fancy indexing in <code>h5py</code> is not nearly as general as with <code>np.ndarray</code>.</p> <p>Set up a small test case:</p> <pre><code>import h5py f=h5py.File('test.h5','w') dset=f.create_dataset('data',(5,3,2),dtype='i') dset[...]=np.arange(5*3*2).reshape(5,3,2) x=np.arange(5*3*2).reshape(5,3,2) ind=np.where(x%2) </code></pre> <p>I can select all odd values with:</p> <pre><code>In [202]: ind Out[202]: (array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32), array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2], dtype=int32), array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)) In [203]: x[ind] Out[203]: array([ 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]) In [204]: dset[ind] ... TypeError: Indexing elements must be in increasing order </code></pre> <p>I can index on a single dimension with a list like: <code>dset[[1,2,3],...]</code>, but repeating index values or changing the order produces an error, <code>dset[[1,1,2,2],...]</code> or <code>dset[[2,1,0],...]</code>. <code>dset[:,[0,1],:]</code> is ok.</p> <p>Several slices is fine, <code>dset[0:3,1:3,:]</code>, or a slice and list, <code>dset[0:3,[1,2],:]</code>.</p> <p>But 2 lists <code>dset[[0,1,2],[1,2],:]</code> produces a </p> <pre><code>TypeError: Only one indexing vector or array is currently allowed for advanced selection </code></pre> <p>So the index tuple for <code>np.where</code> is wrong in several ways. </p> <p>I don't know how much of this is a constraint of the <code>h5</code> storage, and how much is just incomplete development in the <code>h5py</code> module. Maybe bit of both.</p> <p>So you need to load simpler chunks from the file, and perform the fancier indexing on the resulting numpy arrays.</p> <p>In my <code>odd values</code> case, I just need to do:</p> <pre><code>In [225]: dset[:,:,1] Out[225]: array([[ 1, 3, 5], [ 7, 9, 11], [13, 15, 17], [19, 21, 23], [25, 27, 29]]) </code></pre>
1
2016-08-04T18:47:03Z
[ "python", "arrays", "numpy", "indexing", "hdf5" ]
Tensorflow loss is diverging in my RNN
38,762,104
<p>I'm trying to get my hand wet with Tensorflow by solving this challenge: <a href="https://www.kaggle.com/c/integer-sequence-learning" rel="nofollow">https://www.kaggle.com/c/integer-sequence-learning</a>.</p> <p>My work is based on these blog posts: </p> <ul> <li><a href="https://danijar.com/variable-sequence-lengths-in-tensorflow/" rel="nofollow">https://danijar.com/variable-sequence-lengths-in-tensorflow/</a></li> <li><a href="https://gist.github.com/evanthebouncy/8e16148687e807a46e3f" rel="nofollow">https://gist.github.com/evanthebouncy/8e16148687e807a46e3f</a></li> </ul> <p>A complete working example - with my data - can be found here: <a href="https://github.com/bottiger/Integer-Sequence-Learning" rel="nofollow">https://github.com/bottiger/Integer-Sequence-Learning</a> Running the example will print out a lot of debug information. Run execute rnn-lstm-my.py . (Requires tensorflow and pandas)</p> <p>The approach is pretty straight forward. I load all of my train sequences, store their length in a vector and the length of the longest one in a variable I call ''max_length''.</p> <p>In my training data I strip out the last element in all the sequences and store it in a vector called "train_solutions"</p> <p>The I store all the sequences, padded with zeros, in a matrix with the shape: [n_seq, max_length].</p> <p>Since I want to predict the next number in a sequence my output should be a single number, and my input should be a sequence. </p> <p>I use a RNN (tf.nn.rnn) with a BasicLSTMCell as cell, with 24 hidden units. The output is feeded into a basic linear model (xW+B) which should produce my prediction.</p> <p>My cost function is simply the predicted number of my model, I calculate the cost like this:</p> <pre><code> cost = tf.nn.l2_loss(tf_result - prediction) </code></pre> <p>The basics dimensions seems to be correct because the code actually runs. However, after only one or two iterations some NaN starts to occur which quickly spreads, and everything becomes NaN.</p> <p>Here is the important part of the code where I define and run the graph. However, I have omitted posted loading/preparation of the data. Please look at the git repo for details about that - but I pretty sure that part is correct.</p> <pre><code>cell = tf.nn.rnn_cell.BasicLSTMCell(num_hidden, state_is_tuple=True) num_inputs = tf.placeholder(tf.int32, name='NumInputs') seq_length = tf.placeholder(tf.int32, shape=[batch_size], name='NumInputs') # Define the input as a list (num elements = batch_size) of sequences inputs = [tf.placeholder(tf.float32,shape=[1, max_length], name='InputData') for _ in range(batch_size)] # Result should be 1xbatch_szie vector result = tf.placeholder(tf.float32, shape=[batch_size, 1], name='OutputData') tf_seq_length = tf.Print(seq_length, [seq_length, seq_length.get_shape()], 'SequenceLength: ') outputs, states = tf.nn.rnn(cell, inputs, dtype=tf.float32) # Print the output. The NaN first shows up here outputs2 = tf.Print(outputs, [outputs], 'Last: ', name="Last", summarize=800) # Define the model tf_weight = tf.Variable(tf.truncated_normal([batch_size, num_hidden, frame_size]), name='Weight') tf_bias = tf.Variable(tf.constant(0.1, shape=[batch_size]), name='Bias') # Debug the model parameters weight = tf.Print(tf_weight, [tf_weight, tf_weight.get_shape()], "Weight: ") bias = tf.Print(tf_bias, [tf_bias, tf_bias.get_shape()], "bias: ") # More debug info print('bias: ', bias.get_shape()) print('weight: ', weight.get_shape()) print('targets ', result.get_shape()) print('RNN input ', type(inputs)) print('RNN input len()', len(inputs)) print('RNN input[0] ', inputs[0].get_shape()) # Calculate the prediction tf_prediction = tf.batch_matmul(outputs2, weight) + bias prediction = tf.Print(tf_prediction, [tf_prediction, tf_prediction.get_shape()], 'prediction: ') tf_result = result # Calculate the cost cost = tf.nn.l2_loss(tf_result - prediction) #optimizer = tf.train.AdamOptimizer() learning_rate = 0.05 optimizer = tf.train.GradientDescentOptimizer(learning_rate) minimize = optimizer.minimize(cost) mistakes = tf.not_equal(tf.argmax(result, 1), tf.argmax(prediction, 1)) error = tf.reduce_mean(tf.cast(mistakes, tf.float32)) init_op = tf.initialize_all_variables() sess = tf.Session() sess.run(init_op) no_of_batches = int(len(train_input)) / batch_size epoch = 1 val_dict = get_input_dict(val_input, val_output, train_length, inputs, batch_size) for i in range(epoch): ptr = 0 for j in range(no_of_batches): print('eval w: ', weight.eval(session=sess)) # inputs batch t_i = train_input[ptr:ptr+batch_size] # output batch t_o = train_output[ptr:ptr+batch_size] # sequence lengths t_l = train_length[ptr:ptr+batch_size] sess.run(minimize,feed_dict=get_input_dict(t_i, t_o, t_l, inputs, batch_size)) ptr += batch_size print("result: ", tf_result) print("result len: ", tf_result.get_shape()) print("prediction: ", prediction) print("prediction len: ", prediction.get_shape()) c_val = sess.run(error, feed_dict = val_dict ) print "Validation cost: {}, on Epoch {}".format(c_val,i) print "Epoch ",str(i) print('test input: ', type(test_input)) print('test output: ', type(test_output)) incorrect = sess.run(error,get_input_dict(test_input, test_output, test_length, inputs, batch_size)) sess.close() </code></pre> <p>And here is (the first lines of) the output it produces. You can see that everything become NaN: <a href="http://pastebin.com/TnFFNFrr" rel="nofollow">http://pastebin.com/TnFFNFrr</a> (I could not post it here due to the body limit)</p> <p>The first time I see the NaN is here: </p> <blockquote> <p>I tensorflow/core/kernels/logging_ops.cc:79] Last: [0 0.76159418 0 0 0 0 0 -0.76159418 0 -0.76159418 0 0 0 0.76159418 0.76159418 0 -0.76159418 0.76159418 0 0 0 0.76159418 0 0 0 nan nan nan nan 0 0 nan nan 1 0 nan 0 0.76159418 nan nan nan 1 0 nan 0 0.76159418 nan nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan -nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan nan]</p> </blockquote> <p>I hope I made my problem clear. Thanks in advance</p>
0
2016-08-04T08:22:09Z
38,790,860
<p>RNNs suffer from an exploding gradient, so you should clip the gradients for the RNN parameters. Look at this post:</p> <p><a href="http://stackoverflow.com/questions/36498127/how-to-effectively-apply-gradient-clipping-in-tensor-flow">How to effectively apply gradient clipping in tensor flow?</a></p>
0
2016-08-05T13:46:29Z
[ "python", "neural-network", "tensorflow", "sequence", "deep-learning" ]
Django - Single post view, Prev / Next links
38,762,146
<p>I have built a blog app as part of a django tutorial and I can paginate the blog list view using the code from djangoproject - <a href="https://docs.djangoproject.com/en/1.9/topics/pagination/#using-paginator-in-a-view" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/pagination/#using-paginator-in-a-view</a>. I'm just having problems retrieving Prev / Next url slug links based on the current page post view.</p> <p>model.py</p> <pre><code>class Film(Timestamp): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) image = ImageField(upload_to='thumb') video = EmbedVideoField(blank=True) director = models.CharField(max_length=255,blank=True) cinematographer = models.CharField(max_length=255,blank=True) producer = models.CharField(max_length=255,blank=True) publish = models.BooleanField(default=False) date_published = models.DateTimeField() # override the admin name class Meta: verbose_name_plural = "Film Projects" def __unicode__(self): return self.title # helper method def get_absolute_url(self): return "/film/%s/" % self.slug def save(self, *args, **kwargs): super(Film, self).save(*args, **kwargs) </code></pre> <p>views.py</p> <pre><code># film single def film_detail(request, slug): film = Film.objects.get(slug=slug) def get_next(self): next_post = Film.get_next_by_date_published() if next: return next.first() return False def get_next(self): prev_post = Film.get_previous_by_date_published() if prev: return prev.first() return False return render(request, 'film/film_detail.html', { 'film': film, }) </code></pre> <p>urls.py </p> <pre><code>url(r'^film/$', views.film_list, name='film_list'), url(r'^films/(?P&lt;slug&gt;[-\w]+)/$', views.film_detail, name='film_detail'), </code></pre> <p>film_detail.html</p> <pre><code>&lt;a href="{{ film.get_next_by_date_published }}"&gt;Next&lt;/a&gt;&lt;br&gt; &lt;a href="{{ film.get_previous_by_date_published }}"&gt;Previous&lt;/a&gt; </code></pre> <p>The above links return next and previous post titles, not the slug and include the current post slug as well, for example - <a href="http://127.0.0.1:8000/films/sea-chair/Can" rel="nofollow">http://127.0.0.1:8000/films/sea-chair/Can</a> Chair.</p> <p>For such a simple thing (although I am new to django and python), I have spent days researching with no luck, I hope someone can help!</p>
0
2016-08-04T08:24:39Z
38,763,229
<p>The <code>{{ film.get_next_by_date_published }}</code> returns a <code>film</code> object. To turn it into a url, you need to access <code>film.get_next_by_date_published.slug</code>. </p> <p>You could hardcode the url in the template</p> <pre><code>&lt;a href="/films/{{ film.get_next_by_date_published }}"&gt;Next&lt;/a&gt; </code></pre> <p>However it's nicer to use the <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url" rel="nofollow"><code>{% url %}</code></a> tag.</p> <pre><code>&lt;a href="{% url 'film_detail' film.get_previous_by_date_published.slug %}"&gt;Next&lt;/a&gt; </code></pre> <p>The next problem with this is that <code>get_next_by_date_published</code> and <code>get_previous_by_date_published</code> can raise a <code>DoesNotExist</code> exception if you are already at the last or first film respectively. </p> <p>I would suggest fetching the next and previous films in the view, rather than trying to do it in the template. Note that I've used the <code>get_object_or_404</code> shortcut, to handle the case where a film with that slug does not exist.</p> <pre><code>from django.shortcuts import get_object_or_404 def film_detail(request, slug): film = get_object_or_404(Film, slug=slug) try: next_film = film.get_next_by_date_published() except Film.DoesNotExist: next_film = None try: previous_film = film.get_previous_by_date_published() except Film.DoesNotExist: previous_film = None return render(request, 'film/film_detail.html', { 'film': film, 'next_film': next_film, 'previous_film': previous_film }) </code></pre> <p>Then in your template, check that <code>next_film</code> exists before showing the link:</p> <pre><code>{% if next_film %} &lt;a href="{% url 'film_detail' next_film.slug %}"&gt;Next&lt;/a&gt; {% else %} This is the last film! {% endif %} </code></pre>
0
2016-08-04T09:15:25Z
[ "python", "django" ]
Django dynamic inputs
38,762,214
<p>I'd like to create dynamic input system, for example when I enter the folder name - the list of files inside automatically show up another input ChoiceField below, so I can choose the file. The methods are already written, the problem is - How can I make it in Django view? </p> <p>Here is my view:</p> <pre><code>def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): dir_date = format_date(request.POST['date']) files = os.listdir(os.path.join(path+dir_date)) return render(request, 'inform/show_name.html', {'data': request.POST['your_name'], 'date': format_date(request.POST['date'])}) else: form = NameForm() return render(request, 'inform/base.html', {'form': form}) </code></pre> <p>Here is the form class:</p> <pre><code>class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) date = forms.DateField(widget=forms.DateInput(attrs={'class': 'datepicker'})) flights = forms.ChoiceField(choices=?) </code></pre> <p>Finally, here is my template.</p> <pre><code>{% extends 'inform/header.html' %} {% block content %} &lt;script&gt; $( function() { $( ".datepicker" ).datepicker(); $( "#anim" ).on( "change", function() { $( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() ); }); } ); &lt;/script&gt; &lt;div class="container" style="color: red; size: auto;"&gt; &lt;form class="form-vertical" action="get_name" role="form" method="post"&gt; {% csrf_token %} &lt;div class="form-group" style="display: inherit"&gt; &lt;center&gt; {{form}} &lt;input type="submit" value="OK"&gt; &lt;/center&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; {% endblock %} </code></pre> <p>Is there any way to dynamically read the data from the Date input and give it to the method inside the view without clicking the submit button or creating several others? If it can be solved only by ajax, jQuery or JS, could you please give me a simple sample of how it's done? I'm pretty much frustrated by the inability of creating a simple form.</p> <p>Thank you in advance!</p>
0
2016-08-04T08:28:43Z
38,764,905
<p>So basically you are doing it right. You already know that you need the <code>on(change)</code> function for the <code>datepicker</code></p> <p>Now as soon as the user changes a date, your <code>on(change)</code> function is triggered. So all you need to do now is to the get the new date value, which you already have when you do <code>$( this ).val()</code>. After that make an <code>ajax</code> call to the <code>url</code> corresponding to your method <code>get_name</code> in views.py</p> <p>Something like this:</p> <pre><code>$( function() { $( ".datepicker" ).datepicker(); $( "#anim" ).on( "change", function() { $( "#datepicker" ).datepicker( "option", "showAnim", $( this ).val() ); send_changed_date_value(variable_with_new_date); }); }); function send_changed_date_value(new_date) { $.ajax({ type: // "POST" or "GET", whichever you are using url: "/url in urls.py corresponding to get_name method in views.py/", data: new_date, success: function(response){ console.log("Success..!!") } }); } </code></pre> <p>This is how you can send the new date value to your views, everytime it is changed. If you want to submit the complete form data, i.e., <code>your_name</code> and <code>flights</code> data as well, then you may directly send <code>serialzed data</code> of the form in the <code>data</code> attribute of <code>ajax</code>.</p> <p>Note -> You will have to return a <code>HttpResponse</code> from your <code>get_name</code> view as an ajax call requires a <strong>HttpResponse</strong> from the backend to complete the ajax call successfully. You may simply return a string in the response.</p>
0
2016-08-04T10:31:55Z
[ "python", "django", "django-templates", "django-views", "python-3.5" ]
How to show buttons text in a calculator screen
38,762,227
<p>I've made a simple calculator with buttons like 1, 2 ,3 and so on..but i am unable to put those button text like 1 or 2 etc onto the calculator screen. It would be very helpful if you guys give me some hints..</p> <pre><code>from tkinter import * root = Tk() buttons = '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '+', '-' def calc(value): res = num.get() res = res + " " + value res = str(eval(res)) num.set(res) num = StringVar() rows = 1 col = 0 ent = Entry(root, textvariable = num, background = "#D0F3F5", border = 2, width = 50) ent.bind('&lt;FocusOut&gt;') ent.grid(row = 0 , column = 0, columnspan = 4, ipadx = 5, ipady = 5) Button(root, text = '=', width = 45, command = calc).grid(column = 0, row = 5, columnspan = 4) for button in buttons: button = Button(root,width = 10, text = button, command = lambda: calc(button)) #button.bind('&lt;Button-1&gt;', lambda e: screen(button)) button.grid(row = rows, column = col, sticky = "W E") button['relief']="groove" col = col + 1 if col == 4: rows = rows + 1 col = 0 if rows &gt; 6: break root.mainloop() </code></pre>
-2
2016-08-04T08:29:08Z
38,762,992
<p>There are couple problems in here. </p> <p>1) Variable <code>button</code> is used for two different purposes which makes one of them override the other. You need to rename one of them. </p> <p>2) When <a href="http://stackoverflow.com/questions/17677649/tkinter-assign-button-command-in-loop-with-lambda">using lambdas with parameters in for loops</a>, to get current value of that parameter, you need to explicitly write the value. </p> <p>3) You are not passing any parameter to command of equal sign button. </p> <p>4) To make calculations, you need to check if the pressed button is <code>=</code>. If not, you shouldn't try to calculate anything.</p> <p>Applying all these to your code results in:</p> <pre><code>def calc(value): res = num.get() res = res + value if value == "=": res = str(eval(res[:-1])) #to exclude equal sign itself num.set(res) #equal sign button Button(root, text = '=', width = 45, command = lambda: calc("=")).grid(...) #for loop and renaming a variable for x in buttons: button = Button(root,width = 10, text = x, command = lambda x=x: calc(x)) </code></pre>
0
2016-08-04T09:04:07Z
[ "python", "tkinter" ]
Django not responding to ajax autocomplete
38,762,247
<p>I searched for term "bi" which should return a username with initial "bi..." but nothing is displayed, No dropdown Here are my codes.</p> <p><strong>search.html</strong></p> <pre><code>&lt;html&gt; &lt;div class="ui-widget"&gt; &lt;label for="search4"&gt;search4: &lt;/label&gt; &lt;input id="search4"&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $(function(){ $("#search4").autocomplete({ source: '/rating/searchresult/', minLength: 2, }); }); &lt;/script&gt; &lt;/html&gt; </code></pre> <p><strong>url.py</strong></p> <pre><code>url(r'^searchresult/', 'rating.views.search_images'), </code></pre> <p><strong>views.py</strong></p> <pre><code>def search_images(request): if request.is_ajax(): s = request.GET.get("term", '') search_result = UploadImage.objects.filter(user__username__icontains = s )[:20] search = [] for result in search_result: json_d = {} json_d['id'] = result.id json_d['name'] = result json_d['value'] = result search.append(json_d) data = m_json.dumps(search) else: data = 'error' mimetype = 'application/json' return HttpResponse(data, mimetype) </code></pre> <p>if I search a value Ajax doesnot respond and returned nothing in dropdown, while the term is passed in URl</p> <pre><code>[04/Aug/2016 08:48:46] "GET /rating/searchresult/?term=bi HTTP/1.1" 200 2661 </code></pre> <p>I can't understand where is the problem Ajax or Django <a href="http://i.stack.imgur.com/40yYP.png" rel="nofollow">Also my content type is text html see here</a></p>
0
2016-08-04T08:29:55Z
38,764,239
<p>Okay so technically you are doing it all wrong.</p> <p>The <code>source</code> attribute of <code>autocomplete</code> requires an array of strings or data that you want to provide the user as autocomplete options in an input field.</p> <p>Now what you are trying to do is to simply give the <code>url</code> corresponding to a particular view class or method in your <code>views.py</code> in your <code>source</code> of <code>autocomplete</code>, when actually what you need to do was to get an <code>ajax</code> response by hitting that <code>url</code> and then you'll get the required response from that class/method corresponding to that url.</p> <p>Now you'll feed this <code>response</code> to the source of <code>autocomplete</code></p> <p>See here how the <code>source</code> of <code>autocomplete</code> works -> <a href="http://api.jqueryui.com/autocomplete/#option-source" rel="nofollow">http://api.jqueryui.com/autocomplete/#option-source</a></p> <p>And the official documentation of <code>ajax</code> -> <a href="http://api.jquery.com/jquery.ajax/" rel="nofollow">http://api.jquery.com/jquery.ajax/</a></p> <p>Documentation of <code>$.get()</code> -> <a href="https://api.jquery.com/jquery.get/" rel="nofollow">https://api.jquery.com/jquery.get/</a></p> <p>So your javascript file will look like this:</p> <pre><code>$(document).on('ready', function(){ populateSearchFieldList(); // all other code according to your needs }); function populateSearchFieldList() { var url = "/rating/searchresult/"; $.get(url, function(response) { // console.log("Success..!!"); console.log(response); // now in views.py, you've returned a list in which every // object has an id, name and value but you // want only the names in your autocomplete. So for that, first // you'll have to create a list of just the names and then feed // that list to the source of autocomplete. Like this var searchFieldOptions = []; var i = 0; $.each(response,function(){ searchFieldOptions.push(response[i].name); i++; }); // and now make the source of autocomplete as // searchFieldOptions like this $(function(){ $("#search4").autocomplete({ source: searchFieldOptions, minLength: 2, }); }); }); } </code></pre> <p>Now if it worked successfully, then you'll have the required data in the <code>response</code> you received in the <code>success</code> function. Now you can use this <code>response</code> as the <code>source</code> of <code>autocomplete</code> if its simply a list or can further modify this <code>response</code> and form an <code>array</code> of desired contents as per your requirements.</p>
0
2016-08-04T10:01:16Z
[ "javascript", "jquery", "python", "ajax", "django" ]
Pandas column name of the max cell value
38,762,290
<p>I have a df which has some codes in the leftmost column and a forward profile in the other columns (df1 below)</p> <p>df1:</p> <pre><code> code tp1 tp2 tp3 tp4 tp5 tp6 \ 0 1111 0.000000 0.000000 0.018714 0.127218 0.070055 0.084065 1 222 0.000000 0.000000 0.000418 0.000000 0.017540 0.003015 2 333 1.146815 1.305678 0.384918 0.688284 0.000000 0.000000 3 444 0.000000 0.000000 1.838797 0.000000 0.000000 0.000000 4 555 27.190002 27.134837 24.137560 17.739465 11.990806 8.631395 5 666 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 tp7 tp8 tp9 tp10 0 0.019707 0.000000 0.000000 0.000000 1 6.594860 10.535905 15.697232 21.035824 2 0.000000 0.000000 0.000000 0.000000 3 0.000000 0.000000 0.000000 0.000000 4 7.476197 6.461532 5.570051 4.730345 5 0.000000 0.000068 0.000000 0.000000 </code></pre> <p>I want the output to be a 3 column df (df2 below) which has the column name of the cell (for each code) which has the last number (+ve or -ve) after which there are only 0s. The 2nd Column (<code>tp_with_max_num</code>) will have the column name which has the max such number. </p> <p>df2:</p> <pre><code> code max_tp tp_with_max_num 0 1111 tp7 tp4 1 222 tp10 tp10 2 333 tp4 tp2 3 444 tp3 tp3 4 555 tp10 tp1 5 666 tp8 tp8 </code></pre> <p>Using this : <a href="http://stackoverflow.com/questions/34200153/name-of-column-that-contains-the-max-value">name of column, that contains the max value</a> i was able to get the 3rd column:</p> <pre><code>input_df['tp_with_max_num'] = input_df.ix[0:6,1:].apply(lambda x: input_df.columns[1:][x == x.max()][0], axis=1) </code></pre> <p>I am unable to solve for the 2nd column in df2....</p>
2
2016-08-04T08:32:03Z
38,762,426
<p>You can use <code>argmax</code> on the row to return the column name with the largest value for the 2nd column if you temporarily replace <code>0</code> with <code>NaN</code> then you can use <code>last_valid_index</code> to return the column with the last non-zero value:</p> <pre><code>In [117]: df['max_tp'], df['tp_with_max_num'] = df.ix[:,'tp1':].replace(0,np.NaN).apply(lambda x: x.last_valid_index(), axis=1), df.ix[:,'tp1':].apply(lambda x: x.argmax(), axis=1) df[['max_tp','tp_with_max_num']] Out[117]: max_tp tp_with_max_num 0 tp7 tp4 1 tp10 tp10 2 tp4 tp2 3 tp3 tp3 4 tp10 tp1 5 tp8 tp8 </code></pre>
2
2016-08-04T08:39:05Z
[ "python", "pandas", "dataframe", "max", "cumsum" ]
Pandas column name of the max cell value
38,762,290
<p>I have a df which has some codes in the leftmost column and a forward profile in the other columns (df1 below)</p> <p>df1:</p> <pre><code> code tp1 tp2 tp3 tp4 tp5 tp6 \ 0 1111 0.000000 0.000000 0.018714 0.127218 0.070055 0.084065 1 222 0.000000 0.000000 0.000418 0.000000 0.017540 0.003015 2 333 1.146815 1.305678 0.384918 0.688284 0.000000 0.000000 3 444 0.000000 0.000000 1.838797 0.000000 0.000000 0.000000 4 555 27.190002 27.134837 24.137560 17.739465 11.990806 8.631395 5 666 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 tp7 tp8 tp9 tp10 0 0.019707 0.000000 0.000000 0.000000 1 6.594860 10.535905 15.697232 21.035824 2 0.000000 0.000000 0.000000 0.000000 3 0.000000 0.000000 0.000000 0.000000 4 7.476197 6.461532 5.570051 4.730345 5 0.000000 0.000068 0.000000 0.000000 </code></pre> <p>I want the output to be a 3 column df (df2 below) which has the column name of the cell (for each code) which has the last number (+ve or -ve) after which there are only 0s. The 2nd Column (<code>tp_with_max_num</code>) will have the column name which has the max such number. </p> <p>df2:</p> <pre><code> code max_tp tp_with_max_num 0 1111 tp7 tp4 1 222 tp10 tp10 2 333 tp4 tp2 3 444 tp3 tp3 4 555 tp10 tp1 5 666 tp8 tp8 </code></pre> <p>Using this : <a href="http://stackoverflow.com/questions/34200153/name-of-column-that-contains-the-max-value">name of column, that contains the max value</a> i was able to get the 3rd column:</p> <pre><code>input_df['tp_with_max_num'] = input_df.ix[0:6,1:].apply(lambda x: input_df.columns[1:][x == x.max()][0], axis=1) </code></pre> <p>I am unable to solve for the 2nd column in df2....</p>
2
2016-08-04T08:32:03Z
38,762,500
<p>Faster is use:</p> <pre><code>print (df.ix[:,'tp1':].idxmax(axis=1)) 0 tp4 1 tp10 2 tp2 3 tp3 4 tp1 5 tp8 dtype: object </code></pre> <p><strong>Timings</strong>:</p> <pre><code>df = pd.concat([df]*1000).reset_index(drop=True) In [128]: %timeit (df.ix[:,'tp1':].idxmax(axis=1)) 100 loops, best of 3: 5.9 ms per loop In [129]: %timeit (df.ix[:,'tp1':].apply(lambda x: x.argmax(), axis=1)) 1 loop, best of 3: 237 ms per loop In [130]: %timeit (df.ix[:,'tp1':].replace(0,np.NaN).apply(lambda x: x.last_valid_index(), axis=1)) 10 loops, best of 3: 126 ms per loop In [131]: %timeit (df.ix[:, 'tp1':].cumsum(axis=1).idxmax(axis=1)) 100 loops, best of 3: 6.71 ms per loop </code></pre> <p>So the faster is my and <a href="http://stackoverflow.com/a/38762508/2901002">ayhan</a> solution.</p>
1
2016-08-04T08:42:14Z
[ "python", "pandas", "dataframe", "max", "cumsum" ]
Pandas column name of the max cell value
38,762,290
<p>I have a df which has some codes in the leftmost column and a forward profile in the other columns (df1 below)</p> <p>df1:</p> <pre><code> code tp1 tp2 tp3 tp4 tp5 tp6 \ 0 1111 0.000000 0.000000 0.018714 0.127218 0.070055 0.084065 1 222 0.000000 0.000000 0.000418 0.000000 0.017540 0.003015 2 333 1.146815 1.305678 0.384918 0.688284 0.000000 0.000000 3 444 0.000000 0.000000 1.838797 0.000000 0.000000 0.000000 4 555 27.190002 27.134837 24.137560 17.739465 11.990806 8.631395 5 666 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 tp7 tp8 tp9 tp10 0 0.019707 0.000000 0.000000 0.000000 1 6.594860 10.535905 15.697232 21.035824 2 0.000000 0.000000 0.000000 0.000000 3 0.000000 0.000000 0.000000 0.000000 4 7.476197 6.461532 5.570051 4.730345 5 0.000000 0.000068 0.000000 0.000000 </code></pre> <p>I want the output to be a 3 column df (df2 below) which has the column name of the cell (for each code) which has the last number (+ve or -ve) after which there are only 0s. The 2nd Column (<code>tp_with_max_num</code>) will have the column name which has the max such number. </p> <p>df2:</p> <pre><code> code max_tp tp_with_max_num 0 1111 tp7 tp4 1 222 tp10 tp10 2 333 tp4 tp2 3 444 tp3 tp3 4 555 tp10 tp1 5 666 tp8 tp8 </code></pre> <p>Using this : <a href="http://stackoverflow.com/questions/34200153/name-of-column-that-contains-the-max-value">name of column, that contains the max value</a> i was able to get the 3rd column:</p> <pre><code>input_df['tp_with_max_num'] = input_df.ix[0:6,1:].apply(lambda x: input_df.columns[1:][x == x.max()][0], axis=1) </code></pre> <p>I am unable to solve for the 2nd column in df2....</p>
2
2016-08-04T08:32:03Z
38,762,508
<p>Knowing that <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html">idxmax</a> returns the index of the <em>first</em> maximum, you can use cumsum to find the column after which there are only zeros:</p> <pre><code>df.ix[:, 'tp1':].cumsum(axis=1).idxmax(axis=1) Out[61]: 0 tp7 1 tp10 2 tp4 3 tp3 4 tp10 5 tp8 dtype: object </code></pre>
5
2016-08-04T08:42:47Z
[ "python", "pandas", "dataframe", "max", "cumsum" ]
Need program to keep restarting itself after a certain amount of time
38,762,405
<p>I need this program to restart after15 minutes and repeat its process over again. I need it to be on a timer so example it starts ever 15 minutes dynamically without any user imput it will just reset and start over and restart in the Python shell.</p> <pre><code>from twython import Twython, TwythonError import time import random from auth import ( consumer_key, consumer_secret, access_token, access_token_secret ) twitter = Twython( consumer_key, consumer_secret, access_token, access_token_secret ) start_time = time.time() search_results = twitter.search(q="lol", count=100) try: for tweet in search_results["statuses"]: try: st= tweet["entities"]["user_mentions"] if st != []: screen_name = st[0]["screen_name"] twitter.create_friendship(screen_name = st[0]["screen_name"]) twitter.retweet(id = tweet["id_str"]) for name in bot_detectors: if name == screen_name: try: twitter.destroy_friendship(screen_name = st[0]["screen_name"]) twitter.destroy_status(id = tweet["id_str"]) twitter.create_block(screen_name=name) except TwythonError as e: print (e) </code></pre>
1
2016-08-04T08:38:08Z
38,767,091
<p>Unless you have very specific requirements, it is always better to put the logic of restarting the script outside the script itself:</p> <ul> <li>the script is simpler to write and test (one functionality less)</li> <li>if (for any reason including program bugs) the script crashes it will be automatically restarted on next launch time</li> <li>if (for any reason including program bugs) the script uses more and more resources in long runs, it will release everithing on each stop and will do a fresh start on each new run</li> <li><a href="https://en.wikipedia.org/wiki/Separation_of_concerns" rel="nofollow">separation of concern</a> is generaly seen as one of the <em>best practices</em></li> </ul> <p>On Unix-like systems, you will find cron and crontab, on Windows the task scheduler, so it already exists out of the box without any development.</p>
0
2016-08-04T12:16:02Z
[ "python", "loops", "time" ]
Convert possibly incorrect time to seconds
38,762,515
<p>Having such string <code>12:65:84</code> and told that it represents time in <code>h:m:s</code> AND values there can be not correct, e.g. <code>65</code> minutes that should be translated to <code>1</code> hour and <code>5</code> minutes</p> <p>I need to reduce these numbers to total amount of seconds.</p> <p>Naive solution will be:</p> <pre><code>time_string = '12:65:84' hours, minutes, seconds = [int(i) for i in time_string.split(':') total_seconds = hours * 60 * 60 + minutes * 60 + seconds </code></pre> <p>Question: How it can be done better, ideally without using any import, maybe with some combination of <code>map</code>, <code>reduce</code> and their friends?</p>
0
2016-08-04T08:43:06Z
38,766,451
<p>You can also use <code>timedelta</code> for the same as:</p> <pre><code>s='12:65:84' h,m,s=[int(i) for i in s.split(':')] t=timedelta(hours=h, seconds=s, minutes=m) res=t.total_seconds() </code></pre>
1
2016-08-04T11:44:53Z
[ "python", "time" ]
How to get dict of lists from relationship in sqlalchemy?
38,762,607
<p>I've found out that you can use collections in relationship in order to change the type of return value, specifically I was interested in dictionaries. Documentation gives an example:</p> <pre><code>class Item(Base): __tablename__ = 'item' id = Column(Integer, primary_key=True) notes = relationship("Note", collection_class=attribute_mapped_collection('keyword'), cascade="all, delete-orphan") class Note(Base): __tablename__ = 'note' id = Column(Integer, primary_key=True) item_id = Column(Integer, ForeignKey('item.id'), nullable=False) keyword = Column(String) text = Column(String) </code></pre> <p>And it works. However I was hoping that it will make list values if there are more than just one key with the same name. But it only puts the last value under unique key name.</p> <p>Here is an example:</p> <pre><code>| Note table | |---------------------|------------------| | id | keyword | |---------------------|------------------| | 1 | foo | |---------------------|------------------| | 2 | foo | |---------------------|------------------| | 3 | bar | |---------------------|------------------| | 4 | bar | |---------------------|------------------| </code></pre> <p><code>item.notes</code> will return something like this:</p> <pre><code>{'foo': &lt;project.models.note.Note at 0x7fc6840fadd2&gt;, 'bar': &lt;project.models.note.Note at 0x7fc6840fadd4&gt;} </code></pre> <p>Where ids of foo and bar objects are 2 and 4 respectively.</p> <p>What I'm looking for is to get something like this:</p> <pre><code>{'foo': [&lt;project.models.note.Note at 0x7fc6840fadd1, &lt;project.models.note.Note at 0x7fc6840fadd2&gt;], 'bar': [&lt;project.models.note.Note at 0x7fc6840fadd3&gt;, &lt;project.models.note.Note at 0x7fc6840fadd4&gt;]} </code></pre> <p>Is it possible to get dict of lists from relationship in sqlalchemy?</p>
1
2016-08-04T08:47:09Z
38,767,424
<p>So, it turns out you can simply inherit MappedCollection and do whatever you like in <strong>setitem</strong> there.</p> <pre><code>from sqlalchemy.orm.collections import (MappedCollection, _SerializableAttrGetter, collection, _instrument_class) #This will ensure that the MappedCollection has been properly #initialized with custom __setitem__() and __delitem__() methods #before used in a custom subclass _instrument_class(MappedCollection) class DictOfListsCollection(MappedCollection): @collection.internally_instrumented def __setitem__(self, key, value, _sa_initiator=None): if not super(DictOfListsCollection, self).get(key): super(DictOfListsCollection, self).__setitem__(key, [], _sa_initiator) super(DictOfListsCollection, self).__getitem__(key).append(value) </code></pre>
0
2016-08-04T12:31:19Z
[ "python", "dictionary", "sqlalchemy", "relationships" ]
MAC : bash script which invokes a Python script , both these scripts are in the same directory
38,762,615
<p>I have written a bash script in MAC , which is placed in a directory say xyz. Now i have a python file in the same directory xyz</p> <p>We can also say that this python script will always be in the directory where this bash script is</p> <p>So i want this bash script to be general</p> <p>/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Users/labuser/Desktop/Installer/OpenURL_GenericNotification.py Some Arguments</p> <p>So i want to replace /Users/labuser/Desktop/Installer/ so that from wherever this script is run python script is automatically calculated by some system variable like $cd /Users/labuser/Desktop/Installer/ this like $cd in windows not sure how in MAC Any comments on how to go about this script ??</p>
1
2016-08-04T08:47:26Z
38,762,671
<p>In a Bash script, the path to the script is stored in the <code>$0</code> variable.</p> <p>The <code>dirname</code> command returns the directory portion of a path (filename removed).</p> <p>You can use the <code>dirname</code> with <code>$0</code> to get the script's base directory, and <code>cd</code> to that path, and then run the Python script in the current directory:</p> <pre><code>cd "$(dirname "$0")" ./OpenURL_GenericNotification.py </code></pre>
0
2016-08-04T08:49:26Z
[ "python", "bash", "osx", "shell" ]
Extracting numbers in text file
38,762,783
<p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p> <p>I want to take only five digits after <code>#ACA</code> in a text file.</p> <p>my text is like:</p> <pre><code>ERROR_MESSAGE (((#ACA16018)|(#ACA16019))&amp;(#AQV71767='')&amp;(#AQV71765='2'))?1:((#AQV71765='4')?1:((#AQV71767$'')?(((#AQV71765='1')|(#AQV71765='3'))?1:'Hasar veya Lehe Hukuk seçebilirsiniz'):'Rücu sıra numarasını yazıp Hasar veya Lehe Hukuk seçebilirsiniz')) Rücu Oranı Girilmesi Zorunludur...' #ACA17660 #ACA16560 #ACA15623 #ACA17804 BU ALANI BOŞ GEÇEMEZSİNİZ.EKSPER RAPORU GELMEDEN DY YE GERİ GÖNDEREMEZSİNİZ. PERT İHBARI VARSA PERT ÇALINMA OPERASYONU AKTİVİTESİ OLUŞTURULMALIDIR. (#TSC[T008UNSMAS;FIRM_CODE=2 AND UNIT_TYPE='SG' AND UNIT_NO=#AQV71830]&gt;0)?1:'Girdiğiniz değer fihristte yoktur' #ACA17602 #ACA17604 #ACA56169 BU ALANI BOŞ GEÇEMEZSİNİZ #ACA17606 #ACA17608 (#AQV71835='')?'Boş geçilemez':1 Lütfen Gönderilecek Kişinin Mail Adresini Giriniz ! ' LÜTFEN RED NEDENİNİ GİRİNİZ. EKSİK BİLGİ / BELGE ALANINA GİRMİŞ OLDUĞUNUZ DEĞER YANLIŞ VEYA GEÇERŞİZDİR!!! LÜTFEN KONTROL EDİP TEKRAR DENEYİNİZ.' BU ALAN BOŞ GEÇİLEMEZ. ÖDEME YAPILMADAN EK ÖDEME SÜRECİNİ BAŞLATAMAZSINIZ. ONAYLANDI VE REDDEDİLDİ SEÇENEKLERİNİ KULLANAMAZSINIZ BU ALAN BOŞ GEÇİLEMEZ.EVRAKLARINIZI , VARSA EKSPER RAPORUNU VE MUALLAĞI KONTROL EDİNİZ. Muallak Tutarını kontrol ediniz. 'OTO BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' 'OTODIŞI BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' (#AQV70003$'')?((#TSC[T001HASIHB;FIRM_CODE=#FP10100 AND COMPANY_CODE=2 AND CLAIM_NO=#AQV70003]$0)?1:'Bu dosya sistemde bulunmamaktadır'):'Bu alan boş geçilemez' (#AQV70503='')?'Bu alan boş geçilemez.':((#ACA18635=1)?1:'Mağdura ait uygun kriterli ödeme kaydı mevcut değildir.') (#AQV71809=0)?'Boş geçilemez':1 (#FD101AQV71904_AFDS&lt;0)?'Tarih bugünün tarihinden büyük olamaz </code></pre> <p>I want to take every 5 digits which comes after <code>#ACA</code>, so:</p> <p><code>16018</code>, <code>16019</code>, <code>17660</code>, etc...</p>
2
2016-08-04T08:54:39Z
38,762,837
<p>This should do it </p> <pre><code>import re print(re.findall("#ACA(\d+)",str_var)) </code></pre> <p>If you have the whole text in the variable <code>str_var</code></p> <p>Output: </p> <pre><code>['16018', '16019', '17660', '16560', '15623', '17804', '17602', '17604', '56169', '17606', '17608', '18635'] </code></pre>
2
2016-08-04T08:56:49Z
[ "python", "bash", "powershell", "text", "extract" ]
Extracting numbers in text file
38,762,783
<p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p> <p>I want to take only five digits after <code>#ACA</code> in a text file.</p> <p>my text is like:</p> <pre><code>ERROR_MESSAGE (((#ACA16018)|(#ACA16019))&amp;(#AQV71767='')&amp;(#AQV71765='2'))?1:((#AQV71765='4')?1:((#AQV71767$'')?(((#AQV71765='1')|(#AQV71765='3'))?1:'Hasar veya Lehe Hukuk seçebilirsiniz'):'Rücu sıra numarasını yazıp Hasar veya Lehe Hukuk seçebilirsiniz')) Rücu Oranı Girilmesi Zorunludur...' #ACA17660 #ACA16560 #ACA15623 #ACA17804 BU ALANI BOŞ GEÇEMEZSİNİZ.EKSPER RAPORU GELMEDEN DY YE GERİ GÖNDEREMEZSİNİZ. PERT İHBARI VARSA PERT ÇALINMA OPERASYONU AKTİVİTESİ OLUŞTURULMALIDIR. (#TSC[T008UNSMAS;FIRM_CODE=2 AND UNIT_TYPE='SG' AND UNIT_NO=#AQV71830]&gt;0)?1:'Girdiğiniz değer fihristte yoktur' #ACA17602 #ACA17604 #ACA56169 BU ALANI BOŞ GEÇEMEZSİNİZ #ACA17606 #ACA17608 (#AQV71835='')?'Boş geçilemez':1 Lütfen Gönderilecek Kişinin Mail Adresini Giriniz ! ' LÜTFEN RED NEDENİNİ GİRİNİZ. EKSİK BİLGİ / BELGE ALANINA GİRMİŞ OLDUĞUNUZ DEĞER YANLIŞ VEYA GEÇERŞİZDİR!!! LÜTFEN KONTROL EDİP TEKRAR DENEYİNİZ.' BU ALAN BOŞ GEÇİLEMEZ. ÖDEME YAPILMADAN EK ÖDEME SÜRECİNİ BAŞLATAMAZSINIZ. ONAYLANDI VE REDDEDİLDİ SEÇENEKLERİNİ KULLANAMAZSINIZ BU ALAN BOŞ GEÇİLEMEZ.EVRAKLARINIZI , VARSA EKSPER RAPORUNU VE MUALLAĞI KONTROL EDİNİZ. Muallak Tutarını kontrol ediniz. 'OTO BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' 'OTODIŞI BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' (#AQV70003$'')?((#TSC[T001HASIHB;FIRM_CODE=#FP10100 AND COMPANY_CODE=2 AND CLAIM_NO=#AQV70003]$0)?1:'Bu dosya sistemde bulunmamaktadır'):'Bu alan boş geçilemez' (#AQV70503='')?'Bu alan boş geçilemez.':((#ACA18635=1)?1:'Mağdura ait uygun kriterli ödeme kaydı mevcut değildir.') (#AQV71809=0)?'Boş geçilemez':1 (#FD101AQV71904_AFDS&lt;0)?'Tarih bugünün tarihinden büyük olamaz </code></pre> <p>I want to take every 5 digits which comes after <code>#ACA</code>, so:</p> <p><code>16018</code>, <code>16019</code>, <code>17660</code>, etc...</p>
2
2016-08-04T08:54:39Z
38,762,858
<p><code>re.findall(r'#ACA(\d{5})', str_var)</code></p>
2
2016-08-04T08:57:55Z
[ "python", "bash", "powershell", "text", "extract" ]
Extracting numbers in text file
38,762,783
<p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p> <p>I want to take only five digits after <code>#ACA</code> in a text file.</p> <p>my text is like:</p> <pre><code>ERROR_MESSAGE (((#ACA16018)|(#ACA16019))&amp;(#AQV71767='')&amp;(#AQV71765='2'))?1:((#AQV71765='4')?1:((#AQV71767$'')?(((#AQV71765='1')|(#AQV71765='3'))?1:'Hasar veya Lehe Hukuk seçebilirsiniz'):'Rücu sıra numarasını yazıp Hasar veya Lehe Hukuk seçebilirsiniz')) Rücu Oranı Girilmesi Zorunludur...' #ACA17660 #ACA16560 #ACA15623 #ACA17804 BU ALANI BOŞ GEÇEMEZSİNİZ.EKSPER RAPORU GELMEDEN DY YE GERİ GÖNDEREMEZSİNİZ. PERT İHBARI VARSA PERT ÇALINMA OPERASYONU AKTİVİTESİ OLUŞTURULMALIDIR. (#TSC[T008UNSMAS;FIRM_CODE=2 AND UNIT_TYPE='SG' AND UNIT_NO=#AQV71830]&gt;0)?1:'Girdiğiniz değer fihristte yoktur' #ACA17602 #ACA17604 #ACA56169 BU ALANI BOŞ GEÇEMEZSİNİZ #ACA17606 #ACA17608 (#AQV71835='')?'Boş geçilemez':1 Lütfen Gönderilecek Kişinin Mail Adresini Giriniz ! ' LÜTFEN RED NEDENİNİ GİRİNİZ. EKSİK BİLGİ / BELGE ALANINA GİRMİŞ OLDUĞUNUZ DEĞER YANLIŞ VEYA GEÇERŞİZDİR!!! LÜTFEN KONTROL EDİP TEKRAR DENEYİNİZ.' BU ALAN BOŞ GEÇİLEMEZ. ÖDEME YAPILMADAN EK ÖDEME SÜRECİNİ BAŞLATAMAZSINIZ. ONAYLANDI VE REDDEDİLDİ SEÇENEKLERİNİ KULLANAMAZSINIZ BU ALAN BOŞ GEÇİLEMEZ.EVRAKLARINIZI , VARSA EKSPER RAPORUNU VE MUALLAĞI KONTROL EDİNİZ. Muallak Tutarını kontrol ediniz. 'OTO BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' 'OTODIŞI BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' (#AQV70003$'')?((#TSC[T001HASIHB;FIRM_CODE=#FP10100 AND COMPANY_CODE=2 AND CLAIM_NO=#AQV70003]$0)?1:'Bu dosya sistemde bulunmamaktadır'):'Bu alan boş geçilemez' (#AQV70503='')?'Bu alan boş geçilemez.':((#ACA18635=1)?1:'Mağdura ait uygun kriterli ödeme kaydı mevcut değildir.') (#AQV71809=0)?'Boş geçilemez':1 (#FD101AQV71904_AFDS&lt;0)?'Tarih bugünün tarihinden büyük olamaz </code></pre> <p>I want to take every 5 digits which comes after <code>#ACA</code>, so:</p> <p><code>16018</code>, <code>16019</code>, <code>17660</code>, etc...</p>
2
2016-08-04T08:54:39Z
38,762,874
<p>PowerShell solution:</p> <pre><code>$contet = Get-Content -Raw 'your_file' $match = [regex]::Matches($contet, '#ACA(\d{5})') $match | ForEach-Object { $_.Groups[1].Value } </code></pre> <p><strong>Output:</strong></p> <pre><code>16018 16019 17660 16560 15623 17804 17602 17604 56169 17606 17608 18635 </code></pre>
1
2016-08-04T08:58:41Z
[ "python", "bash", "powershell", "text", "extract" ]
Extracting numbers in text file
38,762,783
<p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p> <p>I want to take only five digits after <code>#ACA</code> in a text file.</p> <p>my text is like:</p> <pre><code>ERROR_MESSAGE (((#ACA16018)|(#ACA16019))&amp;(#AQV71767='')&amp;(#AQV71765='2'))?1:((#AQV71765='4')?1:((#AQV71767$'')?(((#AQV71765='1')|(#AQV71765='3'))?1:'Hasar veya Lehe Hukuk seçebilirsiniz'):'Rücu sıra numarasını yazıp Hasar veya Lehe Hukuk seçebilirsiniz')) Rücu Oranı Girilmesi Zorunludur...' #ACA17660 #ACA16560 #ACA15623 #ACA17804 BU ALANI BOŞ GEÇEMEZSİNİZ.EKSPER RAPORU GELMEDEN DY YE GERİ GÖNDEREMEZSİNİZ. PERT İHBARI VARSA PERT ÇALINMA OPERASYONU AKTİVİTESİ OLUŞTURULMALIDIR. (#TSC[T008UNSMAS;FIRM_CODE=2 AND UNIT_TYPE='SG' AND UNIT_NO=#AQV71830]&gt;0)?1:'Girdiğiniz değer fihristte yoktur' #ACA17602 #ACA17604 #ACA56169 BU ALANI BOŞ GEÇEMEZSİNİZ #ACA17606 #ACA17608 (#AQV71835='')?'Boş geçilemez':1 Lütfen Gönderilecek Kişinin Mail Adresini Giriniz ! ' LÜTFEN RED NEDENİNİ GİRİNİZ. EKSİK BİLGİ / BELGE ALANINA GİRMİŞ OLDUĞUNUZ DEĞER YANLIŞ VEYA GEÇERŞİZDİR!!! LÜTFEN KONTROL EDİP TEKRAR DENEYİNİZ.' BU ALAN BOŞ GEÇİLEMEZ. ÖDEME YAPILMADAN EK ÖDEME SÜRECİNİ BAŞLATAMAZSINIZ. ONAYLANDI VE REDDEDİLDİ SEÇENEKLERİNİ KULLANAMAZSINIZ BU ALAN BOŞ GEÇİLEMEZ.EVRAKLARINIZI , VARSA EKSPER RAPORUNU VE MUALLAĞI KONTROL EDİNİZ. Muallak Tutarını kontrol ediniz. 'OTO BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' 'OTODIŞI BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' (#AQV70003$'')?((#TSC[T001HASIHB;FIRM_CODE=#FP10100 AND COMPANY_CODE=2 AND CLAIM_NO=#AQV70003]$0)?1:'Bu dosya sistemde bulunmamaktadır'):'Bu alan boş geçilemez' (#AQV70503='')?'Bu alan boş geçilemez.':((#ACA18635=1)?1:'Mağdura ait uygun kriterli ödeme kaydı mevcut değildir.') (#AQV71809=0)?'Boş geçilemez':1 (#FD101AQV71904_AFDS&lt;0)?'Tarih bugünün tarihinden büyük olamaz </code></pre> <p>I want to take every 5 digits which comes after <code>#ACA</code>, so:</p> <p><code>16018</code>, <code>16019</code>, <code>17660</code>, etc...</p>
2
2016-08-04T08:54:39Z
38,762,878
<p><code>[x[:5] for x in content.split("#ACA")[1:]]</code></p>
2
2016-08-04T08:59:00Z
[ "python", "bash", "powershell", "text", "extract" ]
Extracting numbers in text file
38,762,783
<p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p> <p>I want to take only five digits after <code>#ACA</code> in a text file.</p> <p>my text is like:</p> <pre><code>ERROR_MESSAGE (((#ACA16018)|(#ACA16019))&amp;(#AQV71767='')&amp;(#AQV71765='2'))?1:((#AQV71765='4')?1:((#AQV71767$'')?(((#AQV71765='1')|(#AQV71765='3'))?1:'Hasar veya Lehe Hukuk seçebilirsiniz'):'Rücu sıra numarasını yazıp Hasar veya Lehe Hukuk seçebilirsiniz')) Rücu Oranı Girilmesi Zorunludur...' #ACA17660 #ACA16560 #ACA15623 #ACA17804 BU ALANI BOŞ GEÇEMEZSİNİZ.EKSPER RAPORU GELMEDEN DY YE GERİ GÖNDEREMEZSİNİZ. PERT İHBARI VARSA PERT ÇALINMA OPERASYONU AKTİVİTESİ OLUŞTURULMALIDIR. (#TSC[T008UNSMAS;FIRM_CODE=2 AND UNIT_TYPE='SG' AND UNIT_NO=#AQV71830]&gt;0)?1:'Girdiğiniz değer fihristte yoktur' #ACA17602 #ACA17604 #ACA56169 BU ALANI BOŞ GEÇEMEZSİNİZ #ACA17606 #ACA17608 (#AQV71835='')?'Boş geçilemez':1 Lütfen Gönderilecek Kişinin Mail Adresini Giriniz ! ' LÜTFEN RED NEDENİNİ GİRİNİZ. EKSİK BİLGİ / BELGE ALANINA GİRMİŞ OLDUĞUNUZ DEĞER YANLIŞ VEYA GEÇERŞİZDİR!!! LÜTFEN KONTROL EDİP TEKRAR DENEYİNİZ.' BU ALAN BOŞ GEÇİLEMEZ. ÖDEME YAPILMADAN EK ÖDEME SÜRECİNİ BAŞLATAMAZSINIZ. ONAYLANDI VE REDDEDİLDİ SEÇENEKLERİNİ KULLANAMAZSINIZ BU ALAN BOŞ GEÇİLEMEZ.EVRAKLARINIZI , VARSA EKSPER RAPORUNU VE MUALLAĞI KONTROL EDİNİZ. Muallak Tutarını kontrol ediniz. 'OTO BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' 'OTODIŞI BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' (#AQV70003$'')?((#TSC[T001HASIHB;FIRM_CODE=#FP10100 AND COMPANY_CODE=2 AND CLAIM_NO=#AQV70003]$0)?1:'Bu dosya sistemde bulunmamaktadır'):'Bu alan boş geçilemez' (#AQV70503='')?'Bu alan boş geçilemez.':((#ACA18635=1)?1:'Mağdura ait uygun kriterli ödeme kaydı mevcut değildir.') (#AQV71809=0)?'Boş geçilemez':1 (#FD101AQV71904_AFDS&lt;0)?'Tarih bugünün tarihinden büyük olamaz </code></pre> <p>I want to take every 5 digits which comes after <code>#ACA</code>, so:</p> <p><code>16018</code>, <code>16019</code>, <code>17660</code>, etc...</p>
2
2016-08-04T08:54:39Z
38,762,904
<pre><code>grep -oP '#ACA\K[0-9]{5}' file.txt </code></pre> <ul> <li><code>#ACA\K</code> will match <code>#ACA</code> but not printed as part of output</li> <li><code>[0-9]{5}</code> five digits following <code>#ACA</code></li> </ul> <p>If variable number of digits are needed, use</p> <pre><code>grep -oP '#ACA\K[0-9]+' file.txt </code></pre>
4
2016-08-04T08:59:55Z
[ "python", "bash", "powershell", "text", "extract" ]
Extracting numbers in text file
38,762,783
<p>I have a text file which came from excel. I dont know how to take five digits after a specific character.</p> <p>I want to take only five digits after <code>#ACA</code> in a text file.</p> <p>my text is like:</p> <pre><code>ERROR_MESSAGE (((#ACA16018)|(#ACA16019))&amp;(#AQV71767='')&amp;(#AQV71765='2'))?1:((#AQV71765='4')?1:((#AQV71767$'')?(((#AQV71765='1')|(#AQV71765='3'))?1:'Hasar veya Lehe Hukuk seçebilirsiniz'):'Rücu sıra numarasını yazıp Hasar veya Lehe Hukuk seçebilirsiniz')) Rücu Oranı Girilmesi Zorunludur...' #ACA17660 #ACA16560 #ACA15623 #ACA17804 BU ALANI BOŞ GEÇEMEZSİNİZ.EKSPER RAPORU GELMEDEN DY YE GERİ GÖNDEREMEZSİNİZ. PERT İHBARI VARSA PERT ÇALINMA OPERASYONU AKTİVİTESİ OLUŞTURULMALIDIR. (#TSC[T008UNSMAS;FIRM_CODE=2 AND UNIT_TYPE='SG' AND UNIT_NO=#AQV71830]&gt;0)?1:'Girdiğiniz değer fihristte yoktur' #ACA17602 #ACA17604 #ACA56169 BU ALANI BOŞ GEÇEMEZSİNİZ #ACA17606 #ACA17608 (#AQV71835='')?'Boş geçilemez':1 Lütfen Gönderilecek Kişinin Mail Adresini Giriniz ! ' LÜTFEN RED NEDENİNİ GİRİNİZ. EKSİK BİLGİ / BELGE ALANINA GİRMİŞ OLDUĞUNUZ DEĞER YANLIŞ VEYA GEÇERŞİZDİR!!! LÜTFEN KONTROL EDİP TEKRAR DENEYİNİZ.' BU ALAN BOŞ GEÇİLEMEZ. ÖDEME YAPILMADAN EK ÖDEME SÜRECİNİ BAŞLATAMAZSINIZ. ONAYLANDI VE REDDEDİLDİ SEÇENEKLERİNİ KULLANAMAZSINIZ BU ALAN BOŞ GEÇİLEMEZ.EVRAKLARINIZI , VARSA EKSPER RAPORUNU VE MUALLAĞI KONTROL EDİNİZ. Muallak Tutarını kontrol ediniz. 'OTO BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' 'OTODIŞI BRANŞINDA REDDEDİLDİ NEDENİ SEÇMELİSİNİZ' (#AQV70003$'')?((#TSC[T001HASIHB;FIRM_CODE=#FP10100 AND COMPANY_CODE=2 AND CLAIM_NO=#AQV70003]$0)?1:'Bu dosya sistemde bulunmamaktadır'):'Bu alan boş geçilemez' (#AQV70503='')?'Bu alan boş geçilemez.':((#ACA18635=1)?1:'Mağdura ait uygun kriterli ödeme kaydı mevcut değildir.') (#AQV71809=0)?'Boş geçilemez':1 (#FD101AQV71904_AFDS&lt;0)?'Tarih bugünün tarihinden büyük olamaz </code></pre> <p>I want to take every 5 digits which comes after <code>#ACA</code>, so:</p> <p><code>16018</code>, <code>16019</code>, <code>17660</code>, etc...</p>
2
2016-08-04T08:54:39Z
38,762,905
<p>If you don't know or don't like regular expressions, you can do this, although the code is a bit longer :</p> <pre><code>if __name__ == '__main__': pattern = '#ACA' filename = 'yourfile.txt' res = list() with open(filename, 'rb') as f: # open 'yourfile.txt' in byte-reading mode for line in f: # for each line in the file for s in line.split(pattern)[1:]: # split the line on '#ACA' try: nb = int(s[:5]) # take the first 5 characters after as an int res.append(nb) # add it to the list of numbers we found except (NameError, ValueError): # if conversion fails, that wasn't an int pass print res # if you want them in the same order as in the file print sorted(res) # if you want them in ascending order </code></pre>
3
2016-08-04T08:59:58Z
[ "python", "bash", "powershell", "text", "extract" ]
Trace Function Calls in Python
38,762,815
<p>I need to trace Function Calls based on called functions from a root file It should show the function call sequence without including system functions What is the best approach for this problem What I have tried so far Using AST to get function calls on root page and then opening all imports file and searching for function definition and repeating the process Module Finder has been used to get path of modules for opening but it is not showing path of some files and some are in missing modules section</p> <p>Is there any way to achieve this with or without executing the script I have tried pycallgraph but it is showing the output in image format ,it's json implementation has not been done so I ruled it out</p> <p>Please advice me on solving this problem and is there any other modules that helps to achieve this functionality </p>
0
2016-08-04T08:55:50Z
38,846,913
<p>You can set use the trace function with sys.settrace(). In principle, you can it on every line of your code, but it also helps you to check the function calls. Look at this link for examples. <a href="http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html" rel="nofollow">http://www.dalkescientific.com/writings/diary/archive/2005/04/20/tracing_python_code.html</a></p>
0
2016-08-09T09:27:43Z
[ "python", "python-2.7", "stack-trace", "abstract-syntax-tree", "trace" ]
get a certain request url during Loading a web page
38,762,836
<p>During Loading <a href="http://www.le.com/ptv/vplay/1417484.html" rel="nofollow">this web page</a> , the browser makes many requests, <a href="http://i.stack.imgur.com/shSOu.png" rel="nofollow"><img src="http://i.stack.imgur.com/shSOu.png" alt="enter image description here"></a> now I need a certain request url (e.g.starts with <code>'http://api.le.com/mms/out/video/playJson?'</code>) during the Loading process ,and the request is made on condition that the adobe flash player plugin for NPAPI is enabled , so any way to get the url?</p> <p>P.S. Better to show some code, I am new to this area.</p>
1
2016-08-04T08:56:48Z
38,772,763
<p>Scrapy doesn't handle requests while the page is being processed, you either know specifically the url you want and directly request it </p> <p>or</p> <p>You have to use something like <a href="https://github.com/scrapy-plugins/scrapy-splash" rel="nofollow">scrapy-splash</a> which can return a <code>HAR</code> file with all the requests made while loading the page. The only downside to this is that splash doesn't return the contents of each request, only the headers =(</p> <p>If you absolutely need the contents of the request it's best to use <a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium</a> with <a href="https://github.com/AutomatedTester/browsermob-proxy-py" rel="nofollow">browsermob</a>, if you find a better solution please do tell.</p> <p><strong>EDIT</strong></p> <p>Seems now that Splash does handle requests' body, check @Mikhail comment.</p>
0
2016-08-04T16:27:34Z
[ "python", "qt", "browser", "web-scraping", "scrapy" ]
Python - dig ANY equivalent with scapy module
38,762,870
<p>I want to use the python module scapy to perform an equivalent command of</p> <pre><code>dig ANY google.com @8.8.4.4 +notcp </code></pre> <p>I've made a simple example code:</p> <pre><code>from scapy.all import * a = sr(IP(dst="8.8.4.4")/UDP(sport=RandShort(),dport=53)/DNS(qd=DNSQR(qname="google.com",qtype="ALL",qclass="IN"))) print str(a[0]) </code></pre> <p>And it send and recieve a packet, but when I sniffed the packet the response says <code>Server failure</code>.</p> <p><a href="http://i.stack.imgur.com/Ug2Al.png" rel="nofollow">Wireshark Screenshot - scapy</a></p> <p><a href="http://i.stack.imgur.com/bt1sw.png" rel="nofollow">Wireshark Screenshot - dig</a></p> <p>Sniffing the <code>dig</code> command itself, looks nearly the same but it gives me a correct response and also it does not send another <code>ICMP - Destination unreachable</code> Packet.. this only comes up when sending it with scapy.</p> <p>If you need more information, feel free to ask. Maybe someone can help me with this..</p> <p><strong>EDIT:</strong></p> <p>Maybe the <code>ICMP - Destination unreachable</code> packet were send because <code>8.8.4.4</code> tries to send the response to my <code>sport</code>, wich is closed? But why should <code>dig</code> then work?!</p>
1
2016-08-04T08:58:31Z
38,780,922
<p>Got the Python code working with scapy..</p> <pre><code>srp(Ether()/IP(src="192.168.1.101",dst="8.8.8.8")/UDP(sport=RandShort(),dport=53)/DNS(rd=1,qd=DNSQR(qname="google.com",qtype="ALL",qclass="IN"),ar=DNSRROPT(rclass=3000)),timeout=1,verbose=0) </code></pre> <p>In Wireshark we can see now a correct response: <a href="http://i.stack.imgur.com/UKtIq.png" rel="nofollow">Wireshark Screenshot</a></p> <p>But I'm still getting the <code>ICMP - Destination unreachable</code> packet.. and I don't know why..</p>
0
2016-08-05T04:04:33Z
[ "python", "dns", "scapy", "any", "dig" ]
parsing python file with re
38,762,928
<p>I have a python file as </p> <pre><code>test.py import os class test(): def __init__(self): pass def add(num1, num2): return num1+num2 </code></pre> <p>I am reading this file in a string as :</p> <pre><code>with open('test.py', 'r') as myfile: data=myfile.read() print data </code></pre> <p>Now, my data contains the string with all lines and new lines. I need to find lines with start of class and def. </p> <p>for example: </p> <p>I need the output to be printed as :</p> <pre><code>class test(): def __init__(self): def add(num1, num2): </code></pre> <p>How can I process this using regular expressions?</p>
1
2016-08-04T09:01:20Z
38,763,134
<p>So if you need to find all <code>def</code> and <code>class</code> lines it is much easier to avoid regex. </p> <p>You read the whole content of the file here </p> <pre><code>with open('test.py', 'r') as myfile: data=myfile.read() print data </code></pre> <p>Why don't you just find the answer right there?</p> <pre><code>with open('test.py', 'r') as myfile: for line in myfile: stripped = line.strip() # get rid of spaces left and right if stripped.startswith('def') or stripped.startswith('class'): print(line) </code></pre> <p>To work with a whole string as you requested:</p> <pre><code>import re with open('test.py', 'r') as myfile: data = myfile.read() print(data) print(re.findall("class.+\n|def.+\n",data)) </code></pre> <p>As you can see from the comments this will match ''definied as bla bla' as well. So it is better to use </p> <pre><code>print(re.findall("class .+\n|def .+\n",data)) </code></pre>
2
2016-08-04T09:10:57Z
[ "python", "regex" ]
parsing python file with re
38,762,928
<p>I have a python file as </p> <pre><code>test.py import os class test(): def __init__(self): pass def add(num1, num2): return num1+num2 </code></pre> <p>I am reading this file in a string as :</p> <pre><code>with open('test.py', 'r') as myfile: data=myfile.read() print data </code></pre> <p>Now, my data contains the string with all lines and new lines. I need to find lines with start of class and def. </p> <p>for example: </p> <p>I need the output to be printed as :</p> <pre><code>class test(): def __init__(self): def add(num1, num2): </code></pre> <p>How can I process this using regular expressions?</p>
1
2016-08-04T09:01:20Z
38,763,306
<pre><code>with open('test.py', 'r') as myfile: data=myfile.read().split('\n') for line in data: if re.search("(\s+)?class ", line) or re.search("^\s+def ", line): print line </code></pre>
1
2016-08-04T09:18:56Z
[ "python", "regex" ]
parsing python file with re
38,762,928
<p>I have a python file as </p> <pre><code>test.py import os class test(): def __init__(self): pass def add(num1, num2): return num1+num2 </code></pre> <p>I am reading this file in a string as :</p> <pre><code>with open('test.py', 'r') as myfile: data=myfile.read() print data </code></pre> <p>Now, my data contains the string with all lines and new lines. I need to find lines with start of class and def. </p> <p>for example: </p> <p>I need the output to be printed as :</p> <pre><code>class test(): def __init__(self): def add(num1, num2): </code></pre> <p>How can I process this using regular expressions?</p>
1
2016-08-04T09:01:20Z
38,763,506
<p>If you want to follow a regex approach, use</p> <pre><code>re.findall(r'(?m)^[ \t]*((?:class|def)[ \t].*)', data) </code></pre> <p>or</p> <pre><code>re.findall(r'^[ \t]*((?:class|def)[ \t].*)', data, flags=re.M) </code></pre> <p>See <a href="https://regex101.com/r/xY8qU4/2" rel="nofollow">regex demo</a></p> <p>The point is that you should use <code>^</code> as the beginning of the <em>line</em> anchor (hence, <code>(?m)</code> at the start or <code>re.M</code> flag are necessary), then you match horizontal whitespaces (with <code>[ \t]</code>), then either <code>class</code> or <code>def</code> (with <code>(?:class|def)</code>), and then again a space or tab and then 0+ chars other than a newline (<code>.*</code>).</p> <p>If you plan to also handle Unicode whitespace, you need to replace <code>[ \t]</code> with <code>[^\S\r\n\f\v]</code> (and use the <code>re.UNICODE</code> flag).</p> <p><a href="https://ideone.com/LMu5zK" rel="nofollow">Python demo</a>:</p> <pre><code>import re p = re.compile(r'^[ \t]*((?:class|def)[ \t].*)', re.MULTILINE) s = "test.py \n\nimport os\nclass test():\n\n def __init__(self):\n pass\n\n def add(num1, num2):\n return num1+num2" print(p.findall(s)) # =&gt; ['class test():', 'def __init__(self):', 'def add(num1, num2):'] </code></pre>
2
2016-08-04T09:27:29Z
[ "python", "regex" ]
Function which take as input variable result from other function
38,762,933
<p>As I'm new in python coding, I stuck on defining a function which take as input variable from other function. Generally my code is : </p> <pre><code>#!/usr/bin/python import configparser import re var="abc" class Config: def getSources(var): config = configparser.ConfigParser() config.read("C\\configFile.ini") connection=config.get(connectinfo,'connectStr') if source in connection_source: print (connection_connectstr) else: print ('Something wrong') return connection try: emp1 = Config.getSources(var) except configparser.NoSectionError: print ("Senction is not correct") def getTables(connection) </code></pre> <p>In few words, I get data from Config.ini file, then do some process. Next I want to create next function getTables which as input take result from first function. By the way in getSources I would like to make it as return statement, unfornatelly return is returning null... Print works fine.</p>
-4
2016-08-04T09:01:31Z
38,763,109
<p>You need to return the value or raise an exception:</p> <pre> <code> if source in connection_source: return (connection_connectstr) else: raise configparser.NoSectionError('Something wrong') </code> </pre>
0
2016-08-04T09:09:48Z
[ "python", "function" ]
Write dictionary to csv with one line per value
38,762,960
<p>I am quite new to Python so please excuse me if this is a really basic question. I have a Python dictionary such as this one:</p> <p><code>foo = {'bar1':['a','b','c'], 'bar2':['d','e']}</code></p> <p>I would like to write it to a csv file, with one line per <strong>value</strong> and the key as first element of each row. The output would be (whatever the quotation marks):</p> <pre><code>bar1,'a' bar1,'b' bar1,'c' bar2,'d' bar2,'e' </code></pre> <p>I have tried this <a href="http://stackoverflow.com/questions/8685809/python-writing-a-dictionary-to-a-csv-file-with-one-line-for-every-key-value">such as suggested here</a></p> <pre><code>import csv with open('blah.csv', 'wb') as csv_file: writer = csv.writer(csv_file) for key, value in foo.items(): writer.writerow([key, value]) </code></pre> <p>but this gives the following output, with one line per <strong>key</strong>:</p> <pre><code>bar1,"['a', 'b', 'c']" bar2,"['d', 'e']" </code></pre> <p>Thanks for your help!</p>
0
2016-08-04T09:02:49Z
38,763,027
<p>This is because <code>[key, value]</code> contains multiple "values" within <code>value</code>. Try iterating over this like this:</p> <pre><code>for key, values in foo.items() for value in values: writer.writerow([key, value]) </code></pre>
5
2016-08-04T09:05:33Z
[ "python", "file", "csv", "dictionary", "key" ]
how to use spacy lemmatizer to get a word into basic form
38,763,007
<p>I am new to know spacy and I want to use his lemmatizer founction, but I don't know how to use it, like I into strings of word, which will return the string which have the basic form the words. like 'words'=> word, 'did' => 'do', thank you.</p>
0
2016-08-04T09:04:54Z
38,770,601
<p><strong>Code :</strong> </p> <pre><code>import os from spacy.en import English, LOCAL_DATA_DIR data_dir = os.environ.get('SPACY_DATA', LOCAL_DATA_DIR) nlp = English(data_dir=data_dir) doc3 = nlp(u"this is spacy lemmatize testing. programming books are more better than others") for token in doc3: print token, token.lemma, token.lemma_ </code></pre> <p><strong>Output :</strong></p> <pre><code>this 496 this is 488 be spacy 173779 spacy lemmatize 1510965 lemmatize testing 2900 testing . 419 . programming 3408 programming books 1011 book are 488 be more 529 more better 615 better than 555 than others 871 others </code></pre> <p>Example Ref: <a href="http://textminingonline.com/getting-started-with-spacy" rel="nofollow">here</a></p>
1
2016-08-04T14:46:18Z
[ "python", "nltk", "spacy" ]
DjangoCMS NavigationNode - custom node
38,763,038
<p>The default NavigationNode in <a href="http://docs.django-cms.org/en/release-3.3.x/how_to/menus.html?highlight=navigationnode" rel="nofollow">DjangoCMS</a> has nodes as: </p> <ul> <li>children</li> <li>title</li> <li>get_menu_title</li> <li>get_attribute</li> <li>etc.</li> </ul> <p>In the same context, I want to add my custom node, called: <strong>category</strong>_<strong>name</strong> which would return a string 'something' (just for testing purposes). </p> <p>Following the <a href="http://docs.django-cms.org/en/release-3.3.x/index.html" rel="nofollow">official documentation</a>, nothing that would help me solve my issue, was found. When looking up for the declaration of default NavigationNode, the following code appears:</p> <blockquote> <p>from menus.base import NavigationNode</p> </blockquote> <p><strong>base.py</strong> file:</p> <pre><code>class NavigationNode(object): def __init__(self, title, url, id, parent_id=None, parent_namespace=None, attr=None, visible=True): self.children = [] # do not touch self.parent = None # do not touch, code depends on this self.namespace = None # TODO: Assert why we need this and above self.title = title self.url = url self.id = id self.parent_id = parent_id self.parent_namespace = parent_namespace self.visible = visible self.attr = attr or {} # To avoid declaring a dict in defaults... def __repr__(self): return "&lt;Navigation Node: %s&gt;" % smart_str(self.title) def get_menu_title(self): return self.title def get_absolute_url(self): return self.url def get_attribute(self, name): return self.attr.get(name, None) def get_descendants(self): return sum(([node] + node.get_descendants() for node in self.children), []) def get_ancestors(self): if getattr(self, 'parent', None): return [self.parent] + self.parent.get_ancestors() else: return [] </code></pre> <p>If I add my custom node called category_name here, it will work. But it is not a smart solution to modify base files.</p> <p><strong>So my question is:</strong></p> <blockquote> <p>How to add my custom node outside the base.py ? i.E. if I want to add it in my apps models.py file. Is this even possible?</p> </blockquote>
0
2016-08-04T09:06:03Z
38,764,377
<p>I finally found the solution. The answer is: Yes! It is possible. </p> <p>As it states in the documentation, you can use <strong>modify()</strong> method.</p> <p>But it did not work for me, because I got confused with <code>node.attr["changed_by"]</code> . In templates, I wanted to use something like this: <code>{{ child.category_name }}</code> but as it is obvious, I was modifying it wrong.</p> <p>The correct way is this:</p> <pre><code>from menus.base import Modifier from menus.menu_pool import menu_pool from cms.models import Page class MyMode(Modifier): """ """ def modify(self, request, nodes, namespace, root_id, post_cut, breadcrumb): # if the menu is not yet cut, don't do anything if post_cut: return nodes # otherwise loop over the nodes for node in nodes: # does this node represent a Page? if node.attr["is_page"]: # if so, put its changed_by attribute on the node node.category_name = "Some category name here" return nodes menu_pool.register_modifier(MyMode) </code></pre> <p>Now, in menu.html, you can use child.category_name and it will output the string "Some category name here"</p> <pre><code>{% load i18n menu_tags cache %} {% for child in children %} &lt;li&gt; {% if child.children %} &lt;a href="{{ child.get_absolute_url }}"&gt; {{ child.get_menu_title }} &lt;span class="caret"&gt;&lt;/span&gt; &lt;/a&gt; &lt;ul class="menu-vertical"&gt; {% show_menu from_level to_level extra_inactive extra_active template "" "" child %} &lt;/ul&gt; {% else %} &lt;a class1="{{ child.get_absolute_url }}" href="{{ child.get_absolute_url }}"&gt; {% if child.category_name %} &lt;b&gt;{{ child.category }}&lt;/b&gt; {% endif %} {{ child.get_menu_title }} &lt;/a&gt; {% endif %} &lt;/li&gt; {% if class and forloop.last and not forloop.parentloop %}{% endif %} {% endfor %} </code></pre> <p>Finally, after hours and hours of attempts, I solved this.</p>
0
2016-08-04T10:07:26Z
[ "python", "django", "django-cms" ]
Python TCP Sockets: How to know if a specific connection has sent information
38,763,044
<p>I have a multi-threaded Python 3 application that on thread #1 accepts TCP socket communications. Thread #2 will check all current connections if they have anything to receive, then act accordingly.</p> <p>So, currently I have a list called <code>all_connections</code> which is a list of accepted socket connection objects.</p> <p>Using <code>for connection in all_connections:</code> I can loop through all the connection objects. I know I use <code>conn.recv(256)</code> to check if there is anything ready to recive on this socket. Will this block the loop though untill there is something to receive? I have set <code>conn.setblocking(1)</code> beforehand although Im unsure if this is the best way to get around it:</p> <p>Here is some example code:</p> <h2>Thread 1</h2> <pre><code>self.all_connections = [] # init a list to hold connection objs while 1: try: conn, address = self.socket.accept() conn.setblocking(1) # non blocking except Exception as e: continue self.all_connections.append(conn) # Save the connection object </code></pre> <h2>Thread 2</h2> <pre><code>while True: for connection in self.all_connections: received = connection.recv(256) return </code></pre> <p>So, I'm only interested in connections that have actually sent something, as I will be sending them something back most likely.</p> <p>I know I can use <code>select.select</code> in order to check if there is anything to receive on the socket, but that wouldn't help me reference the specific connection.</p>
1
2016-08-04T09:06:23Z
38,763,586
<p>Yes, <code>read()</code> will block; this is the default behaviour. Calling <code>socket.setblocking(1)</code> actually enables blocking, which is opposite of what you wanted. <code>setblocking(False)</code> will set non-blocking mode. I/O on non-blocking sockets requires that you use exception handling.</p> <p>A better way, and you are already headed in the right direction, is to use <a href="https://docs.python.org/3.5/library/select.html#select.select" rel="nofollow"><code>select()</code></a>. You do in fact know which socket sent data because <code>select()</code> returns a list of sockets that are available for reading, writing, or that have an error status. You pass to <code>select()</code> a list of the sockets that you are interested in and it returns those that are available for I/O. Here is the function signature:</p> <pre><code>select(...) select(rlist, wlist, xlist[, timeout]) -&gt; (rlist, wlist, xlist) </code></pre> <p>So the code in thread 2 would look something like this:</p> <pre><code>from select import select while True: rlist, wlist, xlist = select(self.all_connections, [], []) for connection in rlist: received = connection.recv(256) </code></pre> <p>The above code only checks for readable sockets in the list of all connections and reads data from those that are ready. The read will not block.</p>
2
2016-08-04T09:30:51Z
[ "python", "multithreading", "sockets", "tcp" ]
Is it safe to delete these python files from /usr/bin?
38,763,495
<p><a href="http://i.stack.imgur.com/rmvb0.png" rel="nofollow"><img src="http://i.stack.imgur.com/rmvb0.png" alt="enter image description here"></a></p> <p>I've installed python 2x and 3x with <strong>Homebrew</strong> at <code>/usr/local/Cellar/</code>, and again with <strong>pydev</strong> at <code>~/.pyenv</code> for both versions. Also installed with <strong>.dmg</strong> for both. I can't decide which is nicer to work on. Please advice me.</p> <p>And I'd like to remove some. Which of these would be unnecessary and can be removed?</p> <p><a href="http://i.stack.imgur.com/QUpDM.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/QUpDM.jpg" alt="enter image description here"></a></p>
0
2016-08-04T09:27:06Z
38,764,069
<p>don't delete files on /usr/bin, if you want to remove some python, like python2: <code>brew uninstall python2</code>.</p> <p>The <code>pyenv</code> is a very good tool. I'm use it betw on py2 or py3 very well. And there is another good tool for python dev:<code>virtualenv</code></p>
1
2016-08-04T09:52:52Z
[ "python", "osx", "pycharm", "homebrew", "pyenv" ]
python edge detector - mask the area were it's completly black
38,763,530
<p>I have used canny edge detector on an image. It detected some areas in the image and other areas it displays nothing. Now, I want that on the original image it would mask the areas that were completely black. How can I do it?</p> <p>I am using python and skimage or opencv (doesn't matter which one)</p> <pre><code>from skimage.feature import canny from skimage.morphology import closing import skimage.io import numpy as np import os import matplotlib.pyplot as plt import cv2 img = skimage.io.imread("test.jpg",as_grey=True) fig, ax = plt.subplots(1, 1, figsize=(20,20)) ax.imshow(img,'gray') ax.set_axis_off() plt.show() edges = canny(img) close = closing(edges) fig, ax = plt.subplots(1, 1, figsize=(20,20)) ax.imshow(close,'gray') ax.set_axis_off() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/osYuB.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/osYuB.jpg" alt="Original Image"></a> <a href="http://i.stack.imgur.com/hbkMt.png" rel="nofollow"><img src="http://i.stack.imgur.com/hbkMt.png" alt="After canny and closing"></a></p> <p>Now what I want is that the white part(in the second image) would be the only part that would be displayed in the original image ( Masking )</p>
-2
2016-08-04T09:28:42Z
38,768,036
<p>You can simply apply a binary mask on a RGB image using:</p> <pre><code>close_BGR = cv2.cvtColor(close, cv2.COLOR_GRAY2BGR) # Assuming that the img is of RGB format masked_image = cv2.min(close_BGR, img) </code></pre>
1
2016-08-04T12:58:25Z
[ "python", "opencv", "image-processing", "skimage" ]
importing modules in application, not package
38,763,557
<p>I am writing a Python (Python3) application (not a package) and have some doubts about the correct directory structure. At the moment I have this:</p> <pre><code>myapp/ __init__.py launch.py core/ __init__.py some_core_class.py other_core_class.py gui/ __init__.py some_gui_class.py other_gui_class.py </code></pre> <p>I want the application to be started with <code>python launch.py</code> from any place in my directory structure - of course with prepending the correct path to <code>launch.py</code>, e.g. <code>python myapps/myapp/launch.py</code>.</p> <p>Inside my modules I use absolute imports, e.g. in <code>some_core_class.py</code> I write <code>from myapp.core.other_core_class import OtherCoreClass</code>. I use the same way in <code>launch.py</code>, e.g. <code>from myapp.core.some_core_class import SomeCoreClass</code>.</p> <p>But then launching it for example directly from dir <code>myapp</code> by writing <code>python launch.py</code> results in <code>ImportError: No module named 'myapp'</code>. I found I could make it work by changing my import in <code>launch.py</code> to <code>from core.some_core_class import SomeCoreClass</code> but this does not seem to me as a correct absolute import and is inconsistent with imports in other files.</p> <p>What is the best way to solve my issue? I would like to avoid adding <code>myapp</code> to <code>PATH</code> environment variable which would require manual edit by the user or an installer. How should I change my code or my imports to make the application launchable from anywhere? Is that even possible?</p>
1
2016-08-04T09:30:00Z
38,764,049
<p>I have just found, I can solve it by prepending </p> <pre><code>import os import sys app_parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(app_parent_dir) </code></pre> <p>at the very beginning of my <code>launch.py</code>. But this is so ugly and feels like a hack. There must be a better way. Python should not be ugly. Awaiting for better answers...</p>
0
2016-08-04T09:51:46Z
[ "python", "python-3.x" ]
How to handle errors in Mercurial extension
38,763,626
<p>What is the recommended approach to handling errors in a Mercurial extension? We could not find any docs for this aspect online.</p> <p>The following example will print <code>Hello world</code> and set <code>errorlevel</code> to <code>1</code> in a Windows shell. </p> <pre><code>@command('print-parents', [('','', None, '')], '') def printparents(ui, repo, node, **opts): print "Hello world" return True </code></pre> <p>Why is <code>errorlevel</code> set to <code>1</code>? We expected it to be <code>0</code>. How does Python or Mercurial handle <code>True</code> and <code>False</code> in this context? Changing to return <code>False</code> produces <code>errorlevel</code> <code>0</code>.</p> <p>We have seen some examples of <code>raise error.Abort(..)</code> but this output a very verbose callstack which is not neccessary. A simple text message and correct <code>errorlevel</code> is what is needed.</p> <p>Using Windows 7 and Mercurial 3.4.1</p>
0
2016-08-04T09:33:07Z
38,763,724
<p>In a <code>@command</code> function, use <code>ui.warn()</code> to display an error message, then return an <em>integer</em> value to set the exit code:</p> <pre><code>if something_is_wrong: ui.warn(_('Something is wrong, please correct this')) return 1 </code></pre> <p>However, using <code>raise mercurial.error.Abort()</code> is fine too and doesn't result in a traceback unless you have <code>ui.traceback</code> set to <code>True</code> (it defaults to <code>False</code>). Raising <code>Abort()</code> normally results in a <code>ui.warn('abort: ' + msg_from_exception)</code> and <code>return -1</code> combo (which results in a 255 exit code):</p> <pre><code>$ cat demo.py from mercurial import cmdutil, error cmdtable = {} command = cmdutil.command(cmdtable) @command('demo1', [], '') def demo1(ui, repo, *args, **opts): ui.warn('Error message written directly to ui.warn') return 1 @command('demo2', [], '') def demo2(ui, repo, *args, **opts): raise error.Abort('Error message raised with Abort') $ hg --config extensions.demo=`pwd`/demo.py demo1 Error message written directly to ui.warn $ echo $? 1 $ hg --config extensions.demo=`pwd`/demo.py demo2 abort: Error message raised with Abort $? 255 $ hg --config extensions.demo=`pwd`/demo.py --config ui.traceback=true demo2 Traceback (most recent call last): File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/dispatch.py", line 204, in _runcatch return _dispatch(req) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/dispatch.py", line 880, in _dispatch cmdpats, cmdoptions) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/extensions.py", line 210, in closure return func(*(args + a), **kw) File "/opt/facebook/hg/lib/python2.7/site-packages/fastmanifest/cachemanager.py", line 318, in runcommandtrigger result = orig(*args, **kwargs) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/extensions.py", line 210, in closure return func(*(args + a), **kw) File "/opt/facebook/hg/lib/python2.7/site-packages/fastmanifest/__init__.py", line 174, in _logonexit r = orig(ui, repo, cmd, fullargs, *args) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/extensions.py", line 210, in closure return func(*(args + a), **kw) File "/opt/facebook/hg/lib/python2.7/site-packages/hgext/journal.py", line 79, in runcommand return orig(lui, repo, cmd, fullargs, *args) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/dispatch.py", line 637, in runcommand ret = _runcommand(ui, options, cmd, d) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/extensions.py", line 210, in closure return func(*(args + a), **kw) File "/opt/facebook/hg/lib/python2.7/site-packages/hgext/pager.py", line 160, in pagecmd return orig(ui, options, cmd, cmdfunc) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/extensions.py", line 210, in closure return func(*(args + a), **kw) File "/opt/facebook/hg/lib/python2.7/site-packages/hgext/color.py", line 503, in colorcmd return orig(ui_, opts, cmd, cmdfunc) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/dispatch.py", line 1010, in _runcommand return checkargs() File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/dispatch.py", line 971, in checkargs return cmdfunc() File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/dispatch.py", line 877, in &lt;lambda&gt; d = lambda: util.checksignature(func)(ui, *args, **cmdoptions) File "/opt/facebook/hg/lib/python2.7/site-packages/mercurial/util.py", line 1036, in check return func(*args, **kwargs) File "/tmp/demo/demo.py", line 13, in demo2 raise error.Abort('Error message raised with Abort') Abort: Error message raised with Abort abort: Error message raised with Abort </code></pre> <p>Note that I had to explicitly enable the traceback!</p> <p>In Python, the <code>bool</code> type is a subclass of <code>int</code>, and <code>True</code> has a value of <code>1</code> and <code>False</code> has an integer value of <code>0</code>. Because Mercurial expects <code>@command</code> functions to return an integer to set an exit code (or <code>None</code> for exit code 0), you set the exit code to <code>1</code> by returning <code>True</code>.</p> <p>I generally look over the <code>mercurial.commands</code> module and the various <code>hgext</code> extensions to learn how others have solved specific problems. The <code>hg grep</code> command, for example, contains this example of handling an error:</p> <pre><code>try: regexp = util.re.compile(pattern, reflags) except re.error as inst: ui.warn(_("grep: invalid match pattern: %s\n") % inst) return 1 </code></pre> <p>while the <code>hg addremove</code> code raises <code>error.Abort()</code>:</p> <pre><code>try: sim = float(opts.get('similarity') or 100) except ValueError: raise error.Abort(_('similarity must be a number')) </code></pre> <p>I'd use <code>error.Abort()</code> for command errors, and <code>ui.warn()</code> plus returning an integer only if you specifically need an exit code other than 255.</p>
0
2016-08-04T09:37:28Z
[ "python", "mercurial", "mercurial-extension" ]
Quarter out of datetime64
38,763,766
<p>I have a <code>pd.DataFrame</code> that looks like this:</p> <pre><code>In [119]: df1 Out[119]: DATES 0 2014-01-01 1 2014-01-24 2 2014-03-11 3 2014-04-09 4 2014-04-21 5 2014-05-02 6 2014-05-13 7 2014-06-11 8 2014-06-21 9 2014-07-22 10 2014-08-04 In [120]: df1.dtypes Out[120]: DATES datetime64[ns] dtype: object </code></pre> <p>and I want to calculate the quarter each one of the entries belongs to. What I've tried so far is:</p> <pre><code>df1['QUARTER'] = df1['DATES'].map(lambda x: '2014Q1' if (x.year == 2014 &amp; (x.month == 1 | x.month == 2 | x.month == 3)) else np.nan) </code></pre> <p>and then I get: </p> <pre><code>In [124]: df1 Out[124]: DATES QUARTER 0 2014-01-01 NaN 1 2014-01-24 NaN 2 2014-03-11 NaN 3 2014-04-09 NaN 4 2014-04-21 NaN 5 2014-05-02 NaN 6 2014-05-13 NaN 7 2014-06-11 NaN 8 2014-06-21 NaN 9 2014-07-22 NaN 10 2014-08-04 NaN </code></pre> <p>Finally, I've tried:</p> <p><code>df1['QUARTER'] = df1['DATES'].map(lambda x: x.year + '-Q' + x.quarter)</code></p> <p>and then I get an error: </p> <p><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'</code></p> <p>Any ideas are appreciated, thanks!</p>
1
2016-08-04T09:39:11Z
38,763,795
<p>you can do using <a href="http://pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor" rel="nofollow">dt</a> accessor :</p> <pre><code>df1['QUARTER'] = df1['DATES'].dt.quarter </code></pre>
1
2016-08-04T09:40:39Z
[ "python", "pandas" ]
Quarter out of datetime64
38,763,766
<p>I have a <code>pd.DataFrame</code> that looks like this:</p> <pre><code>In [119]: df1 Out[119]: DATES 0 2014-01-01 1 2014-01-24 2 2014-03-11 3 2014-04-09 4 2014-04-21 5 2014-05-02 6 2014-05-13 7 2014-06-11 8 2014-06-21 9 2014-07-22 10 2014-08-04 In [120]: df1.dtypes Out[120]: DATES datetime64[ns] dtype: object </code></pre> <p>and I want to calculate the quarter each one of the entries belongs to. What I've tried so far is:</p> <pre><code>df1['QUARTER'] = df1['DATES'].map(lambda x: '2014Q1' if (x.year == 2014 &amp; (x.month == 1 | x.month == 2 | x.month == 3)) else np.nan) </code></pre> <p>and then I get: </p> <pre><code>In [124]: df1 Out[124]: DATES QUARTER 0 2014-01-01 NaN 1 2014-01-24 NaN 2 2014-03-11 NaN 3 2014-04-09 NaN 4 2014-04-21 NaN 5 2014-05-02 NaN 6 2014-05-13 NaN 7 2014-06-11 NaN 8 2014-06-21 NaN 9 2014-07-22 NaN 10 2014-08-04 NaN </code></pre> <p>Finally, I've tried:</p> <p><code>df1['QUARTER'] = df1['DATES'].map(lambda x: x.year + '-Q' + x.quarter)</code></p> <p>and then I get an error: </p> <p><code>TypeError: unsupported operand type(s) for +: 'int' and 'str'</code></p> <p>Any ideas are appreciated, thanks!</p>
1
2016-08-04T09:39:11Z
38,763,872
<pre><code>In [30]: df['QUARTER'] = pd.PeriodIndex(df['DATES'], freq='Q') In [31]: df Out[31]: DATES QUARTER 0 2014-01-01 2014Q1 1 2014-01-24 2014Q1 2 2014-03-11 2014Q1 3 2014-04-09 2014Q2 4 2014-04-21 2014Q2 5 2014-05-02 2014Q2 6 2014-05-13 2014Q2 7 2014-06-11 2014Q2 8 2014-06-21 2014Q2 9 2014-07-22 2014Q3 10 2014-08-04 2014Q3 </code></pre> <p>The values in <code>df['QUARTER']</code> are <code>Periods</code>. If you'd like strings, then use </p> <pre><code>df['QUARTER'] = pd.PeriodIndex(df['DATES'], freq='Q').format() </code></pre> <hr> <p>By the way, it is also possible to build the desired result by adding strings and string-valued Series:</p> <pre><code>In [59]: df['DATES'].dt.year.astype(str) + 'Q' + df['DATES'].dt.quarter.astype(str) Out[59]: 0 2014Q1 1 2014Q1 2 2014Q1 3 2014Q2 4 2014Q2 5 2014Q2 6 2014Q2 7 2014Q2 8 2014Q2 9 2014Q3 10 2014Q3 Name: DATES, dtype: object </code></pre> <p>That might be useful to you in the future, though in this case there is no need to get your hands dirty.</p>
3
2016-08-04T09:43:12Z
[ "python", "pandas" ]
How do I remove double back slash from a bytes object?
38,763,771
<p>For example, t = str.encode(msg)</p> <p>print(t) I am getting the double slashes.</p> <p>b'\\xda\\xad\\x94\\xb4\\x0bg\\x92]R\\x9a1y\\x9d\\xed\\x04\\xd5\\x8e+\\x07\\xf8\\x03\\x1bm\\xd6\\x96\\x10\\xca80\\xe26\\x8a</p> <p>I would like to get the result as</p> <p>b'\xda\xad\x94\xb4\x0bg\x92]R\x9a1y\x9d\xed\x04\xd5\x8e+\x07\xf8\x03\x1bm\xd6\x96\x10\xca80\xe26\x8a'</p> <p>Any help would be appreciated.</p>
0
2016-08-04T09:39:22Z
38,764,466
<p>You can't do that because '\\' represent a slash, not a double slash. For example, if you will convert the msg to a string and use the print function to print the msg, you will see only one slash.</p>
0
2016-08-04T10:11:32Z
[ "python", "byte", "backslash" ]
How do I remove double back slash from a bytes object?
38,763,771
<p>For example, t = str.encode(msg)</p> <p>print(t) I am getting the double slashes.</p> <p>b'\\xda\\xad\\x94\\xb4\\x0bg\\x92]R\\x9a1y\\x9d\\xed\\x04\\xd5\\x8e+\\x07\\xf8\\x03\\x1bm\\xd6\\x96\\x10\\xca80\\xe26\\x8a</p> <p>I would like to get the result as</p> <p>b'\xda\xad\x94\xb4\x0bg\x92]R\x9a1y\x9d\xed\x04\xd5\x8e+\x07\xf8\x03\x1bm\xd6\x96\x10\xca80\xe26\x8a'</p> <p>Any help would be appreciated.</p>
0
2016-08-04T09:39:22Z
38,765,098
<p>I wanted to place this as a comment to Adrian Gherasims answer, but it got too long so I put it as a separate "answer". </p> <p>For normal symbols you can use the <code>replace</code>-function</p> <pre><code>In [1]: temp = 'aa1aa2aa3aa4aa5' In [2]: temp Out[2]: 'aa1aa2aa3aa4aa5' In [3]: temp.replace('aa', 'a') Out[3]: 'a1a2a3a4a5' </code></pre> <p>However if you try to do the same with your double slash it gives a syntax error</p> <pre><code>In [4]: temp2 = '\\1\\2\\3\\4' In [5]: temp2 Out[5]: '\\1\\2\\3\\4' In [6]: temp2.replace('\\', '\') File "&lt;ipython-input-6-3973ee057a3e&gt;", line 1 temp2.replace('\\', '\') ^ SyntaxError: EOL while scanning string literal </code></pre>
0
2016-08-04T10:41:14Z
[ "python", "byte", "backslash" ]
Overriding the division operator when lambdifying symbolic expressions in sympy
38,763,772
<p>I'm using Sympy to evaluate symbolic expressions provided by users, but the division operator isn't behaving like any other mathematical operator. When evaluating an expression on objects with overridden operators, I get the expected result for addition, subtraction, and multiplication, but not division. The code below illustrates my problem:</p> <pre><code>import sympy import numpy class NewMath(int): def __add__(self, other): print "Adding!" return def __sub__(self, other): print "Subtracting!" return def __mul__(self, other): print "Multiplying!" return def __div__(self, other): print "Dividing!" return three = NewMath(3) four = NewMath(4) three + four three - four three * four three / four # Override sympys default math func_map = {'+':NewMath.__add__, '/':NewMath.__div__} lambda_args = [sympy.Symbol(arg) for arg in ['three', 'four']] print "Now sympy math:" lambda_addition = sympy.lambdify(lambda_args, sympy.Symbol('three') + sympy.Symbol('four'), modules=func_map) lambda_addition(three, four) lambda_subtraction = sympy.lambdify(lambda_args, sympy.Symbol('three') - sympy.Symbol('four'), modules=func_map) lambda_subtraction(three, four) lambda_multiplucation = sympy.lambdify(lambda_args, sympy.Symbol('three') * sympy.Symbol('four'), modules=func_map) lambda_multiplucation(three, four) lambda_division = sympy.lambdify(lambda_args, sympy.Symbol('three') / sympy.Symbol('four'), modules=func_map) lambda_division(three, four) </code></pre> <p>The output:</p> <pre><code>Adding! Subtracting! Multiplying! Dividing! Now sympy math: Adding! Subtracting! Multiplying! 0.75 </code></pre> <p>I've read the <a href="http://docs.sympy.org/latest/gotchas.html" rel="nofollow">Sympy Docs</a> and seen that the <code>/</code> operator is a common gotcha, but the docs just seem to indicate that division will default to integer division, I can't see anything that indicates <code>/</code> can't be overridden. You can see in my example I even attempted to use the <code>modules</code> argument to manually replace division with my custom operator, to no avail.</p> <p>I've also seen that <a href="http://docs.sympy.org/latest/tutorial/manipulation.html" rel="nofollow">division in sympy is really just a power of -1 and multiplication</a>, does this mean my cause is hopeless?</p> <p>I'm using python 2.7 and sympy 1.0</p>
2
2016-08-04T09:39:23Z
38,766,026
<p>Your cause is certainly not completely hopeless. Here are a few options to get you started.</p> <p>First off, it seems as if you understand the difference between __div__ __truediv__ and __floordiv__ but if you didn't already, <a href="https://docs.python.org/2/library/operator.html" rel="nofollow">here</a> is some python 2.7 documentation for them.</p> <p>In python 2.7, overriding __div__ seems like it should do what you want, except for that sympy documentation you found about a/b being evaluated as a * b^(-1). To get around that, you could also override the exponentiation operator.</p> <p>I tried running your code in my python3 environment, changing all instances of print so they have parentheses and replacing all instances of div with truediv.</p> <p>This isnt really a complete answer, but I can't post comments, so this is what you get!</p>
-1
2016-08-04T11:23:22Z
[ "python", "sympy", "symbolic-math" ]
Is it common to write a lot of code under if __name__ == '__main__': statement
38,763,775
<p>my current coding style is like </p> <pre><code>import xxx def fun1() def fun2() ... if __name__ == '__main__': task = sys.argv[1] if task =='task1': do task1 elif task == 'task2': do task2 ... </code></pre> <p>my problem is that the part of the code under </p> <pre><code>if __name__ == '__main__': </code></pre> <p>is quite huge comparing to the functions defined above and I was told this is not a good programming style. It is due to the fact that I modify stuff and do experiment in each tasks frequently and I want to separate those part of the code away from functions which are less likely to be modified. I want to learn more advice here, thanks!</p>
2
2016-08-04T09:39:40Z
38,763,865
<p>Like BusyAnt said, the common way to do it is </p> <pre><code>import xxx def fun1() def fun2() ... def main(): task = sys.argv[1] if task =='task1': do task1 elif task == 'task2': do task2 ... if __name__ == '__main__': main() </code></pre> <p>The upside of this is it does not run on <code>import</code>, but <code>main()</code> can still be run from another module or file if so preferred.</p>
3
2016-08-04T09:42:59Z
[ "python" ]
Is it common to write a lot of code under if __name__ == '__main__': statement
38,763,775
<p>my current coding style is like </p> <pre><code>import xxx def fun1() def fun2() ... if __name__ == '__main__': task = sys.argv[1] if task =='task1': do task1 elif task == 'task2': do task2 ... </code></pre> <p>my problem is that the part of the code under </p> <pre><code>if __name__ == '__main__': </code></pre> <p>is quite huge comparing to the functions defined above and I was told this is not a good programming style. It is due to the fact that I modify stuff and do experiment in each tasks frequently and I want to separate those part of the code away from functions which are less likely to be modified. I want to learn more advice here, thanks!</p>
2
2016-08-04T09:39:40Z
38,763,909
<p><strong>It is not forbidden</strong> to write a lot of things under <code>if __name__ == '__main__'</code>, though it is considered better and more readable to <strong>wrap everything up in a <code>main()</code> function</strong>. This way, the code in <code>main()</code> isn't executed when you <code>import</code> this module in another module, <strong>but</strong> you can still choose to run it, by calling <code>imported_script.main()</code>.</p> <p>Your code would then look like this :</p> <pre><code>import xxx def fun1() def fun2() ... def main(): task = sys.argv[1] if task =='task1': do task1 elif task == 'task2': do task2 ... if __name__ == '__main__': main() </code></pre> <p>I encourage you to read about what does this <code>if</code> statement do, <a class='doc-link' href="http://stackoverflow.com/documentation/python/1223/the-name-special-variable#t=201608040952269480606">in SO Documentation</a> or <a href="http://stackoverflow.com/q/419163/5018771">among the many questions asked about it</a>.</p>
3
2016-08-04T09:44:55Z
[ "python" ]