title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Django 1.9 + Photologue: no such column | 39,113,057 | <p>I am using Django 1.9+ Photologue 3.x to build a photo gallery web app.</p>
<p>When I am trying to add photo or gallery, it returns <code>'NO SUCH COLUMN EXCEPTION'</code></p>
<pre><code>Request Method: GET
Request URL: http://127.0.0.1:8000/admin/photologue/gallery/
Django Version: 1.9.5
Exception Type: OperationalError
Exception Value:
no such column: photologue_gallery.slug
Exception Location: //anaconda/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 323
Python Executable: //anaconda/bin/python
Python Version: 2.7.12
</code></pre>
<p>Then I have checked the model file and view file.</p>
<p>In <code>model.py</code></p>
<pre><code>@python_2_unicode_compatible
class Gallery(models.Model):
date_added = models.DateTimeField(_('date published'),
default=now)
title = models.CharField(_('title'),
max_length=250,
unique=True)
slug = models.SlugField(_('title slug'),
unique=True,
max_length=250,
help_text=_('A "slug" is a unique URL-friendly title for an object.'))
description = models.TextField(_('description'),
blank=True)
is_public = models.BooleanField(_('is public'),
default=True,
help_text=_('Public galleries will be displayed '
'in the default views.'))
photos = SortedManyToManyField('photologue.Photo',
related_name='galleries',
verbose_name=_('photos'),
blank=True)
sites = models.ManyToManyField(Site, verbose_name=_(u'sites'),
blank=True)
objects = GalleryQuerySet.as_manager()
</code></pre>
<p>It seems to be right.
Since it is Django 1.9, no more <code>syncdb</code> or <code>clear sql methods</code> are available. And I tried migrate/makemigrations, sqlmigrates and none of them works.</p>
<p>My idea is to rebuild the sql table but how to achieve this, or any other approaches to solve this issue?</p>
<p>Thank you. </p>
<p>EDIT1: Tried <code>flush</code> command to flush the data in db, but still not working.</p>
<p>EDIT2: Tried <code>inspectdb</code> command, got</p>
<pre><code>class PhotologueGallery(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
date_added = models.DateTimeField()
title = models.CharField(unique=True, max_length=100)
title_slug = models.CharField(unique=True, max_length=50)
description = models.TextField()
is_public = models.BooleanField()
tags = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'photologue_gallery'
</code></pre>
<p>Does it mean that the 'slug' field in model doesn't match the actual field 'title_slug' in the database? </p>
| 0 | 2016-08-24T01:27:26Z | 39,113,591 | <p>Although <code>syncdb</code> command has removed from Django 1.9</p>
<p>There is <code>python manage.py migrate appname --run-syncdb</code> command.</p>
<p>Which sync the model with the database.</p>
| 0 | 2016-08-24T02:44:34Z | [
"python",
"django",
"photologue"
] |
Django 1.9 + Photologue: no such column | 39,113,057 | <p>I am using Django 1.9+ Photologue 3.x to build a photo gallery web app.</p>
<p>When I am trying to add photo or gallery, it returns <code>'NO SUCH COLUMN EXCEPTION'</code></p>
<pre><code>Request Method: GET
Request URL: http://127.0.0.1:8000/admin/photologue/gallery/
Django Version: 1.9.5
Exception Type: OperationalError
Exception Value:
no such column: photologue_gallery.slug
Exception Location: //anaconda/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 323
Python Executable: //anaconda/bin/python
Python Version: 2.7.12
</code></pre>
<p>Then I have checked the model file and view file.</p>
<p>In <code>model.py</code></p>
<pre><code>@python_2_unicode_compatible
class Gallery(models.Model):
date_added = models.DateTimeField(_('date published'),
default=now)
title = models.CharField(_('title'),
max_length=250,
unique=True)
slug = models.SlugField(_('title slug'),
unique=True,
max_length=250,
help_text=_('A "slug" is a unique URL-friendly title for an object.'))
description = models.TextField(_('description'),
blank=True)
is_public = models.BooleanField(_('is public'),
default=True,
help_text=_('Public galleries will be displayed '
'in the default views.'))
photos = SortedManyToManyField('photologue.Photo',
related_name='galleries',
verbose_name=_('photos'),
blank=True)
sites = models.ManyToManyField(Site, verbose_name=_(u'sites'),
blank=True)
objects = GalleryQuerySet.as_manager()
</code></pre>
<p>It seems to be right.
Since it is Django 1.9, no more <code>syncdb</code> or <code>clear sql methods</code> are available. And I tried migrate/makemigrations, sqlmigrates and none of them works.</p>
<p>My idea is to rebuild the sql table but how to achieve this, or any other approaches to solve this issue?</p>
<p>Thank you. </p>
<p>EDIT1: Tried <code>flush</code> command to flush the data in db, but still not working.</p>
<p>EDIT2: Tried <code>inspectdb</code> command, got</p>
<pre><code>class PhotologueGallery(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
date_added = models.DateTimeField()
title = models.CharField(unique=True, max_length=100)
title_slug = models.CharField(unique=True, max_length=50)
description = models.TextField()
is_public = models.BooleanField()
tags = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'photologue_gallery'
</code></pre>
<p>Does it mean that the 'slug' field in model doesn't match the actual field 'title_slug' in the database? </p>
| 0 | 2016-08-24T01:27:26Z | 39,129,174 | <p>You say that the Django migration system - "python manage.py migrate" does not work.
What happens? Do you get an error message?</p>
| 0 | 2016-08-24T17:02:22Z | [
"python",
"django",
"photologue"
] |
Converting a dictionary into a square matrix | 39,113,110 | <p>I am wanting to learn how to convert a dictionary into a square matrix. From what I have read, I may need to convert this into a numpy array and then reshape it. I do not want to use reshape as I want to be able to do this based on information a user puts in. In other words, I want a code to give out a square matrix no matter how many owners and breeds are input by the user. </p>
<p>Note: The owners and breeds for this dictionary vary upon user input. A user can input 100 names and 50 breeds, or they can input 4 names and 5 breeds. In this example, I did four names and three dogs. </p>
<pre><code>dict1 =
{'Bob VS Sarah': {'shepherd': 1,'collie': 5,'poodle': 8},
'Bob VS Ann': {'shepherd': 3,'collie': 2,'poodle': 1},
'Bob VS Jen': {'shepherd': 3,'collie': 2,'poodle': 2},
'Sarah VS Bob': {'shepherd': 3,'collie': 2,'poodle': 4},
'Sarah VS Ann': {'shepherd': 4,'collie': 6,'poodle': 3},
'Sarah VS Jen': {'shepherd': 1,'collie': 5,'poodle': 8},
'Jen VS Bob': {'shepherd': 4,'collie': 8,'poodle': 1},
'Jen VS Sarah': {'shepherd': 7,'collie': 9,'poodle': 2},
'Jen VS Ann': {'shepherd': 3,'collie': 7,'poodle': 2},
'Ann VS Bob': {'shepherd': 6,'collie': 2,'poodle': 5},
'Ann VS Sarah': {'shepherd': 0,'collie': 2,'poodle': 4},
'Ann VS Jen': {'shepherd': 2,'collie': 8,'poodle': 2},
'Bob VS Bob': {'shepherd': 3,'collie': 2,'poodle': 2},
'Sarah VS Sarah': {'shepherd': 3,'collie': 2,'poodle': 2},
'Ann VS Ann': {'shepherd': 13,'collie': 2,'poodle': 4},
'Jen VS Jen': {'shepherd': 9,'collie': 7,'poodle': 2}}
</code></pre>
<p>For example, I want a 4 x 4 matrix (again, the user can input any number of dog breeds so 3 breeds is not a restriction), since there are four owners.</p>
<p>I apologize ahead of time for not putting in what I want the end result to look like and usually I do. I am just proud of myself for making dict1 :). So the dictionary should be in a form similar to below, but I am not sure how to incorporate the different breeds. The hard part for me is that I am only needing one matrix. I also plan on using the matrix solver numpy has, hence why I am wanting to figure out how to get a square matrix from a dictionary. </p>
<pre><code> Bob Sarah Ann Jen
Bob
Sarah
Ann
Jen
</code></pre>
| 0 | 2016-08-24T01:34:06Z | 39,113,347 | <p>You may achieve this via generating a nested dictionary like:</p>
<pre><code>{'Bob': {'Bob': .., 'Sarah': .., 'Ann': .., 'Jen':..}
'Sarah': {.. .. ..},
'Ann': {.. .. ..},
'Jen': {.. .. ..},
}
</code></pre>
<p>Below is the sample code:</p>
<pre><code>>>> my_dict = {'Bob VS Sarah': {'shepherd': 1,'collie': 5,'poodle': 8},
... 'Bob VS Ann': {'shepherd': 3,'collie': 2,'poodle': 1},
... 'Bob VS Jen': {'shepherd': 3,'collie': 2,'poodle': 2},
... 'Sarah VS Bob': {'shepherd': 3,'collie': 2,'poodle': 4},
... 'Sarah VS Ann': {'shepherd': 4,'collie': 6,'poodle': 3},
... 'Sarah VS Jen': {'shepherd': 1,'collie': 5,'poodle': 8},
... 'Jen VS Bob': {'shepherd': 4,'collie': 8,'poodle': 1},
... 'Jen VS Sarah': {'shepherd': 7,'collie': 9,'poodle': 2},
... 'Jen VS Ann': {'shepherd': 3,'collie': 7,'poodle': 2},
... 'Ann VS Bob': {'shepherd': 6,'collie': 2,'poodle': 5},
... 'Ann VS Sarah': {'shepherd': 0,'collie': 2,'poodle': 4},
... 'Ann VS Jen': {'shepherd': 2,'collie': 8,'poodle': 2},
... 'Bob VS Bob': {'shepherd': 3,'collie': 2,'poodle': 2},
... 'Sarah VS Sarah': {'shepherd': 3,'collie': 2,'poodle': 2},
... 'Ann VS Ann': {'shepherd': 13,'collie': 2,'poodle': 4},
... 'Jen VS Jen': {'shepherd': 9,'collie': 7,'poodle': 2}}
>>> new_dict = {}
>>> for key, value in my_dict.iteritems():
... first_name, second_name = map(lambda x: x.strip(), key.split('VS'))
... if first_name not in new_dict:
... new_dict[first_name] = {}
... new_dict[first_name][second_name] = value
...
>>> new_dict
{'Sarah': {'Sarah': {'shepherd': 3, 'collie': 2, 'poodle': 2},
'Ann': {'shepherd': 4, 'collie': 6, 'poodle': 3},
'Jen': {'shepherd': 1, 'collie': 5, 'poodle': 8},
'Bob': {'shepherd': 3, 'collie': 2, 'poodle': 4}
},
'Bob': {'Sarah': {'shepherd': 1, 'collie': 5, 'poodle': 8},
'Bob': {'shepherd': 3, 'collie': 2, 'poodle': 2},
'Jen': {'shepherd': 3, 'collie': 2, 'poodle': 2},
'Ann': {'shepherd': 3, 'collie': 2, 'poodle': 1}},
'Jen': {'Sarah': {'shepherd': 7, 'collie': 9, 'poodle': 2},
'Bob': {'shepherd': 4, 'collie': 8, 'poodle': 1},
'Jen': {'shepherd': 9, 'collie': 7, 'poodle': 2},
'Ann': {'shepherd': 3, 'collie': 7, 'poodle': 2}
},
'Ann': {'Sarah': {'shepherd': 0, 'collie': 2, 'poodle': 4},
'Bob': {'shepherd': 6, 'collie': 2, 'poodle': 5},
'Jen': {'shepherd': 2, 'collie': 8, 'poodle': 2},
'Ann': {'shepherd': 13, 'collie': 2, 'poodle': 4}
}
}
</code></pre>
| 0 | 2016-08-24T02:07:19Z | [
"python",
"numpy",
"dictionary",
"matrix"
] |
Converting a dictionary into a square matrix | 39,113,110 | <p>I am wanting to learn how to convert a dictionary into a square matrix. From what I have read, I may need to convert this into a numpy array and then reshape it. I do not want to use reshape as I want to be able to do this based on information a user puts in. In other words, I want a code to give out a square matrix no matter how many owners and breeds are input by the user. </p>
<p>Note: The owners and breeds for this dictionary vary upon user input. A user can input 100 names and 50 breeds, or they can input 4 names and 5 breeds. In this example, I did four names and three dogs. </p>
<pre><code>dict1 =
{'Bob VS Sarah': {'shepherd': 1,'collie': 5,'poodle': 8},
'Bob VS Ann': {'shepherd': 3,'collie': 2,'poodle': 1},
'Bob VS Jen': {'shepherd': 3,'collie': 2,'poodle': 2},
'Sarah VS Bob': {'shepherd': 3,'collie': 2,'poodle': 4},
'Sarah VS Ann': {'shepherd': 4,'collie': 6,'poodle': 3},
'Sarah VS Jen': {'shepherd': 1,'collie': 5,'poodle': 8},
'Jen VS Bob': {'shepherd': 4,'collie': 8,'poodle': 1},
'Jen VS Sarah': {'shepherd': 7,'collie': 9,'poodle': 2},
'Jen VS Ann': {'shepherd': 3,'collie': 7,'poodle': 2},
'Ann VS Bob': {'shepherd': 6,'collie': 2,'poodle': 5},
'Ann VS Sarah': {'shepherd': 0,'collie': 2,'poodle': 4},
'Ann VS Jen': {'shepherd': 2,'collie': 8,'poodle': 2},
'Bob VS Bob': {'shepherd': 3,'collie': 2,'poodle': 2},
'Sarah VS Sarah': {'shepherd': 3,'collie': 2,'poodle': 2},
'Ann VS Ann': {'shepherd': 13,'collie': 2,'poodle': 4},
'Jen VS Jen': {'shepherd': 9,'collie': 7,'poodle': 2}}
</code></pre>
<p>For example, I want a 4 x 4 matrix (again, the user can input any number of dog breeds so 3 breeds is not a restriction), since there are four owners.</p>
<p>I apologize ahead of time for not putting in what I want the end result to look like and usually I do. I am just proud of myself for making dict1 :). So the dictionary should be in a form similar to below, but I am not sure how to incorporate the different breeds. The hard part for me is that I am only needing one matrix. I also plan on using the matrix solver numpy has, hence why I am wanting to figure out how to get a square matrix from a dictionary. </p>
<pre><code> Bob Sarah Ann Jen
Bob
Sarah
Ann
Jen
</code></pre>
| 0 | 2016-08-24T01:34:06Z | 39,113,385 | <p>If you can get your data in the format </p>
<pre><code>{name1: {name1:data, name2:data, name3:data, ...},
name2: {name1:data, name2:data, name3:data, ...},
...
}
</code></pre>
<p>then you can just hand it to a pandas DataFrame and it will make it for you. The data at position <code>row = name1 and col = name2</code> will be the value of <code>name1 vs name2</code>. Here is the code that will do it:</p>
<pre><code>from collections import defaultdict
import pandas
result = defaultdict(dict)
for key,value in dict1.items():
names = key.split()
name1 = names[0]
name2 = names[2]
result[name1][name2] = value
df = pandas.DataFrame(result).transpose()
print(df)
</code></pre>
<p>This gives the following output:</p>
<pre><code> Ann Bob Jen Sarah
Ann {'shepherd': 13, 'collie': 2, 'poodle': 4} {'shepherd': 6, 'collie': 2, 'poodle': 5} {'shepherd': 2, 'collie': 8, 'poodle': 2} {'shepherd': 0, 'collie': 2, 'poodle': 4}
Bob {'shepherd': 3, 'collie': 2, 'poodle': 1} {'shepherd': 3, 'collie': 2, 'poodle': 2} {'shepherd': 3, 'collie': 2, 'poodle': 2} {'shepherd': 1, 'collie': 5, 'poodle': 8}
Jen {'shepherd': 3, 'collie': 7, 'poodle': 2} {'shepherd': 4, 'collie': 8, 'poodle': 1} {'shepherd': 9, 'collie': 7, 'poodle': 2} {'shepherd': 7, 'collie': 9, 'poodle': 2}
Sarah {'shepherd': 4, 'collie': 6, 'poodle': 3} {'shepherd': 3, 'collie': 2, 'poodle': 4} {'shepherd': 1, 'collie': 5, 'poodle': 8} {'shepherd': 3, 'collie': 2, 'poodle': 2}
</code></pre>
<p>A simple conversion to a numpy array would look like:</p>
<pre><code>numpy_array = df.as_matrix()
print(numpy_array)
[[{'shepherd': 13, 'collie': 2, 'poodle': 4}
{'shepherd': 6, 'collie': 2, 'poodle': 5}
{'shepherd': 2, 'collie': 8, 'poodle': 2}
{'shepherd': 0, 'collie': 2, 'poodle': 4}]
[{'shepherd': 3, 'collie': 2, 'poodle': 1}
{'shepherd': 3, 'collie': 2, 'poodle': 2}
{'shepherd': 3, 'collie': 2, 'poodle': 2}
{'shepherd': 1, 'collie': 5, 'poodle': 8}]
[{'shepherd': 3, 'collie': 7, 'poodle': 2}
{'shepherd': 4, 'collie': 8, 'poodle': 1}
{'shepherd': 9, 'collie': 7, 'poodle': 2}
{'shepherd': 7, 'collie': 9, 'poodle': 2}]
[{'shepherd': 4, 'collie': 6, 'poodle': 3}
{'shepherd': 3, 'collie': 2, 'poodle': 4}
{'shepherd': 1, 'collie': 5, 'poodle': 8}
{'shepherd': 3, 'collie': 2, 'poodle': 2}]]
</code></pre>
| 2 | 2016-08-24T02:12:21Z | [
"python",
"numpy",
"dictionary",
"matrix"
] |
Concatenating two strings in a list of lists | 39,113,122 | <p>The title is a bit misleading as I'm not quite clever enough to come up with an appropriate header that describes exactly what I'm trying to accomplish, so I apologize for that. Hopefully I can compensate for this with the description below.</p>
<p>I'm working on an exercise from a book that requires a bit of cleanup before I can perform any other operations. I have a list of lists in which elements in <em>some</em>, not all, of these lists require an update through concatenation (or perhaps other, more efficient, means if people suggest them). To better explain, here is a slice from that list of lists:</p>
<pre><code>[['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'],
['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'],
['8ee82ed6c2c5af59', 'General_Desktop', 'Windows', 'XP', 'male', '29'],
['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'],
['3126deccaae39ea1', 'General_Desktop', 'Windows', 'XP', 'male', '24'],
['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']]
</code></pre>
<p>The elements in each list correspond to a userID, device, OS, sex and provinceID, respectively. If you take a look at the third and fifth lists, this is where my dilemma arises--you'll notice that 'Windows' and 'XP' are separate strings where they should instead be a single string, i.e., just 'Windows XP', so that these two strings appear in their respective lists amongst the others as:</p>
<pre><code>['8ee82ed6c2c5af59', 'General_Desktop', 'Windows XP', 'male', '29']
['3126deccaae39ea1', 'General_Desktop', 'Windows XP', 'male', '24']
</code></pre>
<p>The remaining lists above are absolved from this problem, so there is no need to modify them.</p>
<p>So, I've tried to develop some reasonable means by which I can join the two strings in lists that have such a separation (I have other lists not shown in the sample above that are displayed similarly, e.g., 'Windows' '7' instead of 'Windows 7'), but I've yet to do so. Is there a 'clean' way of doing this or would I have to resort to creating a loop that removes these strings and then inserts a concatenation of the two? </p>
| 0 | 2016-08-24T01:35:30Z | 39,113,171 | <p>For your specific case, if it's always the platform that is potentially the issue, you could check if the list has too many items, and if so, combine the items on the 2nd and 3rd indices. If you need a broader solution though, please clarify in your problem.</p>
<pre><code>NUM_ITEMS_PER_LIST = 5
lists = [
['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'],
['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'],
['8ee82ed6c2c5af59', 'General_Desktop', 'Windows', 'XP', 'male', '29'],
['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'],
['3126deccaae39ea1', 'General_Desktop', 'Windows', 'XP', 'male', '24'],
['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']
]
for l in lists:
if len(l) > NUM_ITEMS_PER_LIST:
l[2] = '{} {}'.format(l[2], l[3])
del l[3]
print(lists)
</code></pre>
<p><strong>Output</strong>:</p>
<pre><code>[
['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'],
['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'],
['8ee82ed6c2c5af59', 'General_Desktop', 'Windows XP', 'male', '29'],
['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'],
['3126deccaae39ea1', 'General_Desktop', 'Windows XP', 'male', '24'],
['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']
]
</code></pre>
| 0 | 2016-08-24T01:45:12Z | [
"python",
"python-3.x"
] |
Concatenating two strings in a list of lists | 39,113,122 | <p>The title is a bit misleading as I'm not quite clever enough to come up with an appropriate header that describes exactly what I'm trying to accomplish, so I apologize for that. Hopefully I can compensate for this with the description below.</p>
<p>I'm working on an exercise from a book that requires a bit of cleanup before I can perform any other operations. I have a list of lists in which elements in <em>some</em>, not all, of these lists require an update through concatenation (or perhaps other, more efficient, means if people suggest them). To better explain, here is a slice from that list of lists:</p>
<pre><code>[['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'],
['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'],
['8ee82ed6c2c5af59', 'General_Desktop', 'Windows', 'XP', 'male', '29'],
['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'],
['3126deccaae39ea1', 'General_Desktop', 'Windows', 'XP', 'male', '24'],
['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']]
</code></pre>
<p>The elements in each list correspond to a userID, device, OS, sex and provinceID, respectively. If you take a look at the third and fifth lists, this is where my dilemma arises--you'll notice that 'Windows' and 'XP' are separate strings where they should instead be a single string, i.e., just 'Windows XP', so that these two strings appear in their respective lists amongst the others as:</p>
<pre><code>['8ee82ed6c2c5af59', 'General_Desktop', 'Windows XP', 'male', '29']
['3126deccaae39ea1', 'General_Desktop', 'Windows XP', 'male', '24']
</code></pre>
<p>The remaining lists above are absolved from this problem, so there is no need to modify them.</p>
<p>So, I've tried to develop some reasonable means by which I can join the two strings in lists that have such a separation (I have other lists not shown in the sample above that are displayed similarly, e.g., 'Windows' '7' instead of 'Windows 7'), but I've yet to do so. Is there a 'clean' way of doing this or would I have to resort to creating a loop that removes these strings and then inserts a concatenation of the two? </p>
| 0 | 2016-08-24T01:35:30Z | 39,113,190 | <p>You could use a simple list comprehension:</p>
<pre><code>>>> data = [['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'],
['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'],
['8ee82ed6c2c5af59', 'General_Desktop', 'Windows', 'XP', 'male', '29'],
['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'],
['3126deccaae39ea1', 'General_Desktop', 'Windows', 'XP', 'male', '24'],
['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']]
</code></pre>
<p>and then:</p>
<pre><code>>>> [item if len(item) == 5 else item[:2] + [' '.join(item[2:4])] + item[4:] for item in data]
[['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'], ['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'], ['8ee82ed6c2c5af59', 'General_Desktop', 'Windows XP', 'male', '29'], ['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'], ['3126deccaae39ea1', 'General_Desktop', 'Windows XP', 'male', '24'], ['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']]
</code></pre>
| 2 | 2016-08-24T01:46:52Z | [
"python",
"python-3.x"
] |
Concatenating two strings in a list of lists | 39,113,122 | <p>The title is a bit misleading as I'm not quite clever enough to come up with an appropriate header that describes exactly what I'm trying to accomplish, so I apologize for that. Hopefully I can compensate for this with the description below.</p>
<p>I'm working on an exercise from a book that requires a bit of cleanup before I can perform any other operations. I have a list of lists in which elements in <em>some</em>, not all, of these lists require an update through concatenation (or perhaps other, more efficient, means if people suggest them). To better explain, here is a slice from that list of lists:</p>
<pre><code>[['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'],
['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'],
['8ee82ed6c2c5af59', 'General_Desktop', 'Windows', 'XP', 'male', '29'],
['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'],
['3126deccaae39ea1', 'General_Desktop', 'Windows', 'XP', 'male', '24'],
['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']]
</code></pre>
<p>The elements in each list correspond to a userID, device, OS, sex and provinceID, respectively. If you take a look at the third and fifth lists, this is where my dilemma arises--you'll notice that 'Windows' and 'XP' are separate strings where they should instead be a single string, i.e., just 'Windows XP', so that these two strings appear in their respective lists amongst the others as:</p>
<pre><code>['8ee82ed6c2c5af59', 'General_Desktop', 'Windows XP', 'male', '29']
['3126deccaae39ea1', 'General_Desktop', 'Windows XP', 'male', '24']
</code></pre>
<p>The remaining lists above are absolved from this problem, so there is no need to modify them.</p>
<p>So, I've tried to develop some reasonable means by which I can join the two strings in lists that have such a separation (I have other lists not shown in the sample above that are displayed similarly, e.g., 'Windows' '7' instead of 'Windows 7'), but I've yet to do so. Is there a 'clean' way of doing this or would I have to resort to creating a loop that removes these strings and then inserts a concatenation of the two? </p>
| 0 | 2016-08-24T01:35:30Z | 39,113,220 | <p>Use <code>map</code>:</p>
<pre><code>mylist = [['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'], ['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'], ['8ee82ed6c2c5af59', 'General_Desktop', 'Windows', 'XP', 'male', '29'], ['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'], ['3126deccaae39ea1', 'General_Desktop', 'Windows', 'XP', 'male', '24'], ['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']]
map(lambda x: x[:2]+[" ".join(x[2:4])]+x[4:] if len(x) == 6 else x, mylist)
</code></pre>
<p>Output:</p>
<pre><code>[['e726fb69de83a3ec', 'General_Mobile', 'Android', 'unknown', '0'],
['1b8978f618d59eef', 'General_Mobile', 'iOS', 'unknown', '0'],
['8ee82ed6c2c5af59', 'General_Desktop', 'Windows XP', 'male', '29'],
['d0fff09ca1829e65', 'General_Mobile', 'Android', 'female', '48'],
['3126deccaae39ea1', 'General_Desktop', 'Windows XP', 'male', '24'],
['6778d882a1f59b5b', 'General_Mobile', 'iOS', 'female', '25']]
</code></pre>
| 0 | 2016-08-24T01:50:29Z | [
"python",
"python-3.x"
] |
How to print pass arguments to code object via exec and print in python? | 39,113,137 | <p>How to print pass arguments to code object via exec and print in python? Below are just few examples to see how things work in a generic case.</p>
<pre><code>def foo(x, y):
return x * y
exec(foo.func_code {'x': 1, 'y': 5}) # This didn't work
def bar():
return 3*5
exec(bar.func_code) # this got executed but I couldn't print it?
</code></pre>
| 1 | 2016-08-24T01:38:47Z | 39,113,266 | <p>I don't think you'll be able to pass arguments to a code object without using "black magic". Why not use <code>exec("print foo(1, 5)")</code>?</p>
<p>In your both examples, nothing is printed because <code>exec</code> simply executes <code>xxx.func_code</code>, but function <code>foo</code> and <code>bar</code> contain no print statements. </p>
| -1 | 2016-08-24T01:56:47Z | [
"python"
] |
Seaborn kdeplot not plotting some data? | 39,113,224 | <p>I'm trying to get the <a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.kdeplot.html" rel="nofollow">Seaborn kdeplot</a> example to work on my dataset. For some reason, one of my datasets isn't plotting at all, but the other seems to be plotting fine. To get a minimal working example, I have sampled only 10 rows from my very large data sets.</p>
<p>My input data looks like this:</p>
<pre><code>#Dataframe dfA
index x y category
0 595700 5 1.000000 14.0
1 293559 4 1.000000 14.0
2 562295 3 0.000000 14.0
3 219426 4 1.000000 14.0
4 592731 2 1.000000 14.0
5 178573 3 1.000000 14.0
6 553156 4 0.500000 14.0
7 385031 1 1.000000 14.0
8 391681 3 0.999998 14.0
9 492771 2 1.000000 14.0
# Dataframe dfB
index x y category
0 56345 3 1.000000 6.0
1 383741 4 1.000000 6.0
2 103044 2 1.000000 6.0
3 297357 5 1.000000 6.0
4 257508 3 1.000000 6.0
5 223600 2 0.999938 6.0
6 44530 2 1.000000 6.0
7 82925 3 1.000000 6.0
8 169592 3 0.500000 6.0
9 229482 4 0.285714 6.0
</code></pre>
<p>My code snippet looks like this:</p>
<pre><code>import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="darkgrid")
# Set up the figure
f, ax = plt.subplots(figsize=(8, 8))
# Draw the two density plots
ax = sns.kdeplot(dfA.x, dfA.y,
cmap="Reds", shade=True, shade_lowest=False)
ax = sns.kdeplot(dfB.x, dfB.y,
cmap="Blues", shade=True, shade_lowest=False)
</code></pre>
<p>Why isn't the data from dataframe <code>dfA</code> actually plotting?</p>
| 0 | 2016-08-24T01:50:48Z | 39,126,085 | <p>I don't think gaussian KDE is a good fit for either of your datasets. You have one variable with discrete values and one variable where the large majority of values seem to be a constant. This is not well modeled by a bivariate gaussian distribution.</p>
<p>As for what exactly is happening, without the full dataset I cannot say for sure, but I expect that the KDE bandwidth (particularly on the y axis) is ending up very very narrow such that regions with non-negligible density are tiny. You could try setting a wider bandwidth, but my advice would be to use a different kind of plot for this data.</p>
| 0 | 2016-08-24T14:27:48Z | [
"python",
"pandas",
"matplotlib",
"seaborn"
] |
Infinite loop while adding two integers using bitwise operations in Python 3 | 39,113,479 | <p>I am trying to solve a question which is about writing python code for adding two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers:</p>
<pre><code>def getSum(self, a, b):
while (a & b):
x = a & b
y = a ^ b
a = x << 1
b = y
return a ^ b
</code></pre>
<p>This piece of code works perfectly for if input is two positive integers or two negative integers but it fails when one number is positive and other is negative. It goes into infinite loop. Any idea as to why this might be happening ?</p>
| 3 | 2016-08-24T02:27:39Z | 39,113,614 | <p>Python 3 has <a href="https://www.python.org/dev/peps/pep-0237/">arbitrary-precision integers ("bignums")</a>. This means that anytime <code>x</code> is negative, <code>x << 1</code> will make <code>x</code> a negative number with twice the magnitude. Zeros shifting in from the right will just push the number larger and larger. </p>
<p>In two's complement, positive numbers have a <code>0</code> in the highest bit and negative numbers have a <code>1</code> in the highest bit. That means that, when only one of <code>a</code> and <code>b</code> is negative, the top bits of <code>a</code> and <code>b</code> will differ. Therefore, <code>x</code> will be positive (<code>1 & 0 = 0</code>) and <code>y</code> will be negative (<code>1 ^ 0 = 1</code>). Thus the new <code>a</code> will be positive (<code>x<<1</code>) and the new <code>b</code> will be negative (<code>y</code>). </p>
<p>Now: arbitrary-precision negative integers actually have an infinite number of leading <code>1</code> bits, at least mathematicallly. So <code>a</code> is a larger and larger positive number, expanding by 2 each iteration. <code>b</code> keeps getting more and more leading <code>1</code> bits added to be able to carry out the bitwise <code>&</code> and <code>^</code> with <code>a</code>. Thus whatever bits of <code>a</code> are turned on line up with one of the added <code>1</code> bits of <code>b</code>, so <code>a & b</code> is always true, so the loop runs forever.</p>
| 5 | 2016-08-24T02:47:03Z | [
"python",
"python-3.x",
"bit-manipulation",
"bitwise-operators"
] |
Infinite loop while adding two integers using bitwise operations in Python 3 | 39,113,479 | <p>I am trying to solve a question which is about writing python code for adding two integers without the use of '+' or '-' operators. I have the following code which works perfectly for two positive numbers:</p>
<pre><code>def getSum(self, a, b):
while (a & b):
x = a & b
y = a ^ b
a = x << 1
b = y
return a ^ b
</code></pre>
<p>This piece of code works perfectly for if input is two positive integers or two negative integers but it fails when one number is positive and other is negative. It goes into infinite loop. Any idea as to why this might be happening ?</p>
| 3 | 2016-08-24T02:27:39Z | 39,113,669 | <p>I'm guessing that this is a homework question, so I don't want to just give you a function that works --- you'll learn more by struggling with it.</p>
<p>The issue stems from the way that negative integers are stored. For illustration purposes, let's pretend that you're dealing with 4-bit signed integers (instead of 32-bit signed integers, or whatever). The number +1 is 0001. The number -1 is 1111. You should be able to sit down with a pen and paper and manually run your function using these two numbers. The answer, of course, should be 0000, but I think you'll discover what's going wrong with your code by working this simplified case with a pen and paper.</p>
| 1 | 2016-08-24T02:53:16Z | [
"python",
"python-3.x",
"bit-manipulation",
"bitwise-operators"
] |
TypeError: object of type 'bool' has no len() - Odoo v9 | 39,113,494 | <p>I'm trying to connect to a webservice through an Odoov9 module.</p>
<p>This is my class:</p>
<pre><code>class invoice(models.Model):
_inherit = "account.invoice"
@api.multi
def send_xml_file(self):
# haciendolo para efacturadelsur solamente por ahora
host = 'https://www.efacturadelsur.cl'
post = '/ws/DTE.asmx' # HTTP/1.1
url = host + post
_logger.info('URL to be used %s' % url)
# client = Client(url)
# _logger.info(client)
_logger.info('len (como viene): %s' % len(self.sii_xml_request))
response = pool.urlopen('POST', url, headers={
'Content-Type': 'application/soap+xml',
'charset': 'utf-8',
'Content-Length': len(
self.sii_xml_request)}, body=self.sii_xml_request)
_logger.info(response.status)
_logger.info(response.data)
self.sii_xml_response = response.data
self.sii_result = 'Enviado'
</code></pre>
<p>But everytime it parses the code to connect to the server, it throws this error:</p>
<pre><code>Odoo Server Error
Traceback (most recent call last):
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 646, in _handle_exception
return super(JsonRequest, self)._handle_exception(exception)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 683, in dispatch
result = self._call_function(**self.params)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 319, in _call_function
return checked_call(self.db, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/service/model.py", line 118, in wrapper
return f(dbname, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 312, in checked_call
result = self.endpoint(*a, **kw)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 962, in __call__
return self.method(*args, **kw)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/http.py", line 512, in response_wrap
response = f(*args, **kw)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/web/controllers/main.py", line 901, in call_button
action = self._call_kw(model, method, args, {})
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/web/controllers/main.py", line 889, in _call_kw
return getattr(request.registry.get(model), method)(request.cr, request.uid, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/api.py", line 250, in wrapper
return old_api(self, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/api.py", line 381, in old_api
result = method(recs, *args, **kwargs)
File "/home/kristian/odoov9/odoo-9.0c-20160712/openerp/addons/l10n_cl_dte/models/invoice.py", line 102, in send_xml_file
_logger.info('len (como viene): %s' % len(self.sii_xml_request))
TypeError: object of type 'bool' has no len()
</code></pre>
<p>The error is on this line </p>
<p><code>_logger.info('URL to be used %s' % url)
# client = Client(url)
# _logger.info(client)
_logger.info('len (como viene): %s' % len(self.sii_xml_request))</code></p>
<p>I've searched through SO, and it seems to be related to parenthesis, but I'm still not really sure.</p>
<p>Any ideas on this?</p>
<p>Thanks in advance!</p>
<p><strong>EDIT</strong></p>
<p>This is the code that sets it:</p>
<pre><code> sii_xml_request = fields.Text(
string='SII XML Request',
copy=False,
)
</code></pre>
| 0 | 2016-08-24T02:29:26Z | 39,114,224 | <p>When you try to access <em>self.sii_xml_request.</em> First check it's value weather its empty or not. </p>
<p>In your case, it returns an empty string which is <em>False</em>. To avoid this, try the following code:</p>
<pre><code>_logger.info('len (como viene): %s' % (len(self.sii_xml_request) if self.sii_xml_request else '')
</code></pre>
<p>This will only log 'self.sii_xml_request' if it has a value in it. Otherwise it will just log an empty string. You can change this of course to log something different that you would like to show if there is no value in 'self.sii_xml_request'.</p>
| 2 | 2016-08-24T04:02:08Z | [
"python",
"openerp",
"odoo-9"
] |
Python 3.5: Exporting Chinese Characters | 39,113,533 | <p>I have been trying several times to export Chinese from list variables to csv or txt file and found problems with that. </p>
<p>Specifically, I have already set the encoding as utf-8 or utf-16 when reading the data and writing them to the file. However, I noticed that I cannot do that when my Window 7âs base language is English, even that I change the language setting to Chinese. When I run the Python programs under the Window 7 with Chinese as base language, I can successfully export and show Chinese perfectly. </p>
<p>I am wondering why that happens and any solution helping me show Chinese characters in the exported file when running the Python programs under English-based Window? </p>
| 0 | 2016-08-24T02:35:46Z | 39,114,483 | <p>I just found that you need to do 2 things to achieve this:</p>
<ol>
<li>Change the Window's display language to Chinese.</li>
<li>Use encoding UTF-16 in the writing process.</li>
</ol>
| 0 | 2016-08-24T04:33:06Z | [
"python",
"python-3.x",
"character-encoding"
] |
Python 3.5: Exporting Chinese Characters | 39,113,533 | <p>I have been trying several times to export Chinese from list variables to csv or txt file and found problems with that. </p>
<p>Specifically, I have already set the encoding as utf-8 or utf-16 when reading the data and writing them to the file. However, I noticed that I cannot do that when my Window 7âs base language is English, even that I change the language setting to Chinese. When I run the Python programs under the Window 7 with Chinese as base language, I can successfully export and show Chinese perfectly. </p>
<p>I am wondering why that happens and any solution helping me show Chinese characters in the exported file when running the Python programs under English-based Window? </p>
| 0 | 2016-08-24T02:35:46Z | 39,115,980 | <p>Here's US Windows 10, running a Python IDE called PythonWin. There are no problems with Chinese.</p>
<p><a href="http://i.stack.imgur.com/Szezw.png" rel="nofollow"><img src="http://i.stack.imgur.com/Szezw.png" alt="enter image description here"></a></p>
<p>Here's the same program running in a Windows console. Note the US codepage default for the console is <code>cp437</code>. <code>cp65001</code> is UTF-8. Switching to an encoding that supports Chinese text is the key. The text below was cut-and-pasted directly from the console. While the characters display correctly pasted to Stack Overflow, the console font didn't support Chinese and actually displayed <a href="http://i.stack.imgur.com/RrZzn.png" rel="nofollow"><img src="http://i.stack.imgur.com/RrZzn.png" alt="enter image description here"></a>. </p>
<pre><code>C:\>chcp
Active code page: 437
C:\>x
Traceback (most recent call last):
File "C:\\x.py", line 5, in <module>
print(f.read())
File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-5: character maps to <undefined>
C:\>chcp 65001
Active code page: 65001
C:\>type test.txt
ææ¯ç¾å½äººã
C:\>x
ææ¯ç¾å½äººã
</code></pre>
<p>Notepad displays the output file correctly as well:</p>
<p><a href="http://i.stack.imgur.com/DuYnq.png" rel="nofollow"><img src="http://i.stack.imgur.com/DuYnq.png" alt="enter image description here"></a></p>
<p>Either use an IDE that supports UTF-8, or write your output to a file and read it with a tool like Notepad.</p>
<p>Ways to get the Windows console to actually output Chinese are the <code>win-unicode-console</code> package, and changing the Language and Region settings, Administrative tab, system locale to Chinese. For the latter, Windows will remain English, but the Windows console will use a Chinese code page instead of an English one.</p>
| 0 | 2016-08-24T06:33:18Z | [
"python",
"python-3.x",
"character-encoding"
] |
How to speed up simple loop in python | 39,113,552 | <p>I want to accelerate the speed of loop in python.
There is a code below.</p>
<pre><code>for x in dpath.util.search(self.data, "**", yielded=True):
self.contentsList.append(x)
</code></pre>
<p>dpath.util.search is generator.
how could I speed up this simple loop??</p>
| -2 | 2016-08-24T02:38:16Z | 39,113,572 | <p>Well, the loop itself is unnecessary; you could let Python do the looping & append work with a single function call instead of many calls with:</p>
<pre><code>self.contentsList.extend(dpath.util.search(self.data, "**", yielded=True))
</code></pre>
| 2 | 2016-08-24T02:41:23Z | [
"python",
"optimization"
] |
Psycopg2 execute tuple index out of range | 39,113,555 | <p>I am very new to python and this is my first programming language. This is my first shot at using SQL as well as psycopg2. Any "dumb" advice is much appreciated!</p>
<p>I am not sure what the problem is. My research tells me im feeding too few or too many arguments to the <code>cursor.execute(INSERT...</code> but i have tried a number of different counts and can't seem to get any working correctly. From my point of view the <code>cursor.execute(CREATE...</code> creates a table with 6 columns and i am passing 6 args to it.</p>
<pre><code>from lxml import html # Used to parse XML
import requests #used to service API request
itemtypeid1 = 34
itemtypeid2 = 35
regionid = 10000002
webpage = requests.get('http://api.eve-central.com/api/marketstat?typeid=%i&typeid=%i&regionlimit=%i' % (
itemtypeid1, itemtypeid2, regionid))
if webpage.status_code == 200:
data = html.fromstring(webpage.content)
for item in data.iter('type'):
buy_dict = {node.tag: node.text for node in item.xpath("buy/*")}
sell_dict = {node.tag: node.text for node in item.xpath("sell/*")}
#Variables for output
itemid = (item.get("id"))
buymin = buy_dict['min']
buymax = buy_dict['max']
buymedian = buy_dict['median']
buyvolume = buy_dict['volume']
buyaverage = buy_dict['avg']
#Fail if api webpage unavaliable
else:
print "Webpage unavaliable"
Webpage.raise_for_status()
#############################################################################
import psycopg2
connection = psycopg2.connect(database='evemarketdata', user='postgres', password='black3car')
#open a cursor to perform DB operations
cursor = connection.cursor()
#create new table
cursor.execute("CREATE TABLE arkonor (itemid integer primary key, min integer, max integer, median integer, volume integer, average integer);")
#Insert row data into DB table
cursor.execute("""INSERT INTO arkonor (typeid, min, max, median, volume, average)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
('itemid', 'buymin', 'buymax', 'buymedian', 'buyvolume', 'buyaverage'))
#Commits all changes does with cursor
#connection.commit()
</code></pre>
<p>results in</p>
<pre><code> Traceback (most recent call last):
File "E:\Eve Spreadsheets\Python\PostgreConnect.py", line 49, in <module>
('itemid', 'buymin', 'buymax', 'buymedian', 'buyvolume', 'buyaverage'))
IndexError: tuple index out of range
</code></pre>
| 0 | 2016-08-24T02:38:37Z | 39,113,804 | <p>You have 8 parameters in the query but provided only 6 fields in the tuple. The code should be:</p>
<pre><code>#Insert row data into DB table
cursor.execute("""INSERT INTO arkonor (typeid, min, max, median, volume, average)
VALUES (%s, %s, %s, %s, %s, %s)""",
('itemid', 'buymin', 'buymax', 'buymedian', 'buyvolume', 'buyaverage'))
</code></pre>
| 0 | 2016-08-24T03:11:53Z | [
"python",
"postgresql",
"psycopg2"
] |
My answers are 5, 4, 3, 2,but when I run the code ,the answers are 5, 4.Why? | 39,113,605 | <pre><code>num = 5
if num > 2:
print(num)
num -= 1
print(numï¼
</code></pre>
<p>Here are my thoughts:5>2,5,4; 4>2,4,3; 3>2,3,2; 2.So my answers are the 5, 4, 3, 2 but when I run the code,the answers are the 5 ,4. I really don't understand it.</p>
| -5 | 2016-08-24T02:46:20Z | 39,113,660 | <p>use <code>while</code> instead of <code>if</code>.</p>
<pre><code>>>> num = 5
>>> while num > 2:
... print(num)
... num -= 1
# 5
# 4
# 3
>>> print(num)
# 2
</code></pre>
| 3 | 2016-08-24T02:52:02Z | [
"python",
"python-3.x"
] |
Tensorflow multi-variable logistic regression not working | 39,113,871 | <p>I am trying to create a program which will classify a point as either <code>1</code> or <code>0</code> using <a href="https://www.tensorflow.org/" rel="nofollow">Tensorflow</a>. I am trying to create an oval shape around the center of this plot, where the blue dots are:</p>
<p>Everything in the oval should be classified as <code>1</code>, every thing else should be <code>0</code>. In the graph above, the blue dots are <code>1</code>s and the red x's are <code>0</code>s.</p>
<p>However, every time I try to classify a point, it always choses <code>1</code>, even if it was a point I trained it with, saying it was <code>0</code>.</p>
<p>My question is simple: Why is the guess always <code>1</code>, and what am I doing wrong or should do differently to fix this problem? This is my first machine learning problem I have tried without a tutorial, so I really don't know much about this stuff. </p>
<p>I'd appreciate any help you can give, thanks!</p>
<p>Here's my code:</p>
<pre><code>#!/usr/bin/env python3
import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
training_in = numpy.array([[0, 0], [1, 1], [2, 0], [-2, 0], [-1, -1], [-1, 1], [-1.5, 1], [3, 3], [3, 0], [-3, 0], [0, -3], [-1, 3], [1, -2], [-2, -1.5]])
training_out = numpy.array([1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0])
def transform_data(x):
return [x[0], x[1], x[0]**2, x[1]**2, x[0]*x[1]]
new_training_in = numpy.apply_along_axis(transform_data, 1, training_in)
feature_count = new_training_in.shape[1]
x = tf.placeholder(tf.float32, [None, feature_count])
y = tf.placeholder(tf.float32, [None, 1])
W = tf.Variable(tf.zeros([feature_count, 1]))
b = tf.Variable(tf.zeros([1]))
guess = tf.nn.softmax(tf.matmul(x, W) + b)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(tf.matmul(x, W) + b, y))
opti = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
for (item_x, item_y) in zip(new_training_in, training_out):
sess.run(opti, feed_dict={ x: [item_x], y: [[item_y]]})
print(sess.run(W))
print(sess.run(b))
plt.plot(training_in[:6, 0], training_in[:6, 1], 'bo')
plt.plot(training_in[6:, 0], training_in[6:, 1], 'rx')
results = sess.run(guess, feed_dict={ x: new_training_in })
for i in range(training_in.shape[0]):
xx = [training_in[i:,0]]
yy = [training_in[i:,1]]
res = results[i]
# this always prints `[ 1.]`
print(res)
# uncomment these lines to see the guesses
# if res[0] == 0:
# plt.plot(xx, yy, 'c+')
# else:
# plt.plot(xx, yy, 'g+')
plt.show()
</code></pre>
| 2 | 2016-08-24T03:20:13Z | 39,120,655 | <p>The problem occurs when you use <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#softmax_cross_entropy_with_logits" rel="nofollow">softmax_cross_entropy_with_logits</a>. In your concrete case, both <code>logits</code> and <code>labels</code> should have shape <code>[batch_size, number_of_labels=2]</code>.</p>
<p>Note that your tensors <code>logits=tf.matmul(x, W) + b</code> and <code>labels=y</code> have shape <code>[batch_size, 1]</code>, so Tensorflow is assuming that <code>number_of_labels=1</code>. That's why your guess is always the same.</p>
<p><strong>A)</strong> You could solve this problem by encoding <code>training_out</code> as a one-hot vector. I recommend using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.eye.html" rel="nofollow"><code>np.eye()</code></a> to achieve that:</p>
<pre><code>training_out = [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
training_out = numpy.eye(2)[training_out]
</code></pre>
<p>Then, you will need to make the following changes:</p>
<pre><code>y = tf.placeholder(tf.float32, [None, 2])
W = tf.Variable(tf.zeros([feature_count, 2]))
b = tf.Variable(tf.zeros([2]))
...
for i in range(1000):
for (item_x, item_y) in zip(new_training_in, training_out):
sess.run(opti, feed_dict={x: [item_x], y: [item_y]})
...
results = sess.run(guess, feed_dict={x: new_training_in})[:,1]
</code></pre>
<p><strong>B)</strong> Alternatively, you could use <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/nn.html#sparse_softmax_cross_entropy_with_logits" rel="nofollow">sparse_softmax_cross_entropy_with_logits</a>, which allows <code>labels</code> to have shape <code>[batch_size]</code>. I've tweaked your code to make it work in this way:</p>
<pre><code>import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
training_in = numpy.array(
[[0, 0], [1, 1], [2, 0], [-2, 0], [-1, -1], [-1, 1], [-1.5, 1], [3, 3], [3, 0], [-3, 0], [0, -3], [-1, 3], [1, -2],
[-2, -1.5]])
training_out = numpy.array([1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0])
def transform_data(x):
return [x[0], x[1], x[0] ** 2, x[1] ** 2, x[0] * x[1]]
new_training_in = numpy.apply_along_axis(transform_data, 1, training_in)
feature_count = new_training_in.shape[1]
x = tf.placeholder(tf.float32, [None, feature_count])
y = tf.placeholder(tf.int32, [None])
W = tf.Variable(tf.zeros([feature_count, 2]))
b = tf.Variable(tf.zeros([2]))
guess = tf.nn.softmax(tf.matmul(x, W) + b)
cost = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(tf.matmul(x, W) + b, y))
opti = tf.train.GradientDescentOptimizer(0.01).minimize(cost)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
for (item_x, item_y) in zip(new_training_in, training_out):
sess.run(opti, feed_dict={x: [item_x], y: [item_y]})
print(sess.run(W))
print(sess.run(b))
plt.plot(training_in[:6, 0], training_in[:6, 1], 'bo')
plt.plot(training_in[6:, 0], training_in[6:, 1], 'rx')
results = sess.run(guess, feed_dict={x: new_training_in})
for i in range(training_in.shape[0]):
xx = [training_in[i:, 0]]
yy = [training_in[i:, 1]]
res = results[i]
# this always prints `[ 1.]`
print(res)
# uncomment these lines to see the guesses
if res[0] == 0:
plt.plot(xx, yy, 'c+')
else:
plt.plot(xx, yy, 'g+')
plt.show()
</code></pre>
| 1 | 2016-08-24T10:23:37Z | [
"python",
"machine-learning",
"tensorflow",
"logistic-regression"
] |
Python url encode/decode - Convert % escaped hexadecimal digits into string | 39,113,885 | <p>For example, if I have an encoded string as:</p>
<pre><code>url='locality=Norwood&address=138+The+Parade&region=SA&country=AU&name=Pav%C3%A9+cafe&postalCode=5067'
</code></pre>
<p>The name parameter has the characters %C3%A9 which actually implies the character é.</p>
<p>Hence, I would like the output to be:</p>
<pre><code>new_url='locality=Norwood&address=138+The+Parade&region=SA&country=AU&name=Pavé+cafe&postalCode=5067'
</code></pre>
<p>I tried the following steps on a <strong>Python terminal</strong>:</p>
<pre><code>>>> import urllib2
>>> url='locality=Norwood&address=138+The+Parade&region=SA&country=AU&name=Pav%C3%A9+cafe&postalCode=5067'
>>> new_url=urllib2.unquote(url).decode('utf8')
>>> print new_url
locality=Norwood&address=138+The+Parade&region=SA&country=AU&name=Pavé+cafe&postalCode=5067
>>>
</code></pre>
<p>However, when I tried the same thing within a <strong>Python script</strong> and run as myscript.py, I am getting the following stack trace:</p>
<pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 88: ordinal not in range(128)
</code></pre>
<p>I am using Python 2.6.6 and cannot switch to other versions due to work reasons. </p>
<p>How can I overcome this error? </p>
<p>Any help is greatly appreciated. Thanks in advance!</p>
<pre><code>######################################################
</code></pre>
<p><strong>EDIT</strong></p>
<p><strong>I realized that I am getting the above expected output.</strong> </p>
<p><strong>However</strong>, I would like to convert the parameters in the new_url into a dictionary as follows. While doing so, I am not able to retain the special character 'é' in my name parameter.</p>
<pre><code>print new_url
params_list = new_url.split("&")
print(params_list)
params_dict={}
for p in params_list:
temp = p.split("=")
params_dict[temp[0]] = temp[1]
print(params_dict)
</code></pre>
<p><strong>Outputs:</strong></p>
<p><strong>new_url</strong></p>
<p>locality=Norwood&address=138+The+Parade&region=SA&country=AU&name=Pavé+cafe&postalCode=5067</p>
<p><strong>params_list</strong></p>
<p>[u'locality=Norwood', u'address=138+The+Parade', u'region=SA', u'country=AU', u'name=Pav\xe9+cafe', u'postalCode=5067']</p>
<p><strong>params_dict</strong></p>
<p>{u'name': u'Pav\xe9+cafe', u'locality': u'Norwood', u'country': u'AU', u'region': u'SA', u'address': u'138+The+Parade', u'postalCode': u'5067'}</p>
<p>Basically ... the name is now 'Pav\xe9+cafe' as opposed to the required 'Pavé'.</p>
<p>How can I still retain the same special character in my params_dict?</p>
| 0 | 2016-08-24T03:23:34Z | 39,114,307 | <p>This is actually due to the difference between <code>__repr__</code> and <code>__str__</code>. When printing a unicode string, <code>__str__</code> is used and results in the <code>é</code> you see when printing <code>new_url</code>. However, when a list or dict is printed, <code>__repr__</code> is used, which uses <code>__repr__</code> for each object within lists and dicts. If you print the items separately, they print as you desire.</p>
<pre><code># -*- coding: utf-8 -*-
new_url = u'name=Pavé+cafe&postalCode=5067'
print(new_url) # name=Pavé+cafe&postalCode=5067
params_list = [s for s in new_url.split("&")]
print(params_list) # [u'name=Pav\xe9+cafe', u'postalCode=5067']
print(params_list[0]) # name=Pavé+cafe
print(params_list[1]) # postalCode=5067
params_dict = {}
for p in params_list:
temp = p.split("=")
params_dict[temp[0]] = temp[1]
print(params_dict) # {u'postalCode': u'5067', u'name': u'Pav\xe9+cafe'}
print(params_dict.values()[0]) # 5067
print(params_dict.values()[1]) # Pavé+cafe
</code></pre>
<p>One way to print the list and dict is to get their string representation, then decode them with<code>unicode-escape</code>:</p>
<pre><code>print(str(params_list).decode('unicode-escape')) # [u'name=Pavé+cafe', u'postalCode=5067']
print(str(params_dict).decode('unicode-escape')) # {u'postalCode': u'5067', u'name': u'Pavé+cafe'}
</code></pre>
<p><strong>Note</strong>: This is only an issue in Python 2. Python 3 prints the characters as you would expect. Also, you may want to look into <a href="https://docs.python.org/2.6/library/urlparse.html#urlparse.parse_qs" rel="nofollow"><code>urlparse</code></a> for parsing your URL instead of doing it manually.</p>
<pre><code>import urlparse
new_url = u'name=Pavé+cafe&postalCode=5067'
print dict(urlparse.parse_qsl(new_url)) # {u'postalCode': u'5067', u'name': u'Pav\xe9 cafe'}
</code></pre>
| 0 | 2016-08-24T04:13:18Z | [
"python",
"python-2.6",
"python-unicode"
] |
How python interpreter determine the type of variable at runtime? | 39,114,009 | <p>I just want to know how python's <strong>(python 2.7)</strong> interpreter is find the type of variable. Like How python Dynamic Type Behaviour internally works. </p>
<pre><code>MacBook-Pro:~ neelabhsingh$ python
Python 2.7.12 (default, Jun 29 2016, 14:05:02)
>>> type(i)
<type 'int'>
>>> type(str1)
<type 'str'>
>>> testFloat = 45.67
>>> type(testFloat)
<type 'float'>
</code></pre>
| 3 | 2016-08-24T03:37:17Z | 39,114,156 | <p>In CPython 2.7 (i.e. the C language implementation of Python), there is a <a href="https://docs.python.org/2/c-api/structures.html#c.PyObject" rel="nofollow"><code>PyObject</code> type</a>. There is also a <a href="https://docs.python.org/2/c-api/object.html#c.PyObject_Type" rel="nofollow"><code>PyObject_Type</code></a> function which accesses the type stored in the <code>PyObject</code> i.e. the object carries around type information with it.</p>
| 4 | 2016-08-24T03:55:10Z | [
"python"
] |
Type Error Occured in python executed in visual studio | 39,114,222 | <p>i am running the below code to calculate current age in python using visual studio.</p>
<p>but i am getting the below piece of error:
Error:</p>
<pre><code>Type Error Occured
Unsupported operand Type for built_in_function or method
</code></pre>
<p>code:</p>
<pre><code>import datetime
def my_current_age():
user_input = input("enter year")
date_of_birth = (datetime.date(1990 , 10 , 28))
today_date=(datetime.date.today)
current_age = (today_date - date_of_birth)
print("you lived for {}" .format(current_age))
print(my_current_age())
</code></pre>
<p>any suggestion python developer please</p>
<p>Thanks</p>
| 1 | 2016-08-24T04:01:49Z | 39,114,273 | <p>You are assigning a method of <code>datetime</code> to <code>today_date</code> with:</p>
<pre><code>today_date=(datetime.date.today)
</code></pre>
<p>i.e, you are <em>calling</em> the function. Call it, instead:</p>
<pre><code>today_date=(datetime.date.today())
</code></pre>
<p>in order for it to work.</p>
<p>Apart from that, take note that the parenthesis around your expressions are redundant, that is:</p>
<pre><code>today_date=(datetime.date.today())
</code></pre>
<p>is directly equivalent to:</p>
<pre><code>today_date = datetime.date.today()
</code></pre>
| 1 | 2016-08-24T04:09:25Z | [
"python",
"python-3.x"
] |
How to search phrases in a string in python | 39,114,398 | <p>I change my text file into a string. The string has been formatted to look like</p>
<pre><code>{'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}
</code></pre>
<p>I then used this code to try and find the number of times a name appears in the data. However, it returned the actual original string. Is there anyway to fix this?</p>
<pre><code>searchfile = open('file.txt', 'r')
for line in searchfile:
if 'author name' in line: print (line)
searchfile.close()
</code></pre>
<p>What I would like is for it to print the 'author name'</p>
| 0 | 2016-08-24T04:23:31Z | 39,114,824 | <pre><code>searchfile = open('test', 'r')
word = "test"
lst = []
for line in searchfile:
a = line.split()
for x in a:
if x == word:
lst.append(x)
print(lst)
searchfile.close()
</code></pre>
<p>This took a little bit of research and testing, but it should do what you wanted :). So the line.split() will essentially put words separated by space in the text file into a list. From there, you cycle through the list checking if it matches the world. If it does, it will push it into our list and later on print it so we can see.</p>
<p>If you were searching Smith for example it would be "'Smith," because there's no space separating the ' and , from Smith unless you want to make a function that removes the : , ' { }.</p>
| 0 | 2016-08-24T05:07:20Z | [
"python",
"file"
] |
How to search phrases in a string in python | 39,114,398 | <p>I change my text file into a string. The string has been formatted to look like</p>
<pre><code>{'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}
</code></pre>
<p>I then used this code to try and find the number of times a name appears in the data. However, it returned the actual original string. Is there anyway to fix this?</p>
<pre><code>searchfile = open('file.txt', 'r')
for line in searchfile:
if 'author name' in line: print (line)
searchfile.close()
</code></pre>
<p>What I would like is for it to print the 'author name'</p>
| 0 | 2016-08-24T04:23:31Z | 39,115,009 | <p>if you just want to count the number of times a particular name appears in your string, you can maintain a counter map against it. Something like</p>
<pre><code>import sys
def main(some_name):
counter_map = {}
for x in input_string.split(','):
if some_name in x:
count = counter_map.get(some_name, 0)
counter_map[some_name] = count + 1
print(counter_map[some_name])
if __name__ == '__main__':
main(sys.argv[1])
</code></pre>
<p>and the <code>input_string</code> looks something like below</p>
<pre><code>input_string = """
{'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}, {'AU': 'Smith, hâ}, {'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}, {'AU': 'Smith, hâ},
{'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}, {'AU': 'Smith, hâ}, {'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}, {'AU': 'Smith, hâ},
{'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}, {'AU': 'Smith, hâ}, {'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}, {'AU': 'Smith, hâ},
....
"""
</code></pre>
<p>Prints out the following on my end (used a larger file)</p>
<pre><code>$ python counter.py Smith
576
</code></pre>
| 0 | 2016-08-24T05:23:06Z | [
"python",
"file"
] |
How to search phrases in a string in python | 39,114,398 | <p>I change my text file into a string. The string has been formatted to look like</p>
<pre><code>{'AU': 'Smith, Sâ}, {'AU': 'James, Aâ}, {'AU': 'Stevens, Pâ}
</code></pre>
<p>I then used this code to try and find the number of times a name appears in the data. However, it returned the actual original string. Is there anyway to fix this?</p>
<pre><code>searchfile = open('file.txt', 'r')
for line in searchfile:
if 'author name' in line: print (line)
searchfile.close()
</code></pre>
<p>What I would like is for it to print the 'author name'</p>
| 0 | 2016-08-24T04:23:31Z | 39,115,053 | <p>This should be what you need, assuming that the whole file is a string as you said. It searches for the <code>name</code> argument given and if found prints that <code>name</code> argument. Otherwise it prints <code>"not found"</code>:</p>
<pre><code>file = "{'AU': 'Smith, S'},{'AU': 'James, A'},{'AU': 'Stevens, P'},{'AU': 'James, A'}"
def find_name(name, nameString):
curWord = ""
if name in nameString:
print(name)
return
else:
print("not found")
find_name('James, A', file) # output:'James, A'
find_name('Jane, A', file) # output: 'not found'
</code></pre>
<p><strong>Note</strong>. it only prints the name is finds one time. Your going to have to use a loop if you wanted name printed out as many times as it it found.</p>
| 0 | 2016-08-24T05:26:09Z | [
"python",
"file"
] |
AUC calculation in decision tree in scikit-learn | 39,114,463 | <p>Using scikit-learn with Python 2.7 on Windows, what is wrong with my code to calculate AUC? Thanks.</p>
<pre><code>from sklearn.datasets import load_iris
from sklearn.cross_validation import cross_val_score
from sklearn.tree import DecisionTreeClassifier
clf = DecisionTreeClassifier(random_state=0)
iris = load_iris()
#print cross_val_score(clf, iris.data, iris.target, cv=10, scoring="precision")
#print cross_val_score(clf, iris.data, iris.target, cv=10, scoring="recall")
print cross_val_score(clf, iris.data, iris.target, cv=10, scoring="roc_auc")
Traceback (most recent call last):
File "C:/Users/foo/PycharmProjects/CodeExercise/decisionTree.py", line 8, in <module>
print cross_val_score(clf, iris.data, iris.target, cv=10, scoring="roc_auc")
File "C:\Python27\lib\site-packages\sklearn\cross_validation.py", line 1433, in cross_val_score
for train, test in cv)
File "C:\Python27\lib\site-packages\sklearn\externals\joblib\parallel.py", line 800, in __call__
while self.dispatch_one_batch(iterator):
File "C:\Python27\lib\site-packages\sklearn\externals\joblib\parallel.py", line 658, in dispatch_one_batch
self._dispatch(tasks)
File "C:\Python27\lib\site-packages\sklearn\externals\joblib\parallel.py", line 566, in _dispatch
job = ImmediateComputeBatch(batch)
File "C:\Python27\lib\site-packages\sklearn\externals\joblib\parallel.py", line 180, in __init__
self.results = batch()
File "C:\Python27\lib\site-packages\sklearn\externals\joblib\parallel.py", line 72, in __call__
return [func(*args, **kwargs) for func, args, kwargs in self.items]
File "C:\Python27\lib\site-packages\sklearn\cross_validation.py", line 1550, in _fit_and_score
test_score = _score(estimator, X_test, y_test, scorer)
File "C:\Python27\lib\site-packages\sklearn\cross_validation.py", line 1606, in _score
score = scorer(estimator, X_test, y_test)
File "C:\Python27\lib\site-packages\sklearn\metrics\scorer.py", line 159, in __call__
raise ValueError("{0} format is not supported".format(y_type))
ValueError: multiclass format is not supported
</code></pre>
<p><strong>Edit 1</strong>, looks like scikit learn could even decide threshold without any machine learning models, wondering why,</p>
<pre><code>import numpy as np
from sklearn.metrics import roc_curve
y = np.array([1, 1, 2, 2])
scores = np.array([0.1, 0.4, 0.35, 0.8])
fpr, tpr, thresholds = roc_curve(y, scores, pos_label=2)
print fpr
print tpr
print thresholds
</code></pre>
| 0 | 2016-08-24T04:31:17Z | 39,114,583 | <p>The <code>roc_auc</code> in <code>sklearn</code> works only with binary class:</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html</a></p>
<p>One way to move around this issue is to binarize your label and extend your classification to a one-vs-all scheme. In sklearn you can use <code>sklearn.preprocessing.LabelBinarizer</code>. The documentation is here:</p>
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html</a></p>
| 1 | 2016-08-24T04:43:56Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"decision-tree"
] |
Django Channels using django shell | 39,114,502 | <p>I'm currently am trying to use Celery to send sockets with django channels. However I found the same issue there as with using Django's shell, and was hoping if someone could enlighten me.</p>
<p>I have it set up so that within views.py, when a user sends a POST request it will call </p>
<pre><code>Group("chat").send({'text':'hello'})
</code></pre>
<p>The browser then displays an alert.</p>
<p>However when I try to do the same thing using Django's shell or one of Celery's tasks:</p>
<pre><code>$ python3 manage.py shell
$ from channels import Group
$ Group("chat").send({'text': 'hello'})
</code></pre>
<p>It doesn't do anything, not even returning an error.</p>
| 1 | 2016-08-24T04:35:16Z | 39,311,008 | <p>If you are using <code>In-Memory</code> Channel Layer then likely <code>it does not support cross-process communication.</code> So try with other channel layer types and you are good to go.</p>
| 1 | 2016-09-03T20:20:34Z | [
"python",
"django",
"django-celery",
"django-channels"
] |
For Loop on Plotly Python | 39,114,575 | <p>I am trying to replace</p>
<pre><code>fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 2, 1)
</code></pre>
<p>with the for loop code</p>
<pre><code>totalPlot = 2
x = ['trace%s'%(item + 1) for item in range(totalPlot)]
y = [(item + 1) for item in range(totalPlot)]
z = totalPlot * [1]
for i, j, k in zip(x, y, z):
fig.append_trace(i, j, k)
</code></pre>
<p>so that it will be more scalable as I add more figures. However, the loop code keeps returning 'TypeError: 'str' object does not support item assignment'. What did I do wrong?</p>
<p>Here is the code similar with the one from <a href="https://plot.ly/python/subplots/" rel="nofollow">Plotly</a>:</p>
<pre><code>from plotly import tools
import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Scatter(
x=[1, 2, 3],
y=[4, 5, 6]
)
trace2 = go.Scatter(
x=[20, 30, 40],
y=[50, 60, 70],
)
fig = tools.make_subplots(rows=2, cols=1)
# ----- Loop here ------- START
fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 2, 1)
# ----- Loop here ------- END
fig['layout'].update(height=600, width=600, title='i <3 subplots')
py.iplot(fig, filename='make-subplots')
</code></pre>
| 0 | 2016-08-24T04:43:09Z | 39,114,901 | <p>In this code it looks like <code>trace1</code> is some kind of array-like data structure:</p>
<pre><code>trace1 = go.Scatter(
x=[1, 2, 3],
y=[4, 5, 6]
)
</code></pre>
<p>So I imagine that when you call <code>fig.append_trace(trace1, 1, 1)</code> it's adding an element to this array-like structure, the first parameter.</p>
<p>However in your reimplementation, you've turned the trace data into a string:</p>
<pre><code>x = ['trace%s'%(item + 1) for item in range(totalPlot)]
...
for i, j, k in zip(x, y, z):
fig.append_trace(i, j, k)
</code></pre>
<p>Here <code>i</code> is an element of <code>x</code> which is in turn a string like <code>'trace%s'%(item + 1)</code>. But you cannot append an element to a string. Python strings are immutable. So when you call <code>append_trace</code> you naturally get an error here about not being able to do what you want with strings.</p>
| 1 | 2016-08-24T05:14:19Z | [
"python",
"for-loop",
"plotly"
] |
Python - Applying multiple conditions output in list comprehension | 39,114,636 | <p>I have been trying code an RGB to Hex function in Python when I faced a problem that I wasn't able to figure out how to do.
Here is the function itself: <br></p>
<pre><code>def rgb(r, g, b):
return ''.join([format("{0:x}".format(x).rjust(2, "0").upper()) if int(x) >= 0 else "00" if int(x) <= 255 else "FF" for x in [r,g,b]])
</code></pre>
<p>The important part:
<strong>if int(x) >= 0 else "00" if int(x) <= 255 else "FF"</strong></p>
<p>What I want to be able to do is to apply a different output if the number is lower than 0 or higher than 255. Only the first if works, the second is ignored. How can we properly do multiple conditions in a list comprehension?</p>
| 0 | 2016-08-24T04:50:01Z | 39,114,762 | <p>You current <code>... if ... else ...</code> clause doesn't make much sense:</p>
<pre><code>format("{0:x}".format(x).rjust(2, "0").upper()) if int(x) >= 0 else "00" if int(x) <= 255 else "FF"
</code></pre>
<p>means:</p>
<ul>
<li><code>format(...)</code> if <code>int(x) >= 0</code></li>
<li><p>else, if <code>int(x) < 0</code>, then </p>
<ul>
<li><code>00</code> if <code>int(x) <= 255</code> (<em>but its already less than zero so must be less than 255</em>);</li>
<li>else <code>FF</code></li>
</ul></li>
</ul>
<p>Presumably you meant to have:</p>
<pre><code>"FF" if int(x) > 255 else ("00" if int(x) < 0 else format(...))
</code></pre>
<p>But surely, isn't it easier to use a standard max-min construct?</p>
<pre><code>"{0:02X}".format(max(0, min(int(x), 255)))
</code></pre>
<p>Note that here we do the zero padding and upper casing in the format specifier itself (<code>02X</code>)</p>
| 2 | 2016-08-24T05:01:31Z | [
"python",
"if-statement",
"list-comprehension",
"multiple-conditions"
] |
Python - Applying multiple conditions output in list comprehension | 39,114,636 | <p>I have been trying code an RGB to Hex function in Python when I faced a problem that I wasn't able to figure out how to do.
Here is the function itself: <br></p>
<pre><code>def rgb(r, g, b):
return ''.join([format("{0:x}".format(x).rjust(2, "0").upper()) if int(x) >= 0 else "00" if int(x) <= 255 else "FF" for x in [r,g,b]])
</code></pre>
<p>The important part:
<strong>if int(x) >= 0 else "00" if int(x) <= 255 else "FF"</strong></p>
<p>What I want to be able to do is to apply a different output if the number is lower than 0 or higher than 255. Only the first if works, the second is ignored. How can we properly do multiple conditions in a list comprehension?</p>
| 0 | 2016-08-24T04:50:01Z | 39,114,976 | <p>Here's your current if-else statement, broken down into a function. It should be clear from this where the problem is.</p>
<pre><code>def broken_if_statement(x):
if int(x) >= 0:
# Print value as UPPERCASE hexadecimal.
return format("{0:x}".format(x).rjust(2, "0").upper())
else if int(x) <= 255:
# This code path can only be reached if x < 0!
return "00"
else:
# This code path can never be reached!
return "FF"
</code></pre>
<p>And here's a much simpler way to write your function.</p>
<pre><code>def rgb(r, g, b):
return ''.join([('00' if x < 0
else 'FF' if x > 255
else "{0:02X}".format(x))
for x in (r,g,b) ])
>>> rgb(-10, 45, 300)
'002DFF'
</code></pre>
<p>Edit: I original interpreted "apply a different output" as meaning you wanted input less than zero to be different to input equal to zero, such as 'ff' for 255 but 'FF' for >255, hence the structure above supporting that. But if <0 and =0 should result in the identical output, and likewise for >255 and =255, then just limiting inputs using min and max is simpler.</p>
<pre><code>def rgb(r, g, b):
return "".join("{0:02X}".format(min(255,max(0,x))) for x in (r,g,b))
</code></pre>
| -1 | 2016-08-24T05:20:05Z | [
"python",
"if-statement",
"list-comprehension",
"multiple-conditions"
] |
how can I get python's np.savetxt to save each iteration of a loop in a different column? | 39,114,780 | <p>This is an extremely basic code that does what I want... except with regard to the writing of the text file.</p>
<pre><code>import numpy as np
f = open("..\myfile.txt", 'w')
tst = np.random.random(5)
tst2 = tst/3
for i in range(3):
for j in range(5):
test = np.random.random(5)+j
a = np.random.normal(test, tst2)
np.savetxt(f, np.transpose(a), fmt='%10.2f')
print a
f.close()
</code></pre>
<p>This code will write to a .txt file a single column that is concatenated after each iteration of the for loop. </p>
<p><strong>What I want is independent columns for each iteration.</strong></p>
<p><strong>How does one do that?</strong></p>
<p>note: I have used <code>np.c_[]</code> as well, and that <em>will</em> write the columns <strong>if</strong> I express each iteration within the command. ie: <code>np.c_[a[0],a[1]]</code> and so on. The problem whit this is, what if both my <code>i</code> and <code>j</code> values are very large? It isn't reasonable to follow this method.</p>
| 0 | 2016-08-24T05:02:57Z | 39,115,028 | <p>So a run produces:</p>
<pre><code>2218:~/mypy$ python3 stack39114780.py
[ 4.13312217 4.34823388 4.92073836 4.6214074 4.07212495]
[ 4.39911371 5.15256451 4.97868452 3.97355995 4.96236119]
[ 3.82737975 4.54634489 3.99827574 4.44644041 3.54771411]
2218:~/mypy$ cat myfile.txt
4.13
4.35
4.92
4.62
4.07 # end of 1st iteration
4.40
5.15
4.98
3.97
....
</code></pre>
<p>Do you understand what's going on? One call to <code>savetxt</code> writes a set of lines. With a 1d array like <code>a</code> it prints one number per row. (<code>transpose(a)</code> doesn't do anything). </p>
<p>File writing is done line by line, and can't be rewound to add columns. So to make multiple columns you need to create an array with multiple columns. Then do one <code>savetxt</code>. In other words, collect all the data before writing.</p>
<p>Collect your values in a list, make an array, and write that</p>
<pre><code>alist = []
for i in range(3):
for j in range(5):
test = np.random.random(5)+j
a = np.random.normal(test, tst2)
alist.append(a)
arr = np.array(alist)
print(arr)
np.savetxt('myfile.txt', arr, fmt='%10.2f')
</code></pre>
<p>I'm getting 15 rows of 5 columns, but you can tweak that.</p>
<pre><code>2226:~/mypy$ cat myfile.txt
0.74 0.60 0.29 0.74 0.62
1.72 1.62 1.12 1.95 1.13
2.19 2.55 2.72 2.33 2.65
3.88 3.82 3.63 3.58 3.48
4.59 4.16 4.05 4.26 4.39
</code></pre>
<p>Since <code>arr</code> is now 2d, <code>np.transpose(arr)</code> does something meaningful - I would get 5 rows with 15 columns.</p>
<p>==================</p>
<p>With</p>
<pre><code>for i in range(3):
for j in range(5):
test = np.random.random(5)+j
a = np.random.normal(test, tst2)
np.savetxt(f, np.transpose(a), fmt='%10.2f')
</code></pre>
<p>you write <code>a</code> once for each <code>i</code> - hence the 3 rows. You throwing away 4 of the <code>j</code> iterations. In my variation I collect all <code>a</code>, and hence get 15 rows.</p>
| 1 | 2016-08-24T05:23:54Z | [
"python",
"python-2.7",
"numpy",
"for-loop"
] |
Show user position on 2D maze - Python | 39,114,784 | <p>I have this task where I must print a maze that also provides the user's position. However this position can be dependent on the generated position from another function. What I mean is that the position can have many different possibilites. </p>
<p>I tried to use slicing with a combination of the .replace method to be able to change the character to the user's position symbolled as 'A'. </p>
<p>See the code below, am I doing something wrong here?</p>
<pre><code>def print_maze(maze, position):
"""
Returns maze string from text file and position of the player
print_maze(str, int) -> object
"""
p1 = position[0]
p2 = position[1]
position = position_to_index((p1,p2), len(maze))
for line in maze:
maze = maze[:position].replace(' ', 'A') + maze[position:]
for line in maze:
maze.strip().split('\n')
print(maze)
</code></pre>
<p>For my result so far, all I get is:</p>
<pre><code>>>> maze = load_maze('maze1.txt')
>>> print_maze(maze, (1,1))
#####
#AAZ#
#A###
#AAP#
#####
</code></pre>
| 0 | 2016-08-24T05:03:22Z | 39,116,860 | <p>It seems like you're making it harder than it need be. Rather than load the maze as one string, read it into an array. Do your <code>.strip()</code> one in load_maze rather than every call to <code>print-maze()</code>:</p>
<pre><code>def load_maze(filename):
"""
Returns maze string from text file
load_maze(str) -> list
"""
maze = []
with open(filename) as file:
for line in file:
maze.append(line.strip())
return maze
def print_maze(maze, position):
"""
Prints maze with position of the player
print_maze(str, (int, int)) -> None
"""
(x, y) = position
for row, line in enumerate(maze):
if row == y:
print(line[:x] + 'A' + line[x + 1:])
else:
print(line)
maze = load_maze('maze1.txt')
print_maze(maze, (1, 1))
</code></pre>
| 0 | 2016-08-24T07:21:55Z | [
"python",
"string",
"object-slicing"
] |
Tensorflow TypeError: Fetch argument None has invalid type <type 'NoneType'>? | 39,114,832 | <p>I'm making a RNN loosely based off of tensorflow's <a href="https://www.tensorflow.org/versions/r0.10/tutorials/recurrent/index.html" rel="nofollow" title="tutorial">tutorial</a>. With the relevant parts of my model as follows ("Comment if you need to see more, I don't want to make this post too long xD):</p>
<pre><code>input_sequence = tf.placeholder(tf.float32, [BATCH_SIZE, TIME_STEPS, PIXEL_COUNT + AUX_INPUTS])
output_actual = tf.placeholder(tf.float32, [BATCH_SIZE, OUTPUT_SIZE])
lstm_cell = tf.nn.rnn_cell.BasicLSTMCell(CELL_SIZE, state_is_tuple=False)
stacked_lstm = tf.nn.rnn_cell.MultiRNNCell([lstm_cell] * CELL_LAYERS, state_is_tuple=False)
initial_state = state = stacked_lstm.zero_state(BATCH_SIZE, tf.float32)
outputs = []
with tf.variable_scope("LSTM"):
for step in xrange(TIME_STEPS):
if step > 0:
tf.get_variable_scope().reuse_variables()
cell_output, state = stacked_lstm(input_sequence[:, step, :], state)
outputs.append(cell_output)
final_state = state
</code></pre>
<p>and the feeding:</p>
<pre><code>cross_entropy = tf.reduce_mean(-tf.reduce_sum(output_actual * tf.log(prediction), reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(output_actual, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
numpy_state = initial_state.eval()
for i in xrange(1, ITERATIONS):
batch = DI.next_batch()
print i, type(batch[0]), np.array(batch[1]).shape, numpy_state.shape
if i % LOG_STEP == 0:
train_accuracy = accuracy.eval(feed_dict={
initial_state: numpy_state,
input_sequence: batch[0],
output_actual: batch[1]
})
print "Iteration " + str(i) + " Training Accuracy " + str(train_accuracy)
numpy_state, train_step = sess.run([final_state, train_step], feed_dict={
initial_state: numpy_state,
input_sequence: batch[0],
output_actual: batch[1]
})
</code></pre>
<p>And when I run this, I get the following error: </p>
<pre><code>Traceback (most recent call last):
File "/home/agupta/Documents/Projects/Image-Recognition-with-LSTM/RNN/feature_tracking/model.py", line 109, in <module>
output_actual: batch[1]
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 698, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 838, in _run
fetch_handler = _FetchHandler(self._graph, fetches)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 355, in __init__
self._fetch_mapper = _FetchMapper.for_fetch(fetches)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 181, in for_fetch
return _ListFetchMapper(fetch)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 288, in __init__
self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 178, in for_fetch
(fetch, type(fetch)))
TypeError: Fetch argument None has invalid type <type 'NoneType'>
</code></pre>
<p>Perhaps the weirdest part is that this error gets thrown the <strong>second</strong> iteration, and the first works completely fine. I'm ripping my hair trying to fix this, so any help would be greatly appreciated.</p>
| 0 | 2016-08-24T05:07:54Z | 39,115,010 | <p>You are re-assigning the <code>train_step</code> variable to the second element of the result of <code>sess.run()</code> (which happens to be <code>None</code>). Hence, on the second iteration, <code>train_step</code> is <code>None</code>, which leads to the error.</p>
<p>The fix is fortunately simple:</p>
<pre><code>for i in xrange(1, ITERATIONS):
# ...
# Discard the second element of the result.
numpy_state, _ = sess.run([final_state, train_step], feed_dict={
initial_state: numpy_state,
input_sequence: batch[0],
output_actual: batch[1]
})
</code></pre>
| 1 | 2016-08-24T05:23:06Z | [
"python",
"artificial-intelligence",
"tensorflow",
"typeerror",
"recurrent-neural-network"
] |
Dictionary comprehension to calculate statistics across dict of dicts for each key in inner dicts | 39,114,871 | <p>I have a dictionary like this:</p>
<pre><code>property2region2value = {
'countryA':{
'a': 24,
'b': 56,
'c': 78
},
'countryB':{
'a': 3,
'b': 98
},
'countryC':{
'a': 121,
'b': 12121,
'c': 12989121,
'd':16171
},
'countryD':{
'a': 123,
'b': 1312,
'c': 1231
},
'countryE':{
'a': 1011,
'b': 1911
},
'countryF'{
'a': 1433,
'b': 19829,
'c': 1132,
'd':1791
}
}
</code></pre>
<p>And I am trying to create multiple dictionaries that each contains certain statistics about the master dictionary (min, max, std etc) about all the values for that property (<code>a','b','c</code> etc) across all the countries (e.g. <code>countryA, countryB</code>) etc.</p>
<p>So for example: <code>{'a': min of 'a' across all countries, 'b': min of 'b' across all countries....}</code> might be one dictionary.</p>
<p>At the moment, I do a huge loop of code which a) isn't efficient and b) doesn't allow me to quickly calculate statistics e.g. using <code>np.min()</code> or <code>np.max()</code> as functions in numpy.</p>
<p>How can I use dictionary comprehension to achieve this? Current code for calculating <code>min</code> and <code>max</code>:</p>
<pre><code>for country, property2value in property2region2value.items():
for property,value in property2value.items():
if property not in property2rangeMax:
property2rangeMax[property] = 0
if property2rangeMax[property]<value:
property2rangeMax[property]=value
if property not in property2rangeMin:
property2rangeMin[property] = 0
if property2rangeMin[property]>value:
property2rangeMin[property] = value
</code></pre>
| 1 | 2016-08-24T05:11:26Z | 39,115,014 | <p>You should use <code>pandas</code> for this task:</p>
<h2>Edit</h2>
<p>Pandas can help you accomplish what you want:</p>
<pre><code>In [3]: pd.DataFrame(property2region2value)
Out[3]:
countryA countryB countryC countryD countryE countryF
a 24.0 3.0 121 123.0 1011.0 1433
b 56.0 98.0 12121 1312.0 1911.0 19829
c 78.0 NaN 12989121 1231.0 NaN 1132
d NaN NaN 16171 NaN NaN 1791
In [4]: df.apply(np.min, axis=1)
Out[4]:
a 3.0
b 56.0
c 78.0
d 1791.0
dtype: float64
In [5]: df.apply(np.mean, axis=1)
Out[5]:
a 4.525000e+02
b 5.887833e+03
c 3.247890e+06
d 8.981000e+03
dtype: float64
In [6]: mean_dict = df.apply(np.mean, axis=1).to_dict()
In [7]: mean_dict
Out[7]: {'a': 452.5, 'b': 5887.833333333333, 'c': 3247890.5, 'd': 8981.0}
</code></pre>
<p>Or, even more easily, you can transpose the DataFrame:</p>
<pre><code>In [20]: df.T
Out[20]:
a b c d
countryA 24.0 56.0 78.0 NaN
countryB 3.0 98.0 NaN NaN
countryC 121.0 12121.0 12989121.0 16171.0
countryD 123.0 1312.0 1231.0 NaN
countryE 1011.0 1911.0 NaN NaN
countryF 1433.0 19829.0 1132.0 1791.0
In [21]: df.T.describe()
Out[21]:
a b c d
count 6.000000 6.000000 4.000000e+00 2.000000
mean 452.500000 5887.833333 3.247890e+06 8981.000000
std 612.768717 8215.770187 6.494154e+06 10168.195513
min 3.000000 56.000000 7.800000e+01 1791.000000
25% 48.250000 401.500000 8.685000e+02 5386.000000
50% 122.000000 1611.500000 1.181500e+03 8981.000000
75% 789.000000 9568.500000 3.248204e+06 12576.000000
max 1433.000000 19829.000000 1.298912e+07 16171.000000
In [22]: df.T.describe().to_dict()
Out[22]:
{'a': {'25%': 48.25,
'50%': 122.0,
'75%': 789.0,
'count': 6.0,
'max': 1433.0,
'mean': 452.5,
'min': 3.0,
'std': 612.76871656441472},
'b': {'25%': 401.5,
'50%': 1611.5,
'75%': 9568.5,
'count': 6.0,
'max': 19829.0,
'mean': 5887.833333333333,
'min': 56.0,
'std': 8215.770187065038},
'c': {'25%': 868.5,
'50%': 1181.5,
'75%': 3248203.5,
'count': 4.0,
'max': 12989121.0,
'mean': 3247890.5,
'min': 78.0,
'std': 6494153.687626767},
'd': {'25%': 5386.0,
'50%': 8981.0,
'75%': 12576.0,
'count': 2.0,
'max': 16171.0,
'mean': 8981.0,
'min': 1791.0,
'std': 10168.195513462553}}
</code></pre>
<p>And if you want finer control, you can pick and choose:</p>
<pre><code>In [24]: df.T.describe().loc[['mean','std','min','max'],:]
Out[24]:
a b c d
mean 452.500000 5887.833333 3.247890e+06 8981.000000
std 612.768717 8215.770187 6.494154e+06 10168.195513
min 3.000000 56.000000 7.800000e+01 1791.000000
max 1433.000000 19829.000000 1.298912e+07 16171.000000
In [25]: df.T.describe().loc[['mean','std','min','max'],:].to_dict()
Out[25]:
{'a': {'max': 1433.0,
'mean': 452.5,
'min': 3.0,
'std': 612.76871656441472},
'b': {'max': 19829.0,
'mean': 5887.833333333333,
'min': 56.0,
'std': 8215.770187065038},
'c': {'max': 12989121.0,
'mean': 3247890.5,
'min': 78.0,
'std': 6494153.687626767},
'd': {'max': 16171.0,
'mean': 8981.0,
'min': 1791.0,
'std': 10168.195513462553}}
</code></pre>
<h2>From Original Answer</h2>
<p>Then you can very easily achieve whatever you want:</p>
<pre><code>In [8]: df.apply(np.min)
Out[8]:
countryA 24.0
countryB 3.0
countryC 121.0
countryD 123.0
countryE 1011.0
countryF 1132.0
dtype: float64
In [9]: df.apply(np.max)
Out[9]:
countryA 78.0
countryB 98.0
countryC 12989121.0
countryD 1312.0
countryE 1911.0
countryF 19829.0
dtype: float64
In [10]: df.apply(np.std)
Out[10]:
countryA 2.217105e+01
countryB 4.750000e+01
countryC 5.620356e+06
countryD 5.424170e+02
countryE 4.500000e+02
countryF 7.960893e+03
dtype: float64
</code></pre>
<p>You can even bring everything back to dictionaries with ease:</p>
<pre><code>In [11]: df.apply(np.min).to_dict()
Out[11]:
{'countryA': 24.0,
'countryB': 3.0,
'countryC': 121.0,
'countryD': 123.0,
'countryE': 1011.0,
'countryF': 1132.0}
</code></pre>
<p>Go nuts! All your data-processing needs will be easier:</p>
<pre><code>In [12]: df.describe()
Out[12]:
countryA countryB countryC countryD countryE \
count 3.000000 2.000000 4.000000e+00 3.000000 2.000000
mean 52.666667 50.500000 3.254384e+06 888.666667 1461.000000
std 27.153882 67.175144 6.489829e+06 664.322462 636.396103
min 24.000000 3.000000 1.210000e+02 123.000000 1011.000000
25% 40.000000 26.750000 9.121000e+03 677.000000 1236.000000
50% 56.000000 50.500000 1.414600e+04 1231.000000 1461.000000
75% 67.000000 74.250000 3.259408e+06 1271.500000 1686.000000
max 78.000000 98.000000 1.298912e+07 1312.000000 1911.000000
countryF
count 4.000000
mean 6046.250000
std 9192.447602
min 1132.000000
25% 1357.750000
50% 1612.000000
75% 6300.500000
max 19829.000000
</code></pre>
| 2 | 2016-08-24T05:23:17Z | [
"python",
"loops",
"numpy",
"dictionary",
"dictionary-comprehension"
] |
Dictionary comprehension to calculate statistics across dict of dicts for each key in inner dicts | 39,114,871 | <p>I have a dictionary like this:</p>
<pre><code>property2region2value = {
'countryA':{
'a': 24,
'b': 56,
'c': 78
},
'countryB':{
'a': 3,
'b': 98
},
'countryC':{
'a': 121,
'b': 12121,
'c': 12989121,
'd':16171
},
'countryD':{
'a': 123,
'b': 1312,
'c': 1231
},
'countryE':{
'a': 1011,
'b': 1911
},
'countryF'{
'a': 1433,
'b': 19829,
'c': 1132,
'd':1791
}
}
</code></pre>
<p>And I am trying to create multiple dictionaries that each contains certain statistics about the master dictionary (min, max, std etc) about all the values for that property (<code>a','b','c</code> etc) across all the countries (e.g. <code>countryA, countryB</code>) etc.</p>
<p>So for example: <code>{'a': min of 'a' across all countries, 'b': min of 'b' across all countries....}</code> might be one dictionary.</p>
<p>At the moment, I do a huge loop of code which a) isn't efficient and b) doesn't allow me to quickly calculate statistics e.g. using <code>np.min()</code> or <code>np.max()</code> as functions in numpy.</p>
<p>How can I use dictionary comprehension to achieve this? Current code for calculating <code>min</code> and <code>max</code>:</p>
<pre><code>for country, property2value in property2region2value.items():
for property,value in property2value.items():
if property not in property2rangeMax:
property2rangeMax[property] = 0
if property2rangeMax[property]<value:
property2rangeMax[property]=value
if property not in property2rangeMin:
property2rangeMin[property] = 0
if property2rangeMin[property]>value:
property2rangeMin[property] = value
</code></pre>
| 1 | 2016-08-24T05:11:26Z | 39,115,120 | <p>Undoubtedly, <code>pandas</code> is a good choice for this task, while, in a plain python way, you can simply collect all values for each <strong>property</strong> in one loop.</p>
<pre><code>from collections import defaultdict
xs = defaultdict(list)
for _, vs in property2region2value.items():
for k, v in vs.items():
xs[k].append(v)
# xs: defaultdict(<type 'list'>, {'a': [3, 121, 24, 1433, 123, 1011], 'c': [12989121, 78, 1132, 1231], 'b': [98, 12121, 56, 19829, 1312, 1911], 'd': [16171, 1791]})
</code></pre>
<p>Then you can apply statics on each item.</p>
| 2 | 2016-08-24T05:32:38Z | [
"python",
"loops",
"numpy",
"dictionary",
"dictionary-comprehension"
] |
How to put pickle dict value into an object | 39,114,897 | <p>I am using pickle to dump a dictionary object into a txt file. I need to grab the dictionary from the file and extract only certain values and put them inside of an object as a string.</p>
<p>My dictionary looks something like this:</p>
<pre><code>obj_dict = { 'name': 'MYID', 'value': 'usdf23444',
'name': 'MYID2', 'value' : 'asdfh3479' }
</code></pre>
<p>Part of the dilemma I have is that there are two <code>'name'</code> and two <code>'value'</code> in the dictionary and I need to grab each separately.</p>
<p>Here is the code I am using:</p>
<pre><code>import pickle
filepath = file.txt
output = open(filepath, 'rb')
obj_dict = pickle.load(output)
for i in obj_dict:
NewString = "VALUE1=" + i['value1'] + "VALUE2=" + i['value2']
print(NewString)
</code></pre>
<p>I know this code doesn't work, I'm more showing what I need my end result to look like but basically I need each value to be put into a string that I can use later. How can I reference <code>'value1'</code> and <code>'value2</code>' correctly? Also I am getting this error when trying to just get one 'value':
<code>TypeError: list indices must be integers or slices, not str</code></p>
<p><strong>EDIT FOR COMMENT 2</strong></p>
<p>I'm not sure if that's true, I can run this code:</p>
<pre><code>output = open(filepath, 'rb')
obj_dict = pickle.load(output)
for i in obj_dict:
print(i['value'])
</code></pre>
<p>and my output is:</p>
<pre><code>usdf23444
asdfh3479
</code></pre>
| 0 | 2016-08-24T05:13:58Z | 39,115,121 | <p>After the update, it looks like it is a list of dicts. Try:</p>
<pre><code>strings = ["VALUE{}={}".format(i, d['value']) for i, d in enumerate(obj_dict)]
</code></pre>
| 1 | 2016-08-24T05:32:46Z | [
"python",
"dictionary",
"pickle"
] |
train logistic regression model with different feature dimension in scikit learn | 39,114,952 | <p>Using Python 2.7 on Windows. Want to fit a logistic regression model using feature <code>T1</code> and <code>T2</code> for a classification problem, and target is <code>T3</code>.</p>
<p>I show the values of <code>T1</code> and <code>T2</code>, as well as my code. The question is, since <code>T1</code> has dimension 5, and <code>T2</code> has dimension 1, how should we pre-process them so that it could be leveraged by scikit-learn logistic regression training correctly?</p>
<p>BTW, I mean for training sample 1, its feature of <code>T1</code> is <code>[ 0 -1 -2 -3]</code>, and feature of <code>T2</code> is <code>[0]</code>, for training sample 2, its feature of T1 is <code>[ 1 0 -1 -2]</code> and feature of <code>T2</code> is <code>[1]</code>, ...</p>
<pre><code>import numpy as np
from sklearn import linear_model, datasets
arc = lambda r,c: r-c
T1 = np.array([[arc(r,c) for c in xrange(4)] for r in xrange(5)])
print T1
print type(T1)
T2 = np.array([[arc(r,c) for c in xrange(1)] for r in xrange(5)])
print T2
print type(T2)
T3 = np.array([0,0,1,1,1])
logreg = linear_model.LogisticRegression(C=1e5)
# we create an instance of Neighbours Classifier and fit the data.
# using T1 and T2 as features, and T3 as target
logreg.fit(T1+T2, T3)
</code></pre>
<p>T1,</p>
<pre><code>[[ 0 -1 -2 -3]
[ 1 0 -1 -2]
[ 2 1 0 -1]
[ 3 2 1 0]
[ 4 3 2 1]]
</code></pre>
<p>T2,</p>
<pre><code>[[0]
[1]
[2]
[3]
[4]]
</code></pre>
| 0 | 2016-08-24T05:18:12Z | 39,115,738 | <p>It needs to concatenate the feature data matrices using numpy.concatenate.</p>
<pre><code>import numpy as np
from sklearn import linear_model, datasets
arc = lambda r,c: r-c
T1 = np.array([[arc(r,c) for c in xrange(4)] for r in xrange(5)])
T2 = np.array([[arc(r,c) for c in xrange(1)] for r in xrange(5)])
T3 = np.array([0,0,1,1,1])
X = np.concatenate((T1,T2), axis=1)
Y = T3
logreg = linear_model.LogisticRegression(C=1e5)
# we create an instance of Neighbours Classifier and fit the data.
# using T1 and T2 as features, and T3 as target
logreg.fit(X, Y)
X_test = np.array([[1, 0, -1, -1, 1],
[0, 1, 2, 3, 4,]])
print logreg.predict(X_test)
</code></pre>
| 1 | 2016-08-24T06:19:19Z | [
"python",
"python-2.7",
"machine-learning",
"scikit-learn",
"logistic-regression"
] |
Export button is not visible with django-import-export package | 39,114,969 | <p>I am trying to use django-import-export module in my admin and here are my settings</p>
<p><strong>admin.py</strong></p>
<pre><code>from import_export.admin import ImportExportMixin, ImportMixin, ExportActionModelAdmin, ImportExportActionModelAdmin
class RegistrationAdmin(ImportExportActionModelAdmin):
list_display = ('user', 'activation_key_expired')
raw_id_fields = ['user']
search_fields = ('user__username', 'user__first_name', 'user__last_name')
admin.site.register(RegistrationProfile, RegistrationAdmin)
</code></pre>
<p>With the above code, i can able to see an <em><code>Import</code></em> button in admin as below</p>
<p><a href="http://i.stack.imgur.com/nDGFr.png" rel="nofollow"><img src="http://i.stack.imgur.com/nDGFr.png" alt="enter image description here"></a></p>
<p>But i can't able to see Export option, so what's the problem what am i missing here ?</p>
<p>I have seen some ticket about export button permission here
<a href="https://github.com/django-import-export/django-import-export/issues/38" rel="nofollow">https://github.com/django-import-export/django-import-export/issues/38</a> ? can anyone please let me know what need to be done in order for <em><code>Export</code></em> to appear ?</p>
<p>By the way i am using <em><code>django suit</code></em> as my admin theme</p>
| 0 | 2016-08-24T05:19:32Z | 39,116,457 | <p>You need to use <a href="https://django-import-export.readthedocs.io/en/latest/api_admin.html#import_export.admin.ImportExportModelAdmin" rel="nofollow"><code>ImportExportModelAdmin</code></a></p>
<p><a href="https://django-import-export.readthedocs.io/en/latest/api_admin.html#import_export.admin.ImportExportActionModelAdmin" rel="nofollow"><code>ImportExportActionModelAdmin</code></a> only adds the export to the list of things you can do to selected items (see the dropdown in your screenshot)</p>
<p>Docs for <code>ImportExportActionModelAdmin</code> state</p>
<blockquote>
<p>Export functionality is implemented as an admin action.</p>
</blockquote>
| 0 | 2016-08-24T07:00:44Z | [
"python",
"django",
"django-admin",
"django-import-export"
] |
Find and Edit Text File | 39,114,980 | <p>I'm looking to find if there is a way of automating this process. Basically I have 300,000 rows of data needed to download on a daily basis. There are a couple of rows that need to be edited before it can be uploaded to SQL.</p>
<pre class="lang-none prettyprint-override"><code>Jordan || Michael | 23 | Bulls | Chicago
Bryant | Kobe ||| 8 || LA
</code></pre>
<p>What I want to accomplish is to just have 4 vertical bars per row. Normally, I would search for a keyword then edit it manually then save. These two are the only anomalies in my data.</p>
<ol>
<li>Find "Jordan", then remove the excess 1 vertical bar "|" right after it.</li>
<li>I need to find "Kobe", then remove the two excess vertical bars "|" right after it.</li>
</ol>
<p>Correct format is below -</p>
<pre class="lang-none prettyprint-override"><code>Jordan | Michael | 23 | Bulls | Chicago
Bryant | Kobe | 8 || LA
</code></pre>
<p>Not sure if this can be done in vbscript or Python.
Any help would be appreciated. Thanks!</p>
| 2 | 2016-08-24T05:20:39Z | 39,115,224 | <p>Python or vbscript could be used but they are overkill for something this simple. Try <code>sed</code>:</p>
<pre><code>$ sed -E 's/(Jordan *)\|/\1/g; s/(Kobe *)\| *\|/\1/g' file
Jordan | Michael | 23 | Bulls | Chicago
Bryant | Kobe | 8 || LA
</code></pre>
<p>To save to a new file:</p>
<pre><code>sed -E 's/(Jordan *)\|/\1/g; s/(Kobe *)\| *\|/\1/g' file >newfile
</code></pre>
<p>Or, to change the existing file in-place:</p>
<pre><code>sed -Ei.bak 's/(Jordan *)\|/\1/g; s/(Kobe *)\| *\|/\1/g' file
</code></pre>
<h3>How it works</h3>
<p>sed reads and processes a file line by line. In our case, we need only the substitute command which has the form <code>s/old/new/g</code> where <code>old</code> is a regular expression and, if it is found, it is replaced by <code>new</code>. The optional <code>g</code> at the end of the command tells sed to perform the substitution command 'globally', meaning not just once but as many times as it appears on the line.</p>
<ul>
<li><p><code>s/(Jordan *)\|/\1/g</code></p>
<p>This tells sed to look for Jordan followed by zero or more spaces followed by a vertical bar and remove the vertical bar.</p>
<p>In more detail, the parens in <code>(Jordan *)</code> tell sed to save the string Jordan followed by zero or more spaces as a group. In the replacement side, we reference that group as <code>\1</code>.</p></li>
<li><p><code>s/(Kobe *)\| *\|/\1/g</code></p>
<p>Similarly, this tells sed to look for Kobe followed by zero or more spaces followed by a vertical bar and remove the vertical bar.</p></li>
</ul>
<h2>Using python</h2>
<p>Using the same logic as above, here is a python program:</p>
<pre><code>$ cat kobe.py
import re
with open('file') as f:
for line in f:
line = re.sub(r'(Jordan *)\|', r'\1', line)
line = re.sub(r'(Kobe *)\| *\|', r'\1', line)
print(line.rstrip('\n'))
$ python kobe.py
Jordan | Michael | 23 | Bulls | Chicago
Bryant | Kobe | 8 || LA
</code></pre>
<p>To save that to a new file:</p>
<pre><code>python kobe.py >newfile
</code></pre>
| 2 | 2016-08-24T05:41:23Z | [
"python",
"replace",
"vbscript",
"automation",
"find"
] |
Find and Edit Text File | 39,114,980 | <p>I'm looking to find if there is a way of automating this process. Basically I have 300,000 rows of data needed to download on a daily basis. There are a couple of rows that need to be edited before it can be uploaded to SQL.</p>
<pre class="lang-none prettyprint-override"><code>Jordan || Michael | 23 | Bulls | Chicago
Bryant | Kobe ||| 8 || LA
</code></pre>
<p>What I want to accomplish is to just have 4 vertical bars per row. Normally, I would search for a keyword then edit it manually then save. These two are the only anomalies in my data.</p>
<ol>
<li>Find "Jordan", then remove the excess 1 vertical bar "|" right after it.</li>
<li>I need to find "Kobe", then remove the two excess vertical bars "|" right after it.</li>
</ol>
<p>Correct format is below -</p>
<pre class="lang-none prettyprint-override"><code>Jordan | Michael | 23 | Bulls | Chicago
Bryant | Kobe | 8 || LA
</code></pre>
<p>Not sure if this can be done in vbscript or Python.
Any help would be appreciated. Thanks!</p>
| 2 | 2016-08-24T05:20:39Z | 39,115,460 | <p>I wrote a code snippet in Python 3.5 as follows.</p>
<pre><code># -*- coding: utf-8 -*-
rows = ["Jordan||Michael|23|Bulls|Chicago",
"Bryant|Kobe|||8||LA"]
keywords = ["Jordan", "Kobe"]
def get_keyword(row, keywords):
for word in keywords:
if word in row:
return word
else:
return None
for line in rows:
num_bars = line.count('|')
num_bars_del = num_bars - 4 # Number of bars to be deleted
kw = get_keyword(line, keywords)
if kw: # this line contains a keyword
# Split the line by the keyword
first, second = line.split(kw)
second = second.lstrip()
result = "%s%s%s"%(first, kw, second[num_bars_del:])
print(result)
</code></pre>
| 1 | 2016-08-24T06:00:00Z | [
"python",
"replace",
"vbscript",
"automation",
"find"
] |
How to install module from another python installation | 39,115,001 | <p>I am using winpython. Now for simple distribution, I want to use winpython zero.
Is it possible to install the package from winpython folder to winpython zero folder?</p>
| 0 | 2016-08-24T05:22:13Z | 39,115,859 | <p>One of the simplest ways is just copying the <code>site-package</code> directory in the original winpython to the new one (It is assumed that the versions of two winpythons are the same, saying python 3.5).</p>
<p>If you thinks the above way is silly, then you can use <code>pip</code> instead.</p>
<ol>
<li><p>Extract the installed packages from original winpython
(pip used below should belong to the <strong>original</strong> winpython) </p>
<p>pip freeze --all > python_packages.txt</p></li>
<li><p>Install the extracted package list with pip.
(pip used below should belong to the <strong>new</strong> winpython)</p>
<p>pip install -r python_packages.txt</p></li>
</ol>
| 1 | 2016-08-24T06:25:56Z | [
"python"
] |
How to install module from another python installation | 39,115,001 | <p>I am using winpython. Now for simple distribution, I want to use winpython zero.
Is it possible to install the package from winpython folder to winpython zero folder?</p>
| 0 | 2016-08-24T05:22:13Z | 39,128,838 | <p>In theory, a possible way would be to:</p>
<ul>
<li><p>download packages from <a href="https://sourceforge.net/projects/winpython/files/WinPython_Source/Do_It_Yourself/Winpython_2016-03/" rel="nofollow">https://sourceforge.net/projects/winpython/files/WinPython_Source/Do_It_Yourself/Winpython_2016-03/</a></p></li>
<li><p>unzip them all in d:\toto</p></li>
<li><p>then do </p></li>
</ul>
<p>pip install the_package_i_want --no-index --find-links=d:\toto --trusted-host=None</p>
| 1 | 2016-08-24T16:42:25Z | [
"python"
] |
How to resample a Numpy array of arbitrary dimensions? | 39,115,166 | <p>There is <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html" rel="nofollow"><code>scipy.misc.imresize</code></a> for resampling the first two dimensions of 3D arrays. It also supports bilinear interpolation. However, there does not seem to be an existing function for resizing all dimensions of arrays with any number of dimensions. How can I resample any array given a new shape of the same rank, using multi-linear interpolation?</p>
| 1 | 2016-08-24T05:36:13Z | 39,116,147 | <p>You want <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.zoom.html#scipy.ndimage.zoom" rel="nofollow"><code>scipy.ndimage.zoom</code></a>, which can be used as follows:</p>
<pre><code>>>> x = np.arange(8, dtype=np.float_).reshape(2, 2, 2)
>>> scipy.ndimage.zoom(x, 1.5, order=1)
array([[[ 0. , 0.5, 1. ],
[ 1. , 1.5, 2. ],
[ 2. , 2.5, 3. ]],
[[ 2. , 2.5, 3. ],
[ 3. , 3.5, 4. ],
[ 4. , 4.5, 5. ]],
[[ 4. , 4.5, 5. ],
[ 5. , 5.5, 6. ],
[ 6. , 6.5, 7. ]]])
</code></pre>
<p>Note that this function always preserves the boundaries of the image, essentially resampling a mesh with a node at each pixel center. You might want to look at other functions in <code>scipy.ndimage</code> if you need more control over exactly where the resampling occurs</p>
| 2 | 2016-08-24T06:43:58Z | [
"python",
"numpy",
"multidimensional-array",
"image-resizing",
"linear-interpolation"
] |
Getting an error as var5 is undefined ? but it runs fine without class | 39,115,227 | <pre><code>class roger:
root1 = Tk()
frame1 = Frame(root1, width=100, height=100)
frame1.pack(side=TOP)
label5 = Label(frame1, text="x1=")
label6 = Label(frame1, text="x2=")
label7 = Label(frame1, text="x3=")
label8 = Label(frame1, text="x4=")
label5.grid(row=0)
label6.grid(row=1)
label7.grid(row=2)
label8.grid(row=3)
var5 = StringVar()
var6 = StringVar()
var7 = StringVar()
var8 = StringVar()
textbox1 = Entry(frame1, textvariable=var5, bd=10, width=10, font=30)
textbox1.grid(row=0, column=1)
textbox2 = Entry(frame1, textvariable=var6, bd=10, width=10, font=30)
textbox2.grid(row=1, column=1)
textbox3 = Entry(frame1, textvariable=var7, bd=10, width=10, font=30)
textbox3.grid(row=2, column=1)
textbox4 = Entry(frame1, textvariable=var8, bd=10, width=10, font=30)
textbox4.grid(row=3, column=1)
hoo = Entry(frame1, width=20, bd=10)
hoo.grid(row=5, column=0)
def inverse():
a = ([float(var5.get()), float(var6.get())], [float(var7.get()), float(var8.get())])
ans = inv(a)
hoo.insert(0, ans)
def eigen():
a = ([float(var5.get()), float(var6.get())], [float(var7.get()), float(var8.get())])
ans = eig(a)
hoo.insert(0, ans)
k = Button(frame1, text="inverse", command=inverse)
k.grid(row=4, column=0)
l = Button(frame1, text="eigen value ", command=eigen)
l.grid(row=4, column=1)
root1.mainloop()
</code></pre>
| 0 | 2016-08-24T05:41:32Z | 39,115,669 | <p>Use <code>roger.var5</code> instead of <code>var5</code>, since you have defined it as class's static property. Similarly do for other variables.</p>
| 0 | 2016-08-24T06:14:51Z | [
"python",
"tkinter"
] |
Event when entry's xview changes | 39,115,234 | <p>I am creating a simple program using <code>Tkinter</code>. I want a function to be called every time <code>xview</code> property of <code>entry</code> changes. But there doesn't seem to be an event like this, at least not one that I can find.</p>
<p>The <code><Configure></code> event fires only on resize, which I already handled, but it doesn't fire when actual value I'm tracking changes in a different way, such as the user dragging his mouse to see the end of the entry.</p>
<p>Here is the code:</p>
<pre><code>import Tkinter as Tk
import tkFileDialog
root = Tk.Tk()
class RepositoryFolderFrame(Tk.Frame):
def __init__(self, root):
Tk.Frame.__init__(self, root)
self.build_gui()
self.set_entry_text("Searching...")
#root.after(0, self.find_repo)
self.prev_entry_index = len(self.entry.get())
root.bind("<Configure>", self.on_entry_resize)
#self.entry.bind(???, self.on_entry_change)
#self.entry.bind("<Configure>", self.on_entry_change)
def on_entry_resize(self, event):
cur_entry_index = self.entry.xview()[1]
if cur_entry_index != self.prev_entry_index:
self.entry.xview(self.prev_entry_index)
def on_entry_change(self, event):
# This should be called when xview changes...
cur_entry_index = self.entry.xview()[1]
self.prev_entry_index = cur_entry_index
def set_entry_text(self, text):
self.entry_text.set(text)
self.entry.xview("end")
def build_gui(self):
label = Tk.Label(self, text = "Repository folder:")
label.pack(side = Tk.LEFT)
self.label = label
entry_text = Tk.StringVar()
self.entry_text = entry_text
entry = Tk.Entry(self, width = 50, textvariable = entry_text)
entry.configure(state = 'readonly')
entry.pack(side = Tk.LEFT, fill = Tk.X, expand = 1)
self.entry = entry
button = Tk.Button(self, text = "Browse...")
button.pack(side = Tk.LEFT)
self.button = button
repo_frame = RepositoryFolderFrame(root)
repo_frame.pack(fill = Tk.X, expand = 1)
root.mainloop()
</code></pre>
| 1 | 2016-08-24T05:42:27Z | 39,123,953 | <p>There is no mechanism for getting notified when the xview changes. There are ways to do it by modifying the underlying tcl code, but it's much more difficult than it's worth.</p>
<p>A simple solution is to write a function that polls the xview every few hundred milliseconds. It can keep track of the most recent xview, compare it to the current, and if it has changed it can fire off a custom event (eg: <code><<XviewChanged>></code>) which you can bind to.</p>
<p>It would look something like this:</p>
<pre><code>class RepositoryFolderFrame(Tk.Frame):
def __init__(self, root):
...
self.entry.bind("<<XviewChanged>>", self.on_entry_change)
# keep a cache of previous xviews. A dictionary is
# used in case you want to do this for more than
self._xview = {}
self.watch_xview(self.entry)
def watch_xview(self, widget):
xview = widget.xview()
prev_xview = self._xview.get(widget, "")
self._xview[widget] = xview
if xview != prev_xview:
widget.event_generate("<<XviewChanged>>")
widget.after(100, self.watch_xview, widget)
</code></pre>
<p>You'll need to modify that for the edge case that the entry widget is destroyed, though you can handle that with a simple <code>try</code> around the code. This should be suitably performant, though you might need to verify that if you have literally hundreds of entry widgets. </p>
| 1 | 2016-08-24T12:55:50Z | [
"python",
"tkinter"
] |
Python Code to create Google Project | 39,115,311 | <p>Is it possible to create a new Google Developer/Cloud project(for an existing Google Account) automatically using a python script ? </p>
<p>If its possible, Can someone please redirect me to some helpful links/references ?</p>
<p>Thanks,</p>
| 1 | 2016-08-24T05:48:24Z | 39,128,497 | <p>Is it possible?: Yes, using <a href="https://cloud.google.com/appengine/docs/admin-api" rel="nofollow">App Engine's Admin API</a> or the <a href="https://cloud.google.com/resource-manager/docs/apis" rel="nofollow">Cloud Resource Manager APIs</a> with although this functionality is currently in beta as of the time of writing this (08-24-2016). You can access them directly or through a client library.</p>
<hr>
<p>Directly Via REST API:</p>
<ol>
<li><p><strong>App Engine Admin API v1beta5</strong>:</p>
<p><code>create POST /v1beta5/apps</code></p>
<blockquote>
<p>Creates an App Engine application for a Google Cloud Platform project.
This requires a project that excludes an App Engine application...</p>
</blockquote>
<p>More: <a href="https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta5/apps/create" rel="nofollow">https://cloud.google.com/appengine/docs/admin-api/reference/rest/v1beta5/apps/create</a></p></li>
<li><p><strong>Cloud Resource Manager API v1beta1</strong>:</p>
<p><code>POST https://cloudresourcemanager.googleapis.com/v1beta1/projects/</code></p>
<blockquote>
<p>Creates a Project resource.</p>
</blockquote>
<p>and example request:</p>
<pre><code>{
"name": "project name",
"projectId": "project-id-1",
"labels": {
"environment": "dev"
},
}
</code></pre>
<p>More here: <a href="https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/create" rel="nofollow">https://cloud.google.com/resource-manager/reference/rest/v1beta1/projects/create</a></p></li>
</ol>
<hr>
<p>Via a python client library:</p>
<ol>
<li><p>There's <strong>the <a href="https://github.com/google/google-api-python-client" rel="nofollow">Google Python Client Library</a></strong> </p>
<pre><code>pip install --upgrade google-api-python-client
</code></pre>
<p>Then you'll have to build an authenticated service to the api.
Every other thing you'll need for the request can be found in <a href="https://developers.google.com/resources/api-libraries/documentation/cloudresourcemanager/v1beta1/python/latest/cloudresourcemanager_v1beta1.projects.html#create" rel="nofollow">this doc</a> </p></li>
<li><p><strong><a href="https://github.com/GoogleCloudPlatform/gcloud-python#google-cloud-resource-manager" rel="nofollow">gcloud-python</a></strong>:</p>
<p><strong>Ideally</strong> though, and my personal favorite, you'll want to use this client library to build such a script</p>
<pre><code>pip install --upgrade gcloud
</code></pre>
<p>then you'll create the new project with:</p>
<pre><code>from gcloud import resource_manager
client = resource_manager.Client()
# re-doing above REST example
project = client.new_project('project-id-1', name='project name',
labels={'environment': 'dev'})
project.create()
</code></pre></li>
</ol>
| 3 | 2016-08-24T16:23:25Z | [
"python",
"python-2.7",
"google-app-engine",
"google-cloud-platform"
] |
Is there a way to access the properties of a class created in one function from another function? | 39,115,578 | <p>Is there a way to access the properties of a class created in one function from another function ?</p>
<pre><code>class Component(object):
Name = ''
Num = 100
def __setattr__(self, name, value):
object.__setattr__(self, name, value)
def one():
exec('AAA' + '=Component()')
AAA.Name = 'AAA'
AAA.Num = AAA.Num * 2
print '1', AAA.Name, AAA.Num
def two():
print '2', AAA.Name, AAA.Num
one()
two()
</code></pre>
<p>I get a "NameError: global name 'AAA' is not defined"</p>
| -3 | 2016-08-24T06:09:13Z | 39,115,776 | <p>Class level attributes belong to the class and are therefore shared among all instances of that class.</p>
<p>If you want different instances of the class to have different <code>name</code> and <code>num</code> attributes (by the way, you should be using lowercased attribute names for instances), you should add them as instance attributes. You can access the class attributes using the class name (e.g. <code>Component.NUM</code>).</p>
<pre><code>class Component(object):
NAME = ''
NUM = 100
def __init__(self, name, num):
self.name = name
self.num = num
print Component.NAME # ''
print Component.NUM # 100
c = Component('AAA', Component.NUM * 2)
print c.name # 'AAA'
print c.num # 200
</code></pre>
| 0 | 2016-08-24T06:21:18Z | [
"python",
"python-2.7",
"function",
"global"
] |
Is there a way to access the properties of a class created in one function from another function? | 39,115,578 | <p>Is there a way to access the properties of a class created in one function from another function ?</p>
<pre><code>class Component(object):
Name = ''
Num = 100
def __setattr__(self, name, value):
object.__setattr__(self, name, value)
def one():
exec('AAA' + '=Component()')
AAA.Name = 'AAA'
AAA.Num = AAA.Num * 2
print '1', AAA.Name, AAA.Num
def two():
print '2', AAA.Name, AAA.Num
one()
two()
</code></pre>
<p>I get a "NameError: global name 'AAA' is not defined"</p>
| -3 | 2016-08-24T06:09:13Z | 39,115,829 | <p><strong>One possible solution:</strong></p>
<p>Create a global list(tuple, dict or any proper data structure you want) and add the instance to the list in function one, then get the instance from the list in function two. </p>
<p>However, global variables are not recommended.</p>
| 0 | 2016-08-24T06:24:17Z | [
"python",
"python-2.7",
"function",
"global"
] |
Is there a way to access the properties of a class created in one function from another function? | 39,115,578 | <p>Is there a way to access the properties of a class created in one function from another function ?</p>
<pre><code>class Component(object):
Name = ''
Num = 100
def __setattr__(self, name, value):
object.__setattr__(self, name, value)
def one():
exec('AAA' + '=Component()')
AAA.Name = 'AAA'
AAA.Num = AAA.Num * 2
print '1', AAA.Name, AAA.Num
def two():
print '2', AAA.Name, AAA.Num
one()
two()
</code></pre>
<p>I get a "NameError: global name 'AAA' is not defined"</p>
| -3 | 2016-08-24T06:09:13Z | 39,116,023 | <p>Instantiate <code>class</code> outside the <code>function</code> and use that class instance with in the function. Below is the code:</p>
<pre><code>>>> class Component(object):
... Name = ''
... Num = 100
... def __setattr__(self, name, value):
... object.__setattr__(self, name, value)
...
>>> # Moved object creation to outside of func
... exec('AAA' + '=Component()')
>>>
>>> def one():
... AAA.Name = 'AAA'
... AAA.Num = AAA.Num * 2
... print '1', AAA.Name, AAA.Num
...
>>> def two():
... print '2', AAA.Name, AAA.Num
... AAA.Name = 'BBB'
... AAA.Num = AAA.Num * 2
... print '3', AAA.Name, AAA.Num
...
>>> one()
1 AAA 200
>>> two()
2 AAA 200
3 BBB 400
</code></pre>
| 0 | 2016-08-24T06:36:12Z | [
"python",
"python-2.7",
"function",
"global"
] |
pycharm debugger not working properly | 39,115,603 | <p>I am doing simple python coding in pycharm but the problem is whenever I debug it starts debugging some other file in my project and not the one I am working with.</p>
<p>I did go to run-->edit configuration and check if my file was set for debugging and it was but still it debugs another file when I start debugging.</p>
<p>any help will be appreciated </p>
| 0 | 2016-08-24T06:10:42Z | 39,115,848 | <p>If you debug using pressing <code>SHIFT-F9</code> it debugs the last file you debugged, which might be some file you debugged yesterday...</p>
<p>To debug a new file press <code>ALT-SHIF-F9</code>.</p>
<p>You can see these two different debugging options from the <code>Run</code> menu. There is <code>Debug <last file></code> and there is <code>Debug...</code></p>
| 0 | 2016-08-24T06:25:28Z | [
"python",
"debugging",
"pycharm"
] |
pycharm debugger not working properly | 39,115,603 | <p>I am doing simple python coding in pycharm but the problem is whenever I debug it starts debugging some other file in my project and not the one I am working with.</p>
<p>I did go to run-->edit configuration and check if my file was set for debugging and it was but still it debugs another file when I start debugging.</p>
<p>any help will be appreciated </p>
| 0 | 2016-08-24T06:10:42Z | 39,118,300 | <p>I think you can do it with Right clicking on body of codes and select your project name form there.
Also can select <code>Run</code> > <code>Debug</code> </p>
<p>you can debug it line by line from <a href="http://stackoverflow.com/questions/28687771/how-to-debug-in-pycharm">here</a></p>
| 0 | 2016-08-24T08:35:09Z | [
"python",
"debugging",
"pycharm"
] |
Django: Search Engine | 39,115,743 | <p>I am trying to make a search engine of sorts in Django, where the user enters a query via a form and gets an output if the query exists in the database. Here's my code:</p>
<p>urls.py:</p>
<pre><code>from django.conf.urls import url
from django.contrib import admin
from Search import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', views.form),
url(r'^search/', views.data,name='search'),
]
</code></pre>
<p>models.py:</p>
<pre><code>from __future__ import unicode_literals
from abc import ABCMeta
from django.db import models
# Create your models here.
class Album(models.Model):
artist = models.CharField(max_length=100)
album_title = models.CharField(max_length=100)
genre = models.CharField(max_length=100)
album_logo = models.CharField(max_length=100)
def __str__(self):
return self.album_title + "-" + self.artist
</code></pre>
<p>views.py:</p>
<pre><code>from django.http import HttpResponse,Http404
from models import Album
from forms import FormQuery
from django.shortcuts import render
from django.template import loader
from . import *
def data(request):
if request.method=='POST':
form=FormQuery(request.POST)
data=form.cleaned_data
value=data['query']
if form.is_valid():
try:
album1 = Album.objects.get(artist__contains=value)
return render(request,'Search/form.html',{'album':album1})
except:
raise Http404("Does not exist.")
else:
return render(request,'Search/form.html')
</code></pre>
<p>forms.py:</p>
<pre><code>from django import forms
class FormQuery(forms.Form):
query=forms.CharField()
</code></pre>
<p>form.html:</p>
<pre><code><form action="{% url 'search' %}" method="POST">{% csrf_token %}
<fieldset>
Enter an album:<br>
<input type="text" name="query" ><br>
<input type="submit" value="Submit for Search >>">
</fieldset>
</form>
{% if album %}
<h1>{{ album }}</h1>
{% endif %}
</code></pre>
<p>However, when I type the query, I see the url change ,but the page remains the same and my result(album name) is not displayed. I am new to Django.</p>
| 0 | 2016-08-24T06:19:32Z | 39,117,129 | <p><code>form.is_valid()</code> must be called before accessing to <code>cleaned_data</code>.</p>
| 0 | 2016-08-24T07:36:03Z | [
"python",
"django"
] |
Call constructor of cls object in Python | 39,116,035 | <p>I am trying to call the constructor of a <code>class</code> object in python. I managed to get it to work using the following few lines:</p>
<pre><code>obj = cls.__new__(cls)
n = (List of attribute names)
v = (List of attribute values)
for s in n:
setattr(obj, s, v[s])
</code></pre>
<p>I was wondering if there is a way to directly insert the attribute value + name pairs into the constructor, cause the arguments are just ignored if i call the following:</p>
<pre><code>obj = cls.__new__(cls, v)
</code></pre>
<p>p.s.: I am using <code>python3</code></p>
<p>The class looks similar to this:</p>
<pre><code>class InheritingClass(BaseClass):
def __init__(self, basic_attribute, another_attribute=None):
super().__init__(basic_attribute=basic_attribute)
self.another_attribute= another_attribute
class BaseClass:
def __init__(self, basic_attribute=1):
self.basic_attribute= basic_attribute
</code></pre>
<p>So nothing special there</p>
| 0 | 2016-08-24T06:36:58Z | 39,116,117 | <p><code>__init__</code> is the constructor of Python class instead of <code>__new__</code>. Refer <a href="http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init">Pythons use of new and init</a> for more information.</p>
| 0 | 2016-08-24T06:41:30Z | [
"python"
] |
Call constructor of cls object in Python | 39,116,035 | <p>I am trying to call the constructor of a <code>class</code> object in python. I managed to get it to work using the following few lines:</p>
<pre><code>obj = cls.__new__(cls)
n = (List of attribute names)
v = (List of attribute values)
for s in n:
setattr(obj, s, v[s])
</code></pre>
<p>I was wondering if there is a way to directly insert the attribute value + name pairs into the constructor, cause the arguments are just ignored if i call the following:</p>
<pre><code>obj = cls.__new__(cls, v)
</code></pre>
<p>p.s.: I am using <code>python3</code></p>
<p>The class looks similar to this:</p>
<pre><code>class InheritingClass(BaseClass):
def __init__(self, basic_attribute, another_attribute=None):
super().__init__(basic_attribute=basic_attribute)
self.another_attribute= another_attribute
class BaseClass:
def __init__(self, basic_attribute=1):
self.basic_attribute= basic_attribute
</code></pre>
<p>So nothing special there</p>
| 0 | 2016-08-24T06:36:58Z | 39,116,422 | <p>To add, if you want to store arbitrary attributes to your class, you can use <code>dict.update</code> like so:</p>
<pre><code>class BaseClass:
def __init__(self, basic_attribute=1, **kw):
self.basic_attribute = basic_attribute
self.__dict__.update(**kw)
class InheritingClass(BaseClass):
def __init__(self, basic_attribute, another_attribute=None, **kw):
super().__init__(basic_attribute=basic_attribute, **kw)
self.another_attribute = another_attribute
</code></pre>
<p>Then:</p>
<pre><code>ic = InheritingClass('hi', a=1, b=20)
print(ic.a, ic.b) # prints 1, 20
</code></pre>
| 0 | 2016-08-24T06:58:57Z | [
"python"
] |
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 448: ordinal not in range(128) | 39,116,122 | <p>I am currently using selenium python to scrape linkedin data. I can parse through various webpages and scrape data but the process is interrupted after the first few pages due to the Unicode error. Here's my code:</p>
<pre><code>from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
driver.get('https://www.linkedin.com/jobs/search?locationId=sg%3A0&f_TP=1%2C2&orig=FCTD&trk=jobs_jserp_posted_one_week')
result = []
while True:
while True:
try:
sleep(1)
result +=[i.text for i in driver.find_elements_by_class_name('job-title-text')]
except:
sleep(5)
else:
break
try:
for i in range(50):
nextbutton = driver.find_element_by_class_name('next-btn')
nextbutton.click()
except:
break
with open('jobtitles.csv', 'w') as f:
f.write('\n'.join(i for i in result).encode('utf-8').decode('utf-8'))
</code></pre>
| 1 | 2016-08-24T06:42:02Z | 39,118,524 | <p>You can use UnicodeWriter (from Python docs):</p>
<pre><code>import codecs
import cStringIO
import csv
from time import sleep
from selenium import webdriver
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
driver = webdriver.Firefox()
driver.get('https://www.linkedin.com/jobs/search?locationId=sg%3A0&f_TP=1%2C2&orig=FCTD&trk=jobs_jserp_posted_one_week')
result = []
while True:
while True:
try:
sleep(1)
result +=[i.text for i in driver.find_elements_by_class_name('job-title-text')]
except:
sleep(5)
else:
break
try:
for i in range(50):
nextbutton = driver.find_element_by_class_name('next-btn')
nextbutton.click()
except:
break
with open('jobtitles.csv', 'w') as f:
doc = UnicodeWriter(f)
doc.writerows(result)
</code></pre>
| 0 | 2016-08-24T08:45:11Z | [
"python",
"selenium",
"unicode"
] |
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 448: ordinal not in range(128) | 39,116,122 | <p>I am currently using selenium python to scrape linkedin data. I can parse through various webpages and scrape data but the process is interrupted after the first few pages due to the Unicode error. Here's my code:</p>
<pre><code>from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
driver.get('https://www.linkedin.com/jobs/search?locationId=sg%3A0&f_TP=1%2C2&orig=FCTD&trk=jobs_jserp_posted_one_week')
result = []
while True:
while True:
try:
sleep(1)
result +=[i.text for i in driver.find_elements_by_class_name('job-title-text')]
except:
sleep(5)
else:
break
try:
for i in range(50):
nextbutton = driver.find_element_by_class_name('next-btn')
nextbutton.click()
except:
break
with open('jobtitles.csv', 'w') as f:
f.write('\n'.join(i for i in result).encode('utf-8').decode('utf-8'))
</code></pre>
| 1 | 2016-08-24T06:42:02Z | 39,119,326 | <p>it is an improper encoding... you claim that a bytestream is encoded by UTF-8 and that is not true
at the referred position according to the UTF-8 implementation only ascii character(0-127) is allowed, so the UTF-8 decoding fails... I do not see at your code how and when that UTF-8 decoding fails, so you should trace the exact location by yourself
check the variables with type(), and please also note that python 2 and 3 got differences in this area</p>
| 0 | 2016-08-24T09:23:20Z | [
"python",
"selenium",
"unicode"
] |
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 448: ordinal not in range(128) | 39,116,122 | <p>I am currently using selenium python to scrape linkedin data. I can parse through various webpages and scrape data but the process is interrupted after the first few pages due to the Unicode error. Here's my code:</p>
<pre><code>from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
driver.get('https://www.linkedin.com/jobs/search?locationId=sg%3A0&f_TP=1%2C2&orig=FCTD&trk=jobs_jserp_posted_one_week')
result = []
while True:
while True:
try:
sleep(1)
result +=[i.text for i in driver.find_elements_by_class_name('job-title-text')]
except:
sleep(5)
else:
break
try:
for i in range(50):
nextbutton = driver.find_element_by_class_name('next-btn')
nextbutton.click()
except:
break
with open('jobtitles.csv', 'w') as f:
f.write('\n'.join(i for i in result).encode('utf-8').decode('utf-8'))
</code></pre>
| 1 | 2016-08-24T06:42:02Z | 40,101,810 | <pre><code>import sys
reload(sys)
sys.setdefaultencoding("utf-8")
print sys.getdefaultencoding()
</code></pre>
<p>add it on the top of your code.</p>
<p>also, u might need to preprocess your code to replace some nonenglish words</p>
<pre><code> words=word_tokenize(content)
# print words
word=[]
for w in words:
w= re.sub(r'[^\w\s]', '',w)
w =re.sub("[^A-Za-z]+"," ",w,flags=re.MULTILINE)
w =w .strip("\t\n\r")
word.append(w)
words=word
# print words
stop_words = set(stopwords.words('english'))
filteredword = [w for w in words if not w in stop_words and 3 < len(w)]
# print filteredword
words=" ".join(filteredword)
</code></pre>
| 0 | 2016-10-18T07:13:03Z | [
"python",
"selenium",
"unicode"
] |
ProtocolError IncompleteRead using requests | 39,116,123 | <p>I got this wierd error when I tried to download some images using <code>requests</code> with quite a brief code as follows,</p>
<pre><code>import requests
import StringIO
r = requests.get(image_url, stream=True)
if r.status_code == 200:
r.raw.decode_content = True
data = StringIO.StringIO(r.raw.data)
# other code to deal with data
</code></pre>
<p>then I get this error,</p>
<pre><code>ProtocolError: ('Connection broken: IncompleteRead(15060 bytes read, 55977 more expected)', IncompleteRead(15060 bytes read, 55977 more expected))
</code></pre>
<p>I googled similar problems, and try to force requests using HTTP/1.0 protocol like this,</p>
<pre><code>import httplib
httplib.HTTPConnection._http_vsn = 10
httplib.HTTPConnection._http_vsn_str = 'HTTP/1.0'
</code></pre>
<p>however, the server simply returns me an <code>403</code> status code.</p>
<p>By the way, what's more confusing is the <code>ProtocolError</code> does not happens every time but sometimes.</p>
<p>Any help would be very appreciated!</p>
| 0 | 2016-08-24T06:42:03Z | 39,116,450 | <p>Since you are using <code>stream=True</code> you should iterate over the response and save the file in chunks:</p>
<pre><code>with open('pic1.jpg', 'wb') as handle:
response = requests.get(image_url, stream=True)
if response.ok:
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
</code></pre>
<p>Note that this will save an actual file, but can be modified to use <code>StringIO</code>:</p>
<pre><code>with StringIO() as handle:
response = requests.get(image_url, stream=True)
if response.ok:
for block in response.iter_content(1024):
if not block:
break
handle.write(str(block))
</code></pre>
| 1 | 2016-08-24T07:00:28Z | [
"python",
"python-2.7",
"http",
"python-requests"
] |
How to upload a file to Hug REST API | 39,116,130 | <p>I'm working on a basic Hug API and one of my functions needs a file.</p>
<p>Does Hug have a way to upload a file? </p>
| -1 | 2016-08-24T06:42:22Z | 39,126,169 | <p>I <em>think</em> it can. Looking at the <a href="https://github.com/timothycrosley/hug/blob/develop/hug/input_format.py" rel="nofollow">input_format.py</a> you should be able to extract a file encoded some codex (url, utf-8, etc). Looking at the github readme, there is this example:</p>
<pre><code>@hug.default_input_format("application/json")
def my_input_formatter(data):
return ('Results', hug.input_format.json(data))
</code></pre>
<p>If the file was in json format, then you would extract the encoded file from the json object, convert it to bytes, then write the bytes to a local file.</p>
| 0 | 2016-08-24T14:31:14Z | [
"python",
"python-3.x"
] |
How can I apply decorator to a superclass method in a subclass? | 39,116,151 | <p>Say, we have the following situation,</p>
<pre><code>class A():
def something():
...
...
...
class B(A):
def use_something():
...
...
# Now, at this point I want something() to be decorated with a
# decorator. But, since it is already defined in base class,
# I am not getting how to decorate it here, in the subclass.
self.something()
...
...
</code></pre>
<p>Now, in Class B, I want to use something() from Class A, but I want to apply a decorator to it.
I cannot decorate it in class A, since there are different decorators that I want to apply at different places. Say, Class C(A) and I want to use something() here as well, with a different decorator.</p>
<p>So, coming back to the original question; how can I apply decorator to a superclass's method in a subclass?</p>
| -1 | 2016-08-24T06:44:09Z | 39,116,679 | <p>Here you go (with params and without):</p>
<pre><code>def simple_dec(func):
def wrapped(*args, **kwargs):
return 'No way'
return wrapped
def simple_dec_params(first_param, second_param):
def dec(func):
def wrapped(*args, **kwargs):
return '{} {}'.format(first_param, second_param)
return wrapped
return dec
class A():
def something(self):
print 'Something'
class B(A):
def use_something(self):
first_param = 'No'
second_param = 'Way'
print simple_dec(self.something)()
print simple_dec_params(first_param, second_param)(self.something)()
b = B()
b.use_something()
</code></pre>
| 0 | 2016-08-24T07:12:56Z | [
"python",
"inheritance",
"python-decorators"
] |
How can I apply decorator to a superclass method in a subclass? | 39,116,151 | <p>Say, we have the following situation,</p>
<pre><code>class A():
def something():
...
...
...
class B(A):
def use_something():
...
...
# Now, at this point I want something() to be decorated with a
# decorator. But, since it is already defined in base class,
# I am not getting how to decorate it here, in the subclass.
self.something()
...
...
</code></pre>
<p>Now, in Class B, I want to use something() from Class A, but I want to apply a decorator to it.
I cannot decorate it in class A, since there are different decorators that I want to apply at different places. Say, Class C(A) and I want to use something() here as well, with a different decorator.</p>
<p>So, coming back to the original question; how can I apply decorator to a superclass's method in a subclass?</p>
| -1 | 2016-08-24T06:44:09Z | 39,116,856 | <p>Any particular reason why you can't just override <code>something()</code>?</p>
<pre><code>class A():
def something(self):
...
class B(A):
def use_something(self):
...
self.something()
...
def something(self):
# Do "decorator" stuff
super().something()
# Do more "decorator" stuff
</code></pre>
| 0 | 2016-08-24T07:21:41Z | [
"python",
"inheritance",
"python-decorators"
] |
Custom printing in jupyter notebook | 39,116,201 | <p>I'm looking for an alternative to MathCad to make simple calculations but I wanted the expressions to look like if I was using pen and paper and make it easy to read for people who don't know programming. I tried Sweave, Knitr but I was unhappy with it. I recently found Jupyter notebook with SymPy and it's still not as easy as MathCad for me, but I'll give it a try. With Jupyter I'm having trouble printing formulas: <strong>I want to print both sides of the equation automatically</strong>.</p>
<h3>What I want:</h3>
<p><a href="http://i.stack.imgur.com/kq8Mq.png" rel="nofollow"><img src="http://i.stack.imgur.com/kq8Mq.png" alt="enter image description here"></a></p>
<h3>What i get:</h3>
<p><a href="http://i.stack.imgur.com/j7FEN.png" rel="nofollow"><img src="http://i.stack.imgur.com/j7FEN.png" alt="enter image description here"></a></p>
<h3>What I tried</h3>
<p>ccode doesn't return latex and it's boring always typing "assign_to"
<a href="http://i.stack.imgur.com/Fm8XI.png" rel="nofollow"><img src="http://i.stack.imgur.com/Fm8XI.png" alt="enter image description here"></a></p>
| 3 | 2016-08-24T06:46:46Z | 39,117,457 | <p>You can use sympy.printing.latex.</p>
<p><a href="http://i.stack.imgur.com/4uUqU.png" rel="nofollow"><img src="http://i.stack.imgur.com/4uUqU.png" alt="SymPy using LaTeX printing"></a></p>
<p>Refer to the following link for more information.</p>
<p><a href="http://docs.sympy.org/dev/modules/printing.html?highlight=sympy.printing#module-sympy.printing.latex" rel="nofollow">http://docs.sympy.org/dev/modules/printing.html?highlight=sympy.printing#module-sympy.printing.latex</a></p>
| 0 | 2016-08-24T07:52:59Z | [
"python",
"ipython",
"sympy",
"jupyter-notebook"
] |
Custom printing in jupyter notebook | 39,116,201 | <p>I'm looking for an alternative to MathCad to make simple calculations but I wanted the expressions to look like if I was using pen and paper and make it easy to read for people who don't know programming. I tried Sweave, Knitr but I was unhappy with it. I recently found Jupyter notebook with SymPy and it's still not as easy as MathCad for me, but I'll give it a try. With Jupyter I'm having trouble printing formulas: <strong>I want to print both sides of the equation automatically</strong>.</p>
<h3>What I want:</h3>
<p><a href="http://i.stack.imgur.com/kq8Mq.png" rel="nofollow"><img src="http://i.stack.imgur.com/kq8Mq.png" alt="enter image description here"></a></p>
<h3>What i get:</h3>
<p><a href="http://i.stack.imgur.com/j7FEN.png" rel="nofollow"><img src="http://i.stack.imgur.com/j7FEN.png" alt="enter image description here"></a></p>
<h3>What I tried</h3>
<p>ccode doesn't return latex and it's boring always typing "assign_to"
<a href="http://i.stack.imgur.com/Fm8XI.png" rel="nofollow"><img src="http://i.stack.imgur.com/Fm8XI.png" alt="enter image description here"></a></p>
| 3 | 2016-08-24T06:46:46Z | 39,123,380 | <p>If you need a more convenient way, you can define a wrapper function as follows.</p>
<pre><code>class Equation(object):
def __init__(self, left, right, mode='latex'):
self.mode = mode
self.left = left
self.right = right
self._eq = sym.Eq(left, right)
self._latex = sym.latex(self._eq)
def __repr__(self):
if self.mode == 'latex':
return self._latex.__repr__()
elif self.mode == 'sympy':
return self._eq.__repr__()
def __str__(self):
if self.mode == 'latex':
return self._latex
elif self.mode == 'sympy':
return self.eq.__str__()
def eq(self):
return self._eq
def latex(self):
return self._latex
@property
def mode(self):
return self._mode
@mode.setter
def mode(self, val):
self._mode = val
@property
def left(self):
return self._left
@left.setter
def left(self, val):
self._left = sym
@property
def right(self):
return self._right
@right.setter
def right(self, val):
self._right = val
# end of class
</code></pre>
<p><a href="http://i.stack.imgur.com/CDoBy.png" rel="nofollow"><img src="http://i.stack.imgur.com/CDoBy.png" alt="enter image description here"></a></p>
| 3 | 2016-08-24T12:30:04Z | [
"python",
"ipython",
"sympy",
"jupyter-notebook"
] |
Custom printing in jupyter notebook | 39,116,201 | <p>I'm looking for an alternative to MathCad to make simple calculations but I wanted the expressions to look like if I was using pen and paper and make it easy to read for people who don't know programming. I tried Sweave, Knitr but I was unhappy with it. I recently found Jupyter notebook with SymPy and it's still not as easy as MathCad for me, but I'll give it a try. With Jupyter I'm having trouble printing formulas: <strong>I want to print both sides of the equation automatically</strong>.</p>
<h3>What I want:</h3>
<p><a href="http://i.stack.imgur.com/kq8Mq.png" rel="nofollow"><img src="http://i.stack.imgur.com/kq8Mq.png" alt="enter image description here"></a></p>
<h3>What i get:</h3>
<p><a href="http://i.stack.imgur.com/j7FEN.png" rel="nofollow"><img src="http://i.stack.imgur.com/j7FEN.png" alt="enter image description here"></a></p>
<h3>What I tried</h3>
<p>ccode doesn't return latex and it's boring always typing "assign_to"
<a href="http://i.stack.imgur.com/Fm8XI.png" rel="nofollow"><img src="http://i.stack.imgur.com/Fm8XI.png" alt="enter image description here"></a></p>
| 3 | 2016-08-24T06:46:46Z | 39,128,587 | <p>You need to use <code>sympy.Eq</code> if you want to print an equation. The <code>=</code> operator just assigns variables in Python, meaning in your example, the Python variable <code>R_r</code> is assigned to the SymPy expression <code>(c_1 + (c_2*x/G) + c_3*V)*G</code>. </p>
<p>In general in Python, there is no reverse association with an object and the variable it is assigned to. There is no way for the expression to "know" that it is assigned to a variable named <code>R_r</code>. </p>
<p>Instead, you need to create a symbol named <code>R_r</code> and use <code>Eq(R_r, (c_1 + (c_2*x/G) + c_3*V)*G)</code>. </p>
<p>See also <a href="http://docs.sympy.org/latest/tutorial/gotchas.html" rel="nofollow">http://docs.sympy.org/latest/tutorial/gotchas.html</a> and <a href="http://nedbatchelder.com/text/names.html" rel="nofollow">http://nedbatchelder.com/text/names.html</a>.</p>
| 2 | 2016-08-24T16:28:26Z | [
"python",
"ipython",
"sympy",
"jupyter-notebook"
] |
how many loops to execute in nested generators | 39,116,276 | <p>I readed the famous article <a href="http://www.dabeaz.com/generators/" rel="nofollow">Generator Tricks for Systems Programmers</a> and very confused with nested generators (or you can call it generator pipeline ? ).so I have some questions about following code.</p>
<pre><code>def field_map(dictseq, name, func):
for d in dictseq:
d[name] = func(d[name])
yield d
loglines = open("access-log")
import re
logpats = r'(\S+) (\S+) (\S+) \[(.*?)\] ' \
r'"(\S+) (\S+) (\S+)" (\S+) (\S+)'
logpat = re.compile(logpats)
groups = (logpat.match(line) for line in loglines)
tuples = (g.groups() for g in groups if g)
colnames = ('host','referrer','user','datetime',
'method', 'request','proto','status','bytes')
log = (dict(zip(colnames,t)) for t in tuples)
log = field_map(log,"status",int)
log = field_map(log,"bytes",lambda s: int(s) if s != '-' else 0)
for x in log:
print(x)
</code></pre>
<p>we can abstract it into the following code</p>
<pre><code>loglines = open("access-log")
log_dict = generatorC(generatorB(generatorA(loglines)))
log_dict = tradition_loop(log_dict,foo)
log_dict = tradition_loop(log_dict,bar)
</code></pre>
<p>I know the function <code>field_map(dictseq, name, func)</code> will traverses <code>log_dict</code> once it's called. and we need to avoid calling this method multiple times.</p>
<p>Here is the question :</p>
<ul>
<li>How many times does the code <code>generatorC(generatorB(generatorA(loglines)))</code> traverse the <code>loglines</code>? one or three times ?</li>
</ul>
| -3 | 2016-08-24T06:50:42Z | 39,116,337 | <p><code>loglines</code> is traversed once. If it were traversed multiple times, it wouldn't work, as generators become exhausted after they are iterated over.</p>
| 0 | 2016-08-24T06:54:28Z | [
"python",
"generator"
] |
Python 3.5: Web-scraping with Stripping html codes | 39,116,455 | <p>I am scraping the web content but stuck with a problem. After a series of processing to strip the scope that I want, I cannot strip the html code to make it plain text in a list. I have tried using the function of replace, re.compile and join (try to change the list to text for stripping). All doesn't work as they are designed for string or pops out errors when running. </p>
<p>Could anyone give me some hint how to do that. For example, I want the output from the following code change from</p>
<pre><code><p class="course-d-title">Instructor</p>
</code></pre>
<p>to <code>Instructor</code>.</p>
<pre><code>import tkinter as tk
import re
def test():
from bs4 import BeautifulSoup
import urllib.request
from urllib.parse import urljoin
'''for layer 0'''
url_text = 'http://www.scs.cuhk.edu.hk/en/part-time/accounting-and-finance/accounting-and-finance/fundamental-accounting/162-610441-01'
resp = urllib.request.urlopen(url_text)
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))
a = soup.find_all('p')
k=0
for item in a[:]:
if 'Instructor' in item:
a=a[k:]
break
k+=1
j=0
for item in a[:]:
if 'Enquiries' in item:
a=a[:j-1]
break
j+=1
for i in range(0,a.__len__()):
print (a[i])
if __name__ == '__main__':
test()
</code></pre>
| 0 | 2016-08-24T07:00:36Z | 39,116,696 | <p>use <code>.text</code> to extract text from bs4 element</p>
<pre><code>>>> a = soup.find_all('p')
>>> data = [ item for item in a if 'Instructor' in item]
[<p class="course-d-title">Instructor</p>]
>>> data[0].text
'Instructor'
</code></pre>
| 1 | 2016-08-24T07:13:48Z | [
"python",
"web-scraping"
] |
Python 3.5: Web-scraping with Stripping html codes | 39,116,455 | <p>I am scraping the web content but stuck with a problem. After a series of processing to strip the scope that I want, I cannot strip the html code to make it plain text in a list. I have tried using the function of replace, re.compile and join (try to change the list to text for stripping). All doesn't work as they are designed for string or pops out errors when running. </p>
<p>Could anyone give me some hint how to do that. For example, I want the output from the following code change from</p>
<pre><code><p class="course-d-title">Instructor</p>
</code></pre>
<p>to <code>Instructor</code>.</p>
<pre><code>import tkinter as tk
import re
def test():
from bs4 import BeautifulSoup
import urllib.request
from urllib.parse import urljoin
'''for layer 0'''
url_text = 'http://www.scs.cuhk.edu.hk/en/part-time/accounting-and-finance/accounting-and-finance/fundamental-accounting/162-610441-01'
resp = urllib.request.urlopen(url_text)
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))
a = soup.find_all('p')
k=0
for item in a[:]:
if 'Instructor' in item:
a=a[k:]
break
k+=1
j=0
for item in a[:]:
if 'Enquiries' in item:
a=a[:j-1]
break
j+=1
for i in range(0,a.__len__()):
print (a[i])
if __name__ == '__main__':
test()
</code></pre>
| 0 | 2016-08-24T07:00:36Z | 39,124,909 | <p>If you want to take the Name of Instructor and Enquiries phone number also, below code can help you.</p>
<pre><code> import requests
from bs4 import BeautifulSoup
url_text = 'http://www.scs.cuhk.edu.hk/en/part-time/accounting-and-finance/accounting-and-finance/fundamental-accounting/162-610441-01'
resp = requests.get(url_text)
soup = BeautifulSoup(resp.text, 'html.parser')
a = soup.find_all('p')
for i in a:
if 'Instructor' in i:
print i.get_text(), "Name is " + soup.find('p',{'class':'course-d-val'}).get_text()
elif 'Enquiries' in i:
print i.get_text(), "The number is " + soup.find('span',{'class':'enq-phone'}).get_text() ,"The Fax is " + soup.find('span',{'class':'enq-fax'}).get_text()
</code></pre>
<p>This code will give you printout as </p>
<pre><code>Instructor Name is Ms. MACK Shui San
Enquiries The number is 3943 9046 The Fax is 2770 8275
</code></pre>
| 0 | 2016-08-24T13:37:47Z | [
"python",
"web-scraping"
] |
Python 3.5: Web-scraping with Stripping html codes | 39,116,455 | <p>I am scraping the web content but stuck with a problem. After a series of processing to strip the scope that I want, I cannot strip the html code to make it plain text in a list. I have tried using the function of replace, re.compile and join (try to change the list to text for stripping). All doesn't work as they are designed for string or pops out errors when running. </p>
<p>Could anyone give me some hint how to do that. For example, I want the output from the following code change from</p>
<pre><code><p class="course-d-title">Instructor</p>
</code></pre>
<p>to <code>Instructor</code>.</p>
<pre><code>import tkinter as tk
import re
def test():
from bs4 import BeautifulSoup
import urllib.request
from urllib.parse import urljoin
'''for layer 0'''
url_text = 'http://www.scs.cuhk.edu.hk/en/part-time/accounting-and-finance/accounting-and-finance/fundamental-accounting/162-610441-01'
resp = urllib.request.urlopen(url_text)
soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))
a = soup.find_all('p')
k=0
for item in a[:]:
if 'Instructor' in item:
a=a[k:]
break
k+=1
j=0
for item in a[:]:
if 'Enquiries' in item:
a=a[:j-1]
break
j+=1
for i in range(0,a.__len__()):
print (a[i])
if __name__ == '__main__':
test()
</code></pre>
| 0 | 2016-08-24T07:00:36Z | 39,136,160 | <p>I found the following code, in a simpler and more flexible way, can achieve the same purposes but allow keyword search:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
url_text = 'http://www.scs.cuhk.edu.hk/en/part-time/accounting-and-finance/accounting-and-finance/fundamental-accounting/162-610441-01'
resp = requests.get(url_text)
soup = BeautifulSoup(resp.text, 'html.parser')
print (soup.find(text="Instructor").findNext('p').text)
</code></pre>
| 0 | 2016-08-25T03:18:13Z | [
"python",
"web-scraping"
] |
Group by of a Column and Sum Contents of another column with python | 39,116,735 | <p>I have a dataframe merged_df_energy:</p>
<pre><code>merged_df_energy.head()
ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 ACT_TIME_AERATEUR_1_F5 class_energy
63.333333 63.333333 63.333333 low
0 0 0 high
45.67 0 55.94 high
0 0 23.99 low
0 20 23.99 medium
</code></pre>
<p>I would like to create for each <code>ACT_TIME_AERATEUR_1_Fx</code> (<code>ACT_TIME_AERATEUR_1_F1</code>, <code>ACT_TIME_AERATEUR_1_F3</code> and <code>ACT_TIME_AERATEUR_1_F5</code>) a dataframe wich contains these columns : <code>class_energy</code> and <code>sum_time</code></p>
<p>For example for the dataframe corresponding to <code>ACT_TIME_AERATEUR_1_F1</code>:</p>
<pre><code>class_energy sum_time
low 63.333333
medium 0
high 45.67
</code></pre>
<p>I thing to do I should use the group by like this:</p>
<pre><code>data.groupby(by=['class_energy'])['sum_time'].sum()
</code></pre>
<p>Any idea to help me please?</p>
| 2 | 2016-08-24T07:16:01Z | 39,116,796 | <p>You can add all columns to <code>[]</code> for aggregating:</p>
<pre><code>print (df.groupby(by=['class_energy'])['ACT_TIME_AERATEUR_1_F1', 'ACT_TIME_AERATEUR_1_F3','ACT_TIME_AERATEUR_1_F5'].sum())
ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 \
class_energy
high 45.670000 0.000000
low 63.333333 63.333333
medium 0.000000 20.000000
ACT_TIME_AERATEUR_1_F5
class_energy
high 55.940000
low 87.323333
medium 23.990000
</code></pre>
<p>You can use also parameter <code>as_index=False</code>:</p>
<pre><code>print (df.groupby(by=['class_energy'], as_index=False)['ACT_TIME_AERATEUR_1_F1', 'ACT_TIME_AERATEUR_1_F3','ACT_TIME_AERATEUR_1_F5'].sum())
class_energy ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 \
0 high 45.670000 0.000000
1 low 63.333333 63.333333
2 medium 0.000000 20.000000
ACT_TIME_AERATEUR_1_F5
0 55.940000
1 87.323333
2 23.990000
</code></pre>
<p>If need aggregate only first <code>3</code> columns:</p>
<pre><code>print (df.groupby(by=['class_energy'], as_index=False)[df.columns[:3]].sum())
class_energy ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 \
0 high 45.670000 0.000000
1 low 63.333333 63.333333
2 medium 0.000000 20.000000
ACT_TIME_AERATEUR_1_F5
0 55.940000
1 87.323333
2 23.990000
</code></pre>
<p>...or all columns without last:</p>
<pre><code>print (df.groupby(by=['class_energy'], as_index=False)[df.columns[:-1]].sum())
class_energy ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F3 \
0 high 45.670000 0.000000
1 low 63.333333 63.333333
2 medium 0.000000 20.000000
ACT_TIME_AERATEUR_1_F5
0 55.940000
1 87.323333
2 23.990000
</code></pre>
| 2 | 2016-08-24T07:19:03Z | [
"python",
"pandas",
"dataframe",
"group-by",
"aggregate"
] |
Plot average on subplots (pandas) | 39,116,827 | <p>I've managed to plot subplots from a groupby. I have two columns 'A', and 'B', which I want to plot on subplot (1 per value in 'B') with their respective averages.
I prepare my data by counting, dropping the duplicates, and then summing it up (if there is a more elegant way to do it, please let me know!).</p>
<pre><code>df = pd.DataFrame([[1, 'cat1'], [1, 'cat1'], [4, 'cat2'], [3, 'cat1'], [5, 'cat1'],[1, 'cat2']], columns=['A', 'B'])
df = df[['A','B']]
df['count'] = df.groupby(['A','B'])['A'].transform('count')
df = df.drop_duplicates(['A','B'])
df = df.groupby(['A','B']).sum()
</code></pre>
<p>Then I unstack it and plot it with subplots:</p>
<pre><code>plot = df.unstack().plot(kind='bar',subplots=True, sharex=True, sharey=True, layout = (3,3), legend=False)
plt.show(block=True)
</code></pre>
<p>I would like to add the mean for each category, but I have don't know:
1. How to calculate the mean. If I calculate it on the unstacked groupby, I get the mean of the count, rather than the value 'A'.
2. Once I have the mean value, I don't know how to plot it on the same subplot.</p>
<p>Any help is welcomed :)</p>
<p>--</p>
<p>Edit following Nickil Maveli's answer:
What I'm trying to achieve is to plot bars of the grouped values on A, and to plot a vertical line with the mean value on B. So using the graphs from Nickil Maveli, this would be:<a href="http://i.stack.imgur.com/u75GX.png" rel="nofollow"><img src="http://i.stack.imgur.com/u75GX.png" alt="enter image description here"></a></p>
<p>From what I've found on stackexchange, I think I should be using <code>plt.axvline(mean, color='r', linestyle='--')</code>. However, I don't know how to call have a different mean per plot.</p>
| 0 | 2016-08-24T07:20:30Z | 39,118,463 | <p>IIUC, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#aggregation" rel="nofollow"><code>agg</code></a> on the mean and count to compute averages and counts beforehand.</p>
<pre><code>df_1 = df.groupby(['A', 'B'])['A'].agg({'counts': 'count'}).reset_index()
df_2 = df.groupby('B')['A'].agg({'average': 'mean'}).reset_index()
</code></pre>
<p>Followed by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html" rel="nofollow"><code>DF.merge</code></a> on column B, as it is the common column in both the groupby operations. Then, the duplicated entries among columns A and B can be removed.</p>
<pre><code>df = df_1.merge(df_2, on='B').drop_duplicates(['A', 'B'])
df.drop('average', axis=1, inplace=True)
df = df.groupby(['A','B']).sum()
</code></pre>
<p>Make modifications to the second dataframe to let column A take the mean values.</p>
<pre><code>df_2['A'] = df_2['average']
df_2 = df_2.groupby(['A','B']).sum()
</code></pre>
<p>Using Layout and Targetting Multiple Axes.</p>
<pre><code>fig, ax = plt.subplots(2, 2, figsize=(8, 8))
target1 = [ax[0][0], ax[0][1]]
target2 = [ax[1][0], ax[1][1]]
</code></pre>
<p>Count groupby plot.</p>
<pre><code>df.unstack().plot(kind='bar', subplots=True, rot=0, xlim=(0,5), ax=target1,
ylim=(0,3), layout=(2,2), legend=False)
</code></pre>
<p>Mean groupby plot. </p>
<pre><code>df_2.unstack().plot(kind='bar', width=0.005, subplots=True, rot=0, xlim=(0,5), ax=target2,
ylim=(0,3), layout=(2,2), legend=False, color='k')
</code></pre>
<p>Adjusting the spacing between subplots.</p>
<pre><code>plt.subplots_adjust(wspace=0.5, hspace=0.5)
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/qWD0x.png" rel="nofollow"><img src="http://i.stack.imgur.com/qWD0x.png" alt="Image"></a></p>
| 0 | 2016-08-24T08:42:30Z | [
"python",
"pandas",
"matplotlib",
"plot"
] |
python2.7 histogram comparison - white background anomaly | 39,116,877 | <p>my program's purpose is to take 2 images and decide how similar they are.
im not talking here about identical, but similarity. for example, if i take 2 screenshots of 2 different pages of the same website, their theme colors would probably be very similar and therefor i want the program to declare that they are similar.</p>
<p>my problem starts when both images have a white background that pretty much takes over the histogram calculation (over then 30% of the image is white and the rest is distributed).</p>
<p>in that case, the cv2.compareHist (using correlation method, which works for the other cases) gives very bad results, that is, the grade is very high even though they look very different.</p>
<p>i have thought about taking the white (255) off the histogram before comparing, but that requires me to calculate the histogram with 256 bins, which is not good when i want to check similarity (i thought that using 32 or 64 bins would be best)</p>
<p>unfortunately i cant add images im working with due to legal reasons</p>
<p>if anyone can help with an idea, or code that solves it i would be very grateful</p>
<p>thank you very much</p>
| 0 | 2016-08-24T07:22:45Z | 39,119,151 | <p>You can remove the white color, rebin the histogra and then compare:</p>
<ul>
<li>Compute a histrogram with 256 bins.</li>
<li>Remove the white bin (or make it zero).</li>
<li>Regroup the bins to have 64 bins by adding the values of 4 consecutive bins. </li>
<li>Perform the compareHist().</li>
</ul>
<p>This would work for any "predominant color". To generalize, you can do the following:</p>
<p>Compare full histrograms. If they are different, then finish.
If they are similar, look for the predominant color (with a 256-bin histogram), and perform the procedure described above, to remove the predominant color from the comparisson.</p>
| 0 | 2016-08-24T09:15:17Z | [
"python",
"python-2.7",
"opencv",
"image-processing",
"histogram"
] |
Iterate a pymongo cursor from MLab | 39,116,919 | <p>Why won't the cursor iterate? I feel sure there <em>should</em> be an easy solution.</p>
<p>I have tried multiple Stack Overflow answers and the documentation for Mongodb
<a href="https://docs.mongodb.com/getting-started/python/query/" rel="nofollow">https://docs.mongodb.com/getting-started/python/query/</a></p>
<p>The code is as per below:</p>
<pre><code>from pymongo import MongoClient
#Connect to Mongo Client
client = MongoClient('mongodb://the_username:the_password@ds047124.mlab.com:47124/politicians_from_theage')
db = client.politicians_from_theage #define database used
# Define Collection
collection = db.posts
print collection
</code></pre>
<p><strong>Result:</strong> </p>
<pre><code>Collection(Database(MongoClient(host=['ds047124.mlab.com:47124'], document_class=dict, tz_aware=False, connect=True), u'politicians_from_theage'), u'posts')
</code></pre>
<p>Then the cursor will print its location:</p>
<pre><code># Define Cursor
my_cursor = collection.find()
print my_cursor
</code></pre>
<p><strong>Result:</strong></p>
<pre><code><pymongo.cursor.Cursor object at 0x0000000003247518>
</code></pre>
<p>Then to try and iterate over the cursor provides a timeout:</p>
<pre><code> # Perform query
cursor = db.posts.find()
#Iterate the cursor and print the documents.
for document in cursor:
print(document) #No Luck
</code></pre>
<p><strong>Traceback Error or Iteration:</strong></p>
<pre><code>Traceback (most recent call last):
File "C:\PythonC\PythonWebScraping\17_MongoInterface\mongoget.py", line 18, in <module>
for result_object in my_cursor:
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 1090, in next
if len(self.__data) or self._refresh():
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 1012, in _refresh
self.__read_concern))
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 850, in __send_message
**kwargs)
File "C:\Python27\lib\site-packages\pymongo\mongo_client.py", line 827, in _send_message_with_response
server = topology.select_server(selector)
File "C:\Python27\lib\site-packages\pymongo\topology.py", line 210, in select_server
address))
File "C:\Python27\lib\site-packages\pymongo\topology.py", line 186, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: ds047124.mlab.com:47124: timed out
</code></pre>
<p>I have tried iterating on 'cursor', 'my_cursor' and 'collection', each of which provides a traceback error of server timeout.
Any help/insight would be greatly appreciated</p>
| 1 | 2016-08-24T07:25:13Z | 39,117,013 | <p>This may help you:-</p>
<pre><code> # Perform query
cursor = db.posts.find().toAray(function(err, result){
#Iterate the cursor and print the documents.
for document in result:
print(document);
}) //Will give you array of objects.
</code></pre>
<p>Let me know if it works.</p>
| 0 | 2016-08-24T07:30:25Z | [
"python",
"mongodb",
"pymongo"
] |
Iterate a pymongo cursor from MLab | 39,116,919 | <p>Why won't the cursor iterate? I feel sure there <em>should</em> be an easy solution.</p>
<p>I have tried multiple Stack Overflow answers and the documentation for Mongodb
<a href="https://docs.mongodb.com/getting-started/python/query/" rel="nofollow">https://docs.mongodb.com/getting-started/python/query/</a></p>
<p>The code is as per below:</p>
<pre><code>from pymongo import MongoClient
#Connect to Mongo Client
client = MongoClient('mongodb://the_username:the_password@ds047124.mlab.com:47124/politicians_from_theage')
db = client.politicians_from_theage #define database used
# Define Collection
collection = db.posts
print collection
</code></pre>
<p><strong>Result:</strong> </p>
<pre><code>Collection(Database(MongoClient(host=['ds047124.mlab.com:47124'], document_class=dict, tz_aware=False, connect=True), u'politicians_from_theage'), u'posts')
</code></pre>
<p>Then the cursor will print its location:</p>
<pre><code># Define Cursor
my_cursor = collection.find()
print my_cursor
</code></pre>
<p><strong>Result:</strong></p>
<pre><code><pymongo.cursor.Cursor object at 0x0000000003247518>
</code></pre>
<p>Then to try and iterate over the cursor provides a timeout:</p>
<pre><code> # Perform query
cursor = db.posts.find()
#Iterate the cursor and print the documents.
for document in cursor:
print(document) #No Luck
</code></pre>
<p><strong>Traceback Error or Iteration:</strong></p>
<pre><code>Traceback (most recent call last):
File "C:\PythonC\PythonWebScraping\17_MongoInterface\mongoget.py", line 18, in <module>
for result_object in my_cursor:
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 1090, in next
if len(self.__data) or self._refresh():
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 1012, in _refresh
self.__read_concern))
File "C:\Python27\lib\site-packages\pymongo\cursor.py", line 850, in __send_message
**kwargs)
File "C:\Python27\lib\site-packages\pymongo\mongo_client.py", line 827, in _send_message_with_response
server = topology.select_server(selector)
File "C:\Python27\lib\site-packages\pymongo\topology.py", line 210, in select_server
address))
File "C:\Python27\lib\site-packages\pymongo\topology.py", line 186, in select_servers
self._error_message(selector))
pymongo.errors.ServerSelectionTimeoutError: ds047124.mlab.com:47124: timed out
</code></pre>
<p>I have tried iterating on 'cursor', 'my_cursor' and 'collection', each of which provides a traceback error of server timeout.
Any help/insight would be greatly appreciated</p>
| 1 | 2016-08-24T07:25:13Z | 39,121,808 | <p>Found the answer, I was focusing on the cursor rather than loading the object from the cursor from JSON to a list of JSON.</p>
<p>Final code is below (removing the URI)</p>
<pre><code>import json
from datetime import date, timedelta
from pymongo import MongoClient
from bson import json_util
#Connect to Mongo Client
client = MongoClient('mongodb://user:pword@ds047124.mlab.com:47124/politicians_from_theage')
db = client.politicians_from_theage #define database used
print db
# Define Collection
collection = db.posts
print collection # print Collection(Database(MongoClient(host=['ds047124.mlab.com:47124']...
cursor = collection.find()
print cursor
# Obtain json
json_docs = []
for doc in cursor:
json_doc = json.dumps(doc, default=json_util.default)
json_docs.append(json_doc)
print json_docs #json result
# List Comprehension version
#json_docs = [json.dumps(doc, default=json_util.default) for doc in cursor]
#To get back from json again as string list
docs = [json.loads(j_doc, object_hook=json_util.object_hook) for j_doc in json_docs]
print docs
print 'kitty terminates program'
</code></pre>
| 0 | 2016-08-24T11:14:53Z | [
"python",
"mongodb",
"pymongo"
] |
Raspberry Pi Photobooth Printing | 39,117,196 | <p>I've built <a href="http://makezine.com/projects/raspberry-pi-photo-booth/" rel="nofollow">this</a> photobooth, and I am struggling to figure out what code i would need to add to the script in order to get this to print a copy of each photo. I have already mapped my printer to the raspberry pi using cups. </p>
<p><a href="https://github.com/wyolum/TouchSelfie/blob/master/scripts/photobooth_gui.py" rel="nofollow">Here</a> is the github with the script.</p>
<p>Thanks!</p>
| 0 | 2016-08-24T07:39:32Z | 39,118,346 | <p>First, you will need <a href="https://pypi.python.org/pypi/pycups" rel="nofollow">pycups</a>. Then this code <em>should</em> work but I cannot test it:</p>
<pre><code># Set up CUPS
conn = cups.Connection()
printers = conn.getPrinters()
printer_name = printers.keys()[0]
cups.setUser('pi')
# Save the picture to a temporary file for printing
from tempfile import mktemp
output = mktemp(prefix='jpg')
im.save(output, format='jpeg')
# Send the picture to the printer
print_id = conn.printFile(printer_name, output, "Photo Booth", {})
# Wait until the job finishes
from time import sleep
while conn.getJobs().get(print_id, None):
sleep(1)
</code></pre>
<p>The picture is <code>im</code>, which is created at <a href="https://github.com/wyolum/TouchSelfie/blob/master/scripts/photobooth_gui.py#L168" rel="nofollow">line 168</a>. Just paste the code below this line.</p>
<p>For more details, you can find the <code>snap</code> method in <a href="https://github.com/wyolum/TouchSelfie/blob/641bef5d351aa9b0152d67275c1779706e15c8e4/scripts/boothcam.py#L99" rel="nofollow">boothcam.py#L99</a>. </p>
<p>This is a script I succesfully tested:</p>
<pre><code>#!/usr/bin/env python
# coding: utf-8
import cups
import Image
from tempfile import mktemp
from time import sleep
# Set up CUPS
conn = cups.Connection()
printers = conn.getPrinters()
printer_name = printers.keys()[0]
cups.setUser('tiger-222')
# Image (code taken from boothcam.py)
im = Image.new('RGBA', (683, 384))
im.paste(Image.open('test.jpg').resize((683, 384)), ( 0, 0, 683, 384))
# Save data to a temporary file
output = mktemp(prefix='jpg')
im.save(output, format='jpeg')
# Send the picture to the printer
print_id = conn.printFile(printer_name, output, "Photo Booth", {})
# Wait until the job finishes
while conn.getJobs().get(print_id, None):
sleep(1)
unlink(output)
</code></pre>
| 0 | 2016-08-24T08:37:29Z | [
"python",
"printing",
"raspberry-pi"
] |
Python Websocket - with time and message limit | 39,117,226 | <p>I am getting the data from websocket (ws://localhost:8080) and doing command line args with that. code mentioned below.. </p>
<p>python datapy.py -i 127.0.0.1 -p 8080</p>
<pre><code>from websocket import create_connection
#import ConfigParser
#from test import settings
import sys
import argparse
import socket
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='ip' , help='host name / IP')
parser.add_argument('-p', dest='port' , type=int, help='port')
parser.add_argument('-t', dest='time' , type=int, help='Time (in seconds) to keep reading data from websocket. After this process will be exit. Default value is 0. For 0 it will run infinitely')
parser.add_argument('-m', dest='msg' , type=int, help='Number of message. Process will exit after receiving Number of messages. Default is 0, means runs for ever.')
args = parser.parse_args()
print(args.ip)
#ws://%s:%s" % (args.ip,args.port)
url = "ws://%s:%s" % (args.ip,args.port)
ws = create_connection(url)
print "Receiving data from the socket..."
for each in ws:
result = ws.recv();
print "Received '%s'" % result
ws.close();
</code></pre>
<h2>Console:</h2>
<pre><code>C:\Users\556718\Desktop\pythonprac>python datapy.py -i 127.0.0.1 -p 8080
127.0.0.1
Receiving data from the socket...
Received 'sound'
Received 'eokeoe'
Received 'mdmmd'
Received 'ssss'
Received 'tttt'
</code></pre>
<p>As mentioned in argparse, I want to pass -m and -t - like </p>
<pre><code>python data.py -i 127.0.0.1 -p 8080 -m 5 --> It will limit to only 5 messages in the console..
python data.py -i 127.0.0.1 -p 8080 -t 120 --> Send me the messages until 120 seconds - after that exit ....
python data.py -i 127.0.0.1 -p 8080 -m 5 -t 120 --> for limiting to 120 seconds (2 minutes) and 5 messages - either of the condition
</code></pre>
<p>Can anyone help me in this</p>
| 1 | 2016-08-24T07:40:39Z | 39,117,633 | <p>I couldn't test, but something along these lines should work.</p>
<pre><code>from websocket import create_connection
#import ConfigParser
#from test import settings
import sys
import argparse
import socket
import time
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='ip' , help='host name / IP')
parser.add_argument('-p', dest='port' , type=int, help='port')
parser.add_argument('-t', dest='time' , type=int, help='Time (in seconds) to keep reading data from websocket. After this process will be exit. Default value is 0. For 0 it will run infinitely')
parser.add_argument('-m', dest='msg' , type=int, help='Number of message. Process will exit after receiving Number of messages. Default is 0, means runs for ever.')
args = parser.parse_args()
print(args.ip)
#ws://%s:%s" % (args.ip,args.port)
url = "ws://%s:%s" % (args.ip,args.port)
ws = create_connection(url)
print "Receiving data from the socket..."
tstart = time.time()
nbmsg = 0
for each in ws:
result = ws.recv();
nbmsg += 1
if args.time is not None:
if time.time() > tstart + args.time:
print('Time limit reached.')
sys.exit()
if args.msg is not None and nbmsg >= args.msg:
print('Message limit reached')
sys.exit()
print "Received '%s'" % result
ws.close();
</code></pre>
| 1 | 2016-08-24T08:01:27Z | [
"python",
"websocket",
"argparse"
] |
nginx flask aws 502 Bad Gateway | 39,117,239 | <p>My server is running great yesterday but now it returned a 502 error, how could this happen?</p>
<p>In my access.log shows:</p>
<pre><code>[24/Aug/2016:07:40:29 +0000] "GET /ad/image/414 HTTP/1.1" 502 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
</code></pre>
<p>In my error.log shows:</p>
<pre><code>2016/08/24 07:38:50 [error] 14465#0: *12513 connect() failed (111: Connection refused) while connecting to upstream, client: 123.49.616.74, server: app.example.com.au, request: "GET /ad/image/414 HTTP/1.1", upstream: "http://127.0.0.1:8000/ad/image/414", host: "app.example.com.au"
</code></pre>
<p>This is the result when I run grep:</p>
<pre><code>ubuntu 6856 0.0 0.6 56624 12652 ? S 00:08 0:03 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 6865 0.0 1.8 180832 36892 ? S 00:08 0:00 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 14300 0.0 0.0 10464 948 pts/0 S+ 08:06 0:00 grep --color=auto -i gunicorn
</code></pre>
| -1 | 2016-08-24T07:41:08Z | 39,117,320 | <p>The HTTP status code 502 normally means that the application server Nginx is proxying to is not running. As this is a Flask app I presume this is something like Gunicorn or uwsgi. Check to see if that is running.</p>
<p>I normally use something like Supervisor to ensure that the application server gets restarted automatically if it goes down.</p>
| 1 | 2016-08-24T07:45:47Z | [
"python",
"amazon-web-services",
"nginx",
"flask"
] |
nginx flask aws 502 Bad Gateway | 39,117,239 | <p>My server is running great yesterday but now it returned a 502 error, how could this happen?</p>
<p>In my access.log shows:</p>
<pre><code>[24/Aug/2016:07:40:29 +0000] "GET /ad/image/414 HTTP/1.1" 502 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
</code></pre>
<p>In my error.log shows:</p>
<pre><code>2016/08/24 07:38:50 [error] 14465#0: *12513 connect() failed (111: Connection refused) while connecting to upstream, client: 123.49.616.74, server: app.example.com.au, request: "GET /ad/image/414 HTTP/1.1", upstream: "http://127.0.0.1:8000/ad/image/414", host: "app.example.com.au"
</code></pre>
<p>This is the result when I run grep:</p>
<pre><code>ubuntu 6856 0.0 0.6 56624 12652 ? S 00:08 0:03 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 6865 0.0 1.8 180832 36892 ? S 00:08 0:00 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 14300 0.0 0.0 10464 948 pts/0 S+ 08:06 0:00 grep --color=auto -i gunicorn
</code></pre>
| -1 | 2016-08-24T07:41:08Z | 39,117,324 | <p>It usually happens when the service isn't running.</p>
<p>So I'd bet your flask application or <code>wsgi</code> isn't running.</p>
| 1 | 2016-08-24T07:45:59Z | [
"python",
"amazon-web-services",
"nginx",
"flask"
] |
nginx flask aws 502 Bad Gateway | 39,117,239 | <p>My server is running great yesterday but now it returned a 502 error, how could this happen?</p>
<p>In my access.log shows:</p>
<pre><code>[24/Aug/2016:07:40:29 +0000] "GET /ad/image/414 HTTP/1.1" 502 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
</code></pre>
<p>In my error.log shows:</p>
<pre><code>2016/08/24 07:38:50 [error] 14465#0: *12513 connect() failed (111: Connection refused) while connecting to upstream, client: 123.49.616.74, server: app.example.com.au, request: "GET /ad/image/414 HTTP/1.1", upstream: "http://127.0.0.1:8000/ad/image/414", host: "app.example.com.au"
</code></pre>
<p>This is the result when I run grep:</p>
<pre><code>ubuntu 6856 0.0 0.6 56624 12652 ? S 00:08 0:03 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 6865 0.0 1.8 180832 36892 ? S 00:08 0:00 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 14300 0.0 0.0 10464 948 pts/0 S+ 08:06 0:00 grep --color=auto -i gunicorn
</code></pre>
| -1 | 2016-08-24T07:41:08Z | 39,117,338 | <p>I believe that <code>gunicorn</code> is not running on your system. Check the status of gunicorn process, and if it is not runningm start the process </p>
| 1 | 2016-08-24T07:46:51Z | [
"python",
"amazon-web-services",
"nginx",
"flask"
] |
nginx flask aws 502 Bad Gateway | 39,117,239 | <p>My server is running great yesterday but now it returned a 502 error, how could this happen?</p>
<p>In my access.log shows:</p>
<pre><code>[24/Aug/2016:07:40:29 +0000] "GET /ad/image/414 HTTP/1.1" 502 583 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36"
</code></pre>
<p>In my error.log shows:</p>
<pre><code>2016/08/24 07:38:50 [error] 14465#0: *12513 connect() failed (111: Connection refused) while connecting to upstream, client: 123.49.616.74, server: app.example.com.au, request: "GET /ad/image/414 HTTP/1.1", upstream: "http://127.0.0.1:8000/ad/image/414", host: "app.example.com.au"
</code></pre>
<p>This is the result when I run grep:</p>
<pre><code>ubuntu 6856 0.0 0.6 56624 12652 ? S 00:08 0:03 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 6865 0.0 1.8 180832 36892 ? S 00:08 0:00 /home/www/carbuzzz_admin/env/bin/python /home/www/carbuzzz_admin/env/bin/gunicorn application:application -b localhost:4215
ubuntu 14300 0.0 0.0 10464 948 pts/0 S+ 08:06 0:00 grep --color=auto -i gunicorn
</code></pre>
| -1 | 2016-08-24T07:41:08Z | 39,117,535 | <p>Looking at your <code>error</code> it mentions <code>123.49.616.74, server: app.example.com.au</code>, I think within your configuration you have mentioned the IP address of your server. Replace that with your local IP i.e <code>127.0.0.1</code>. </p>
<p>Since you are making the request as <code>127.0.0.1</code> in your browser and <code>host</code> specified in the Nginx configuration is: "app.example.com.au". Due to this connection will be refused by the server.</p>
| 1 | 2016-08-24T07:57:17Z | [
"python",
"amazon-web-services",
"nginx",
"flask"
] |
Python xml generation automatically | 39,117,292 | <p>I have suppose to save my data which derived from my script to xml. I need to automate it. Think if there is a array so i need to add items of this array to xml as its elements one by one automatically. Is there is any way to do this.</p>
<p>this is my python script used to pass data to xml</p>
<pre><code>if score >= 0.4:
print('%s (score = %.5f)' % (human_string, score))
predicted_list.append(human_string)
print (image)
data_management.create_xml.write_xml(predicted_list, image)
</code></pre>
<p>here is my xml generation code</p>
<pre><code>def write_xml(predicted_list, frameno):
root = ET.Element("root")
doc = ET.SubElement(root, "test")
ET.SubElement(doc, frameno, name="frame").text = predicted_list
tree = ET.ElementTree(root)
tree.write("/opt/lampp/htdocs/video_frames/test.xml")
</code></pre>
| 0 | 2016-08-24T07:44:20Z | 39,117,499 | <p>Maybe try something like this :</p>
<pre><code>ET.SubElement(doc, frameno, name="frame").text = ' - '.join(predicted_list)
</code></pre>
| 0 | 2016-08-24T07:54:55Z | [
"python",
"xml"
] |
Fitting and aligning two lists together in python | 39,117,304 | <p>I'm trying to match up two lists made up of tuples (x,y,z). I need to fit them together based on the z-values, and remove any tuples containing z-values that are not common to both lists. </p>
<p>Input: </p>
<pre><code>a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b = [(0,1,1),(2,3,2),(3,4,4)]
</code></pre>
<p>Output:</p>
<pre><code>a1 = [(3,4,1),(5,3,2)]
b1 = [(0,1,1),(2,3,2)]
</code></pre>
<p>EDIT: z-values will be integers, not repeated</p>
| 1 | 2016-08-24T07:45:00Z | 39,117,537 | <p>This will partially satisfy your requirement and be a good starting point.
From here you can tweak it to return the cases of repetitions and how to order your stuff.</p>
<pre><code>a= [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b= [(0,1,1),(2,3,2),(3,4,4)]
a1=[]
b1=[]
for i in a:
for j in b:
if i[2] == j[2]:
a1.append(i)
b1.append(j)
</code></pre>
| 0 | 2016-08-24T07:57:27Z | [
"python",
"python-3.x"
] |
Fitting and aligning two lists together in python | 39,117,304 | <p>I'm trying to match up two lists made up of tuples (x,y,z). I need to fit them together based on the z-values, and remove any tuples containing z-values that are not common to both lists. </p>
<p>Input: </p>
<pre><code>a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b = [(0,1,1),(2,3,2),(3,4,4)]
</code></pre>
<p>Output:</p>
<pre><code>a1 = [(3,4,1),(5,3,2)]
b1 = [(0,1,1),(2,3,2)]
</code></pre>
<p>EDIT: z-values will be integers, not repeated</p>
| 1 | 2016-08-24T07:45:00Z | 39,117,664 | <pre><code>common_z = set([tup[2] for tup in a]).intersection([tup[2] for tup in b])
a_ = [tup for tup in a if tup[2] in common_z]
b_ = [tup for tup in b if tup[2] in common_z]
>>> a_
[(3, 4, 1), (5, 3, 2)]
>>> b_
[(0, 1, 1), (2, 3, 2)]
</code></pre>
| 4 | 2016-08-24T08:02:44Z | [
"python",
"python-3.x"
] |
Fitting and aligning two lists together in python | 39,117,304 | <p>I'm trying to match up two lists made up of tuples (x,y,z). I need to fit them together based on the z-values, and remove any tuples containing z-values that are not common to both lists. </p>
<p>Input: </p>
<pre><code>a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b = [(0,1,1),(2,3,2),(3,4,4)]
</code></pre>
<p>Output:</p>
<pre><code>a1 = [(3,4,1),(5,3,2)]
b1 = [(0,1,1),(2,3,2)]
</code></pre>
<p>EDIT: z-values will be integers, not repeated</p>
| 1 | 2016-08-24T07:45:00Z | 39,117,740 | <p>You may achieve it by using <code>set</code> as:</p>
<pre><code>>>> a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
>>> b = [(0,1,1),(2,3,2),(3,4,4)]
# Intersection of z co-ordinates in 'a' and 'b' list
>>> z_ab = set(map(lambda x: x[2], a)) & set(map(lambda x: x[2], b))
>>> new_a = filter(lambda x: x[2] in z_ab, a)
# new_a = [(3, 4, 1), (5, 3, 2)]
>>> new_b = filter(lambda x: x[2] in z_ab, b)
# new_b = [(0, 1, 1), (2, 3, 2)]
</code></pre>
| 0 | 2016-08-24T08:06:27Z | [
"python",
"python-3.x"
] |
Fitting and aligning two lists together in python | 39,117,304 | <p>I'm trying to match up two lists made up of tuples (x,y,z). I need to fit them together based on the z-values, and remove any tuples containing z-values that are not common to both lists. </p>
<p>Input: </p>
<pre><code>a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b = [(0,1,1),(2,3,2),(3,4,4)]
</code></pre>
<p>Output:</p>
<pre><code>a1 = [(3,4,1),(5,3,2)]
b1 = [(0,1,1),(2,3,2)]
</code></pre>
<p>EDIT: z-values will be integers, not repeated</p>
| 1 | 2016-08-24T07:45:00Z | 39,117,945 | <pre><code>a = [(0,0,0),(3,4,1),(5,3,2),(1,2,3)]
b = [(0,1,1),(2,3,2),(3,4,4)]
a_dict = {z:[x,y] for x,y,z in a}
b_dict = {z:[x,y] for x,y,z in b}
a1=[]
b1=[]
for item in a_dict.keys():
if item in b_dict.keys():
a_dict[item].append(item)
a1.append(tuple(a_dict[item]))
b_dict[item].append(item)
b1.append(tuple(b_dict[item]))
print(a1)
print(b1)
</code></pre>
| 0 | 2016-08-24T08:16:25Z | [
"python",
"python-3.x"
] |
How to delete records of main model when records of child model (created using inherits main model) deleted in odoo | 39,117,421 | <p>In my odoo application, i have Two models. One main model and a child model.</p>
<p>main model</p>
<pre><code>class main_model(models.Model):
_name = 'main.model'
</code></pre>
<p>My child model is</p>
<pre><code>class child_model(models.Model):
_inherits = {
'main.model: 'main_ref'
}
_name = 'child.model'
main_ref = fields.Many2one('main.model')
</code></pre>
<p>With this coding. When i create a record in child model, a record will be created in main model also. But when i delete a record in child model corresponding record in main also should be deleted.</p>
<p>For this what i done is...</p>
<pre><code>@api.multi
def unlink(self):
self.main_ref.unlink()
return super(child_model, self).unlink()
</code></pre>
<p>But this is not working. It is showing error as..</p>
<pre><code>The operation cannot be completed, probably due to the following:- deletion: you may be trying to delete a record while other records still reference it- creation/update: a mandatory field is not correctly set
</code></pre>
| 0 | 2016-08-24T07:51:09Z | 39,118,249 | <p>Use attribute <strong>ondelete='cascade'</strong> in fields definition.</p>
<pre><code>main_ref = fields.Many2one('main.model', ondelete='cascade' )
</code></pre>
<p>Hope it will solve your problem.</p>
| 1 | 2016-08-24T08:32:07Z | [
"python",
"odoo-8"
] |
How to interpret list as an integer in python | 39,117,445 | <p>I am fetching data from MySQL database which is then converted to a list in python.
Since the data being fetched is of integer type, I am passing it as index to find character within a string.
I am getting the following error </p>
<pre><code>TypeError: 'list' object cannot be interpreted as an index
</code></pre>
<p>How can I treat my list as an index and pass it to a string to find a character within a text?</p>
<p>Here is my code </p>
<pre><code>import urllib2
import MySQLdb as mdb
con = mdb.connect('localhost', 'root', 'root', 'sample_db');
with con:
cur1 = con.cursor()
cur1.execute("SELECT site_id FROM positive_outcomes")
row1 = [item[0] for item in cur1.fetchall()]
site_id_list = row1
uniprot_url = "http://www.uniprot.org/uniprot/" # constant Uniprot Namespace
def get_fasta(site):
with open('Q9L422_112.fasta', 'r') as myfile:
data=myfile.read()
str1 = data[site:site+20]
temp = data[site-1:site-1-20:-1]
str2 = temp[::-1]
print str2+str1
def main():
# iterate over the list of IDS
for k,v in enumerate(site_id_list):
get_fasta(v)
# or read from a text file
# input_file = open("positive_copy.txt").readlines()
# get_fasta(input_file)
if __name__ == '__main__':
main()
</code></pre>
| -1 | 2016-08-24T07:52:14Z | 39,117,670 | <p>You can´t handle a list like an int.</p>
<p>Guessing you can recover one value of the list (and parse it if it is needed) or use a dictionary for assigning int to a list:</p>
<pre><code>var dict = {1: your_list}
</code></pre>
<p>or:</p>
<pre><code>int i = (int)your_list[i]
</code></pre>
| 0 | 2016-08-24T08:03:02Z | [
"python"
] |
How to interpret list as an integer in python | 39,117,445 | <p>I am fetching data from MySQL database which is then converted to a list in python.
Since the data being fetched is of integer type, I am passing it as index to find character within a string.
I am getting the following error </p>
<pre><code>TypeError: 'list' object cannot be interpreted as an index
</code></pre>
<p>How can I treat my list as an index and pass it to a string to find a character within a text?</p>
<p>Here is my code </p>
<pre><code>import urllib2
import MySQLdb as mdb
con = mdb.connect('localhost', 'root', 'root', 'sample_db');
with con:
cur1 = con.cursor()
cur1.execute("SELECT site_id FROM positive_outcomes")
row1 = [item[0] for item in cur1.fetchall()]
site_id_list = row1
uniprot_url = "http://www.uniprot.org/uniprot/" # constant Uniprot Namespace
def get_fasta(site):
with open('Q9L422_112.fasta', 'r') as myfile:
data=myfile.read()
str1 = data[site:site+20]
temp = data[site-1:site-1-20:-1]
str2 = temp[::-1]
print str2+str1
def main():
# iterate over the list of IDS
for k,v in enumerate(site_id_list):
get_fasta(v)
# or read from a text file
# input_file = open("positive_copy.txt").readlines()
# get_fasta(input_file)
if __name__ == '__main__':
main()
</code></pre>
| -1 | 2016-08-24T07:52:14Z | 39,117,690 | <p>So I guess the exception is here</p>
<pre><code>row1 = [item[0] for item in cur1.fetchall()]
</code></pre>
<p>What you want is probably</p>
<pre><code>row1 = [(item[0] for item in cur1.fetchall())[0]]
</code></pre>
<p>Still, it's not very efficient. Use <code>cursor.fetchone()</code> instead</p>
<pre><code>row1 = [cur1.fetchone()[0]]
</code></pre>
<p>It's still not safe, though, since <code>curl.fetchone()</code> may returns <code>None</code> if no results found.</p>
| 0 | 2016-08-24T08:03:57Z | [
"python"
] |
Printing a corresponding value of a column in Pandas | 39,117,547 | <p>I have a table with 3 parameters "Date", "Time" and "Value". I want to add a new column to this table which has values corresponding to "Time" after every <strong>10 minutes</strong>.</p>
<p><img src="http://i.stack.imgur.com/UYHu5.png" alt="Image"></p>
<p>I though of creating a new column with Seconds for ease.</p>
<p>Now I want a new column suppose "x" which would have the first vlaue and the values which correspond to the "Time" only after 10 minutes. What can we do in this case? </p>
| 1 | 2016-08-24T07:57:48Z | 39,117,985 | <p>IIUC you can first remove <code>dates</code> and <code>hours</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sub.html" rel="nofollow"><code>sub</code></a>, add <code>10 Min</code>, then convert to <code>miliseconds</code> and divide <code>1000</code>:</p>
<pre><code>df = pd.DataFrame({'Time': ['08:01:29:12','08:03:29:12','08:05:29:12'],
'Date':['1/2/2016','1/2/2016','1/2/2016']})
df['Date'] = pd.to_datetime(df.Date)
df['Time'] = pd.to_datetime(df.Time, format='%H:%M:%S:%f')
</code></pre>
<hr>
<pre><code>df['new'] = df.Time.sub(df.Time.values.astype('<M8[h]') +
pd.offsets.Minute(10)).astype('timedelta64[ms]') / 1000
print (df)
Date Time new
0 2016-01-02 1900-01-01 08:01:29.120 689.12
1 2016-01-02 1900-01-01 08:03:29.120 809.12
2 2016-01-02 1900-01-01 08:05:29.120 929.12
</code></pre>
<p>Or:</p>
<pre><code>df['new'] = df.Time.sub(df.Time.values.astype('<M8[h]') +
pd.to_timedelta('00:10:00')).astype('timedelta64[ms]') / 1000
print (df)
Date Time new
0 2016-01-02 1900-01-01 08:01:29.120 689.12
1 2016-01-02 1900-01-01 08:03:29.120 809.12
2 2016-01-02 1900-01-01 08:05:29.120 929.12
</code></pre>
| 0 | 2016-08-24T08:18:40Z | [
"python",
"datetime",
"pandas",
"dataframe",
"timedelta"
] |
The file copied by python can not be access by another process | 39,117,734 | <p>I use python <strong>shuitl.copy2</strong> method to copy some file from a share folder, after copy success there will start a process which need access these copied file. <strong>The question</strong> is sometimes there have a file can not be access by the new process, <strong>Error 32</strong> is reported. My script is running circularly, but the issue does not happen every time. Does any one know what the problem is?</p>
<p>Update some simple code. Specific request trigger the <em>MyThread</em> run, after the copy end, another excutable application will use these files and the applicaiton report Error32.</p>
<pre><code>class MyThread(threading.Thread):
def __init__(self, fileList, destFolder):
threading.Thread.__init__(self)
def run(self):
for fileItem in self.fileList:
if self.stop:
break
try:
self.__copyFile(fileItem, localDestFolder)
self.successList.append(fileItem)
except Exception, e:
self.errorList.append((fileItem, str(e)))
@staticmethod
def __copyFile(source, destination):
print 'Use shutil to copy file %s' % source
shutil.copy2(source, destination)
print 'Copy end'
</code></pre>
| 0 | 2016-08-24T08:06:12Z | 39,117,794 | <p>The file pointer is probably not closed properly.</p>
<p>Maybe add a little <code>time.sleep()</code> between the copy and the start of the process.</p>
| 0 | 2016-08-24T08:08:45Z | [
"python",
"file",
"copy",
"shutil"
] |
The file copied by python can not be access by another process | 39,117,734 | <p>I use python <strong>shuitl.copy2</strong> method to copy some file from a share folder, after copy success there will start a process which need access these copied file. <strong>The question</strong> is sometimes there have a file can not be access by the new process, <strong>Error 32</strong> is reported. My script is running circularly, but the issue does not happen every time. Does any one know what the problem is?</p>
<p>Update some simple code. Specific request trigger the <em>MyThread</em> run, after the copy end, another excutable application will use these files and the applicaiton report Error32.</p>
<pre><code>class MyThread(threading.Thread):
def __init__(self, fileList, destFolder):
threading.Thread.__init__(self)
def run(self):
for fileItem in self.fileList:
if self.stop:
break
try:
self.__copyFile(fileItem, localDestFolder)
self.successList.append(fileItem)
except Exception, e:
self.errorList.append((fileItem, str(e)))
@staticmethod
def __copyFile(source, destination):
print 'Use shutil to copy file %s' % source
shutil.copy2(source, destination)
print 'Copy end'
</code></pre>
| 0 | 2016-08-24T08:06:12Z | 39,327,474 | <p>I got it! The issue happened because another process created by the parent process during the copy thread coping files. so the file handle of one copied file be passed to the new process, and the new process keeps handle the file handle until it end. So during the process running, the file can not be access by other applications. That's it.</p>
| 0 | 2016-09-05T09:22:53Z | [
"python",
"file",
"copy",
"shutil"
] |
Settings for timedata in seaborn FacetGrid plots | 39,117,835 | <p>I want to plot data monthly and show year label once per each year.
Here is the data:</p>
<pre><code>timedates = ['2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01', '2013-05-01', '2013-06-01', '2013-07-01',
'2013-08-01', '2013-09-01', '2013-10-01', '2013-11-01', '2013-12-01', '2014-01-01', '2014-02-01',
'2014-03-01', '2014-04-01', '2014-05-01', '2014-06-01', '2014-07-01', '2014-08-01', '2014-09-01',
'2014-10-01', '2014-11-01', '2014-12-01']
timedates = pd.to_datetime(timedates)
amount = [38870, 42501, 44855, 44504, 41194, 42087, 43687, 42347, 45098, 43783, 47275, 49767,
39502, 35951, 47059, 47639, 44236, 40826, 46087, 41462, 38384, 41452, 36811, 37943]
types = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C',
'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df_x = pd.DataFrame({'timedates': timedates, 'amount': amount, 'types': types})
</code></pre>
<p>I found out how to do that with matplotlib</p>
<pre><code>plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.plot_date(df_x.timedates, df_x.amount, 'v-')
ax.xaxis.set_minor_locator(md.MonthLocator())
ax.xaxis.set_minor_formatter(md.DateFormatter('%m'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(md.YearLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('\n\n%Y'))
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/iWUkc.png" rel="nofollow"><img src="http://i.stack.imgur.com/iWUkc.png" alt="Plot data monthly with labels"></a></p>
<p>Now I move to seaborn to take into account different types of data. Is it possible to have the same style of ticks using seaborn FacetGrid?</p>
<pre><code>g = sns.FacetGrid(df_x, hue='types', size=8, aspect=1.5)
g.map(sns.pointplot, 'timedates', 'amount')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/cxQFC.png" rel="nofollow"><img src="http://i.stack.imgur.com/cxQFC.png" alt="Seaborn timedata ticks"></a>
When I try to apply ticks formatting - they just disappear. </p>
| 3 | 2016-08-24T08:10:38Z | 39,121,507 | <p>By far, I did it manually. Just separated lines by type and plotted them together. </p>
<p>Changed this line </p>
<pre><code>ax.plot_date(df_x.timedates, df_x.amount, 'v-')
</code></pre>
<p>Into three plot-lines:</p>
<pre><code>types_levels = df_x.types.unique()
for i in types_levels:
ax.plot_date(df_x[df_x.types==i].timedates, df_x[df_x.types==i].amount, 'v-')
plt.legend(types_levels)
</code></pre>
<p><a href="http://i.stack.imgur.com/TSRwy.png" rel="nofollow"><img src="http://i.stack.imgur.com/TSRwy.png" alt="Multiple lines on plot_date"></a></p>
<p>Though it's not an answer, I can't use other advantages of seaborn FacetGrid.</p>
| 0 | 2016-08-24T11:01:40Z | [
"python",
"matplotlib",
"plot",
"time-series",
"seaborn"
] |
Settings for timedata in seaborn FacetGrid plots | 39,117,835 | <p>I want to plot data monthly and show year label once per each year.
Here is the data:</p>
<pre><code>timedates = ['2013-01-01', '2013-02-01', '2013-03-01', '2013-04-01', '2013-05-01', '2013-06-01', '2013-07-01',
'2013-08-01', '2013-09-01', '2013-10-01', '2013-11-01', '2013-12-01', '2014-01-01', '2014-02-01',
'2014-03-01', '2014-04-01', '2014-05-01', '2014-06-01', '2014-07-01', '2014-08-01', '2014-09-01',
'2014-10-01', '2014-11-01', '2014-12-01']
timedates = pd.to_datetime(timedates)
amount = [38870, 42501, 44855, 44504, 41194, 42087, 43687, 42347, 45098, 43783, 47275, 49767,
39502, 35951, 47059, 47639, 44236, 40826, 46087, 41462, 38384, 41452, 36811, 37943]
types = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C',
'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df_x = pd.DataFrame({'timedates': timedates, 'amount': amount, 'types': types})
</code></pre>
<p>I found out how to do that with matplotlib</p>
<pre><code>plt.style.use('ggplot')
fig, ax = plt.subplots()
ax.plot_date(df_x.timedates, df_x.amount, 'v-')
ax.xaxis.set_minor_locator(md.MonthLocator())
ax.xaxis.set_minor_formatter(md.DateFormatter('%m'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(md.YearLocator())
ax.xaxis.set_major_formatter(md.DateFormatter('\n\n%Y'))
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/iWUkc.png" rel="nofollow"><img src="http://i.stack.imgur.com/iWUkc.png" alt="Plot data monthly with labels"></a></p>
<p>Now I move to seaborn to take into account different types of data. Is it possible to have the same style of ticks using seaborn FacetGrid?</p>
<pre><code>g = sns.FacetGrid(df_x, hue='types', size=8, aspect=1.5)
g.map(sns.pointplot, 'timedates', 'amount')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/cxQFC.png" rel="nofollow"><img src="http://i.stack.imgur.com/cxQFC.png" alt="Seaborn timedata ticks"></a>
When I try to apply ticks formatting - they just disappear. </p>
| 3 | 2016-08-24T08:10:38Z | 39,121,567 | <p>You could format the <code>xticks</code> to just include the <code>month</code> and <code>year</code> of the <code>datetime</code> object and get a <code>pointplot</code> with <code>xticks</code> corresponding to the position of scatter plot points.</p>
<pre><code>df['timedates'] = df['timedates'].map(lambda x: x.strftime('%Y-%m'))
def plot(x, y, data=None, label=None, **kwargs):
sns.pointplot(x, y, data=data, label=label, **kwargs)
g = sns.FacetGrid(df, hue='types', size=8, aspect=1.5)
g.map_dataframe(plot, 'timedates', 'amount')
plt.show()
</code></pre>
<p><a href="http://i.stack.imgur.com/7zJDG.png" rel="nofollow"><img src="http://i.stack.imgur.com/7zJDG.png" alt="Image"></a></p>
| 2 | 2016-08-24T11:04:33Z | [
"python",
"matplotlib",
"plot",
"time-series",
"seaborn"
] |
Assigning strings to a variable in python | 39,117,843 | <p>Consider the below string which will be given as the input to a function.</p>
<blockquote>
<p>01 02 01 <strong>0D A1 D6 72 02 00</strong> 01 00 00 00 00 53 73 F2</p>
</blockquote>
<p>The highlighted part is the address I need. </p>
<p>If the preceding byte is 1 then I have to take only 6 octet and assign it to a variable. </p>
<p>If it is more than 1 the I should read 6 * Num(preceding value) and assign 6 octets for each variable. </p>
<p>Currently I am assigning it statically.</p>
<pre><code>def main(line_input):
Device = ' '.join(line_input[9:3:-1])
Length = line_input[2]
var1 = line_input[3]
main("01 02 02 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2")
</code></pre>
<p>Can this be done?</p>
| 0 | 2016-08-24T08:11:04Z | 39,118,349 | <p>Here I think this does it, let me know if there is anything that needs changing: </p>
<pre><code>import string
def address_extract(line_input):
line_input = string.split(line_input, ' ')
length = 6 * int(line_input[2])
device_list = []
for x in range(3, 3+length, 6):
if x+6 > len(line_input):
print "Length multiplier too long for input string"
else:
device_list.append(' '.join(line_input[x:x+6]))
return device_list
print address_extract("01 02 02 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2")
#output = ['0D A1 D6 72 02 00', '01 00 00 00 00 53']
</code></pre>
| 0 | 2016-08-24T08:37:37Z | [
"python",
"python-2.7"
] |
Assigning strings to a variable in python | 39,117,843 | <p>Consider the below string which will be given as the input to a function.</p>
<blockquote>
<p>01 02 01 <strong>0D A1 D6 72 02 00</strong> 01 00 00 00 00 53 73 F2</p>
</blockquote>
<p>The highlighted part is the address I need. </p>
<p>If the preceding byte is 1 then I have to take only 6 octet and assign it to a variable. </p>
<p>If it is more than 1 the I should read 6 * Num(preceding value) and assign 6 octets for each variable. </p>
<p>Currently I am assigning it statically.</p>
<pre><code>def main(line_input):
Device = ' '.join(line_input[9:3:-1])
Length = line_input[2]
var1 = line_input[3]
main("01 02 02 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2")
</code></pre>
<p>Can this be done?</p>
| 0 | 2016-08-24T08:11:04Z | 39,118,535 | <p>Here is some code that I hope will help you. I tried to add many comments to explain what is happening</p>
<pre><code>import binascii
import struct
#note python 3 behaves differently and won't work with this code (personnaly I find it easyer for strings convertion to bytes)
def main(line_input):
formated_line = line_input.split(" ") #I start by cutting the input on each space character
print formated_line #the output is a list. Each element is composed of 2 chars
formated_line = [binascii.unhexlify(xx) for xx in formated_line] #create a list composed of unhelified bytes of each elements of the original list
print formated_line #the output is a list of bytes char
#can be done in one step but I try to be clearer as you are nee to python (moereover this is easyer in python-3.x)
formated_line = map(ord, formated_line) #convert to a list of int (this is not needed in python 3)
print formated_line
Length = formated_line[2] #this is an int
unformated_var1 = formated_line[3:3+(6*length)] #keep only interesting data
#now you can format your address
main("01 02 02 0D A1 D6 72 02 00 01 00 00 00 00 53 73 F2")
#if the input comes from a machine and not a human, they could exchange 17bytes instead of (17x3)characters
#main("\x01\x02\x02\x0D\xA1\xD6\x72\x02\x00\x01\x00\x00\x00\x00\x53\x73\xF2")
#then the parsing could be done with struct.unpack
</code></pre>
| 0 | 2016-08-24T08:45:48Z | [
"python",
"python-2.7"
] |
Download files after opening a webpage using Python | 39,117,979 | <p>I have opened a webpage('<a href="http://example.com/protected_page.php" rel="nofollow">http://example.com/protected_page.php</a>') using Python's requests Library.</p>
<pre><code>from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post('http://example.com/login.php', data=payload)
response = c.get('http://example.com/protected_page.php')
</code></pre>
<p>Now there are around 15 links on that page to download files.</p>
<p>I wish to download files from only 2 links(say, linkA and linkB).</p>
<p>How can I specify this in my code, so that the 2 files get downloaded when I run my code.</p>
| -1 | 2016-08-24T08:18:14Z | 39,118,343 | <p>Can you please give more information about these links ?</p>
<p>Are these linkA and linkB always the same links ?
If yes then you can use :</p>
<pre><code>r = requests.get(linkA, stream=True)
</code></pre>
<p>If the url links are not the same all the time , then maybe you can find another way, using the order of the link maybe, for instance if the linkA and linkB is always the first and the second link on the page etc.</p>
<p>Another way is to use any unique class name or id from the page. But it would be better if you could provide us more informations.</p>
| 0 | 2016-08-24T08:37:14Z | [
"python",
"web-scraping"
] |
Download files after opening a webpage using Python | 39,117,979 | <p>I have opened a webpage('<a href="http://example.com/protected_page.php" rel="nofollow">http://example.com/protected_page.php</a>') using Python's requests Library.</p>
<pre><code>from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post('http://example.com/login.php', data=payload)
response = c.get('http://example.com/protected_page.php')
</code></pre>
<p>Now there are around 15 links on that page to download files.</p>
<p>I wish to download files from only 2 links(say, linkA and linkB).</p>
<p>How can I specify this in my code, so that the 2 files get downloaded when I run my code.</p>
| -1 | 2016-08-24T08:18:14Z | 39,118,867 | <p>In fact what you are referring is more precisely called as web scrapping , in which one can scrape some specific contents from the given web site:</p>
<blockquote>
<p>Web scraping is a computer software technique of extracting
information from websites. This technique mostly focuses on the
transformation of unstructured data (HTML format) on the web into
structured data (database or spreadsheet).</p>
</blockquote>
<p>without knowing the HTML semantics it is not possible to give you a snap of code , for what you are looking for. But here i can advice you some of the way using which you can do web scrape from your site.</p>
<p><strong>1. Non-programming way:</strong></p>
<blockquote>
<p>For those of you, who need a non-programming way to extract
information out of web pages, you can also look at <a href="http://import.io" rel="nofollow">import.io</a> . It
provides a GUI driven interface to perform all basic web scraping
operations.</p>
</blockquote>
<p><strong>2. Programmers way:</strong></p>
<p>You may find many libraries to perform one function using python. Hence, it is necessary to find the best to use library. I prefer BeautifulSoup , since it is easy and intuitive to work on. Precisely, you use two Python modules for scraping data:</p>
<ul>
<li><blockquote>
<p>Urllib2: It is a Python module which can be used for fetching URLs. It defines functions and classes to help with URL actions (basic
and digest authentication, redirections, cookies, etc). For more
detail refer to the documentation page.</p>
</blockquote></li>
</ul>
<p><br/></p>
<ul>
<li><blockquote>
<p>BeautifulSoup: It is an incredible tool for pulling out information
from a webpage. You can use it to extract tables, lists, paragraph and
you can also put filters to extract information from web pages. the latest available version is BeautifulSoup 4. You can look
at the installation instruction in its documentation page.</p>
</blockquote></li>
</ul>
<p>BeautifulSoup does not fetch the web page for us. Thatâs why, need to use urllib2 in combination with the BeautifulSoup library.</p>
<p>Python has several other options for HTML scraping in addition to BeatifulSoup. Here are some others:</p>
<ul>
<li><em><a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a></em></li>
<li><em><a href="http://arshaw.com/scrapemark/" rel="nofollow">scrapemark</a></em></li>
<li><em><a href="http://scrapy.org/" rel="nofollow">scrapy</a></em></li>
</ul>
| 0 | 2016-08-24T09:01:14Z | [
"python",
"web-scraping"
] |
Python 3, Variables in loops | 39,117,991 | <p>I'm new to python, and just playing around, getting to learn different features with this code.(Please read note)</p>
<pre><code>less = ["science", "maths"]
for i in range(0,len(less)):
a = ("You have got; " + (less[i]))
b = (a)
#By putting in print here I figured out that it added science first then maths overrides it.
print(b)
print (b)
</code></pre>
<p>At the moment when you print the string at the moment it says:</p>
<p>"You have got; maths"</p>
<p>But i was trying to get it to say:</p>
<p>"You have got; science maths"</p>
<p>Basically, i'm trying to find a way to just add to the variable and not one override the other so when i print it at the end it will have both science and maths.</p>
<p>I am going to expand upon it which is why i need to have the length of the list is the loop and etc.</p>
| 1 | 2016-08-24T08:18:54Z | 39,118,047 | <p>You can iterate simply over objects in the list and make <code>print</code> statement not terminate the line. </p>
<pre><code>less = ["science", "maths"]
print ("You have got; ", end="")
for i in less:
print (i, end=" ")
</code></pre>
| 1 | 2016-08-24T08:21:25Z | [
"python",
"loops",
"python-3.x",
"variables"
] |
Python 3, Variables in loops | 39,117,991 | <p>I'm new to python, and just playing around, getting to learn different features with this code.(Please read note)</p>
<pre><code>less = ["science", "maths"]
for i in range(0,len(less)):
a = ("You have got; " + (less[i]))
b = (a)
#By putting in print here I figured out that it added science first then maths overrides it.
print(b)
print (b)
</code></pre>
<p>At the moment when you print the string at the moment it says:</p>
<p>"You have got; maths"</p>
<p>But i was trying to get it to say:</p>
<p>"You have got; science maths"</p>
<p>Basically, i'm trying to find a way to just add to the variable and not one override the other so when i print it at the end it will have both science and maths.</p>
<p>I am going to expand upon it which is why i need to have the length of the list is the loop and etc.</p>
| 1 | 2016-08-24T08:18:54Z | 39,118,061 | <p>To achieve this, use <code>join</code>:</p>
<pre><code>>>> less = ["science", "maths"]
>>> print("You have got; %s" % ' '.join(less))
You have got; science maths
</code></pre>
<p>Explanation: <code>join</code> joins the elements in the list as a single <code>string</code> which you may add at the end of your required string</p>
| 0 | 2016-08-24T08:22:18Z | [
"python",
"loops",
"python-3.x",
"variables"
] |
Python 3, Variables in loops | 39,117,991 | <p>I'm new to python, and just playing around, getting to learn different features with this code.(Please read note)</p>
<pre><code>less = ["science", "maths"]
for i in range(0,len(less)):
a = ("You have got; " + (less[i]))
b = (a)
#By putting in print here I figured out that it added science first then maths overrides it.
print(b)
print (b)
</code></pre>
<p>At the moment when you print the string at the moment it says:</p>
<p>"You have got; maths"</p>
<p>But i was trying to get it to say:</p>
<p>"You have got; science maths"</p>
<p>Basically, i'm trying to find a way to just add to the variable and not one override the other so when i print it at the end it will have both science and maths.</p>
<p>I am going to expand upon it which is why i need to have the length of the list is the loop and etc.</p>
| 1 | 2016-08-24T08:18:54Z | 39,118,066 | <pre><code>less = ["science", "maths"]
print ('You have got; {}'.format(' '.join(less)))
</code></pre>
| 1 | 2016-08-24T08:22:37Z | [
"python",
"loops",
"python-3.x",
"variables"
] |
XLRDError when reading xls files | 39,118,056 | <p>I tried reading excel files by the following code:</p>
<pre><code>import os
import xlrd
files = os.listdir(".")[1:101]
for file in files:
workbook = xlrd.open_workbook(file)
</code></pre>
<p>but I got an error message like this.</p>
<blockquote>
<p>XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\r\n\r\n\r\n\r\n'</p>
</blockquote>
<p>So I tried opening the files one by one.</p>
<p>And I found files named like this are readable,
"<strong>14.08.01-08.07.xlsx.xlsx</strong>"
but files named like this format are not readable. "<strong>14.08.22-08.28.xlsx.xls</strong>"</p>
<p>So I opened the files and found that files with extension "<strong>xlsx.xls</strong>" have problem with encoding. </p>
<p>These files include Korean characters, so I tried opening them by changing encoding into utf-8, in vain.</p>
<p>In conclusion I think I cannot read <strong>xlsx.xls</strong> files because of the encoding problem. </p>
<p>Is there anyway to solve this sort of problem?</p>
| 0 | 2016-08-24T08:22:06Z | 39,119,373 | <p>Try <code>xlrd.open_workbook(file, encoding_override="utf-8")</code></p>
| 1 | 2016-08-24T09:25:25Z | [
"python",
"encoding",
"xlrd"
] |
Using javascript to update HTML in python loop | 39,118,093 | <p>I'm currently trying to integrate a progress bar to my website. I've successfully put it in my web page, and I am trying to animate it now.</p>
<p>I have a js script that updates the progress bar every second, which is exactly what I want, but the problem is that if you refresh the page, the progress bar gets back to the beginning, even if it was in progress when the page was refreshed.</p>
<p>So I've decided to use python, to start a thread, so refreshing the page would not make the progress bar going back to 0%, and that is basically a loop that calculates the percentage of progress every second.</p>
<p>I'm now trying to find a way to make my progress bar moving by changing the HTML and the CSS every second.</p>
<p>So, my question is : Can I call a js function from my python thread?
And if it's not possible, is there a way to update HTML directly from python? Like a library or something?</p>
<p>If you have any other idea about this, do not hesitate.</p>
<p>If you wonder how the code looks like, here is a part of the python : </p>
<pre><code>print "starting test"
while s <= total:
percent = (100 * s) / total
print percent
res["data"]["value"] = percent
//!\\-->Want to send RES to JS
time.sleep(1)
s = s + 1
print "test is over"
</code></pre>
<p>and here is a part of the js : </p>
<pre><code>if (data.type == "init") {
console.log("Receiving Init info");
}
else if (data.type == "record") {
console.log("Receiving record info");
if (data.data.object == "progress-bar") {
var elem = document.getElementById("myBar");
elem.style.width = data.data.value + '%';
document.getElementById("label").innerHTML = data.data.value * 1 + '%';
}
}
</code></pre>
<p>Thanks in advance!</p>
| 2 | 2016-08-24T08:24:26Z | 39,124,187 | <p>You can use Web Sockets and in javascript you can receive the data from server and update the progress bar. Please check the article below:</p>
<p><a href="https://www.fullstackpython.com/websockets.html" rel="nofollow">Web Sockets</a></p>
| 1 | 2016-08-24T13:06:12Z | [
"javascript",
"python",
"html",
"multithreading",
"progress-bar"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.