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
sequence
Add additional line to QTableView object at a given position
40,053,267
<p>In my Gui I creats a QTableView with a QStandardItemModel and I would like to add either an additional row or column at a given position.</p> <pre><code>class Output(object): def __init__(self): ''' ''' self.tabs = QtGui.QTabWidget() self.group_box = QtGui.QGroupBox('Example') def run(self): form_layout = QtGui.QFormLayout(self.group_box) self.tabs.addTab(self.__genTable(),"Tab 1") self.tabs.addTab(self.__genTable(),"Tab 2") form_layout.addWidget(self.tabs) return self.group_box def __genTable(self): table_view = QtGui.QTableView() table_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) table_view.customContextMenuRequested.connect( self.__openMenu ) table_view.setSelectionBehavior( QtGui.QTableView.SelectItems ) table_view.setModel(QtGui.QStandardItemModel(4, 2)) return table_view def __openMenu(self, position): menu = QtGui.QMenu() sub_menu_row = QtGui.QMenu("Row") menu.addMenu(sub_menu_row) addRowBelowAction = sub_menu_row.addAction("add Row below") action = menu.exec_(QtGui.QCursor.pos()) if action == addRowBelowAction: idx = self.tabs.currentWidget().selectionModel().currentIndex() for i in range(self.tabs.count()): model = self.tabs.widget(i).selectionModel() model.insertRow(idx.row(), QtCore.QModelIndex()) </code></pre> <p>Unfortunately i get the following error:</p> <pre><code>model.insertRow(idx.row(), QtCore.QModelIndex()) AttributeError: 'PySide.QtGui.QItemSelectionModel' object has no attribute 'insertRow' </code></pre>
0
2016-10-14T23:14:16Z
40,053,416
<p>Untested, but try holding a reference to your model<br> then call the appropriate methods of the model (insertRow, insertColumn).<br> The effect of these methods will be apparent in the view. E.g.:</p> <pre><code>table_view = QtGui.QTableView() table_view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) table_view.setSelectionBehavior( QtGui.QTableView.SelectItems ) model = QtGui.QStandardItemModel(4, 2) table_view.setModel(model) model.insertRow(2, QtCore.QModelIndex()) </code></pre>
1
2016-10-14T23:34:38Z
[ "python", "qt", "pyside" ]
Getting error on if and elif
40,053,366
<p>Does anyone know why I keep getting an error with this section of my code?</p> <pre><code> if db_orientation2 =="Z": a="/C=C\" elif db_orientation2=="E": a="\C=C\" </code></pre> <p>This is the error:</p> <pre><code>File "&lt;ipython-input-7-25cda51c429e&gt;", line 11 a="/C=C\" ^ SyntaxError: EOL while scanning string literal </code></pre> <p>The <code>elif</code> is highlighted as red as if the operation is not allowed...</p>
1
2016-10-14T23:26:21Z
40,053,376
<p>String literals cannot end with a backslash. You'll have to double it:</p> <pre><code>a="/C=C\\" # ^ </code></pre> <p>The highlighting of your code also clearly shows the problem.</p>
4
2016-10-14T23:28:14Z
[ "python" ]
Python: sorting the lists of dictionary based on the indices of one list
40,053,399
<p>So I have dict like the following:</p> <pre><code>dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} </code></pre> <p>How can I sort the lists in <code>dict1</code> based on the indices that would sort one of the lists. Such as the sorted indices of list </p> <pre><code>[11, 10, 9, 8, 7] </code></pre> <p>which is</p> <pre><code>[4, 3, 2, 1, 0] </code></pre> <p>So the new <code>dict1</code> will be:</p> <pre><code>dict1 = {1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]} </code></pre> <p>I have tried the code like this:</p> <pre><code>sorted(dict1.items(), key=lambda t: t[1]) </code></pre> <p>But still cannot figure it out? I can use a for loop to do this work but I believe there exist a more pythonic way. Any idea?</p>
1
2016-10-14T23:32:34Z
40,053,451
<p>One way would be to compute the index list and apply it to all lists:</p> <pre><code>&gt;&gt;&gt; dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} &gt;&gt;&gt; basis = dict1[2] &gt;&gt;&gt; indexes = sorted(range(len(basis)), key=basis.__getitem__) &gt;&gt;&gt; for lst in dict1.values(): lst[:] = [lst[i] for i in indexes] &gt;&gt;&gt; dict1 {1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]} </code></pre> <p>If you're ok with "the first" list determining the order (you only said <em>"based on [...] one of the lists"</em>), you could also build columns and sort those:</p> <pre><code>&gt;&gt;&gt; dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} &gt;&gt;&gt; dict(zip(dict1.keys(), zip(*sorted(zip(*dict1.values()))))) {1: (-1, 1, 2, 3, 4), 2: (11, 10, 9, 7, 8)} </code></pre>
4
2016-10-14T23:39:03Z
[ "python", "list", "dictionary" ]
Python: sorting the lists of dictionary based on the indices of one list
40,053,399
<p>So I have dict like the following:</p> <pre><code>dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} </code></pre> <p>How can I sort the lists in <code>dict1</code> based on the indices that would sort one of the lists. Such as the sorted indices of list </p> <pre><code>[11, 10, 9, 8, 7] </code></pre> <p>which is</p> <pre><code>[4, 3, 2, 1, 0] </code></pre> <p>So the new <code>dict1</code> will be:</p> <pre><code>dict1 = {1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]} </code></pre> <p>I have tried the code like this:</p> <pre><code>sorted(dict1.items(), key=lambda t: t[1]) </code></pre> <p>But still cannot figure it out? I can use a for loop to do this work but I believe there exist a more pythonic way. Any idea?</p>
1
2016-10-14T23:32:34Z
40,053,494
<p>Sort using enumerate to get the sorted indexes and just use the indexes to sort the other lists:</p> <pre><code>from operator import itemgetter dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} l = [i for i, _ in sorted(enumerate(dict1[2]), key=itemgetter(1))] for v in dict1.values(): v[:] = (v[i] for i in l) print(dict1) </code></pre> <p>Or if you want a new dict:</p> <pre><code>l = [i for i, _ in sorted(enumerate(dict1[2]), key=itemgetter(1))] new = {k: [v[i] for i in l] for k, v in dict1.items()} </code></pre> <p>Or if you don't mind tuples:</p> <pre><code>new = {k: itemgetter(*l)(v) for k, v in dict1.items()}) </code></pre>
1
2016-10-14T23:44:41Z
[ "python", "list", "dictionary" ]
Python: sorting the lists of dictionary based on the indices of one list
40,053,399
<p>So I have dict like the following:</p> <pre><code>dict1 = {1: [-1, 1, 2, 4, 3], 2: [11, 10, 9, 8, 7]} </code></pre> <p>How can I sort the lists in <code>dict1</code> based on the indices that would sort one of the lists. Such as the sorted indices of list </p> <pre><code>[11, 10, 9, 8, 7] </code></pre> <p>which is</p> <pre><code>[4, 3, 2, 1, 0] </code></pre> <p>So the new <code>dict1</code> will be:</p> <pre><code>dict1 = {1: [3, 4, 2, 1, -1], 2: [7, 8, 9, 10, 11]} </code></pre> <p>I have tried the code like this:</p> <pre><code>sorted(dict1.items(), key=lambda t: t[1]) </code></pre> <p>But still cannot figure it out? I can use a for loop to do this work but I believe there exist a more pythonic way. Any idea?</p>
1
2016-10-14T23:32:34Z
40,054,577
<p>Using <a href="https://docs.python.org/2/library/operator.html#operator.itemgetter" rel="nofollow"><code>itemgetter</code></a> in a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dictionary comprehension</a></p> <pre><code>&gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; order = [4, 3, 2, 1, 0] &gt;&gt;&gt; key = itemgetter(*order) &gt;&gt;&gt; {k: key(dict1[k]) for k in dict1} {1: (3, 4, 2, 1, -1), 2: (7, 8, 9, 10, 11)} </code></pre>
0
2016-10-15T03:21:06Z
[ "python", "list", "dictionary" ]
OpenGL - Show Texture Only
40,053,433
<p>I'm working on a 2D isometric game, using pygame and pyopengl.</p> <p>I'm drawing sprites as quads, with a texture. I managed to get the alpha transparency to work for the texture, but the quad itself is still filled in a solid color (whatever colour gl pipeline is set with at the time). </p> <p>How do I hide the quad shape, and just show the texture?</p> <p>Here is a pic showing the problem (gl pipeline set to pink/purple color):</p> <p><a href="https://i.stack.imgur.com/mCaU4.png" rel="nofollow"><img src="https://i.stack.imgur.com/mCaU4.png" alt="enter image description here"></a></p> <p>The code is a bit messy, and I've been blindly copy 'n pasting gl calls hoping it solves the problem so there are bound to be quite a few calls in the wrong place or duplicated (or both).</p> <p>GL Setup code (called once at start of script)</p> <pre><code>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glViewport(0, 0, screen_size[0], screen_size[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glDisable(GL_LIGHTING) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) </code></pre> <p>Drawing setup code (called once at the start of each frame)</p> <pre><code>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glViewport(0, 0, screen_size[0], screen_size[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glDisable(GL_LIGHTING) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) </code></pre> <p>Quad draw code (called for every sprite draw call):</p> <pre><code>glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_TEXTURE_2D) glEnable(GL_ALPHA_TEST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) # Start new transformation matrix glPushMatrix() # Apply translation glTranslatef(self.rect.centerx, self.rect.centery, 0.0) # Start gl drawing cursor glColor4f(1.0, 0.0, 1.0, 1.0) # Bind the texture to this draw session glBindTexture(GL_TEXTURE_2D, self.texture.id) # Start drawing a quad glBegin(GL_QUADS) # Grab new copy of rect, and move to the origin r = self.rect.copy() r.center = (0, 0) # Draw top left point glTexCoord2f(1.0, 0.0) glVertex2f(*r.topleft) # Draw top right point glTexCoord2f(0.0, 0.0) glVertex2f(*r.topright) # Draw bottom right point glTexCoord2f(0.0, 1.0) glVertex2f(*r.bottomright) # Draw bottom left point glTexCoord2f(1.0, 1.0) glVertex2f(*r.bottomleft) # End quad glEnd() # Apply transformation matrix glPopMatrix() </code></pre>
-1
2016-10-14T23:36:27Z
40,056,514
<p>Well, either use <em>blending</em>, so that the alpha value actually has effect on opacity. Or use alpha testing, so that incoming fragments with an alpha below/above a certain threshold are discarded.</p> <p>Blending requires to sort geometry back to front. And given what you want to do alpha testing may be the easier, more straightforward solution.</p> <p><strong>Update:</strong></p> <p>Either way it's imperative that the texture's alpha value makes it through to the fragment. If you were using shaders this would be as simple as making sure that the fragment output alpha would receive its value from the texture. But you're using the fixed function pipeline and the mess that's the texture environment state machine.</p> <p>Using only a single texture your best bet would be a GL_REPLACE texture mode (completely ignores the vertex color). Or GL_MODULATE that takes the vertex color into account. Right now you're assumingly using GL_DECAL mode.</p> <p>My suggestion: Drop the fixed function pipeline and use shaders. Much easier to get things related to texturing working. Also you'll hard pressed to find hardware that's not using shaders anyway (unless you're planning to run your program on stuff that's been built before 2004).</p>
2
2016-10-15T07:49:12Z
[ "python", "opengl" ]
OpenGL - Show Texture Only
40,053,433
<p>I'm working on a 2D isometric game, using pygame and pyopengl.</p> <p>I'm drawing sprites as quads, with a texture. I managed to get the alpha transparency to work for the texture, but the quad itself is still filled in a solid color (whatever colour gl pipeline is set with at the time). </p> <p>How do I hide the quad shape, and just show the texture?</p> <p>Here is a pic showing the problem (gl pipeline set to pink/purple color):</p> <p><a href="https://i.stack.imgur.com/mCaU4.png" rel="nofollow"><img src="https://i.stack.imgur.com/mCaU4.png" alt="enter image description here"></a></p> <p>The code is a bit messy, and I've been blindly copy 'n pasting gl calls hoping it solves the problem so there are bound to be quite a few calls in the wrong place or duplicated (or both).</p> <p>GL Setup code (called once at start of script)</p> <pre><code>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glViewport(0, 0, screen_size[0], screen_size[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glDisable(GL_LIGHTING) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) </code></pre> <p>Drawing setup code (called once at the start of each frame)</p> <pre><code>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() glViewport(0, 0, screen_size[0], screen_size[1]) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0.0, screen_size[0], 0.0, screen_size[1], 0.0, 1.0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() glDisable(GL_LIGHTING) glEnable(GL_TEXTURE_2D) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) </code></pre> <p>Quad draw code (called for every sprite draw call):</p> <pre><code>glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_TEXTURE_2D) glEnable(GL_ALPHA_TEST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) # Start new transformation matrix glPushMatrix() # Apply translation glTranslatef(self.rect.centerx, self.rect.centery, 0.0) # Start gl drawing cursor glColor4f(1.0, 0.0, 1.0, 1.0) # Bind the texture to this draw session glBindTexture(GL_TEXTURE_2D, self.texture.id) # Start drawing a quad glBegin(GL_QUADS) # Grab new copy of rect, and move to the origin r = self.rect.copy() r.center = (0, 0) # Draw top left point glTexCoord2f(1.0, 0.0) glVertex2f(*r.topleft) # Draw top right point glTexCoord2f(0.0, 0.0) glVertex2f(*r.topright) # Draw bottom right point glTexCoord2f(0.0, 1.0) glVertex2f(*r.bottomright) # Draw bottom left point glTexCoord2f(1.0, 1.0) glVertex2f(*r.bottomleft) # End quad glEnd() # Apply transformation matrix glPopMatrix() </code></pre>
-1
2016-10-14T23:36:27Z
40,057,459
<p>The colored background behind your tiles is probably due to this line when you set up your texture:</p> <pre><code>glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL) </code></pre> <p>Just remove this as the default texture environment settings are probably fine for standard tile rendering. As an example of what messing with these parameters can do, if you wanted <code>glColor</code> calls to "tint" your texture instead, then replace <code>GL_DECAL</code> with <code>GL_BLEND</code>.</p> <p>There is no need for any of those lighting calls included in your code as far as I can tell unless you are working with 3d models and ancient per-vertex lighting (I assume you are not since this is a 2d isometric game). Also you only need blending for this, no need for alpha testing. Assuming you are working with images with alpha (RGBA format), here is a simple demo that displays two tiles with a transparent background (supply your own image of course instead of <code>./images/grass.png</code>):</p> <pre><code>import pygame from pygame.locals import * from OpenGL.GL import * import sys class Sprite(object): def __init__(self): self.x = 0 self.y = 0 self.width = 0 self.height = 0 self.texture = glGenTextures(1) def load_texture(self, texture_url): tex = pygame.image.load(texture_url) tex_surface = pygame.image.tostring(tex, 'RGBA') tex_width, tex_height = tex.get_size() glBindTexture(GL_TEXTURE_2D, self.texture) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, tex_width, tex_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex_surface) glBindTexture(GL_TEXTURE_2D, 0) self.width = tex_width self.height = tex_height def set_position(self, x, y): self.x = x self.y = y def render(self): #glColor(1, 1, 1, 1) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glBindTexture(GL_TEXTURE_2D, self.texture) glBegin(GL_QUADS) glTexCoord(0, 0) glVertex(self.x, self.y, 0) glTexCoord(0, 1) glVertex(self.x, self.y + self.height, 0) glTexCoord(1, 1) glVertex(self.x + self.width, self.y + self.height, 0) glTexCoord(1, 0) glVertex(self.x + self.width, self.y, 0) glEnd() glBindTexture(GL_TEXTURE_2D, 0) def init_gl(): window_size = width, height = (550, 400) pygame.init() pygame.display.set_mode(window_size, OPENGL | DOUBLEBUF) glEnable(GL_TEXTURE_2D) glMatrixMode(GL_PROJECTION) glOrtho(0, width, height, 0, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() if __name__ == "__main__": init_gl() tile1 = Sprite() tile1.load_texture("./images/grass.png") tile1.set_position(50, 100) tile2 = Sprite() tile2.load_texture("./images/grass.png") tile2.set_position(80, 130) tiles = [tile1, tile2] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() glClear(GL_COLOR_BUFFER_BIT) glColor(1, 0, 0, 1) for tile in tiles: tile.render() pygame.display.flip() </code></pre> <p>Let me know if this helps!</p>
2
2016-10-15T09:40:52Z
[ "python", "opengl" ]
Python Indexing not returning expected value
40,053,486
<p>I am trying to return the value M from Mr. Smith but whenever I run my code below it returns ''</p> <pre><code>&gt;&gt;&gt;name = input("Please input your name: ") Please input your name: Mr. Smith &gt;&gt;&gt; if name == name.find(' ') and name.isalpha(): get_initial = name[0] &gt;&gt;&gt;get_initial '' </code></pre>
0
2016-10-14T23:43:48Z
40,053,621
<p>I see a lot of problems in this proposed code.</p> <p>First of all, <code>input()</code> evaluates the input string as a python expression and that's not what you want, you need to use <code>raw_input()</code> instead. Second, <code>isalpha()</code> won't return True if input includes '.' or spaces, so you need to find another metric, for example, if only alphabetical characters are allowed, you can use <code>isalpha()</code> this way:</p> <pre><code>name_nospaces = "".join(name.split()) if name_nospaces.isalpha(): ... </code></pre> <p>Then, it doesn't make much sense to do <code>name == name.find(' ')</code>, just have:</p> <pre><code>if name.find(' '): ... </code></pre>
0
2016-10-15T00:04:01Z
[ "python" ]
Python Indexing not returning expected value
40,053,486
<p>I am trying to return the value M from Mr. Smith but whenever I run my code below it returns ''</p> <pre><code>&gt;&gt;&gt;name = input("Please input your name: ") Please input your name: Mr. Smith &gt;&gt;&gt; if name == name.find(' ') and name.isalpha(): get_initial = name[0] &gt;&gt;&gt;get_initial '' </code></pre>
0
2016-10-14T23:43:48Z
40,053,625
<p>python 3 </p> <pre><code> name = input("Please input your name: ") c=name.strip()[0] if c.isalpha(): print(c) </code></pre> <p>python 2 :</p> <pre><code>&gt;&gt;&gt; name = raw_input("Please input your name: ") Please input your name: Hisham &gt;&gt;&gt; c=name.strip()[0] &gt;&gt;&gt; if c.isalpha(): print c </code></pre> <p>output py3:</p> <pre><code>Python 3.5.2 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux Please input your name: dsfgsdf d </code></pre> <p>output py2:</p> <pre><code>H </code></pre>
2
2016-10-15T00:04:20Z
[ "python" ]
Python Indexing not returning expected value
40,053,486
<p>I am trying to return the value M from Mr. Smith but whenever I run my code below it returns ''</p> <pre><code>&gt;&gt;&gt;name = input("Please input your name: ") Please input your name: Mr. Smith &gt;&gt;&gt; if name == name.find(' ') and name.isalpha(): get_initial = name[0] &gt;&gt;&gt;get_initial '' </code></pre>
0
2016-10-14T23:43:48Z
40,053,640
<p>Assuming you have to find the first character of a name....</p> <pre><code>def find_initial(name): i = 0 initial_name_size = len(name) while True: name = name[i:] if name.isalpha(): get_initial = name[0] return get_initial else: i = i+1 if i &gt;= initial_name_size: return 'There is no initial' name = input("Please input your name: ") print find_initial(name) </code></pre>
0
2016-10-15T00:06:53Z
[ "python" ]
Django unapply migration
40,053,515
<p>I have a custom made migration:</p> <pre><code>class Migration(migrations.Migration): dependencies = [('blah', 'my_previous_migration'),] operations = [ migrations.RunSQL( sql=[("SQL HERE")], reverse_sql=[("SQL UNDO HERE")]) ] </code></pre> <p>This migration is already applied. I want to create a migration to undo that migration, basically following what the docs say: <a href="https://docs.djangoproject.com/es/1.10/ref/migration-operations/#runsql" rel="nofollow">unapply migration</a></p> <p>But I can't find any reference on how to unapply a migration or have a migration run the <code>reverse_sql</code> portion of the migration.</p>
0
2016-10-14T23:47:43Z
40,053,751
<p>Let's call the snippet <code>accident</code> and the additional one <code>fix</code>.</p> <p>When writing custom SQL migrations you should usually provide the reverse part otherwise you can not roll it back to prior state without loosing the integrity of your schema and/or data.</p> <p><code>accident</code> should provide sql to revert itself. The <code>fix</code> that rolls <code>accident</code> back should therefor consist of both operations interchanged.</p> <p>You might want to read <a href="https://docs.djangoproject.com/es/1.10/topics/migrations/#migration-squashing" rel="nofollow">about squashing migrations</a> afterwards.</p> <p>EDIT: the term operations might by confusing as it is part of the migration system :) - will say: interchange <code>sql</code> and <code>reverse_sql</code> in <code>fix</code> migration</p>
1
2016-10-15T00:26:02Z
[ "python", "django", "migration" ]
APScheduler - ImportWarning but code still runs. What is wrong?
40,053,575
<p>My code follows the example from <a href="http://apscheduler.readthedocs.io/en/latest/modules/triggers/interval.html#examples" rel="nofollow">APScheduler Docs</a> but I changed its format to follow mine. It works no problem. "Hello World" is printed every 10 seconds.</p> <pre><code>#! /usr/bin/python import datetime from apscheduler.schedulers.blocking import BlockingScheduler class Class1: def job_function(): print("Hello World") class Class2: def go(): sched = BlockingScheduler() # Schedule job_function to be called every 10 seconds sched.add_job(Classy.job_function, 'interval', seconds = 10) sched.start() if __name__ == '__main__': Class2.go() </code></pre> <p>My actual code however, does not work so well. </p> <pre><code>#! /usr/bin/python import time import praw import OAuth2Util import redditNewsBot import redditFreeGameBot import redditWorldNewsBot from datetime import datetime from apscheduler.schedulers.blocking import BlockingScheduler class Aggregate: def aggr() ... def x(): print('x') class RunSchedule: def go(): sched = BlockingScheduler() # Schedule job_function to be called every ten seconds sched.add_job(Aggregate.x, 'interval', seconds = 10) sched.start() if __name__ == '__main__': RunSchedule.go() </code></pre> <p>Everything will run at the specified interval but I get all this first:</p> <pre><code>C:\Users\Nick\AppData\Local\Programs\Python\Python35-32\lib\importlib\_bootstrap_external.py:415: ImportWarning: Not importing directory C:\Users\Nick\AppData\Local\Programs\Python\Python35-32\lib\site-packages\mpl_toolkits: missing __init___warnings.warn(msg.format(portions[0]), ImportWarning) C:\Users\Nick\AppData\Local\Programs\Python\Python35-32\lib\importlib\_bootstrap_external.py:415: ImportWarning: Not importing directory c:\users\nick\appdata\local\programs\python\python35-32\lib\site-packages\mpl_toolkits: missing __init___warnings.warn(msg.format(portions[0]), ImportWarning) C:\Users\Nick\AppData\Local\Programs\Python\Python35-32\lib\importlib\_bootstrap_external.py:415: ImportWarning: Not importing directory C:\Users\Nick\AppData\Local\Programs\Python\Python35-32\lib\site-packages\zope: missing __init___warnings.warn(msg.format(portions[0]), ImportWarning) </code></pre>
0
2016-10-14T23:56:31Z
40,056,516
<p>It was <code>praw</code>.</p> <p>I imported it to the test script behind <code>datetime</code> and <code>from apscheduler.schedulers.blocking import BlockingScheduler</code> and it ran error free. </p> <p>I then moved it in front of the latter and it threw the errors.</p> <p>In order to run error free from <code>apscheduler.schedulers.blocking import BlockingSchedulerhad</code> to move to the very front of the import list. <code>time</code> and <code>datetime</code> can be in front without errors as well.</p> <pre><code>from apscheduler.schedulers.blocking import BlockingScheduler import praw import time import datetime import OAuth2Util import redditNewsBot import redditFreeGameBot import redditWorldNewsBot </code></pre>
0
2016-10-15T07:49:17Z
[ "python", "apscheduler" ]
Python Regular Expression [\d+]
40,053,653
<p>I am working on regular expression python, I came across this problem.</p> <p>A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x): </code></pre> <p>for which i was getting error. later I changed it to</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+\d+$',x): </code></pre> <p>for which all test cases passed. I want to know what the difference between using and not using <code>[]</code> for <code>\d+</code> in regex ?</p> <p>Thanks </p>
2
2016-10-15T00:08:05Z
40,053,690
<p><code>[\d+]</code> = one digit (<code>0-9</code>) or <code>+</code> character.</p> <p><code>\d+</code> = one or more digits.</p>
3
2016-10-15T00:14:07Z
[ "python", "regex" ]
Python Regular Expression [\d+]
40,053,653
<p>I am working on regular expression python, I came across this problem.</p> <p>A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x): </code></pre> <p>for which i was getting error. later I changed it to</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+\d+$',x): </code></pre> <p>for which all test cases passed. I want to know what the difference between using and not using <code>[]</code> for <code>\d+</code> in regex ?</p> <p>Thanks </p>
2
2016-10-15T00:08:05Z
40,055,254
<p>You could also do:</p> <pre><code>if re.search(r'^[789]\d{9}$', x): </code></pre> <p>letting the regex handle the <code>len(x)==10</code> part by using explicit lengths instead of unbounded repetitions.</p>
1
2016-10-15T05:18:43Z
[ "python", "regex" ]
Python Regular Expression [\d+]
40,053,653
<p>I am working on regular expression python, I came across this problem.</p> <p>A valid mobile number is a ten digit number starting with a 7,8 or 9. my solution to this was :</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+[\d+]$',x): </code></pre> <p>for which i was getting error. later I changed it to</p> <pre><code>if len(x)==10 and re.search(r'^[7|8|9]+\d+$',x): </code></pre> <p>for which all test cases passed. I want to know what the difference between using and not using <code>[]</code> for <code>\d+</code> in regex ?</p> <p>Thanks </p>
2
2016-10-15T00:08:05Z
40,055,675
<p>I think a general explanation about <code>[]</code> and <code>+</code> is what you need. </p> <p><code>[]</code> will match with a single character specified inside.<br> Eg: <code>[qwe]</code> will match with <code>q</code>, <code>w</code> or <code>e</code>. </p> <p><strong>If you want to enter an expression inside <code>[]</code>, you need to use it as <code>[^ expression]</code>.</strong></p> <p><code>+</code> will match the preceding element one or more times. Eg: <code>qw+e</code> matches <code>qwe</code>, <code>qwwe</code>, <code>qwwwwe</code>, etc...<br> Note: this is different from <code>*</code> as <code>*</code> matches preceding element zero or more times. i.e. <code>qw*e</code> matches <code>qe</code> as well.</p> <p><code>\d</code> matches with numerals. (not just <code>0-9</code>, but numerals from other language scripts as well.)</p>
0
2016-10-15T06:16:46Z
[ "python", "regex" ]
Object Detection OpenCV-Python does not work
40,053,655
<p>For several days I am have been trying to build my own object classification program using Python-Open cv and Haar Cascade.</p> <p>After creating the samples, here is how train the system:</p> <pre><code> opencv_traincascade -data classifier -vec samples.vec -bg negatives.txt -numStages 12 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 1000 -numNeg 600 -w 50 -h 50 -mode ALL -precalcValBufSize 1024 -precalcIdxBufSize 1024 </code></pre> <p>and after stage 8 I have received this output</p> <pre><code>===== TRAINING 8-stage ===== &lt;BEGIN POS count : consumed 1000 : 1000 NEG count : acceptanceRatio 600 : 0.00221078 Precalculation time: 10 +----+---------+---------+ | N | HR | FA | +----+---------+---------+ | 1| 1| 1| +----+---------+---------+ | 2| 1| 1| +----+---------+---------+ | 3| 1| 0.898333| +----+---------+---------+ | 4| 1| 0.916667| +----+---------+---------+ | 5| 1| 0.691667| +----+---------+---------+ | 6| 1| 0.681667| +----+---------+---------+ | 7| 1| 0.518333| +----+---------+---------+ | 8| 1| 0.626667| +----+---------+---------+ | 9| 1| 0.441667| +----+---------+---------+ ===== TRAINING 9-stage ===== &lt;BEGIN POS count : consumed 1000 : 1000 NEG count : acceptanceRatio 0 : 0 Required leaf false alarm rate achieved. Branch training terminated. </code></pre> <p>However the trained model does not detect any object (watch in this case). I am stucked and don't know how to solve this out. Any useful ideas are appreciated greatly.</p>
0
2016-10-15T00:08:39Z
40,062,710
<p>Your desired parameters were acheived: "-minHitRate 0.999 -maxFalseAlarmRate 0.5".</p> <p>You have (according the table you show above): HitRate=1 and FalseAlarmRate=0.441667, that's why training stopped.</p>
0
2016-10-15T18:27:57Z
[ "python", "opencv" ]
How to plot two level x-axis labels for a histogram?
40,053,660
<p>Is there a way to do the same of this two x-axis labels but for a histogram plot? <a href="http://stackoverflow.com/questions/31803817/how-to-add-second-x-axis-at-the-bottom-of-the-first-one-in-matplotlib/40053591#40053591">How to add second x-axis at the bottom of the first one in matplotlib.?</a></p> <p>I want to show the values in two levels, one for metric and the second for English units. I tried to adapt the script in the link above to a histogram script but I'm not sure how to connect the histogram function with the ax1. handle.</p> <pre><code>""" Demo of the histogram (hist) function with a few features. In addition to the basic histogram, this demo shows a few optional features: * Setting the number of data bins * The ``normed`` flag, which normalizes bin heights so that the integral of the histogram is 1. The resulting histogram is a probability density. * Setting the face color of the bars * Setting the opacity (alpha value). """ import numpy as np import matplotlib.mlab as mlab import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twiny() # example data mu = 100 # mean of distribution sigma = 15 # standard deviation of distribution x = mu + sigma * np.random.randn(10000) num_bins = 50 # the histogram of the data n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) ax1.set_xlabel(r"Original x-axis: $X$") new_tick_locations = np.array([.2, .5, .9]) def tick_function(X): V = 1/(1+X) return ["%.3f" % z for z in V] # Move twinned axis ticks and label from top to bottom ax2.xaxis.set_ticks_position("bottom") ax2.xaxis.set_label_position("bottom") # Offset the twin axis below the host ax2.spines["bottom"].set_position(("axes", -0.15)) # Turn on the frame for the twin axis, but then hide all # but the bottom spine ax2.set_frame_on(True) ax2.patch.set_visible(False) for sp in ax2.spines.itervalues(): sp.set_visible(False) ax2.spines["bottom"].set_visible(True) ax2.set_xticks(new_tick_locations) ax2.set_xticklabels(tick_function(new_tick_locations)) ax2.set_xlabel(r"Modified x-axis: $1/(1+X)$") y = mlab.normpdf(bins, mu, sigma) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$') # Tweak spacing to prevent clipping of ylabel plt.subplots_adjust(left=0.15) plt.show() </code></pre>
1
2016-10-15T00:09:13Z
40,060,879
<p>just replace your <code>hist</code> call by:</p> <pre><code>n, bins, patches = ax1.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5) </code></pre> <p>Check the <a href="http://matplotlib.org/api/axes_api.html" rel="nofollow">documentation for <code>Axes</code></a> to see what member functions are available</p>
0
2016-10-15T15:28:31Z
[ "python", "matplotlib", "histogram", "axis" ]
using a tail and a buffer to get last K lines in a file
40,053,673
<p>I was given this buffer and told to make a reverse input that get the last K lines in a file. From what I've been trying to do, every time I tried to run the code it says that used is not an attribute of Input. Can someone please tell me why this keeps happening? Thank you in advance.</p> <pre><code>class Input: def __init___( self, file ): self.file = file # must open( &lt;filename&gt;, "rb" ) self.length = 0 self.used = 0 self.buffer = "" def read( self ): if self.used &lt; self.length: # if something in buffer c = self.buffer[self.used] self.used += 1 return c else: self.buffer = self.file.read( 20 ) # or 2048 self.length = len( self.buffer ) if self.length == 0: return -1 else: c = self.buffer[0] self.used = 1 ` </code></pre>
1
2016-10-15T00:11:48Z
40,053,750
<p>Try indenting...</p> <pre><code>class Input: def __init___( self, file ): self.file = file # must open( &lt;filename&gt;, "rb" ) self.length = 0 self.used = 0 self.buffer = "" def read( self ): if self.used &lt; self.length: # if something in buffer c = self.buffer[self.used] self.used += 1 return c else: self.buffer = self.file.read( 20 ) # or 2048 self.length = len( self.buffer ) if self.length == 0: return -1 else: c = self.buffer[0] self.used = 1 </code></pre>
-1
2016-10-15T00:26:01Z
[ "python", "file", "buffer", "tail" ]
using a tail and a buffer to get last K lines in a file
40,053,673
<p>I was given this buffer and told to make a reverse input that get the last K lines in a file. From what I've been trying to do, every time I tried to run the code it says that used is not an attribute of Input. Can someone please tell me why this keeps happening? Thank you in advance.</p> <pre><code>class Input: def __init___( self, file ): self.file = file # must open( &lt;filename&gt;, "rb" ) self.length = 0 self.used = 0 self.buffer = "" def read( self ): if self.used &lt; self.length: # if something in buffer c = self.buffer[self.used] self.used += 1 return c else: self.buffer = self.file.read( 20 ) # or 2048 self.length = len( self.buffer ) if self.length == 0: return -1 else: c = self.buffer[0] self.used = 1 ` </code></pre>
1
2016-10-15T00:11:48Z
40,053,800
<p>I'm going to go out on a limb here and try guessing that the problem is that you are using the wrong name for the <code>__init__</code> magic method (as noticed by <a href="https://stackoverflow.com/users/459745/hai-vu">Hai Vu</a>). Notice that there are three trailing underscores in your code instead of two.</p> <p>Since the <code>__init__</code> method is the one called during the construction of the object to set its various attributes, the <code>used</code> attribute never gets set because the <code>__init__</code> function never gets run.</p> <p>Afterwards, <code>used</code> is the first attribute accessed in Input.read, which makes Python complain about it being missing.</p> <p>If I'm right, remove the underscore and it will fix the problem (though there may be others).</p>
2
2016-10-15T00:33:46Z
[ "python", "file", "buffer", "tail" ]
Django: How to use AJAX to check if username exists on registration form?
40,053,752
<p>When the user enters a username, I want to check the db if that username already exists and display an error message. How would I do that without refreshing the page? With AJAX?</p> <p>registration_form.html</p> <pre><code>&lt;div class="container-fluid userformcontainer"&gt; &lt;div class="row"&gt; &lt;div class="col-md-offset-2 col-sm-offset-1 col-sm-8 userformdiv"&gt; &lt;h1 class="title userformtitle"&gt;Sign up&lt;/h1&gt; &lt;form method="POST" class="post-form"&gt; {% csrf_token %} {% bootstrap_form form %} {% buttons %} &lt;button type="submit" class="save btn btn-default btn-lg userformbutton center-block"&gt;Register&lt;/button&gt; {% endbuttons %} &lt;/form&gt; &lt;/div&gt;&lt;!--col--&gt; &lt;/div&gt;&lt;!--row--&gt; &lt;/div&gt;&lt;!--container--&gt; </code></pre> <p>views.py</p> <pre><code>class UserFormView(View): form_class = SignUpForm template_name = 'card/registration_form.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] user.first_name = form.cleaned_data['first_name'] user.last_name = form.cleaned_data['last_name'] if not User.objects.filter(username=username).exists(): password = form.cleaned_data['password'] user.set_password(password) user.save() user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect('card:deck_list') else: pass else: pass </code></pre> <p>forms.py</p> <pre><code>class SignUpForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password'] </code></pre>
0
2016-10-15T00:26:03Z
40,053,980
<p>You can build your form manually (at least the username field) as per django documentation below:</p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-fields-manually" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-fields-manually</a></p> <p>Then you can set "onchange" event for your field to call a javascript fuction that does the AJAX work for you and display the success/failure message in a div tag of your own.</p> <p>Alternatively, you may want to let a javascript code that runs on page load to attach an "onchange" event to the "username" field based on its name to the same job for you.</p>
0
2016-10-15T01:10:34Z
[ "python", "ajax", "django" ]
binary tree issue: unorderable types: str() < int()
40,053,801
<p>I am trying to create a binary tree. I am testing what I have with the test code at the bottom but I receive the error message "elif var &lt; here._variable: TypeError: unorderable types: str() &lt; int()" any insight would be great</p> <pre><code>class vartree: class Node: __slots__= "_left", "_value", "_variable", "_right" def __init__ (self, l, var,val,r): self._left = l self._variable = var self._value = val self._right = r def __init__(self): self._root = None def _search (self, here, var): if here is None: return self.Node(None, var, '0', None) elif var &lt; here._variable: return self._search(here._left, var) elif var &gt; here._variable: return self._search(here._right, var) else: return here._value def _insert(self, here, var, val): if here is None: return self.Node(None, val, var, None) elif var &lt; here._variable: return self.Node(self._insert(here._left, var, val), here._value, here._variable, here._right) elif var &gt; here._variable: return self.Node(here._left , here._value, here._variable, self._insert(here._right, var, val)) else: return var def assign(self, var, val): self._root = self._insert(self._root, var, val) #self._insert(self._root, var, val) def lookup(self, var): return self._search(self._root, var) if __name__ == "__main__": T = vartree() T.assign("x",9) T.lookup("x") </code></pre>
0
2016-10-15T00:33:52Z
40,053,847
<p>The problem is that one is an integer and the other a string at the line at which error occurs. After analyzing your code, i think i know why this is happening. Do this:</p> <p>In your _insert() function, change this line: </p> <pre><code> return self.Node(None, val, var, None) </code></pre> <p>to this: </p> <pre><code>return self.Node(None, var, val, None) </code></pre> <p>Hope this help :)</p>
1
2016-10-15T00:43:39Z
[ "python" ]
How would I use Dask to perform parallel operations on slices of NumPy arrays?
40,053,875
<p>I have a numpy array of coordinates of size n_slice x 2048 x 3, where n_slice is in the tens of thousands. I want to apply the following operation on each 2048 x 3 slice separately</p> <pre><code>import numpy as np from scipy.spatial.distance import pdist # load coor from a binary xyz file, dcd format n_slice, n_coor, _ = coor.shape r = np.arange(n_coor) dist = np.zeros([n_slice, n_coor, n_coor]) # this loop is what I want to parallelize, each slice is completely independent for i in xrange(n_slice): dist[i, r[:, None] &lt; r] = pdist(coor[i]) </code></pre> <p>I tried using Dask by making <code>coor</code> a <code>dask.array</code>,</p> <pre><code>import dask.array as da dcoor = da.from_array(coor, chunks=(1, 2048, 3)) </code></pre> <p>but simply replacing <code>coor</code> by <code>dcoor</code> will not expose the parallelism. I could see setting up parallel threads to run for each slice but how do I leverage Dask to handle the parallelism?</p> <p>Here is the parallel implementation using <code>concurrent.futures</code></p> <pre><code>import concurrent.futures import multiprocessing n_cpu = multiprocessing.cpu_count() def get_dist(coor, dist, r): dist[r[:, None] &lt; r] = pdist(coor) # load coor from a binary xyz file, dcd format n_slice, n_coor, _ = coor.shape r = np.arange(n_coor) dist = np.zeros([n_slice, n_coor, n_coor]) with concurrent.futures.ThreadPoolExecutor(max_workers=n_cpu) as executor: for i in xrange(n_slice): executor.submit(get_dist, cool[i], dist[i], r) </code></pre> <p>It is possible this problem is not well suited to Dask since there are no inter-chunk computations.</p>
2
2016-10-15T00:49:31Z
40,054,094
<h3><code>map_blocks</code></h3> <p>The <a href="http://dask.pydata.org/en/latest/array-api.html#dask.array.core.map_blocks" rel="nofollow">map_blocks</a> method may be helpful:</p> <pre><code>dcoor.map_blocks(pdist) </code></pre> <h3>Uneven arrays</h3> <p>It looks like you're doing a bit of fancy slicing to insert particular values into particular locations of an output array. This will probably be awkward to do with dask.arrays. Instead, I recommend making a function that produces a numpy array</p> <pre><code>def myfunc(chunk): values = pdist(chunk[0, :, :]) output = np.zeroes((2048, 2048)) r = np.arange(2048) output[r[:, None] &lt; r] = values return output dcoor.map_blocks(myfunc) </code></pre> <h3><code>delayed</code></h3> <p>Worst case scenario you can always use <a href="http://dask.pydata.org/en/latest/delayed.html" rel="nofollow">dask.delayed</a></p> <pre><code>from dask import delayed, compute coor2 = delayed(coor) slices = [coor2[i] for i in range(coor.shape[0])] slices2 = [delayed(pdist)(slice) for slice in slices] results = compute(*slices2) </code></pre>
2
2016-10-15T01:35:29Z
[ "python", "arrays", "numpy", "parallel-processing", "dask" ]
Extract JSON object
40,053,964
<p>I have a JSON file that looks like this:</p> <pre><code>[ "{'_filled': False,\n 'affiliation': u'Postdoctoral Scholar, University of California, Berkeley',\n 'citedby': 113,\n 'email': u'@berkeley.edu',\n 'id': u'4bahYMkAAAAJ',\n 'interests': [u'3D Shape',\n u'Shape from Texture',\n u'Shape from Shading',\n u'Naive Physics',\n u'Haptics'],\n 'name': u'Steven A. Cholewiak',\n 'url_citations': u'/citations?user=4bahYMkAAAAJ&amp;hl=en',\n 'url_picture': u'/citations?view_op=view_photo&amp;user=4bahYMkAAAAJ&amp;citpid=1'}", "\n"] </code></pre> <p>I am using python to extract the value of citedby. However, I am not able to figure. Here is my code:</p> <pre><code>import json json_data = open("output.json") data = json.load(json_data) print data[] </code></pre> <p>Now I know data would take an integer value whereas I would want to have it as a dictionary where in I could search using the key. Is there any way I can achieve this?</p>
0
2016-10-15T01:06:51Z
40,054,017
<pre><code>import json import ast json_data = open("output.json") data = json.load(json_data) print ast.literal_eval(data[0])['citedby'] </code></pre>
1
2016-10-15T01:18:44Z
[ "python", "json" ]
What regular expression selects a string between two "*" characters
40,054,031
<p>I want to select text between two * characters in a file and am having trouble forming the regular expression to do so.</p> <p>For example with a file like the following:</p> <pre><code>* Apple Are good * Banana Are great * Cauliflower Are bad </code></pre> <p>It would select 3 different groups</p> <p>Apple Are good</p> <p>Banana Are great</p> <p>and </p> <p>Cauliflower Are bad</p> <p>I believe I need to use ^ and $ for this but my selector: <code>^\*$\*</code></p> <p>is not working.</p>
-1
2016-10-15T01:21:06Z
40,054,057
<p>Regular expressions aren't even necessary here. Just use <code>str.split</code> and <code>str.strip</code>:</p> <pre><code>&gt;&gt;&gt; f = '''* Apple ... Are good ... ... * Banana ... Are great ... ... * Cauliflower ... Are bad''' &gt;&gt;&gt; for line in f.split('*'): ... if line.strip(): ... print('start') ... print(line.strip()) ... print('end') ... start Apple Are good end start Banana Are great end start Cauliflower Are bad end </code></pre>
2
2016-10-15T01:28:27Z
[ "python", "regex" ]
Import file from another app in Django 1.10
40,054,066
<p>I'm trying to import a file from another app, and I get this error:</p> <pre><code>Unhandled exception in thread started by &lt;function wrapper at 0x7fe7bc281d70&gt; Traceback (most recent call last): File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/carlos/.envs/lafam/local/lib/python2.7/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/carlos/www/lafam/apps/maquina/models.py", line 6, in &lt;module&gt; from apps.website.managers import GenericManager ImportError: No module named website.managers </code></pre> <p><strong>INSTALLED APPS in settings.py</strong></p> <pre><code>SYSTEM_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] PROJECT_APPS = [ 'apps.website', 'apps.maquina', ] INSTALLED_APPS = SYSTEM_APPS + PROJECT_APPS </code></pre> <p>All my apps are in apps folder. I have an app called "maquina". And this is its <strong>modals.py</strong></p> <pre><code>from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from apps.website.managers import GenericManager from .utils import path_and_rename class Fabricante(models.Model): ... </code></pre> <p>I created a file called <strong>managers.py</strong> from another app called <strong>website</strong></p> <pre><code>from django.db import models class GenericManager(models.Manager): def get_or_none(self, *args, **kwargs): try: return self.get(*args, **kwargs) except self.model.DoesNotExist: return None except self.model.MultipleObjectsReturned: return None </code></pre> <p>I notice that the error is this line:</p> <pre><code>from apps.website.managers import GenericManager </code></pre> <p>This is my code structure:</p> <p><a href="https://i.stack.imgur.com/1NfMI.png" rel="nofollow"><img src="https://i.stack.imgur.com/1NfMI.png" alt="enter image description here"></a></p> <p>How is the correct way to import a file from another app? Thanks!</p>
0
2016-10-15T01:30:46Z
40,054,163
<p>in setting try to add this line after BASE_DIR <code>sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))</code> dont forget <code>import os import sys</code></p>
1
2016-10-15T01:50:17Z
[ "python", "django", "django-1.10" ]
parallel ping using gevent
40,054,079
<p>I am new to python and I am trying to run this code to want parallel ping of multiple machines.but I can not ping all IP concurrently. seems it run one after another .can some one please guide me on how can i ping multiple server concurrently.</p> <pre><code>import gevent import urllib2 import os from gevent import monkey monkey.patch_all() def print_head(i): switch='192.168.182.170' response = os.system("ping -c 5 " + switch) jobs = [gevent.spawn(print_head, i) for i in range(1,10)] gevent.joinall(jobs, timeout=2) </code></pre>
2
2016-10-15T01:32:33Z
40,054,236
<p><code>os.system</code> is not patched, but <a href="https://docs.python.org/3/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call</code></a> is patched; Replace <code>os.system</code> with <code>subprocess.call</code> (You can also use <a href="https://docs.python.org/3/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.run</code></a> if you are using Python 3.5+)</p> <pre><code>import subprocess ... def print_head(i): switch = '192.168.182.170' response = subprocess.call("ping " + switch) </code></pre>
0
2016-10-15T02:06:36Z
[ "python", "gevent" ]
parallel ping using gevent
40,054,079
<p>I am new to python and I am trying to run this code to want parallel ping of multiple machines.but I can not ping all IP concurrently. seems it run one after another .can some one please guide me on how can i ping multiple server concurrently.</p> <pre><code>import gevent import urllib2 import os from gevent import monkey monkey.patch_all() def print_head(i): switch='192.168.182.170' response = os.system("ping -c 5 " + switch) jobs = [gevent.spawn(print_head, i) for i in range(1,10)] gevent.joinall(jobs, timeout=2) </code></pre>
2
2016-10-15T01:32:33Z
40,054,250
<p>The problem is that <code>os.system("ping -c 5 " + switch)</code> is running synchronously, because the function is blocking. You should try to do it in different processes.</p> <p>Here is a concurrent code that does the same.</p> <pre><code>from multiprocessing import Process import os def print_head(i): switch='192.168.182.170' response = os.system("ping -c 5 " + switch) processes = [Process(target=print_head, args=(i,)) for i in range(1,10)] for process in processes: process.start() </code></pre>
0
2016-10-15T02:10:11Z
[ "python", "gevent" ]
Unable to run code through python file or jupyter (ipython notebook), working successfully through terminal python
40,054,142
<p>I have this python code:</p> <pre><code>#!/usr/bin/env python import pyodbc from pandas import * conn = pyodbc.connect("DSN=drill64", autocommit=True) cursor = conn.cursor() </code></pre> <p>which on running as a .py file aur running through ipython notebook gives me the below error</p> <pre><code>Traceback (most recent call last): File "/home/ubuntu/TestingDrillQuery.py", line 14, in &lt;module&gt; conn = pyodbc.connect("DSN=drill64", autocommit=True) pyodbc.Error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib '/opt/mapr/drillodbc/lib/64/libmaprdrillodbc64.so' : file not found (0) (SQLDriverConnect)") [Finished in 0.4s with exit code 1] </code></pre> <p>On running through terminal python everything works smoothly, any suggestions appreciated.</p>
0
2016-10-15T01:44:52Z
40,054,184
<p>Ok, I was able to solve it by changing permission to .py file <code>chmod +x TestingDrillQuery.py</code></p>
0
2016-10-15T01:55:41Z
[ "python", "odbc", "pyodbc" ]
Editing a value in a DataFrame
40,054,147
<p>I'm trying to:</p> <p>Import a CSV of UPC codes into a dataframe. If the UPC code is 11 characters , append '0' to it. Ex: 19962123818 --> 019962123818</p> <p>This is the code:</p> <pre><code> #check UPC code length. If 11 characters, adds '0' before. If &lt; 11 or &gt; 13, throws Error for index, row in clean_data.iterrows(): if len(row['UPC']) == 11: row['UPC'] = ('0' + row['UPC']) #clean_data.set_value(row, 'UPC',('0' + (row['UPC'])) print ("Edited UPC:", row['UPC'], type(row['UPC'])) if len(row['UPC']) &lt; 11 or len(row['UPC']) &gt; 13: print ('Error, UPC length &lt; 11 or &gt; 13:') print ("Error in UPC:", row['UPC']) quit() </code></pre> <p>However, when I print the data, the original value is not edited:</p> <p><a href="https://i.stack.imgur.com/xMad7.png" rel="nofollow"><img src="https://i.stack.imgur.com/xMad7.png" alt="enter image description here"></a></p> <p>Does anyone know what is causing this issue?</p> <p>I tried the set_value method as mentioned in other posts, but it didn't work.</p> <p>Thanks!</p> <hr> <p>Thanks for the vectorized approach, much cleaner! However, I get the following error, and the value is still not updating:</p> <p><a href="https://i.stack.imgur.com/IjFSt.png" rel="nofollow"><img src="https://i.stack.imgur.com/IjFSt.png" alt="enter image description here"></a></p>
1
2016-10-15T01:46:40Z
40,054,276
<p>Can I suggest a different method? </p> <pre><code>#identify the strings shorter than 11 characters fix_indx = clean_data.UPC.astype(str).str.len()&lt;11 #append these strings with a '0' clean_data.loc[fix_indx] = '0'+clean_data[fix_indx].astype(str) </code></pre> <p>To fix the others, you can similarly do:</p> <pre><code>bad_length_indx = clean_data.UPC.astype(str).str.len()&gt;13 clean_data.loc[bad_length] = np.nan </code></pre>
4
2016-10-15T02:14:25Z
[ "python", "csv", "pandas", "dataframe" ]
Editing a value in a DataFrame
40,054,147
<p>I'm trying to:</p> <p>Import a CSV of UPC codes into a dataframe. If the UPC code is 11 characters , append '0' to it. Ex: 19962123818 --> 019962123818</p> <p>This is the code:</p> <pre><code> #check UPC code length. If 11 characters, adds '0' before. If &lt; 11 or &gt; 13, throws Error for index, row in clean_data.iterrows(): if len(row['UPC']) == 11: row['UPC'] = ('0' + row['UPC']) #clean_data.set_value(row, 'UPC',('0' + (row['UPC'])) print ("Edited UPC:", row['UPC'], type(row['UPC'])) if len(row['UPC']) &lt; 11 or len(row['UPC']) &gt; 13: print ('Error, UPC length &lt; 11 or &gt; 13:') print ("Error in UPC:", row['UPC']) quit() </code></pre> <p>However, when I print the data, the original value is not edited:</p> <p><a href="https://i.stack.imgur.com/xMad7.png" rel="nofollow"><img src="https://i.stack.imgur.com/xMad7.png" alt="enter image description here"></a></p> <p>Does anyone know what is causing this issue?</p> <p>I tried the set_value method as mentioned in other posts, but it didn't work.</p> <p>Thanks!</p> <hr> <p>Thanks for the vectorized approach, much cleaner! However, I get the following error, and the value is still not updating:</p> <p><a href="https://i.stack.imgur.com/IjFSt.png" rel="nofollow"><img src="https://i.stack.imgur.com/IjFSt.png" alt="enter image description here"></a></p>
1
2016-10-15T01:46:40Z
40,054,360
<p>According to <code>iterrows</code>documentation:</p> <blockquote> <ol start="2"> <li>You should <strong>never modify</strong> something you are iterating over. This is not guaranteed to work in all cases. Depending on the data types, the iterator returns a copy and not a view, and writing to it will have no effect.</li> </ol> </blockquote> <p><code>row['UPC'] = ('0' + row['UPC'])</code> silently modifies a copy of the row, and <code>clean_data</code> is kept unmodified.</p> <p>Do adopt a vectorized approach of your algorithm like @Gene is suggesting.</p>
1
2016-10-15T02:32:35Z
[ "python", "csv", "pandas", "dataframe" ]
Editing a value in a DataFrame
40,054,147
<p>I'm trying to:</p> <p>Import a CSV of UPC codes into a dataframe. If the UPC code is 11 characters , append '0' to it. Ex: 19962123818 --> 019962123818</p> <p>This is the code:</p> <pre><code> #check UPC code length. If 11 characters, adds '0' before. If &lt; 11 or &gt; 13, throws Error for index, row in clean_data.iterrows(): if len(row['UPC']) == 11: row['UPC'] = ('0' + row['UPC']) #clean_data.set_value(row, 'UPC',('0' + (row['UPC'])) print ("Edited UPC:", row['UPC'], type(row['UPC'])) if len(row['UPC']) &lt; 11 or len(row['UPC']) &gt; 13: print ('Error, UPC length &lt; 11 or &gt; 13:') print ("Error in UPC:", row['UPC']) quit() </code></pre> <p>However, when I print the data, the original value is not edited:</p> <p><a href="https://i.stack.imgur.com/xMad7.png" rel="nofollow"><img src="https://i.stack.imgur.com/xMad7.png" alt="enter image description here"></a></p> <p>Does anyone know what is causing this issue?</p> <p>I tried the set_value method as mentioned in other posts, but it didn't work.</p> <p>Thanks!</p> <hr> <p>Thanks for the vectorized approach, much cleaner! However, I get the following error, and the value is still not updating:</p> <p><a href="https://i.stack.imgur.com/IjFSt.png" rel="nofollow"><img src="https://i.stack.imgur.com/IjFSt.png" alt="enter image description here"></a></p>
1
2016-10-15T01:46:40Z
40,059,261
<p>I finally fixed it. Thanks again for the vectorized idea. If anyone has this issue in the future, here's the code I used. Also, see <a href="http://stackoverflow.com/questions/13842088/set-value-for-particular-cell-in-pandas-dataframe">this post</a> for more info.</p> <pre><code>UPC_11_char = clean_data.UPC.astype(str).str.len() == 11 clean_data.ix[UPC_11_char, 'UPC'] = '0' + clean_data[UPC_11_char]['UPC'].astype(str) print clean_data[UPC_11_char]['UPC'] </code></pre>
0
2016-10-15T12:54:12Z
[ "python", "csv", "pandas", "dataframe" ]
Get wget to never time out or catch timeout on python
40,054,167
<p>I am using python 2.7 with the wget module. <a href="https://pypi.python.org/pypi/wget" rel="nofollow">https://pypi.python.org/pypi/wget</a></p> <p>The URL to download is not responsive sometimes. It can take ages to download and when this happens, <code>wget</code> times out. How can I get wget to never time out or at least catch the timeout?</p> <p>The code to download is simple.</p> <pre><code>wget.download(url_download) </code></pre>
1
2016-10-15T01:50:47Z
40,054,214
<p>You could use <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a> instead:</p> <pre><code>requests.get(url_download) </code></pre> <p>if you don't specify a timeout argument it never times out.</p>
0
2016-10-15T02:02:10Z
[ "python", "python-2.7", "wget" ]
Include multiple headers in python requests
40,054,357
<p>I have this HTTPS call in curl below;</p> <pre><code>header1="projectName: zhikovapp" header2="Authorization: Bearer HZCdsf=" bl_url="https://BlazerNpymh.com/api/documents?pdfDate=$today" curl -s -k -H "$header1" -H "$header2" "$bl_url" </code></pre> <p>I would like to write an equivalent python call using requests module.</p> <pre><code>header ={ "projectName": "zhikovapp", "Authorization": "Bearer HZCdsf=" } response = requests.get(bl_url, headers = header) </code></pre> <p>However, the request was not valid. What is wrong?</p> <p>The contents of the returned response is like this;</p> <pre><code>&lt;Response [400]&gt; _content = '{"Message":"The request is invalid."}' headers = {'Content-Length': '37', 'Access-Control-Allow-Headers': 'projectname, authorization, Content-Type', 'Expires': '-1', 'cacheControlHeader': 'max-age=604800', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Date': 'Sat, 15 Oct 2016 02:41:13 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Content-Type': 'application/json; charset=utf-8'} reason = 'Bad Request' </code></pre> <p>I am using python 2.7</p> <p>EDIT: I corrected some syntex errors after Soviut pointed them out.</p>
1
2016-10-15T02:32:18Z
40,054,376
<p>In <code>request.get()</code> the <a href="http://docs.python-requests.org/en/master/user/quickstart/#custom-headers" rel="nofollow"><code>headers</code></a> argument should be defined as a dictionary, a set of key/value pairs. You've defined a set (a unique list) of strings instead.</p> <p>You should declare your headers like this:</p> <pre><code>headers = { "projectName": "zhikovapp", "Authorization": "Bearer HZCdsf=" } response = requests.get(bl_url, headers=headers) </code></pre> <p>Note the <code>"key": "value"</code> format of each line inside the dictionary.</p>
1
2016-10-15T02:37:14Z
[ "python", "python-2.7", "curl", "python-requests" ]
Element Tree find output empty text
40,054,420
<p>I have a problem using Element Tree to extract the text.</p> <p>My format of my xml file is</p> <pre><code>&lt;elecs id = 'elecs'&gt; &lt;elec id = "CLM-0001" num = "0001"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&gt; &lt;elec id = "CLM-0002" num = "0002"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&gt; &lt;/elecs&gt; </code></pre> <p>I want to extract out all the text inside the tag </p> <p>Assume that our xml file is in the variable xml</p> <pre><code>import xml.etree.ElementTree as ET import lxml import etree parser = etree.XMLParser(recover = True) contents = open(xml).read() tree = ET.fromstring(contents, parser = parser) elecsN = tree.find('elecs') for element in elecsN: print element.text </code></pre> <p>The problem is, the code above returns empty strings. I have tried my code above with other tags in my document and it works. I do not know why it returns empty string this time.</p> <p>Is there anyway i can solve this problem.</p> <p>Thank you very much</p>
0
2016-10-15T02:47:00Z
40,054,813
<p>If you actually mean 'any way' you could use lxml.</p> <pre><code>&gt;&gt;&gt; from io import StringIO &gt;&gt;&gt; html = StringIO('''\ ... &lt;elecs id = 'elecs'&gt; ... &lt;elec id = "CLM-0001" num = "0001"&gt; ... &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; ... &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; ... &lt;/elec&gt; ... &lt;elec id = "CLM-0002" num = "0002"&gt; ... &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; ... &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; ... &lt;/elec&gt; ... &lt;/elecs&gt; ... ''' ... ) &gt;&gt;&gt; from lxml import etree &gt;&gt;&gt; doc = etree.parse(html) &gt;&gt;&gt; doc.xpath('//elecs/elec/*/text()') [' blah blah blah ', ' blah blah blah ', ' blah blah blah ', ' blah blah blah '] </code></pre>
0
2016-10-15T04:03:49Z
[ "python", "xml", "elementtree" ]
Element Tree find output empty text
40,054,420
<p>I have a problem using Element Tree to extract the text.</p> <p>My format of my xml file is</p> <pre><code>&lt;elecs id = 'elecs'&gt; &lt;elec id = "CLM-0001" num = "0001"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&gt; &lt;elec id = "CLM-0002" num = "0002"&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;elec-text&gt; blah blah blah &lt;/elec-text&gt; &lt;/elec&gt; &lt;/elecs&gt; </code></pre> <p>I want to extract out all the text inside the tag </p> <p>Assume that our xml file is in the variable xml</p> <pre><code>import xml.etree.ElementTree as ET import lxml import etree parser = etree.XMLParser(recover = True) contents = open(xml).read() tree = ET.fromstring(contents, parser = parser) elecsN = tree.find('elecs') for element in elecsN: print element.text </code></pre> <p>The problem is, the code above returns empty strings. I have tried my code above with other tags in my document and it works. I do not know why it returns empty string this time.</p> <p>Is there anyway i can solve this problem.</p> <p>Thank you very much</p>
0
2016-10-15T02:47:00Z
40,055,313
<p>You can simply find elements that directly contains the text by name i.e <code>elec-text</code> in this case :</p> <pre><code>&gt;&gt;&gt; elec_texts = tree.findall('.//elec-text') &gt;&gt;&gt; for elec_text in elec_texts: ... print elec_text.text ... blah blah blah blah blah blah blah blah blah blah blah blah </code></pre>
1
2016-10-15T05:27:04Z
[ "python", "xml", "elementtree" ]
Python insert variable to mysql via mysql.connector
40,054,426
<p>I am trying to create one python script to insert data into mysql, but I got an error when I try to test it.</p> <p>This is how I create the table:</p> <pre><code>CREATE TABLE aaa ( id MEDIUMINT NOT NULL AUTO_INCREMENT, data CHAR(30) NOT NULL, PRIMARY KEY (id) ); </code></pre> <p>This is my python script:</p> <pre><code>import mysql.connector from time import strftime, gmtime, sleep cnx = mysql.connector.connect( user='root', password='abcd', database='test_db' ) cur = cnx.cursor() # get current timestamp curr_time = strftime("%Y%m%d_%H%M%S", gmtime()) cur.execute( "INSERT INTO aaa(data) VALUES (%s)", (curr_time) ) cnx.commit() cnx.close() </code></pre> <p>The error is like this:</p> <pre><code>mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1 </code></pre> <p>Can anyone help me solve this problem?</p>
0
2016-10-15T02:47:54Z
40,054,688
<p>replace <code>,</code> with <code>%</code> in <code>"INSERT INTO aaa(data) VALUES (%s)", (curr_time)</code> it should be <code>"INSERT INTO aaa(data) VALUES (%s)"%(curr_time)</code></p>
0
2016-10-15T03:37:55Z
[ "python", "mysql" ]
Python - utility program to check module availability
40,054,462
<p>Is there a command line(preferably) utility program that lists all <code>major</code> versions of python that come bundled with a particular module in that version's library? </p> <p>For example <code>json</code> module is only available in versions 2.6+</p> <p>So running this utility should list:</p> <pre><code>2.6 2.7 .. and the 3.x versions </code></pre>
0
2016-10-15T02:57:02Z
40,056,605
<p>There is no such built-in command.</p> <p>If having an internet connection is not an issue you can simply check the url at <code>https://docs.python.org/&lt;version-number&gt;/library/&lt;module-name&gt;.html</code>:</p> <pre><code>from urllib.request import urlopen from urllib.error import HTTPError def has_module(version, module_name): try: urlopen('https://docs.python.org/{}/library/{}.html'.format(version, module_name)) except HTTPError as e: if e.code == 404: return False raise e return True </code></pre> <p>Example usage:</p> <pre><code>In [2]: has_module('2.7', 'asyncio') Out[2]: False In [3]: has_module('3.3', 'asyncio') Out[3]: False In [4]: has_module('3.4', 'asyncio') Out[4]: True </code></pre> <p>Must be run in python3, but a python2 version isn't hard to write.</p> <p>If you want an offline tool you can always parse the page <code>https://docs.python.org/&lt;version-number&gt;/library/index.html</code> and obtain a list of module pages for that python version and then just build a <code>dict</code> that maps the python version to the set of available modules.</p>
1
2016-10-15T07:59:45Z
[ "python", "python-3.x" ]
scikit-learn vectorizing with big dataset
40,054,473
<p>I have 9GB of segmented documents on my disk and my vps only has 4GB memory.</p> <p>How can I vectorize all the data set without loading all the corpus at initialization? Is there any sample code? </p> <p>my code is as follows:</p> <pre><code>contents = [open('./seg_corpus/' + filename).read() for filename in filenames] vectorizer = CountVectorizer(stop_words=stop_words) vectorizer.fit(contents) </code></pre>
1
2016-10-15T02:59:20Z
40,056,620
<p>Try this, instead of loading all texts into memory you can pass only handles to files into <code>fit</code> method, but you must specify <code>input='file'</code> in <code>CountVectorizer</code> constructor.</p> <pre><code>contents = [open('./seg_corpus/' + filename) for filename in filenames] vectorizer = CountVectorizer(stop_words=stop_words, input='file') vectorizer.fit(contents) </code></pre>
1
2016-10-15T08:01:08Z
[ "python", "numpy", "machine-learning", "scikit-learn" ]
How to create a DataFrame series as a sub-string of a DataFrame Index?
40,054,615
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p> <p>As an example, if the index for a row is "32779", I'd like the new series' value to be "327".</p> <p>I thought a Lambda function may work e.g.</p> <pre><code>fte5['Zip3'] = fte5.index.astype(str).apply(lambda x: x[:3]) </code></pre> <p>But this gives an error</p>
1
2016-10-15T03:26:44Z
40,054,811
<p>This worked:</p> <pre><code>fte5['Zip3'] = fte5.index.get_level_values(0) fte5['Zip3'] = fte5['Zip3'].astype(str).apply(lambda x: x[:3]) </code></pre>
0
2016-10-15T04:03:15Z
[ "python", "pandas", "dataframe" ]
How to create a DataFrame series as a sub-string of a DataFrame Index?
40,054,615
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p> <p>As an example, if the index for a row is "32779", I'd like the new series' value to be "327".</p> <p>I thought a Lambda function may work e.g.</p> <pre><code>fte5['Zip3'] = fte5.index.astype(str).apply(lambda x: x[:3]) </code></pre> <p>But this gives an error</p>
1
2016-10-15T03:26:44Z
40,054,917
<p>The bracket operator on strings is exposed through <code>str.slice</code> function:</p> <pre><code>fte5.index.astype(str).str.slice(0,3) </code></pre>
2
2016-10-15T04:22:03Z
[ "python", "pandas", "dataframe" ]
How to create a DataFrame series as a sub-string of a DataFrame Index?
40,054,615
<p>I have a Pandas DataFrame which has a 5-digit string as its index (the index is a 5 digit zip code). I'd need to create another series in the DataFrame which is the first three characters of the index (i.e. the 3-Digit zip code).</p> <p>As an example, if the index for a row is "32779", I'd like the new series' value to be "327".</p> <p>I thought a Lambda function may work e.g.</p> <pre><code>fte5['Zip3'] = fte5.index.astype(str).apply(lambda x: x[:3]) </code></pre> <p>But this gives an error</p>
1
2016-10-15T03:26:44Z
40,055,494
<p>consider the <code>pd.DataFrame</code> <code>fte5</code></p> <pre><code>fte5 = pd.DataFrame(np.ones((3, 2)), ['01234', '34567', '56789'], ['X', 'Y']) fte5 </code></pre> <p><a href="https://i.stack.imgur.com/1AHww.png" rel="nofollow"><img src="https://i.stack.imgur.com/1AHww.png" alt="enter image description here"></a></p> <p>If you already have 5 digit zipcodes that start with <code>0</code> then they must be <code>str</code> already. The simplest way to get at the first 3 characters in a vectorized way is to use the <code>.str</code> string accessor rather than use <code>apply</code>.</p> <pre><code>fte5.index.str[:3] Index(['012', '345', '567'], dtype='object') </code></pre> <p>We can assign it to <code>fte5['Zip3']</code> with <code>insert</code></p> <pre><code>fte5.insert(2, 'Zip3', fte5.index[:3]) </code></pre>
0
2016-10-15T05:50:51Z
[ "python", "pandas", "dataframe" ]
How to save code file on GitHub and run on Jupyter notebook?
40,054,672
<p>With GitHub we can store our code online, and with Jupyter notebook we can execute only a segment of our Python code. I want to use them together. I am able to edit code with Jupyter notebook that is stored on my computer. But, I am unable to find a way to run a code that stored on GitHub. So, do you know a way to do that.</p> <p>Here are some examples: <a href="https://github.com/biolab/ipynb/blob/master/2015-bi/lcs.ipynb" rel="nofollow">https://github.com/biolab/ipynb/blob/master/2015-bi/lcs.ipynb</a> <a href="https://github.com/julienr/ipynb_playground/blob/master/misc_ml/curse_dimensionality.ipynb" rel="nofollow">https://github.com/julienr/ipynb_playground/blob/master/misc_ml/curse_dimensionality.ipynb</a> <a href="https://github.com/rvuduc/cse6040-ipynbs/blob/master/01--intro-py.ipynb" rel="nofollow">https://github.com/rvuduc/cse6040-ipynbs/blob/master/01--intro-py.ipynb</a></p>
-1
2016-10-15T03:34:52Z
40,054,705
<p>Github is a tool for version and source control, you will need to get a copy of the code to a local environment.</p> <p>There is a beginner's tutorial <a href="http://readwrite.com/2013/09/30/understanding-github-a-journey-for-beginners-part-1/" rel="nofollow">here</a></p> <p>Once that you have set up a github account and define your local and remote repositories, you will be able to retrieve the code with <code>git checkout</code>. Further explanation is in the tutorial </p>
1
2016-10-15T03:40:43Z
[ "python", "git", "github", "jupyter-notebook" ]
Strange behaviour of delete dictionary operation on nested dictionary
40,054,685
<pre><code>#!/usr/bin/python import numpy as np td={} d = {} for col in ['foo','bar','baz']: for row in ['a','b','c','d']: td.setdefault(row, np.random.randn()) d.setdefault(col, td) print d del d['foo']['c'] print d </code></pre> <p>output:</p> <pre><code>{'baz': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'foo': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'bar': {'a': -1.6340274257732716, 'c': 0.6674016962534858, 'b': 2.0410088421902652, 'd': -1.2602923734811284}} {'baz': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'foo': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}, 'bar': {'a': -1.6340274257732716, 'b': 2.0410088421902652, 'd': -1.2602923734811284}} </code></pre> <p>Intention here is to delete only <code>d['foo']['c]</code>, but all the <code>'c'</code>'s are getting deleted across <code>'foo', 'bar', 'baz'</code> .. Not sure if this has been already answered on this forum, if yes please point me to that answer.</p>
0
2016-10-15T03:36:55Z
40,054,709
<p>You are setting each value in <code>d</code> to reference the same copy of <code>td</code>. If you want the copies to be distinct, you'll need to create more than one <code>td</code> dictionary.</p> <p>Try this:</p> <pre><code>#!/usr/bin/python import numpy as np d = {} for col in ['foo','bar','baz']: td = {} for row in ['a','b','c','d']: td.setdefault(row, np.random.randn()) d.setdefault(col, td) print d del d['foo']['c'] print d </code></pre>
0
2016-10-15T03:41:15Z
[ "python" ]
Python: HTTPConnectionPool(host='%s', port=80):
40,054,711
<pre><code>import requests import urllib3 from time import sleep from sys import argv script, filename = argv http = urllib3.PoolManager() datafile = open('datafile.txt','w') crawl = "" with open(filename) as f: mylist = f.read().splitlines() def crawlling(x): for i in mylist: domain = ("http://" + "%s") % i crawl = http.request('GET','%s',preload_content=False) % domain for crawl in crawl.stream(32): print crawl sleep(10) crawl.release_conn() datafile.write(crawl.status) datafile.write('&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;\n') datafile.write(crawl.data) datafile.close() return x crawlling(crawl) _______________________________________________________________________ Extract of domain.txt file: fjarorojo.info buscadordeproductos.com </code></pre> <p>I'm new to python so bear with me: I'm trying to trying get content from URL but it's throwing error. Further, it's working fine in browser. Object of script is to get the data from domain.txt file and iterate over it and fetch the content and save it in file.</p> <pre><code>Getting this error: raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='%s', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('&lt;urllib3.connection.HTTPConnection object at 0x7ff45e4f9cd0&gt;: Failed to establish a new connection: [Errno -2] Name or service not known',)) </code></pre>
1
2016-10-15T03:41:39Z
40,060,810
<p>This line is the problem:</p> <pre><code>crawl = http.request('GET','%s',preload_content=False) % domain </code></pre> <p>Right now you're trying to make a request to the domain <code>%s</code> which is not a valid domain, hence the error "Name or service not known".</p> <p>It should be:</p> <pre><code>crawl = http.request('GET', '%s' % domain, preload_content=False) </code></pre> <p>Or more simply:</p> <pre><code>crawl = http.request('GET', domain, preload_content=False) </code></pre> <p>Also, unrelated to the error you posted, these lines will likely cause problems too:</p> <pre><code> for crawl in crawl.stream(32): print crawl sleep(10) crawl.release_conn() # &lt;-- </code></pre> <p>You're releasing the connection in a loop, so the loop will fail to yield the expected results on the second iteration. Instead, you should only release the connection once you're done with the request. <a href="http://urllib3.readthedocs.io/en/latest/advanced-usage.html?highlight=stream#streaming-and-io" rel="nofollow">More details here</a>.</p>
0
2016-10-15T15:22:12Z
[ "python", "web-scraping", "python-requests", "urllib3" ]
Python TypeError: unsupported operand type(s) for -: 'str' and 'str'
40,054,715
<p>I am trying to convert the following code written in Python 2 to code that is compatible with Python 3. I am receiving the following error:</p> <blockquote> <p>File "C:/Users/brand/AppData/Local/Programs/Python/Python35-32/Ch‌​ange Maker.py", </p> <p>line 5, in CHANGE = MONEY - PRICE</p> <p>TypeError: unsupported operand type(s) for -: 'str' and 'str'</p> </blockquote> <p>Here is the code that I am using:</p> <pre><code>PRICE = input("Price of item: ") MONEY = input("Cash tendered: ") CHANGE = MONEY - PRICE print ("Change: ", CHANGE) </code></pre>
0
2016-10-15T03:42:35Z
40,054,741
<p><code>input()</code> in Python 3 is equivalent to <code>raw_input()</code> in Python 2. Thus, <code>PRICE</code> and <code>MONEY</code> are strings, not integers as you are expecting.</p> <p>To fix this, change them to integers:</p> <pre><code>PRICE = int(input("Price of item: ")) MONEY = int(input("Cash tendered: ")) </code></pre>
4
2016-10-15T03:48:55Z
[ "python" ]
Python TypeError: unsupported operand type(s) for -: 'str' and 'str'
40,054,715
<p>I am trying to convert the following code written in Python 2 to code that is compatible with Python 3. I am receiving the following error:</p> <blockquote> <p>File "C:/Users/brand/AppData/Local/Programs/Python/Python35-32/Ch‌​ange Maker.py", </p> <p>line 5, in CHANGE = MONEY - PRICE</p> <p>TypeError: unsupported operand type(s) for -: 'str' and 'str'</p> </blockquote> <p>Here is the code that I am using:</p> <pre><code>PRICE = input("Price of item: ") MONEY = input("Cash tendered: ") CHANGE = MONEY - PRICE print ("Change: ", CHANGE) </code></pre>
0
2016-10-15T03:42:35Z
40,054,891
<p><code>input</code> returns a string in Python 3</p> <p>Also for money I would recommend <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code></a> due to <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow"><code>float</code> lack of precision</a></p> <pre><code>import decimal price = decimal.Decimal(input("Price of item: ")) money = decimal.Decimal(input("Cash tendered: ")) change = money - price print("Change: {change}".format(change=change)) </code></pre>
0
2016-10-15T04:17:05Z
[ "python" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:</p> <pre><code>[38.00, 15.20] [69.99] </code></pre>
0
2016-10-15T03:47:18Z
40,054,782
<p>You can try something like</p> <pre><code>the_string = "38.00,SALE ,15.20" floats = [] for possible_float in the_string.split(','): try: floats.append (float (possible_float.strip()) except: pass print floats </code></pre>
0
2016-10-15T03:56:18Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:</p> <pre><code>[38.00, 15.20] [69.99] </code></pre>
0
2016-10-15T03:47:18Z
40,054,810
<pre><code>def extract_nums(text): for item in text.split(','): try: yield float(item) except ValueError: pass print list(extract_nums("38.00,SALE ,15.20")) print list(extract_nums("69.99")) </code></pre> <hr> <pre><code>[38.0, 15.2] [69.99] </code></pre> <p>However by using <code>float</code> conversion you are <a href="https://docs.python.org/2/tutorial/floatingpoint.html" rel="nofollow">losing precision</a>, If you want to keep the precision you can use <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow"><code>decimal</code></a>:</p> <pre><code>import decimal def extract_nums(text): for item in text.split(','): try: yield decimal.Decimal(item) except decimal.InvalidOperation: pass print list(extract_nums("38.00,SALE ,15.20")) print list(extract_nums("69.99")) </code></pre> <hr> <pre><code>[Decimal('38.00'), Decimal('15.20')] [Decimal('69.99')] </code></pre>
2
2016-10-15T04:02:59Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:</p> <pre><code>[38.00, 15.20] [69.99] </code></pre>
0
2016-10-15T03:47:18Z
40,054,831
<p>Try a list comprehension: </p> <pre><code>just_floats = [i for i in your_list.split(',') if i.count('.') == 1] </code></pre> <p>first you split the string where the commas are, then you filter through the string and get rid of values that don't have a decimal place</p>
0
2016-10-15T04:06:26Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:</p> <pre><code>[38.00, 15.20] [69.99] </code></pre>
0
2016-10-15T03:47:18Z
40,054,851
<p>You said you're only interested in floats at the start and end of the string, so assuming it's comma-delimited:</p> <pre><code>items = the_string.split(',') try: first = float(items[0]) except (ValueError, IndexError): pass try: second = float(items[-1]) except (ValueError, IndexError): pass </code></pre> <p>We have to wrap the operations in exception handlers since the value might not be a valid float (<code>ValueError</code>) or the index might not exist in the <code>list</code> (an <code>IndexError</code>).</p> <p>This will handle all cases including if one or both of the floats is omitted.</p>
0
2016-10-15T04:09:50Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:</p> <pre><code>[38.00, 15.20] [69.99] </code></pre>
0
2016-10-15T03:47:18Z
40,054,882
<p>You could also use regex to do this</p> <pre><code>import re s = "38.00,SALE ,15.20" p = re.compile(r'\d+\.\d+') # Compile a pattern to capture float values floats = [float(i) for i in p.findall(s)] # Convert strings to float print floats </code></pre> <p>Output:</p> <pre><code>[38.0, 15.2] </code></pre>
2
2016-10-15T04:15:37Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:</p> <pre><code>[38.00, 15.20] [69.99] </code></pre>
0
2016-10-15T03:47:18Z
40,054,890
<pre><code>import re map(float, filter(lambda x: re.match("\s*\d+.?\d+\s*", x) , input.split(",")) </code></pre> <p>Input : <code>input = '38.00,SALE ,15.20'</code> Output: <code>[38.0, 15.2]</code></p> <p>Input : <code>input = '38.00,SALE ,15.20, 15, 34.'</code> Output: <code>[38.0, 15.2, 15.0, 34.0]</code></p> <p>Explanation: </p> <ol> <li>Idea is to split the string : <code>list_to_filter = input.split(",")</code> splits on <code>,</code> </li> <li>Then using regex filter strings which are real numbers: <code>filtered_list = filter(&lt;lambda&gt;, list_to_filter)</code> , here item is included in output of filter if lamda expression is true. So when <code>re.match("\s*\d+.?\d+\s*", x)</code> matches for string <code>x</code> filter keeps it. </li> <li>And finally convert into float. <code>map(float, filtered_list)</code>. What it does is apply <code>float()</code> function to each element of the list</li> </ol>
0
2016-10-15T04:17:02Z
[ "python", "string" ]
Python: Extract multiple float numbers from string
40,054,733
<p>Forgive me, I'm new to Python.</p> <p>Given a string that starts with a float of indeterminate length and ends with the same, how can I extract both of them into an array, or if there is just one float, just the one.</p> <p>Example: </p> <pre><code>"38.00,SALE ,15.20" "69.99" </code></pre> <p>I'd like to return:</p> <pre><code>[38.00, 15.20] [69.99] </code></pre>
0
2016-10-15T03:47:18Z
40,055,072
<p>Split the input, check if each element is numeric when the period is removed, convert to float if it is.</p> <pre><code>def to_float(input): return [float(x) for x in input.split(",") if unicode(x).replace(".", "").isdecimal()] </code></pre>
0
2016-10-15T04:51:09Z
[ "python", "string" ]
R-Python : how to eliminate specific rows and columns?
40,054,765
<p>Take this <strong>R</strong> demo as an example : </p> <pre><code>df &lt;- matrix(1:100, nrow = 10, ncol = 10) </code></pre> <p><em>df</em> :</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 85 95 [6,] 6 16 26 36 46 56 66 76 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100 </code></pre> <p>Now I want to eliminate <code>2:8</code> rows and <code>3:7</code> columns, so I did:</p> <pre><code>&gt; eliminated.rows &lt;- 2:8 &gt; eliminated.cols &lt;- 3:7 &gt; df &lt;- df[-eliminated.rows, -eliminated.cols] </code></pre> <p>Then I got what I want:</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [1,] 1 11 71 81 91 [2,] 9 19 79 89 99 [3,] 10 20 80 90 100 </code></pre> <p>Question is : </p> <p><strong>How to achieve my goal with Python ?</strong></p> <p><strong>EDIT:</strong></p> <p>To be specific, if I got lists of rows and columns to be eliminated, like <code>eliminated_rows = list(), eliminated_cols = list()</code>, and I want result <code>df = df[-eliminated_rows, -eliminated_cols]</code> with python.</p> <p>Any help will be appreciated.</p>
1
2016-10-15T03:52:23Z
40,055,105
<p>Try this (careful with the indices):</p> <pre><code>Try this: matrix = [] for row in range(0,100,10): column = [i for i in range(row,row+10)] matrix.append(column) columns_to_remove = [1,2,8] rows_to_remove = [4,5,9] for i in rows_to_remove: matrix.pop(i) for remaining_rows in matrix: for remove_column in matrix: matrix.pop(matrix[remaining_rows][remove_column]) </code></pre>
0
2016-10-15T04:56:25Z
[ "python" ]
R-Python : how to eliminate specific rows and columns?
40,054,765
<p>Take this <strong>R</strong> demo as an example : </p> <pre><code>df &lt;- matrix(1:100, nrow = 10, ncol = 10) </code></pre> <p><em>df</em> :</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 85 95 [6,] 6 16 26 36 46 56 66 76 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100 </code></pre> <p>Now I want to eliminate <code>2:8</code> rows and <code>3:7</code> columns, so I did:</p> <pre><code>&gt; eliminated.rows &lt;- 2:8 &gt; eliminated.cols &lt;- 3:7 &gt; df &lt;- df[-eliminated.rows, -eliminated.cols] </code></pre> <p>Then I got what I want:</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [1,] 1 11 71 81 91 [2,] 9 19 79 89 99 [3,] 10 20 80 90 100 </code></pre> <p>Question is : </p> <p><strong>How to achieve my goal with Python ?</strong></p> <p><strong>EDIT:</strong></p> <p>To be specific, if I got lists of rows and columns to be eliminated, like <code>eliminated_rows = list(), eliminated_cols = list()</code>, and I want result <code>df = df[-eliminated_rows, -eliminated_cols]</code> with python.</p> <p>Any help will be appreciated.</p>
1
2016-10-15T03:52:23Z
40,055,907
<p>You could do this:</p> <pre><code>df = pd.DataFrame(np.random.randint(0,100,size=(10, 10)), columns=list('ABCDEFGHIJ')) row_i= df.index.isin(range(1,8)) col_i=df.index.isin(range(2,7)) df.iloc[~row_i,~col_i] </code></pre> <p>Be careful of the index as it starts from 0 in python.</p>
1
2016-10-15T06:44:42Z
[ "python" ]
R-Python : how to eliminate specific rows and columns?
40,054,765
<p>Take this <strong>R</strong> demo as an example : </p> <pre><code>df &lt;- matrix(1:100, nrow = 10, ncol = 10) </code></pre> <p><em>df</em> :</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 11 21 31 41 51 61 71 81 91 [2,] 2 12 22 32 42 52 62 72 82 92 [3,] 3 13 23 33 43 53 63 73 83 93 [4,] 4 14 24 34 44 54 64 74 84 94 [5,] 5 15 25 35 45 55 65 75 85 95 [6,] 6 16 26 36 46 56 66 76 86 96 [7,] 7 17 27 37 47 57 67 77 87 97 [8,] 8 18 28 38 48 58 68 78 88 98 [9,] 9 19 29 39 49 59 69 79 89 99 [10,] 10 20 30 40 50 60 70 80 90 100 </code></pre> <p>Now I want to eliminate <code>2:8</code> rows and <code>3:7</code> columns, so I did:</p> <pre><code>&gt; eliminated.rows &lt;- 2:8 &gt; eliminated.cols &lt;- 3:7 &gt; df &lt;- df[-eliminated.rows, -eliminated.cols] </code></pre> <p>Then I got what I want:</p> <pre><code>&gt; df [,1] [,2] [,3] [,4] [,5] [1,] 1 11 71 81 91 [2,] 9 19 79 89 99 [3,] 10 20 80 90 100 </code></pre> <p>Question is : </p> <p><strong>How to achieve my goal with Python ?</strong></p> <p><strong>EDIT:</strong></p> <p>To be specific, if I got lists of rows and columns to be eliminated, like <code>eliminated_rows = list(), eliminated_cols = list()</code>, and I want result <code>df = df[-eliminated_rows, -eliminated_cols]</code> with python.</p> <p>Any help will be appreciated.</p>
1
2016-10-15T03:52:23Z
40,068,568
<p>After checking <a href="https://community.modeanalytics.com/python/tutorial/pandas-dataframe/" rel="nofollow">select data from data frame</a>,I think this solution may be easier to understand : </p> <p>E.g. <code>3 * 3</code> DataFrame, eliminate rows <code>1,2</code>, columns <code>0,1</code>: </p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(np.random.randint(0, 9, size = (3, 3))) #print df eliminated_rows = [1, 2] #rows to eliminated eliminated_cols = [0, 1] #cols to eliminated range_rows = range(0, df.shape[0]) remaining_rows = [row for row in range_rows if row not in eliminated_rows] range_cols = range(0, df.shape[1]) remaining_cols = [col for col in range_cols if col not in eliminated_cols] df = df.iloc[remaining_rows, remaining_cols] #print df </code></pre> <blockquote> <p>Original DataFrame <code>3 * 3</code>:</p> </blockquote> <pre><code> 0 1 2 0 4 3 3 1 2 8 7 2 5 1 7 </code></pre> <blockquote> <p>Result :</p> </blockquote> <pre><code> 2 0 3 </code></pre>
0
2016-10-16T08:54:06Z
[ "python" ]
numpy.load() wrong magic string error
40,054,872
<p>I have two files. One creates a <code>numpy</code> array in compressed sparse row format</p> <pre><code>from sklearn.feature_extraction.text import TfidfTransformer import pdb def stem_document(document): translatedict = "" stemmer = PorterStemmer() for word in string.punctuation: translatedict = translatedict + word doc_stemmed = [] for word in document.split(): lowerstrippedword = ''.join(c for c in word.lower() if c not in translatedict) try: stemmed_word = stemmer.stem(lowerstrippedword) doc_stemmed.append(stemmed_word) except: print lowerstrippedword + " could not be stemmed." return ' '.join(doc_stemmed) def readFileandStem(filestring): with open(filestring, 'r') as file: reader = csv.reader(file) file_extras = [] vector_data = [] error = False while (error == False): try: next = reader.next() if len(next) == 3 and next[2] != "": document = next[2] stemmed_document = stem_document(document) vector_data.append(stemmed_document) file_extra = [] file_extra.append(next[0]) file_extra.append(next[1]) file_extras.append(file_extra) except: error = True return [vector_data, file_extras] filestring = 'Data.csv' print "Reading File" data = readFileandStem(filestring) documents = data[0] file_extras = data[1] print "Vectorizing Data" vectorizer = CountVectorizer() matrix = vectorizer.fit_transform(documents) tf_idf_transform = TfidfTransformer(use_idf=False).fit(matrix) tf_idf_matrix = tf_idf_transform.transform(matrix) with open('matrix/matrix.npy', 'w') as matrix_file: np.save(matrix_file, tf_idf_matrix) file_json_map = {} file_json_map['extras'] = file_extras with open('matrix/extras.json', 'w') as extras_file: extras_file.write(json.dumps(file_json_map)) print "finished" </code></pre> <p>The next file is supposed to load the same file...</p> <pre><code>import numpy as np from scipy.cluster.hierarchy import dendrogram, linkage import json import pdb with open('matrix/matrix.npy', 'r') as matrix_file: matrix = np.load(matrix_file) hcluster = linkage(matrix, "complete") </code></pre> <p>However, I get the following error:</p> <pre><code>File "Cluster.py", line 7, in &lt;module&gt; matrix = np.load(matrix_file) File "C:\Users\jarek\Anaconda2\lib\site-packages\numpy\lib\npyio.py", line 406, in load pickle_kwargs=pickle_kwargs) File "C:\Users\jarek\Anaconda2\lib\site-packages\numpy\lib\format.py", line 620, in read_array version = read_magic(fp) File "C:\Users\jarek\Anaconda2\lib\site-packages\numpy\lib\format.py", line 216, in read_magic raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2])) ValueError: the magic string is not correct; expected '\x93NUMPY', got '\x00\x00I\x1c\x00\x00' </code></pre> <p>I don't know why the magic string would be incorrect because from what I've looked into, all .npy files are supposed to have the same magic string "\x93NUMPY".</p> <p>Ideas?</p>
1
2016-10-15T04:13:56Z
40,079,904
<p>I encountered similar issue before.</p> <p>Changing</p> <pre><code>open('matrix/matrix.npy', 'w') ... open('matrix/matrix.npy', 'r') </code></pre> <p>to</p> <pre><code>open('matrix/matrix.npy', 'wb') ... open('matrix/matrix.npy', 'rb') </code></pre> <p>solved my problem.</p>
0
2016-10-17T06:37:11Z
[ "python", "numpy" ]
Python urlopen "expected string or buffer"
40,054,894
<p>I am getting the "expected string or buffer" error in my simple python file. I am trying to get the titles of reddit articles written down.</p> <pre><code>from urllib import urlopen import re worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/") collectTitle = re.compile('&lt;p class="title"&gt;&lt;a.*&gt;(.*)&lt;/a&gt;') findTitle = re.findall(collectTitle, worldNewsPage) listIterator = [] listIterator[:] = range(1,3) for i in listIterator: print findTitle print </code></pre>
0
2016-10-15T04:17:59Z
40,054,905
<p>Change</p> <pre><code>worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/") </code></pre> <p>to</p> <pre><code>worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/").read() </code></pre> <p>Also <a href="http://stackoverflow.com/a/1732454/1219006">don't use <code>regex</code> to parse <code>html</code></a>. You can use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>BeautifulSoup</code></a></p>
1
2016-10-15T04:19:47Z
[ "python", "rss" ]
Python urlopen "expected string or buffer"
40,054,894
<p>I am getting the "expected string or buffer" error in my simple python file. I am trying to get the titles of reddit articles written down.</p> <pre><code>from urllib import urlopen import re worldNewsPage = urlopen("https://www.reddit.com/r/worldnews/") collectTitle = re.compile('&lt;p class="title"&gt;&lt;a.*&gt;(.*)&lt;/a&gt;') findTitle = re.findall(collectTitle, worldNewsPage) listIterator = [] listIterator[:] = range(1,3) for i in listIterator: print findTitle print </code></pre>
0
2016-10-15T04:17:59Z
40,055,536
<p>Urlopen is an object so you have to call the method read to get the contents you downloaded (like files).</p>
0
2016-10-15T05:57:01Z
[ "python", "rss" ]
Dynamic IMDb scrapper to see ranked personalities
40,054,914
<p>I want to create an online dynamic ranklist of actors/directors from their IMDb data. I have used BeautifulSoup previously to create an offline version for movies. But as it is over 2 years old, the top 250 rankings have changed.</p> <p>Is there a specific recommended method to create an online ranker? I hear about Scrapy+Flask but I have no idea about them.</p>
-4
2016-10-15T04:20:46Z
40,054,948
<p>IMDB releases data in plain text and you do not need to scrape it - <a href="http://www.imdb.com/interfaces" rel="nofollow">http://www.imdb.com/interfaces</a>. Diffs are released weekly. (So that the whole does not need to be downloaded again and again)</p>
1
2016-10-15T04:28:20Z
[ "python", "web-scraping", "imdb" ]
How do you install Tensorflow on Windows?
40,054,935
<p>I am trying to install Tensorflow on Windows. </p> <p>I have Anaconda 4.2.0. I tried running </p> <pre><code>conda create -n tensorflow python=3.5 </code></pre> <p>in my command prompt. This seemed to do something, but I'm not sure what this accomplished. It created a folder within the Anaconda3 program in my username folder. </p> <p><a href="https://i.stack.imgur.com/1AUIU.png" rel="nofollow"><img src="https://i.stack.imgur.com/1AUIU.png" alt="enter image description here"></a></p> <p>This folder is filled with the following content:</p> <p><a href="https://i.stack.imgur.com/X8JL6.png" rel="nofollow"><img src="https://i.stack.imgur.com/X8JL6.png" alt="enter image description here"></a></p> <p>Over the summer, I used mainly Jupyter Notebooks to do my python coding. Within this environment, there is a tab marked <code>Condas</code></p> <p><a href="https://i.stack.imgur.com/DFYBa.png" rel="nofollow"><img src="https://i.stack.imgur.com/DFYBa.png" alt="enter image description here"></a></p> <p>So it looks like I should be able to switch to the Tensorflow environment. But this doesn't work when I try to switch, there is no option to change my kernel to a Tensorflow one. <a href="https://i.stack.imgur.com/gIBIY.png" rel="nofollow"><img src="https://i.stack.imgur.com/gIBIY.png" alt="enter image description here"></a></p> <p>I tried running </p> <pre><code>conda search tensorflow </code></pre> <p><a href="https://i.stack.imgur.com/UAH96.png" rel="nofollow"><img src="https://i.stack.imgur.com/UAH96.png" alt="enter image description here"></a></p> <p>But nothing appears. </p> <p>I'm not sure what to do. I asked a few grad students in my economics research group, but they weren't sure what to do either. </p> <h1>My Question</h1> <p>How do I properly install Tensorflow on Windows?</p>
2
2016-10-15T04:26:06Z
40,055,000
<p>The syntax of the command is <code>conda create -n &lt;name_of_new_env&gt; &lt;packages&gt;</code>. As a result, you created a clean environment named <code>tensorflow</code> with only Python 3.5 installed. Since <code>conda search tensorflow</code> returned nothing, you will have to use <code>pip</code> or some other method of installing the package. Since there is spotty official support for Windows, the conda-forge package (CPU only) at <a href="https://github.com/conda-forge/tensorflow-feedstock" rel="nofollow">https://github.com/conda-forge/tensorflow-feedstock</a> is probably the best way.</p> <p>People have also reported success installing Tensorflow with docker, if you have docker set up already.</p>
2
2016-10-15T04:38:46Z
[ "python", "tensorflow" ]
How do you install Tensorflow on Windows?
40,054,935
<p>I am trying to install Tensorflow on Windows. </p> <p>I have Anaconda 4.2.0. I tried running </p> <pre><code>conda create -n tensorflow python=3.5 </code></pre> <p>in my command prompt. This seemed to do something, but I'm not sure what this accomplished. It created a folder within the Anaconda3 program in my username folder. </p> <p><a href="https://i.stack.imgur.com/1AUIU.png" rel="nofollow"><img src="https://i.stack.imgur.com/1AUIU.png" alt="enter image description here"></a></p> <p>This folder is filled with the following content:</p> <p><a href="https://i.stack.imgur.com/X8JL6.png" rel="nofollow"><img src="https://i.stack.imgur.com/X8JL6.png" alt="enter image description here"></a></p> <p>Over the summer, I used mainly Jupyter Notebooks to do my python coding. Within this environment, there is a tab marked <code>Condas</code></p> <p><a href="https://i.stack.imgur.com/DFYBa.png" rel="nofollow"><img src="https://i.stack.imgur.com/DFYBa.png" alt="enter image description here"></a></p> <p>So it looks like I should be able to switch to the Tensorflow environment. But this doesn't work when I try to switch, there is no option to change my kernel to a Tensorflow one. <a href="https://i.stack.imgur.com/gIBIY.png" rel="nofollow"><img src="https://i.stack.imgur.com/gIBIY.png" alt="enter image description here"></a></p> <p>I tried running </p> <pre><code>conda search tensorflow </code></pre> <p><a href="https://i.stack.imgur.com/UAH96.png" rel="nofollow"><img src="https://i.stack.imgur.com/UAH96.png" alt="enter image description here"></a></p> <p>But nothing appears. </p> <p>I'm not sure what to do. I asked a few grad students in my economics research group, but they weren't sure what to do either. </p> <h1>My Question</h1> <p>How do I properly install Tensorflow on Windows?</p>
2
2016-10-15T04:26:06Z
40,064,285
<p>I was able to run it under the Windows 10 linux subsystem (<a href="https://msdn.microsoft.com/en-us/commandline/wsl/install_guide" rel="nofollow">https://msdn.microsoft.com/en-us/commandline/wsl/install_guide</a>)</p> <p>Which is basically a linux environment within windows.</p>
0
2016-10-15T21:14:06Z
[ "python", "tensorflow" ]
Creating nested dictionary using python
40,055,008
<p>I am having a data for nodes in csv format. I want to create a dictionary for the analysis. The data I have looks like </p> <pre><code>Init node Term node Capacity 1 2 25900.20064 1 3 23403.47319 2 1 25900.20064 2 6 4958.180928 3 1 23403.47319 3 4 17110.52372 3 12 23403.47319 4 3 17110.52372 4 5 17782.7941 </code></pre> <p>So one node is connected to other node having some capacity. So, I want a dictionary in python which creates a data like this</p> <pre><code>graph = {'1': {'2': 25900.20064, '3': 23403.47319}, '2': {'1': 25900.20064, '6':4958.180928}, '3': {'1': 23403.47319, '4'}} </code></pre> <p>I tried following code to do this..</p> <pre><code>import xlrd file_location = "C:/Users/12/Desktop/SiouxFalls_net1.xlsx" workbook = xlrd.open_workbook(file_location) sheet = workbook.sheet_by_index(0) dict = {} z = {} for rows in range(sheet.nrows): a = sheet.cell_value(rows,0) dict[a] = {} for rows in range(sheet.nrows): b = sheet.cell_value(rows,1) c = sheet.cell_value(rows, 2) dict[a][b] = c </code></pre> <p>But I am having trouble in picking up the unique value from first column and assign other nodes data linked to it. Please help!</p> <pre><code>print(dict) </code></pre>
0
2016-10-15T04:40:01Z
40,055,147
<p>Try this loop:</p> <pre><code>sheet = workbook.sheet_by_index(0) d = {} for rows in range(sheet.nrows): a = sheet.cell_value(rows, 0) b = sheet.cell_value(rows, 1) c = sheet.cell_value(rows, 2) d.setdefault(a, {})[b] = c d.setdefault(b, {})[a] = c </code></pre>
1
2016-10-15T05:03:17Z
[ "python", "dictionary", "hyperlink", "nodes" ]
Pygame responds incorrectly to button clicks
40,055,096
<p>I'm having an issue with pygame. I've set up a window that randomly places circles across the screen very quickly, just for testing purposes. There are also three buttons: play/pause (switches back and forth, stops circles from appearing) and an increase speed and decrease speed button. I'm not very experienced with python or pygame, but I've come up with this function to create a clickable button on the screen:</p> <pre><code>def makeButton(rect, color, hovercolor, text, textsize, textcolor): clicked = False for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: clicked = True mouse = pygame.mouse.get_pos() rect = pygame.Rect(rect) displaycolor = color if rect.collidepoint(mouse): displaycolor = hovercolor buttonSurface = pygame.draw.rect(gameDisplay, displaycolor, rect, 0) font = pygame.font.Font('freesansbold.ttf',textsize) TextSurf = font.render(text, True, textcolor) TextRect = TextSurf.get_rect() TextRect.center = rect.center gameDisplay.blit(TextSurf, TextRect) if clicked: return True else: return False </code></pre> <p>This function can definitely be shortened and simplified, but it has worked for me, up until now. I took out a big chunk of code that I realized was useless (having a completely different block of code to render the button when hovered, instead of just changing the display color). Now, whenever I click any of the three previously-mentioned buttons, it seems to pick a random one and return True, messing up the rest of the program. For example, the play button will increase the speed one time, pressing decrease speed will pause, etc. Sometimes it does do what it is supposed to, but it seems to be random.</p> <p>Some extra info, if it's useful:</p> <p>-This function is called three times every tick. It's inside a loop, and if it returns true, its corresponding actions are supposed to be performed (pause or play the game, increase/decrease speed)</p> <p>-The play/pause button is one button that toggles between green with an 'play' arrow, and red with a pause symbol. They are two separate buttons and functions, and only one of them is executed at a time.</p> <p>-I have almost zero experience with classes, so they may be way better at handling this situation.</p> <p>-The only explanation I can think of for this problem is that the returned booleans are getting mixed up between the different places this function is used. I'm pretty sure the problem is within this chunk of code, but ask me and I will post the places it is called too.</p>
0
2016-10-15T04:54:45Z
40,093,414
<p>"pygame.event.get()" takes one event at a time, and *clears it** from the list of events that need to be processed.</p> <p>So, more specifically, pygame.event.get() returns each event only <strong>once</strong>.</p> <p>Take a look at the following code:</p> <pre><code>clicked = False for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: clicked = True </code></pre> <p>After this is called, all of the events are removed. Here is an analysis of the code. Assume that there are currently two events that haven't been processed, the first being a key pressed down and the other being a mouse button that's been pressed down.</p> <ol> <li>The first event, event.KEYDOWN, is put into the variable <em>"event"</em>.</li> <li>The program checks whether "event" (currently equal to event.KEYDOWN) is equal to event.MOUSEBUTTONDOWN. They are obviously not the same thing, so the next line is skipped.</li> <li>The second event, event.MOUSEBUTTONDOWN, is put into variable <em>"event"</em>. <strong>This removes what was previously in the variable "event", removing the first event from existence.</strong></li> <li>The program checks whether "event" (currently equal to event.MOUSEBUTTONDOWN) is equal to event.MOUSEBUTTONDOWN. It is, so it proceeds to the next line...</li> <li>"clicked" is set to True, and the for loop exits, because there are no event remaining. </li> </ol> <p>You should now have a better understanding of how Pygame processes events.</p> <p>There are also many problems with the function you gave (makeButton). You should find a python tutorial to learn the rest. I suggest a book called "Hello World", by Carter and Warren Sande. The book is kind of out of date (teaches Python 2.5), but its code still works with Python 2.7, and it is one of the few decent Python books I've been able to find.</p> <p>I have included the code to do what you are trying to do. I don't use Rect objects, but if you want them you can change the code to include them. I also didn't include the text, because I am short on time. Instead of placing random circles, this prints text (to the shell) when buttons are clicked. </p> <pre><code>import pygame, sys pygame.init() screen = pygame.display.set_mode([640,480]) clock = pygame.time.Clock() buttons = [] #buttons = [[rect, color, hovercolor, hovering, clicked, msg]] def makeButton(rect, color, hovercolor, text): global buttons buttons.append([rect, color, hovercolor, False, False, text]) makeButton([0,0,50,50], [0,127,0], [0,255,0], "Clicked Green") makeButton([50,0,50,50], [190,190,0], [255,255,0], "Clicked Yellow") makeButton([100,0,50,50], [0,0,127], [0,0,255], "Clicked Blue") while 1: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.MOUSEMOTION: mousepos = event.pos for a in range(len(buttons)): if mousepos[0] &gt;= buttons[a][0][0] and mousepos[0] &lt;= buttons[a][0][0]+buttons[a][0][2] and mousepos[1] &gt;= buttons[a][0][1] and mousepos[1] &lt;= buttons[a][0][1]+buttons[a][0][3]: buttons[3] = True else: buttons[3] = False if event.type == pygame.MOUSEBUTTONDOWN: mousepos = event.pos for a in range(len(buttons)): if mousepos[0] &gt;= buttons[a][0][0] and mousepos[0] &lt;= buttons[a][0][0]+buttons[a][0][2] and mousepos[1] &gt;= buttons[a][0][1] and mousepos[1] &lt;= buttons[a][0][1]+buttons[a][0][3]: buttons[4] = True else: buttons[4] = False for a in range(len(buttons)): if buttons[3] == 0: pygame.draw.rect(screen, buttons[1], buttons[0]) else: pygame.draw.rect(screen, buttons[2], buttons[0]) if buttons[4] == 1: buttons[4] = 0 print buttons[5] pygame.display.flip() </code></pre> <p>I haven't had the opportunity to test out the code I just typed (using school computer), but it should work. If there are any problems with the code, just leave a comment and I'll fix it.</p> <p>Also leave a comment if you don't understand something. Don't give up, you can do it!</p>
0
2016-10-17T18:39:15Z
[ "python", "button", "pygame" ]
Python: Why can't I assign new value to an array in this case?
40,055,177
<pre><code>import numpy as np data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']]) data[0,0] = data[0,0] + "_1" </code></pre> <p><strong>data[0,0]</strong> is <strong>'Height'</strong>, and I want to replace it with <strong>'Height_1'</strong>. But the code above doesn't work. It returned the result as:</p> <pre><code>data[0,0] </code></pre> <blockquote> <p>'Height'</p> </blockquote> <p>The <strong>data[0,0]</strong> element remained the same. And if I replace it directly without referring to itself, it still doesn't work.</p> <pre><code>data[0,0] = "Height" + "_1" </code></pre> <p>result:</p> <pre><code>data[0,0] </code></pre> <blockquote> <p>'Height'</p> </blockquote> <p>But if I replace it with some characters other than <strong>"Height"</strong>, it works.</p> <pre><code>data[0,0] = "str" + "_1" </code></pre> <p>Result:</p> <pre><code>data[0,0] </code></pre> <blockquote> <p>'str_1'</p> </blockquote> <p>I took this case to explain the problem I'm coming across. And in my work I have to refer to the array itself because I need to replace the elements which don't meet some requirements. Anyone have solutions on this? Thank you.</p>
3
2016-10-15T05:07:22Z
40,055,245
<p>specify an <strong>object</strong> type for your array, such as:</p> <pre><code>a = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']],dtype=object) </code></pre> <p>Then, <code>a[0][0]+='_1'</code> will do the trick, you will get:</p> <pre><code>array([['Height_1', 'Weight'], ['165', '48'], ['168', '50'], ['173', '53']], dtype=object) </code></pre>
3
2016-10-15T05:17:48Z
[ "python", "arrays", "numpy", "variable-assignment" ]
Python: Why can't I assign new value to an array in this case?
40,055,177
<pre><code>import numpy as np data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']]) data[0,0] = data[0,0] + "_1" </code></pre> <p><strong>data[0,0]</strong> is <strong>'Height'</strong>, and I want to replace it with <strong>'Height_1'</strong>. But the code above doesn't work. It returned the result as:</p> <pre><code>data[0,0] </code></pre> <blockquote> <p>'Height'</p> </blockquote> <p>The <strong>data[0,0]</strong> element remained the same. And if I replace it directly without referring to itself, it still doesn't work.</p> <pre><code>data[0,0] = "Height" + "_1" </code></pre> <p>result:</p> <pre><code>data[0,0] </code></pre> <blockquote> <p>'Height'</p> </blockquote> <p>But if I replace it with some characters other than <strong>"Height"</strong>, it works.</p> <pre><code>data[0,0] = "str" + "_1" </code></pre> <p>Result:</p> <pre><code>data[0,0] </code></pre> <blockquote> <p>'str_1'</p> </blockquote> <p>I took this case to explain the problem I'm coming across. And in my work I have to refer to the array itself because I need to replace the elements which don't meet some requirements. Anyone have solutions on this? Thank you.</p>
3
2016-10-15T05:07:22Z
40,055,250
<p>The problem is your array is of <code>dtype('&lt;U6')</code></p> <pre><code>&gt;&gt;&gt; data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53']]) &gt;&gt;&gt; data.dtype dtype('&lt;U6') &gt;&gt;&gt; </code></pre> <p>It will automatically truncate:</p> <pre><code>&gt;&gt;&gt; data[0,0] = "123456789" &gt;&gt;&gt; data array([['123456', 'Weight'], ['165', '48'], ['168', '50'], ['173', '53']], dtype='&lt;U6') &gt;&gt;&gt; </code></pre> <p>You can always specify your dtype as 'object' when you create your array, but this removes a lot of the speed benefits of <code>numpy</code> to begin with.</p> <p>Alternatively, you can specify a longer string type:</p> <pre><code>&gt;&gt;&gt; data array([['Height', 'Weight'], ['165', '48'], ['168', '50'], ['173', '53']], dtype='&lt;U20') &gt;&gt;&gt; data[0,0]='Height_1' &gt;&gt;&gt; data array([['Height_1', 'Weight'], ['165', '48'], ['168', '50'], ['173', '53']], dtype='&lt;U20') &gt;&gt;&gt; </code></pre> <p>But be careful, as if you set the limit too-long you will be wasting memory:</p> <pre><code>&gt;&gt;&gt; data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53'], ['42','88']], dtype='U20') &gt;&gt;&gt; data.nbytes 800 &gt;&gt;&gt; data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53'], ['42','88']], dtype='U6') &gt;&gt;&gt; data.nbytes 240 </code></pre> <p>If you only need a limited amount of characters, consider using byte-strings (1/4th the memory requirement):</p> <pre><code>&gt;&gt;&gt; data = np.array([['Height', 'Weight'],['165', '48'],['168', '50'],['173', '53'], ['42','88']], dtype='S20') &gt;&gt;&gt; data.nbytes 200 &gt;&gt;&gt; </code></pre>
4
2016-10-15T05:18:16Z
[ "python", "arrays", "numpy", "variable-assignment" ]
python error returning a variable but it prints fine
40,055,277
<p>Trying to figure out this why I'm getting this error about not declaring a variable.</p> <p>this works fine:</p> <pre><code> def findLargestIP(): for i in tagList: #remove all the spacing in the tags ec2Tags = i.strip() #seperate any multiple tags ec2SingleTag = ec2Tags.split(',') #find the last octect of the ip address fullIPTag = ec2SingleTag[1].split('.') #remove the CIDR from ip to get the last octect lastIPsTag = fullIPTag[3].split('/') lastOctect = lastIPsTag[0] ipList.append(lastOctect) largestIP = int(ipList[0]) for latestIP in ipList: if int(latestIP) &gt; largestIP: largestIP = latestIP # return largestIP print largestIP </code></pre> <p>In the list of number tags the largest # is 16 and it outputs :</p> <pre><code>python botoGetTags.py 16 </code></pre> <p>But the above only printed out the variable I need to pass that on to another function but when I modify the code above </p> <pre><code> return largestIP # print largestIP </code></pre> <p>And call the function:</p> <pre><code> return largestIP #print largestIP findLargestIP() print largestIP </code></pre> <p>I get this error :</p> <pre><code>python botoGetTags.py Traceback (most recent call last): File "botoGetTags.py", line 43, in &lt;module&gt; print largestIP NameError: name 'largestIP' is not defined </code></pre> <p>My guess is I have to initialize the variable in global.. But when I do that by making largestIP = 0, it returns 0 instead of the value that is in the function</p> <p>Thanks!</p>
-1
2016-10-15T05:22:00Z
40,055,337
<p>When a function returns a value, it has to be assigned to a value to be kept. Variables defined inside a function (like <code>b</code> in the example below) <strong>only exist inside the function and cannot be used outside the function</strong>.</p> <pre><code>def test(a): b=a+1 return b test(2) # Returns 3 but nothing happens print b # b was not defined outside function scope, so error # Proper way is as follows result=test(2) # Assigns the result of test (3) to result print(result) # Prints the value of result </code></pre>
3
2016-10-15T05:30:35Z
[ "python", "function", "loops" ]
python error returning a variable but it prints fine
40,055,277
<p>Trying to figure out this why I'm getting this error about not declaring a variable.</p> <p>this works fine:</p> <pre><code> def findLargestIP(): for i in tagList: #remove all the spacing in the tags ec2Tags = i.strip() #seperate any multiple tags ec2SingleTag = ec2Tags.split(',') #find the last octect of the ip address fullIPTag = ec2SingleTag[1].split('.') #remove the CIDR from ip to get the last octect lastIPsTag = fullIPTag[3].split('/') lastOctect = lastIPsTag[0] ipList.append(lastOctect) largestIP = int(ipList[0]) for latestIP in ipList: if int(latestIP) &gt; largestIP: largestIP = latestIP # return largestIP print largestIP </code></pre> <p>In the list of number tags the largest # is 16 and it outputs :</p> <pre><code>python botoGetTags.py 16 </code></pre> <p>But the above only printed out the variable I need to pass that on to another function but when I modify the code above </p> <pre><code> return largestIP # print largestIP </code></pre> <p>And call the function:</p> <pre><code> return largestIP #print largestIP findLargestIP() print largestIP </code></pre> <p>I get this error :</p> <pre><code>python botoGetTags.py Traceback (most recent call last): File "botoGetTags.py", line 43, in &lt;module&gt; print largestIP NameError: name 'largestIP' is not defined </code></pre> <p>My guess is I have to initialize the variable in global.. But when I do that by making largestIP = 0, it returns 0 instead of the value that is in the function</p> <p>Thanks!</p>
-1
2016-10-15T05:22:00Z
40,055,380
<p>It's because <code>largestIP</code> only exists in the scope of your <code>findLargestIP</code> function.</p> <p>Since this function returns a value but you simply call it without assigning to a new variable, this value gets "lost" afterwards.</p> <p>You should try something like:</p> <pre><code>def findLargestIP(): # ... return largestIP myIP = findLargestIP() # myIP takes the value returned by the function print myIP </code></pre>
1
2016-10-15T05:35:48Z
[ "python", "function", "loops" ]
Why do i get this error "TypeError: 'int' object is not callable"?
40,055,370
<pre><code>def diameter(Points): '''Given a list of 2d points, returns the pair that's farthest apart.''' diam,pair = max([((p[0]-q[0])**2 + (p[1]-q[1])**2, (p,q)) for p,q in rotatingCalipers(Points)]) return pair n=int(input()) a=[] max=0 for i in xrange(n): m,n=map(int,raw_input().split()) a.append((m,n)) diameter(a) </code></pre> <p>Traceback</p> <pre><code>Traceback (most recent call last): File "geocheat1.py", line 56, in &lt;module&gt; diameter(a) File "geocheat1.py", line 43, in diameter for p,q in rotatingCalipers(Points)]) TypeError: 'int' object is not callable </code></pre>
0
2016-10-15T05:34:03Z
40,055,491
<p>From the Traceback it's clear than you are trying to call <code>int</code> object, So <code>rotatingCalipers</code> may be declared as integer in your code. </p> <p>See this example you will understand the error,</p> <pre><code>In [1]: a = (1,2,3) In [2]: list(a) Out[1]: [1, 2, 3] In [3]: list = 5 In [4]: list(a) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-20-61edcfee5862&gt; in &lt;module&gt;() ----&gt; 1 list(a) TypeError: 'int' object is not callable </code></pre>
1
2016-10-15T05:49:39Z
[ "python", "python-2.7" ]
Python multiprocessing Pool.imap throws ValueError: list.remove(x): x not in list
40,055,378
<p>I have a very simple test fixture that instantiate and close a test class 'APMSim' in different threads, the class is not picklable, so I have to use multiprocessing Pool.imap to avoid them being transferred between processes:</p> <pre><code>class APMSimFixture(TestCase): def setUp(self): self.pool = multiprocessing.Pool() self.sims = self.pool.imap( apmSimUp, range(numCores) ) def tearDown(self): self.pool.map( simDown, self.sims ) def test_empty(self): pass </code></pre> <p>However, when I run the empty Python unittest I encounter the following error:</p> <pre><code>Error Traceback (most recent call last): File "/home/peng/git/datapassport/spookystuff/mav/pyspookystuff_test/mav/__init__.py", line 87, in tearDown self.sims File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get raise self._value </code></pre> <p>Why this could happen? Is there a fix to this?</p>
0
2016-10-15T05:35:40Z
40,055,477
<p><code>multiprocessing</code> is re-raising an exception from your worker function/child process in the parent process, but it loses the traceback in the transfer from child to parent. Check your worker function, it's that code that's going wrong. It might help to take whatever your worker function is and change:</p> <pre><code>def apmSimUp(...): ... body ... </code></pre> <p>to:</p> <pre><code>import traceback def apmSimUp(...): try: ... body ... except: traceback.print_exc() raise </code></pre> <p>This explicitly prints the full, original exception traceback (then lets it propagate normally), so you can see what the real problem is.</p>
1
2016-10-15T05:47:31Z
[ "python", "python-2.7", "python-multiprocessing", "python-unittest" ]
Flask-restful API not accepting json
40,055,384
<p>I am trying to learn how to do apis. I copied everything from the book exactly but i am unable to post to the api. I tried posting <code>{'name':'holy'}</code> as raw data in <code>postman</code>( an json posting tool) to api and I get the vladation help message error"No Name provided":but when i try <code>name=holy</code> it works fine. I thought it was not suppose to work like that, How do i get it to work with <code>{'name':'holy'}</code></p> <pre><code>from flask import Flask, request,render_template, jsonify from flask_restful import Resource, Api,marshal_with, fields, reqparse app = Flask(__name__) api = Api(app) class UserApi(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument( 'name', required=True, help='No name provided', location=['form', 'json'] ) def get(self): return jsonify ({"first_name":"Holy","last_name": "Johnson"}) def post(self): args = self.reqparse.parse_args() return jsonify ({"first_name":"Holy","last_name": "Johnson"}) api.add_resource(UserApi, '/users') if __name__ == '__main__': app.run(debug=True) </code></pre>
0
2016-10-15T05:36:00Z
40,062,569
<p>Your code should work - you have to specify the request header <code>Content-Type: application/json</code>. The reason why is because <code>flask-restful</code>'s <code>reqparse</code> module tries to parse <a href="http://flask-restful-cn.readthedocs.io/en/0.3.5/reqparse.html#argument-locations" rel="nofollow">its data from <code>flask.request.json</code></a>, which is only set if <code>Content-Type: application/json</code> is set.</p> <p>If you have access to <code>curl</code> (or <code>wget</code>), you can do the following to test:</p> <pre><code>$shell&gt; curl -X POST -H "Content-Type: application/json" -d '{"name": "holly"}' http://localhost:5000/users { "first_name": "Holy", "last_name": "Johnson" } </code></pre> <p>In Postman, you can set a header, like shown in the screenshot below. <a href="https://i.stack.imgur.com/3nS91.png" rel="nofollow"><img src="https://i.stack.imgur.com/3nS91.png" alt="enter image description here"></a></p>
2
2016-10-15T18:14:40Z
[ "python", "rest", "api", "flask-restful" ]
Unable to get OpenCV 3.1 FPS over ~15 FPS
40,055,428
<p>I have some extremely simple performance testing code below for measuring the FPS of my webcam with OpenCV 3.1 + Python3 on a Late 2011 Macbook Pro:</p> <pre><code>cap = cv2.VideoCapture(0) count = 0 start_time = time.perf_counter() end_time = time.perf_counter() while (start_time + 1) &gt; end_time: count += 1 cap.read() # Attempt to force camera FPS to be higher cap.set(cv2.CAP_PROP_FPS, 30) end_time = time.perf_counter() print("Got count", count) </code></pre> <p>Doing no processing, not even displaying the image or doing this in another thread, I am only getting around 15 FPS. </p> <p>Trying to access the FPS of the camera with cap.get(cv2.CAP_PROP_FPS) I get 0.0.</p> <p>Any ideas why?</p> <p>I've already searched the internet a fair amount for answers, so things I've thought about:</p> <ul> <li><p>I build OpenCV with release flags, so it shouldn't be doing extra debugging logic</p></li> <li><p>Tried manually setting the FPS each frame (see above)</p></li> <li><p>My FPS with other apps (e.g. Camera toy in Chrome) is 30FPS</p></li> <li><p>There is no work being done in the app on the main thread, so putting the video capture logic in another thread as most other posts suggest shouldn't make a difference</p></li> </ul> <p>** EDIT ** Additional details: it seems like the first frame I capture is quick, then subsequent frames are slower; seems like this could be a buffer issues (i.e. the camera is being paused after the first frame because a new buffer must be allocated to write to?)</p> <p>Tweaked the code to calculate the average FPS so far after each read:</p> <pre><code> cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_CONVERT_RGB, False) cap.set(cv2.CAP_PROP_FPS, 30) start_time = time.perf_counter() count = 0 cv2.CAP_PROP_FPS end_time = time.perf_counter() while True: count += 1 ret, frame = cap.read() end_time = time.perf_counter() print("Reached FPS of: ", count / (end_time - start_time)) </code></pre> <p>And I get one frame around 30FPS, and then subsequent frames are slower:</p> <p>Reached FPS of: 27.805818385257446</p> <p>Reached FPS of: 19.736237223924398</p> <p>Reached FPS of: 18.173748156583795</p> <p>Reached FPS of: 17.214809956810114</p> <p>Reached FPS of: 16.94737657138959</p> <p>Reached FPS of: 16.73624509452099</p> <p>Reached FPS of: 16.33156408530572</p>
0
2016-10-15T05:41:23Z
40,067,019
<p>IT'S NOT ANSWER. Since the comment in original question is too long for your attention. I post outside instead. </p> <p>First, it's normal when CV_CAP_PROP_FPS return 0. OpenCV for Python just a wrapper for OpenCV C++. As far as I know, this property only works for video file, not camera. You have to calculate FPS yourself (like your edited). </p> <p>Second, OpenCV have a bug that always convert the image get from camera to RGB <a href="https://github.com/opencv/opencv/issues/4831" rel="nofollow">https://github.com/opencv/opencv/issues/4831</a>. Normal camera usually use YUYV color. It's take a lot of time. You can check all supported resolution + fps <a href="https://trac.ffmpeg.org/wiki/Capture/Webcam" rel="nofollow">https://trac.ffmpeg.org/wiki/Capture/Webcam</a>. I see some camera not support RGB color and OpenCV force to get RGB and take terrible FPS. Due to camera limitation, in the same codec, the higher resolution, the slower fps. In different supported codec, the bigger output in same resolution, the slower fps. For example, my camera support yuyv and mjpeg, in HD resolution, YUYV have max 10 fps while MJPEG have max 30 fps. </p> <p>So, first you can try ffmpeg executable to get frames. After identifying where error come from, if ffmpeg works well, you can use ffmpeg library (not ffmpeg executable) to get frame from your camera (OpenCV using ffmpeg for most video I/O including camera).</p> <p>Be aware that the I only work with ffmpeg and OpenCV in C++ language, not Python. Using ffmpeg library is another long story. </p> <p>Good luck! </p>
1
2016-10-16T04:58:59Z
[ "python", "c++", "opencv", "video", "camera" ]
Syntax Error with Django, WSGI, and Apache
40,055,541
<p>I am getting a weird error while trying to run my Django site under Apache using mod_wsgi. I have been working on this for hours to no avail.</p> <p>FYI: I am also using Mezzanine.</p> <p>Log:</p> <pre><code>[Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] mod_wsgi (pid=15554): Target WSGI script '/opt/mysite/mysite/wsgi.py' cannot be loaded as Python module. [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] mod_wsgi (pid=15554): Exception occurred processing WSGI script '/opt/mysite/mysite/wsgi.py'. [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] Traceback (most recent call last): [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/opt/mysite/mysite/wsgi.py", line 12, in &lt;module&gt; [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] from django.core.wsgi import get_wsgi_application [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/__init__.py", line 3, in &lt;module&gt; [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] from django.utils.version import get_version [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/utils/version.py", line 7, in &lt;module&gt; [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] from django.utils.lru_cache import lru_cache [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/utils/lru_cache.py", line 28 [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] fasttypes = {int, str, frozenset, type(None)}, [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] ^ [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] SyntaxError: invalid syntax </code></pre> <p>httpd.conf for mysite (there are others on the server)</p> <pre><code># Redirects all HTTP traffic to HTTPS &lt;VirtualHost *:80&gt; #ServerName test-mysite #ServerAlias test-mysite mysite.com mysite ServerName mysite.com ServerAlias mysite test-mysite.com test-mysite DocumentRoot /opt/mysite RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} WSGIScriptAlias / /opt/mysite/mysite/wsgi.py &lt;/VirtualHost&gt; WSGISocketPrefix /var/run/wsgi &lt;VirtualHost *:443&gt; #ServerName test-mysite.com #ServerAlias test-mysite ServerName mysite.com ServerAlias mysite test-mysite.com test-mysite ErrorLog /var/log/httpd/ssl_mysite_error_log CustomLog /var/log/httpd/ssl_mysite_request_log \ "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b" TransferLog /var/log/httpd/ssl_mysite_access_log LogLevel warn WSGIDaemonProcess mysite.com processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup mysite.com WSGIScriptAlias / /opt/mysite/mysite/wsgi.py &lt;Directory /opt/mysite/mysite&gt; Options +FollowSymLinks -Indexes AllowOverride All order allow,deny allow from all &lt;/Directory&gt; SSLEngine On SSLProtocol all -SSLv2 SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW SSLCertificateFile /etc/pki/tls/certs/othersite_com.crt SSLCertificateKeyFile /etc/pki/tls/private/othersite.com.key SSLCertificateChainFile /etc/pki/tls/certs/DigiCertCA.crt &lt;/VirtualHost&gt; </code></pre> <p><code>httpd -V</code> output:</p> <pre><code>Server version: Apache/2.2.15 (Unix) Server built: Jul 12 2016 07:03:49 Server's Module Magic Number: 20051115:25 Server loaded: APR 1.3.9, APR-Util 1.3.9 Compiled using: APR 1.3.9, APR-Util 1.3.9 Architecture: 64-bit Server MPM: Prefork threaded: no forked: yes (variable process count) Server compiled with.... -D APACHE_MPM_DIR="server/mpm/prefork" -D APR_HAS_SENDFILE -D APR_HAS_MMAP -D APR_HAVE_IPV6 (IPv4-mapped addresses enabled) -D APR_USE_SYSVSEM_SERIALIZE -D APR_USE_PTHREAD_SERIALIZE -D SINGLE_LISTEN_UNSERIALIZED_ACCEPT -D APR_HAS_OTHER_CHILD -D AP_HAVE_RELIABLE_PIPED_LOGS -D DYNAMIC_MODULE_LIMIT=128 -D HTTPD_ROOT="/etc/httpd" -D SUEXEC_BIN="/usr/sbin/suexec" -D DEFAULT_PIDLOG="run/httpd.pid" -D DEFAULT_SCOREBOARD="logs/apache_runtime_status" -D DEFAULT_LOCKFILE="logs/accept.lock" -D DEFAULT_ERRORLOG="logs/error_log" -D AP_TYPES_CONFIG_FILE="conf/mime.types" -D SERVER_CONFIG_FILE="conf/httpd.conf" </code></pre> <p>How do I fix this?</p>
1
2016-10-15T05:57:51Z
40,055,573
<pre><code>[Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] File "/usr/lib/python2.6/site-packages/django/utils/lru_cache.py", line 28 [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] fasttypes = {int, str, frozenset, type(None)}, [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] ^ [Fri Oct 14 23:48:13 2016] [error] [client 128.187.3.30] SyntaxError: invalid syntax </code></pre> <p>Python 2.6 doesn't support <code>set</code> syntax <code>{....}</code></p> <p>You may <a href="https://www.quora.com/Where-can-I-find-a-version-of-Django-to-use-with-python-2-6" rel="nofollow">use a version of Django that supports Python 2.6</a> but make sure it also supports <code>Mezzanine</code> OR Update your Python installation to <code>2.7</code></p>
2
2016-10-15T06:01:29Z
[ "python", "django", "apache", "mod-wsgi" ]
Python pexpect scripts run without error,but there are no outputs in output file
40,055,592
<p>I want to put the results of 'ls /home' into mylog1.txt through ssh.So,I can check it on my computer.When I run the script,there is no error,there is no output in mylog1.txt。</p> <blockquote> <pre><code>#!/usr/bin/env python import pexpect import sys child=pexpect.spawn('ssh [email protected]') fout=file('mylog1.txt','w') child.logfile=fout child.expect("password:") child.sendline("xxxxx") child.expect('$') child.sendline('ls /home') </code></pre> </blockquote> <pre><code>shiyanlou:pythontest/ $ cat mylog1.txt [email protected]'s password: xxxxxxx ls /home </code></pre> <p>There are just tow commands in the mylog1.txt file.Why?</p>
1
2016-10-15T06:04:07Z
40,055,650
<p>pexpect is good to intereact with an application.</p> <p>But if you simply want ssh and execute some command, i will advice you to try out <a href="http://www.paramiko.org/" rel="nofollow">Paramiko</a></p>
0
2016-10-15T06:13:22Z
[ "python", "linux", "devops", "pexpect" ]
Python pexpect scripts run without error,but there are no outputs in output file
40,055,592
<p>I want to put the results of 'ls /home' into mylog1.txt through ssh.So,I can check it on my computer.When I run the script,there is no error,there is no output in mylog1.txt。</p> <blockquote> <pre><code>#!/usr/bin/env python import pexpect import sys child=pexpect.spawn('ssh [email protected]') fout=file('mylog1.txt','w') child.logfile=fout child.expect("password:") child.sendline("xxxxx") child.expect('$') child.sendline('ls /home') </code></pre> </blockquote> <pre><code>shiyanlou:pythontest/ $ cat mylog1.txt [email protected]'s password: xxxxxxx ls /home </code></pre> <p>There are just tow commands in the mylog1.txt file.Why?</p>
1
2016-10-15T06:04:07Z
40,058,575
<p>You have to wait until the <code>ls</code> command finishes, just like when you are interacting with the terminal. See following example (I'm using public key auth for ssh so no password prompt):</p> <pre class="lang-none prettyprint-override"><code>[STEP 106] # cat foo.py import pexpect shell_prompt = 'bash-[.0-9]+[$#] ' ssh = pexpect.spawn('ssh -t 127.0.0.1 bash --noprofile --norc') ofile = file('file.out', 'w') ssh.logfile_read = ofile ssh.expect(shell_prompt) ssh.sendline('echo hello world') ssh.expect(shell_prompt) ssh.sendline('exit') ssh.expect(pexpect.EOF) [STEP 107] # python foo.py [STEP 108] # cat file.out bash-4.3# echo hello world hello world bash-4.3# exit exit Connection to 127.0.0.1 closed. [STEP 109] # </code></pre>
0
2016-10-15T11:41:34Z
[ "python", "linux", "devops", "pexpect" ]
Django returning static HTML in views.py?
40,055,632
<p>So I have a standard <code>Django</code> project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using <code>HttpResponse()</code> I know it's a bit <code>unorthodox</code>, but this is an example of what I'm thinking about:</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): html = """ &lt;html&gt; &lt;body&gt; This is my bare-bones html page. &lt;/body&gt; &lt;/html&gt; """ return HttpResponse(html) </code></pre> <p>My corresponding <code>JS</code> and <code>stylesheets</code> would be stored in the same directory as views. py in my app in this example. Just making sure: I'm not asking if this works, because I already know the answer is yes, I just want to know if there are any disadvantages/drawbacks to this method, and why don't more people do this?</p>
0
2016-10-15T06:10:33Z
40,055,641
<p>Most people dont use this because it mixes Python with HTML and gets very messy and out of hand very quickly</p>
0
2016-10-15T06:11:39Z
[ "python", "html", "django", "http", "httpresponse" ]
Django returning static HTML in views.py?
40,055,632
<p>So I have a standard <code>Django</code> project with a basic view that returns a simple HTML confirmation statement. Would it be plausible for me to define all of my HTML in the view itself as a really long string and return that using <code>HttpResponse()</code> I know it's a bit <code>unorthodox</code>, but this is an example of what I'm thinking about:</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): html = """ &lt;html&gt; &lt;body&gt; This is my bare-bones html page. &lt;/body&gt; &lt;/html&gt; """ return HttpResponse(html) </code></pre> <p>My corresponding <code>JS</code> and <code>stylesheets</code> would be stored in the same directory as views. py in my app in this example. Just making sure: I'm not asking if this works, because I already know the answer is yes, I just want to know if there are any disadvantages/drawbacks to this method, and why don't more people do this?</p>
0
2016-10-15T06:10:33Z
40,055,667
<p>You can use built-in <a href="https://docs.djangoproject.com/en/1.10/ref/templates/api/#django.template.Template.render" rel="nofollow">template renderer</a> to get works filters/templatetags/etc </p>
0
2016-10-15T06:15:37Z
[ "python", "html", "django", "http", "httpresponse" ]
Python concurrent.futures - method not called
40,055,652
<p>I am running a local django server with the following code: </p> <pre><code>import concurrent.futures media_download_manager = concurrent.futures.ProcessPoolExecutor(max_workers=2) def hello(): print "hello" for i in range(1, 1000): print "submitting task " media_download_manager.map(hello) </code></pre> <p>I am initializing a process pool executor to accept tasks with 2 worker threads. The tasks are being submitter but the worker threads handling the submitted tasks do not seem to have triggered. </p> <p>Following it the console output: </p> <pre><code>submitting task 1 submitting task 2 submitting task 3 submitting task 4 submitting task 5 submitting task 6 submitting task 7 submitting task 8 submitting task 9 Performing system checks... System check identified no issues (0 silenced). October 15, 2016 - 06:09:31 Django version 1.8.4, using settings 'Learn.settings' Starting development server at http://192.168.1.3:8000/ Quit the server with CONTROL-C. </code></pre> <p>What am I missing here ?</p>
0
2016-10-15T06:13:27Z
40,055,710
<p><a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.map" rel="nofollow">The <code>Executor.map</code> function</a> is intended to pass arguments from an iterable(s) to a mapping function. You didn't provide any iterables so it doesn't run (and your function takes no arguments, so if you had provided iterables, it would have failed when it passed too many arguments).</p> <p>If you just want to run that function without arguments some number of times, call <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor.submit" rel="nofollow"><code>submit</code></a>; <code>map</code> is intended to pass arguments and accumulate results from what it returns, not just run something for side-effects (it's a functional programming tool, and functional code is side-effect free in general).</p> <p>Fixed code would be:</p> <pre><code>futures = [] for i in range(1, 1000): print "submitting task " futures.append(media_download_manager.submit(hello)) concurrent.futures.wait(futures) # Wait for all tasks to finish </code></pre>
1
2016-10-15T06:20:17Z
[ "python", "django", "multithreading" ]
Python concurrent.futures - method not called
40,055,652
<p>I am running a local django server with the following code: </p> <pre><code>import concurrent.futures media_download_manager = concurrent.futures.ProcessPoolExecutor(max_workers=2) def hello(): print "hello" for i in range(1, 1000): print "submitting task " media_download_manager.map(hello) </code></pre> <p>I am initializing a process pool executor to accept tasks with 2 worker threads. The tasks are being submitter but the worker threads handling the submitted tasks do not seem to have triggered. </p> <p>Following it the console output: </p> <pre><code>submitting task 1 submitting task 2 submitting task 3 submitting task 4 submitting task 5 submitting task 6 submitting task 7 submitting task 8 submitting task 9 Performing system checks... System check identified no issues (0 silenced). October 15, 2016 - 06:09:31 Django version 1.8.4, using settings 'Learn.settings' Starting development server at http://192.168.1.3:8000/ Quit the server with CONTROL-C. </code></pre> <p>What am I missing here ?</p>
0
2016-10-15T06:13:27Z
40,055,997
<p>First, you are using <code>map</code> instead of <code>submit</code>. The former is a way similar to the built-in <code>map</code> function to map arguments to a function that you want to run asynchronically on all of them. You used <code>map</code> with <code>i+1</code> instead of an iterable (e.g. <code>[i+1]</code>), but don't do that in your case. You are passing only one value to the map.</p> <p><code>submit</code> however, fires up only one function asynchorincally in your pool. That's exactly what you want to do!</p> <p>I've modified your example a bit, following is the code. Also consider about reading if <code>ThreadPoolManager</code>might be favorable in your case instead of <code>ProcessPoolManager</code> as it seems to be I/O bound (network stuff). But don't catch me on that.</p> <pre><code>import concurrent.futures from time import sleep from random import random media_download_manager = concurrent.futures.ProcessPoolExecutor(max_workers=4) def hello(i): be_sleepy = random() * 2 sleep(be_sleepy) print("hello", i) if __name__ == '__main__': # protecting funny multiprocessing error on Windows for i in range(10): print("submitting task", i) media_download_manager.submit(hello, i+1) # media_download_manager.map(hello, [i+1]) # &lt;--awkward ;), notice additional [] </code></pre> <p>Example output:</p> <pre><code>submitting task 0 submitting task 1 submitting task 2 submitting task 3 submitting task 4 submitting task 5 submitting task 6 submitting task 7 submitting task 8 submitting task 9 hello 1 hello 3 hello 6 hello 2 hello 7 hello 9 hello 5 hello 4 hello 8 hello 10 </code></pre> <p>Also note @ShadowRanger's answer which has a way to determine when all your tasks finished.</p>
1
2016-10-15T06:53:47Z
[ "python", "django", "multithreading" ]
How is Django able to grant reserved port numbers?
40,055,676
<p>Using this command </p> <blockquote> <p><code>python manage.py runserver 0.0.0.0:8000</code></p> </blockquote> <p>we can host a Django server locally on any port.So a developer can use reserved and privileged port numbers say</p> <blockquote> <p><code>python manage.py runserver 127.0.0.1:80</code></p> </blockquote> <p>So, now I am using port 80 defined for the HTTP protocol.</p> <p>So, why does this not raise any issues and how is this request granted ? </p>
1
2016-10-15T06:17:05Z
40,055,695
<p>You should use a proper server instead of Django's test server such as <code>nginx</code> or <code>apache</code> to run the server in production on port <code>80</code>. Running something like <code>sudo python manage.py runserver 0.0.0.0:80</code> is not recommended at all.</p>
1
2016-10-15T06:19:06Z
[ "python", "django", "port" ]
How is Django able to grant reserved port numbers?
40,055,676
<p>Using this command </p> <blockquote> <p><code>python manage.py runserver 0.0.0.0:8000</code></p> </blockquote> <p>we can host a Django server locally on any port.So a developer can use reserved and privileged port numbers say</p> <blockquote> <p><code>python manage.py runserver 127.0.0.1:80</code></p> </blockquote> <p>So, now I am using port 80 defined for the HTTP protocol.</p> <p>So, why does this not raise any issues and how is this request granted ? </p>
1
2016-10-15T06:17:05Z
40,063,068
<p>Port 80 has no magical meaning, it is not "reserved" or "privileged" on your server (besides most likely requiring root privileges to access, as others have mentioned). It is just a regular port that was chosen to be a default for http, so you don't have to write <code>google.com:80</code> every time in your browser, that's it. </p> <p>If you have no web server running such as apache or nginx which usually listen to that port, then port 80 is up for grabs. You can run django runserver on it, you can run a plain python script listening to it, whatever you like.</p>
1
2016-10-15T19:03:16Z
[ "python", "django", "port" ]
Append/concatenate Numpy array to Numpy array
40,055,737
<p>I have two np arrays, one is 1 dimensional, and the other it between 0 and 8 dimensional. I'm trying to append the multidimensional array onto the other array, as you would with a list. I've tried <code>np.append(1dim, multidim)</code> and <code>np.concatenate([1dim, multidim])</code> but neither have worked.</p> <pre><code>[-33.752, 150.902, 38.022, 203.0, 1.0] [[ -33.75 150.9 39.805 0. 1. ] [ -33.75 150.902 44.697 1. 1. ] [ -33.75 150.905 49.054 2. 1. ] [ -33.752 150.905 39.062 204. 1. ] [ -33.755 150.905 40.698 406. 1. ] [ -33.755 150.902 37.512 405. 1. ] [ -33.755 150.9 36.249 404. 1. ] [ -33.752 150.9 36.627 202. 1. ]] </code></pre> <p>to become:</p> <pre><code>[-33.752, 150.902, 38.022, 203.0, 1.0], [ -33.75 150.9 39.805 0. 1. ] [ -33.75 150.902 44.697 1. 1. ] [ -33.75 150.905 49.054 2. 1. ] [ -33.752 150.905 39.062 204. 1. ] [ -33.755 150.905 40.698 406. 1. ] [ -33.755 150.902 37.512 405. 1. ] [ -33.755 150.9 36.249 404. 1. ] [ -33.752 150.9 36.627 202. 1. ]] </code></pre> <p>I would like to be able to reference the multidim array by using <code>1dim[1]</code></p>
0
2016-10-15T06:23:58Z
40,056,265
<p>Your example output shows a (1x8) array concatenated with an (Nx8) array to form an (N+1 x 8) array. </p> <p>If you want to create a "thing" where the first element is the 1-D array and the second element is the N-D array, a list or tuple is your bet. Numpy doesn't really have a great facility for this.</p> <p>If you want to create an array that is the combination of the two 2D, based on your example, <code>np.vstack([flat_array, big_array])</code> will do that.</p> <p>By the way, when describing the number of dimensions something has, array.ndim is the same as len(array.shape). Note that an array with 5 rows and 8 columns is two dimensional in the context of numpy.</p>
3
2016-10-15T07:20:51Z
[ "python", "numpy" ]
Append/concatenate Numpy array to Numpy array
40,055,737
<p>I have two np arrays, one is 1 dimensional, and the other it between 0 and 8 dimensional. I'm trying to append the multidimensional array onto the other array, as you would with a list. I've tried <code>np.append(1dim, multidim)</code> and <code>np.concatenate([1dim, multidim])</code> but neither have worked.</p> <pre><code>[-33.752, 150.902, 38.022, 203.0, 1.0] [[ -33.75 150.9 39.805 0. 1. ] [ -33.75 150.902 44.697 1. 1. ] [ -33.75 150.905 49.054 2. 1. ] [ -33.752 150.905 39.062 204. 1. ] [ -33.755 150.905 40.698 406. 1. ] [ -33.755 150.902 37.512 405. 1. ] [ -33.755 150.9 36.249 404. 1. ] [ -33.752 150.9 36.627 202. 1. ]] </code></pre> <p>to become:</p> <pre><code>[-33.752, 150.902, 38.022, 203.0, 1.0], [ -33.75 150.9 39.805 0. 1. ] [ -33.75 150.902 44.697 1. 1. ] [ -33.75 150.905 49.054 2. 1. ] [ -33.752 150.905 39.062 204. 1. ] [ -33.755 150.905 40.698 406. 1. ] [ -33.755 150.902 37.512 405. 1. ] [ -33.755 150.9 36.249 404. 1. ] [ -33.752 150.9 36.627 202. 1. ]] </code></pre> <p>I would like to be able to reference the multidim array by using <code>1dim[1]</code></p>
0
2016-10-15T06:23:58Z
40,058,195
<p>You have to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html" rel="nofollow">numpy.append</a> or <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html" rel="nofollow">numpy.concatenate</a>. But careful about the shape of your array. For your case you have to define the correct shape</p> <p>ans=np.append([[small array]],[big array], axis=0) (Note that the extra [] is for correct shape, read the numpy.append tutorial)</p>
0
2016-10-15T11:00:14Z
[ "python", "numpy" ]
Append/concatenate Numpy array to Numpy array
40,055,737
<p>I have two np arrays, one is 1 dimensional, and the other it between 0 and 8 dimensional. I'm trying to append the multidimensional array onto the other array, as you would with a list. I've tried <code>np.append(1dim, multidim)</code> and <code>np.concatenate([1dim, multidim])</code> but neither have worked.</p> <pre><code>[-33.752, 150.902, 38.022, 203.0, 1.0] [[ -33.75 150.9 39.805 0. 1. ] [ -33.75 150.902 44.697 1. 1. ] [ -33.75 150.905 49.054 2. 1. ] [ -33.752 150.905 39.062 204. 1. ] [ -33.755 150.905 40.698 406. 1. ] [ -33.755 150.902 37.512 405. 1. ] [ -33.755 150.9 36.249 404. 1. ] [ -33.752 150.9 36.627 202. 1. ]] </code></pre> <p>to become:</p> <pre><code>[-33.752, 150.902, 38.022, 203.0, 1.0], [ -33.75 150.9 39.805 0. 1. ] [ -33.75 150.902 44.697 1. 1. ] [ -33.75 150.905 49.054 2. 1. ] [ -33.752 150.905 39.062 204. 1. ] [ -33.755 150.905 40.698 406. 1. ] [ -33.755 150.902 37.512 405. 1. ] [ -33.755 150.9 36.249 404. 1. ] [ -33.752 150.9 36.627 202. 1. ]] </code></pre> <p>I would like to be able to reference the multidim array by using <code>1dim[1]</code></p>
0
2016-10-15T06:23:58Z
40,058,338
<p>Or you can do it manually for any shape </p> <pre><code>blank= [ ] #create a blank list a=1D array blank.append(a) b=nD array for i in range(len(b)): blank.append(b[i]) answer=np.array(blank) </code></pre>
0
2016-10-15T11:15:52Z
[ "python", "numpy" ]
while connecting to a host using fabric in python, getting a prompt(Login password for 'root':) asking for root password
40,055,761
<p>In python file code is something like this: with settings(host_string=elasticIP, key_filename = '/path/to/keyfile.pem', user = 'root', use_ssh_config = False): run("any command")</p> <p>After executing this, a prompt appears in console stating "Login password for 'root':" As we dont have a password for this user 'root' so we are not sure what password to provide, but, randomly giving any text as a password for 'root' in the console it accepts and moves further.</p> <p>When we run same python program in background using nohup then same prompt sometimes appears sometimes it dose not appears.</p> <p>We are working on eucalyptus instances and hope environment is not an issue here. Please suggest...</p>
0
2016-10-15T06:27:54Z
40,074,457
<p>When you are using <code>settings</code>, don’t use <code>run</code>, use <code>execute</code>.</p> <pre><code>from fabric.decorators import task from fabric.operations import run, execute def my_command(): run('echo "hello fabric!"') @task def my_task(): with settings(host_string=elasticIP, key_filename = '/path/to/keyfile.pem', user = 'root', use_ssh_config = False): execute(my_command) </code></pre>
0
2016-10-16T19:23:36Z
[ "python", "shell", "unix", "root", "fabric" ]
while connecting to a host using fabric in python, getting a prompt(Login password for 'root':) asking for root password
40,055,761
<p>In python file code is something like this: with settings(host_string=elasticIP, key_filename = '/path/to/keyfile.pem', user = 'root', use_ssh_config = False): run("any command")</p> <p>After executing this, a prompt appears in console stating "Login password for 'root':" As we dont have a password for this user 'root' so we are not sure what password to provide, but, randomly giving any text as a password for 'root' in the console it accepts and moves further.</p> <p>When we run same python program in background using nohup then same prompt sometimes appears sometimes it dose not appears.</p> <p>We are working on eucalyptus instances and hope environment is not an issue here. Please suggest...</p>
0
2016-10-15T06:27:54Z
40,084,005
<p>I diged more into this issue and finally got an answer: file :/etc/ssh/ssh_config holds a property 'UserKnownHostsFile' and 'StrictHostKeyChecking' these properties should be addressed as : StrictHostKeyChecking no UserKnownHostsFile=/dev/null UserKnownHostsFile defines the storing of ssh and some metadata regarding to a particular machine. If there is a mismatch in these details it asks you to confirm whether the machine u SSHed is the correct machine or not. So making these changes, all went well. references: <a href="http://linuxcommando.blogspot.in/2008/10/how-to-disable-ssh-host-key-checking.html" rel="nofollow">http://linuxcommando.blogspot.in/2008/10/how-to-disable-ssh-host-key-checking.html</a></p> <p>and</p> <p><a href="http://superuser.com/questions/19563/how-do-i-skip-the-known-host-question-the-first-time-i-connect-to-a-machine-vi">http://superuser.com/questions/19563/how-do-i-skip-the-known-host-question-the-first-time-i-connect-to-a-machine-vi</a></p>
0
2016-10-17T10:29:15Z
[ "python", "shell", "unix", "root", "fabric" ]
Python 3: How do I get one class to modify values in an instance of another class?
40,055,765
<p>I am learning to code in Python and am writing a short program with three classes as practice. The first class uses instances of the second and third classes as attributes. I am trying to get a method in the third class change a value in an instance of itself as well as in an instance of the second class. So far I have something like this:</p> <pre><code>Class_a(): self.b_attribute = Class_b() self.c_attribute = Class_c() Class_b(): self.b_value = 5 Class_c(): self.c_value = 1 def change_values(): self.c_value += 1 instance = Class_a() instance.c_attribute.change_values() </code></pre> <p>Calling <code>instance.c_attribute.change_values()</code> increases <code>c_value</code> for this instance of <code>Class_a</code> by 1. Is it possible to write <code>change_values()</code> such that calling <code>instance.c_attribute.change_values()</code> also changes of <code>b_value</code> this instance of <code>Class_a</code>? If it is possible how would I write that code?</p>
0
2016-10-15T06:28:26Z
40,056,740
<p>You have a hierarchy on classes of this Class_a | | Class_b Class_c</p> <p>now you have done making changes in Class_c and it affects Class_a with regard to the c_attribute component.</p> <p>This technique is very advanced, and I am surprised you learn it as a beginner.</p> <p>However, this is accessible only because c is part of a. But notice c is not part of b, and vice versa. See the hierarchy that b and c have no relationship.</p> <p>A clear way to handle it is to make a general function in a.</p> <p>But if you want to make a change in attribute_c so that it has a chain effect on attribute_b, you have to set up a trigger in a that can be called by c.</p> <p>e.g</p> <pre><code>class a(): def a_change_b(): #trigger function self.b_attribute += 1 class c(): def change_b(): a_change_b() #try to call the trigger function outside c but inside a </code></pre> <p>Hope it works.</p>
0
2016-10-15T08:17:33Z
[ "python", "class", "attributes" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would like to do something like this.</p> <pre><code>data = some numpy array label = some numpy array A = np.argwhere(label==0) #[[1 1 1], [1 1 2], [1 1 3], [1 1 4]] B = np.argwhere(data&gt;1.5) #[[0 0 0], [1 0 2], [1 0 3], [1 0 4], [1 1 0], [1 1 1], [1 1 4]] out = np.argwhere(label==0 and data&gt;1.5) #[[1 1 2], [1 1 3]] </code></pre>
11
2016-10-15T06:36:16Z
40,055,892
<p>If you want to do it the numpy way,</p> <pre><code>import numpy as np A = np.array([[1, 1, 1,], [1, 1, 2], [1, 1, 3], [1, 1, 4]]) B = np.array([[0, 0, 0], [1, 0, 2], [1, 0, 3], [1, 0, 4], [1, 1, 0], [1, 1, 1], [1, 1, 4]]) A_rows = A.view([('', A.dtype)] * A.shape[1]) B_rows = B.view([('', B.dtype)] * B.shape[1]) diff_array = np.setdiff1d(A_rows, B_rows).view(A.dtype).reshape(-1, A.shape[1]) </code></pre> <p>As @Rahul suggested, for a non numpy easy solution,</p> <pre><code>diff_array = [i for i in A if i not in B] </code></pre>
3
2016-10-15T06:43:10Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would like to do something like this.</p> <pre><code>data = some numpy array label = some numpy array A = np.argwhere(label==0) #[[1 1 1], [1 1 2], [1 1 3], [1 1 4]] B = np.argwhere(data&gt;1.5) #[[0 0 0], [1 0 2], [1 0 3], [1 0 4], [1 1 0], [1 1 1], [1 1 4]] out = np.argwhere(label==0 and data&gt;1.5) #[[1 1 2], [1 1 3]] </code></pre>
11
2016-10-15T06:36:16Z
40,055,928
<p>there is a easy solution with <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a>,</p> <pre><code>A = [i for i in A if i not in B] </code></pre> <p>Result</p> <pre><code>[[1, 1, 2], [1, 1, 3]] </code></pre> <p>List comprehension it's not removing the elements from the array, It's just reassigning, </p> <p>if you want to remove the elements use this method</p> <pre><code>for i in B: if i in A: A.remove(i) </code></pre>
4
2016-10-15T06:47:34Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would like to do something like this.</p> <pre><code>data = some numpy array label = some numpy array A = np.argwhere(label==0) #[[1 1 1], [1 1 2], [1 1 3], [1 1 4]] B = np.argwhere(data&gt;1.5) #[[0 0 0], [1 0 2], [1 0 3], [1 0 4], [1 1 0], [1 1 1], [1 1 4]] out = np.argwhere(label==0 and data&gt;1.5) #[[1 1 2], [1 1 3]] </code></pre>
11
2016-10-15T06:36:16Z
40,055,932
<p>Another non-numpy solution:</p> <pre><code>[i for i in A if i not in B] </code></pre>
3
2016-10-15T06:48:09Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would like to do something like this.</p> <pre><code>data = some numpy array label = some numpy array A = np.argwhere(label==0) #[[1 1 1], [1 1 2], [1 1 3], [1 1 4]] B = np.argwhere(data&gt;1.5) #[[0 0 0], [1 0 2], [1 0 3], [1 0 4], [1 1 0], [1 1 1], [1 1 4]] out = np.argwhere(label==0 and data&gt;1.5) #[[1 1 2], [1 1 3]] </code></pre>
11
2016-10-15T06:36:16Z
40,056,135
<p>Here is a Numpythonic approach with <em>broadcasting</em>:</p> <pre><code>In [83]: A[np.all(np.any((A-B[:, None]), axis=2), axis=0)] Out[83]: array([[1, 1, 2], [1, 1, 3]]) </code></pre> <p>Here is a timeit with other answer:</p> <pre><code>In [90]: def cal_diff(A, B): ....: A_rows = A.view([('', A.dtype)] * A.shape[1]) ....: B_rows = B.view([('', B.dtype)] * B.shape[1]) ....: return np.setdiff1d(A_rows, B_rows).view(A.dtype).reshape(-1, A.shape[1]) ....: In [93]: %timeit cal_diff(A, B) 10000 loops, best of 3: 54.1 µs per loop In [94]: %timeit A[np.all(np.any((A-B[:, None]), axis=2), axis=0)] 100000 loops, best of 3: 9.41 µs per loop # Even better with Divakar's suggestion In [97]: %timeit A[~((A[:,None,:] == B).all(-1)).any(1)] 100000 loops, best of 3: 7.41 µs per loop </code></pre> <p>Well, if you are looking for a faster way you should looking for ways that reduce the number of comparisons. In this case (without considering the order) you can generate a unique number from your rows and compare the numbers which can be done with summing the items power of two.</p> <p>Here is the benchmark with Divakar's in1d approach:</p> <pre><code>In [144]: def in1d_approach(A,B): .....: dims = np.maximum(B.max(0),A.max(0))+1 .....: return A[~np.in1d(np.ravel_multi_index(A.T,dims),\ .....: np.ravel_multi_index(B.T,dims))] .....: In [146]: %timeit in1d_approach(A, B) 10000 loops, best of 3: 23.8 µs per loop In [145]: %timeit A[~np.in1d(np.power(A, 2).sum(1), np.power(B, 2).sum(1))] 10000 loops, best of 3: 20.2 µs per loop </code></pre> <p>You can use <code>np.diff</code> to get the an order independent result:</p> <pre><code>In [194]: B=np.array([[0, 0, 0,], [1, 0, 2,], [1, 0, 3,], [1, 0, 4,], [1, 1, 0,], [1, 1, 1,], [1, 1, 4,], [4, 1, 1]]) In [195]: A[~np.in1d(np.diff(np.diff(np.power(A, 2))), np.diff(np.diff(np.power(B, 2))))] Out[195]: array([[1, 1, 2], [1, 1, 3]]) In [196]: %timeit A[~np.in1d(np.diff(np.diff(np.power(A, 2))), np.diff(np.diff(np.power(B, 2))))] 10000 loops, best of 3: 30.7 µs per loop </code></pre> <p>Benchmark with Divakar's setup:</p> <pre><code>In [198]: B = np.random.randint(0,9,(1000,3)) In [199]: A = np.random.randint(0,9,(100,3)) In [200]: A_idx = np.random.choice(np.arange(A.shape[0]),size=10,replace=0) In [201]: B_idx = np.random.choice(np.arange(B.shape[0]),size=10,replace=0) In [202]: A[A_idx] = B[B_idx] In [203]: %timeit A[~np.in1d(np.diff(np.diff(np.power(A, 2))), np.diff(np.diff(np.power(B, 2))))] 10000 loops, best of 3: 137 µs per loop In [204]: %timeit A[~np.in1d(np.power(A, 2).sum(1), np.power(B, 2).sum(1))] 10000 loops, best of 3: 112 µs per loop In [205]: %timeit in1d_approach(A, B) 10000 loops, best of 3: 115 µs per loop </code></pre> <p>Timing with larger arrays (Divakar's solution is slightly faster):</p> <pre><code>In [231]: %timeit A[~np.in1d(np.diff(np.diff(np.power(A, 2))), np.diff(np.diff(np.power(B, 2))))] 1000 loops, best of 3: 1.01 ms per loop In [232]: %timeit A[~np.in1d(np.power(A, 2).sum(1), np.power(B, 2).sum(1))] 1000 loops, best of 3: 880 µs per loop In [233]: %timeit in1d_approach(A, B) 1000 loops, best of 3: 807 µs per loop </code></pre>
9
2016-10-15T07:07:33Z
[ "python", "arrays", "numpy" ]
Removing elements from an array that are in another array
40,055,835
<p>Say I have these 2D arrays A and B.</p> <p>How can I remove elements from A that are in B.</p> <pre><code>A=np.asarray([[1,1,1], [1,1,2], [1,1,3], [1,1,4]]) B=np.asarray([[0,0,0], [1,0,2], [1,0,3], [1,0,4], [1,1,0], [1,1,1], [1,1,4]]) #output = [[1,1,2], [1,1,3]] </code></pre> <hr> <p>To be more precise, I would like to do something like this.</p> <pre><code>data = some numpy array label = some numpy array A = np.argwhere(label==0) #[[1 1 1], [1 1 2], [1 1 3], [1 1 4]] B = np.argwhere(data&gt;1.5) #[[0 0 0], [1 0 2], [1 0 3], [1 0 4], [1 1 0], [1 1 1], [1 1 4]] out = np.argwhere(label==0 and data&gt;1.5) #[[1 1 2], [1 1 3]] </code></pre>
11
2016-10-15T06:36:16Z
40,056,251
<p>Based on <a href="http://stackoverflow.com/a/38674038/3293881"><code>this solution</code></a> to <a href="http://stackoverflow.com/questions/38674027/find-the-row-indexes-of-several-values-in-a-numpy-array"><code>Find the row indexes of several values in a numpy array</code></a>, here's a NumPy based solution with less memory footprint and could be beneficial when working with large arrays -</p> <pre><code>dims = np.maximum(B.max(0),A.max(0))+1 out = A[~np.in1d(np.ravel_multi_index(A.T,dims),np.ravel_multi_index(B.T,dims))] </code></pre> <p>Sample run -</p> <pre><code>In [38]: A Out[38]: array([[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4]]) In [39]: B Out[39]: array([[0, 0, 0], [1, 0, 2], [1, 0, 3], [1, 0, 4], [1, 1, 0], [1, 1, 1], [1, 1, 4]]) In [40]: out Out[40]: array([[1, 1, 2], [1, 1, 3]]) </code></pre> <p>Runtime test on large arrays -</p> <pre><code>In [107]: def in1d_approach(A,B): ...: dims = np.maximum(B.max(0),A.max(0))+1 ...: return A[~np.in1d(np.ravel_multi_index(A.T,dims),\ ...: np.ravel_multi_index(B.T,dims))] ...: In [108]: # Setup arrays with B as large array and A contains some of B's rows ...: B = np.random.randint(0,9,(1000,3)) ...: A = np.random.randint(0,9,(100,3)) ...: A_idx = np.random.choice(np.arange(A.shape[0]),size=10,replace=0) ...: B_idx = np.random.choice(np.arange(B.shape[0]),size=10,replace=0) ...: A[A_idx] = B[B_idx] ...: </code></pre> <p>Timings with <code>broadcasting</code> based solutions -</p> <pre><code>In [109]: %timeit A[np.all(np.any((A-B[:, None]), axis=2), axis=0)] 100 loops, best of 3: 4.64 ms per loop # @Kasramvd's soln In [110]: %timeit A[~((A[:,None,:] == B).all(-1)).any(1)] 100 loops, best of 3: 3.66 ms per loop </code></pre> <p>Timing with less memory footprint based solution -</p> <pre><code>In [111]: %timeit in1d_approach(A,B) 1000 loops, best of 3: 231 µs per loop </code></pre> <p><strong>Further performance boost</strong></p> <p><code>in1d_approach</code> reduces each row by considering each row as an indexing tuple. We can do the same a bit more efficiently by introducing matrix-multiplication with <code>np.dot</code>, like so -</p> <pre><code>def in1d_dot_approach(A,B): cumdims = (np.maximum(A.max(),B.max())+1)**np.arange(B.shape[1]) return A[~np.in1d(A.dot(cumdims),B.dot(cumdims))] </code></pre> <p>Let's test it against the previous on much larger arrays -</p> <pre><code>In [251]: # Setup arrays with B as large array and A contains some of B's rows ...: B = np.random.randint(0,9,(10000,3)) ...: A = np.random.randint(0,9,(1000,3)) ...: A_idx = np.random.choice(np.arange(A.shape[0]),size=10,replace=0) ...: B_idx = np.random.choice(np.arange(B.shape[0]),size=10,replace=0) ...: A[A_idx] = B[B_idx] ...: In [252]: %timeit in1d_approach(A,B) 1000 loops, best of 3: 1.28 ms per loop In [253]: %timeit in1d_dot_approach(A, B) 1000 loops, best of 3: 1.2 ms per loop </code></pre>
9
2016-10-15T07:19:03Z
[ "python", "arrays", "numpy" ]
I am trying to print some predefined sequence in python
40,055,852
<p>I am trying to add to more paragraph but getting error? I am able to print first three paragraph but while I trying to add to more paragraph getting error. Can anyone please correct?</p> <p>Input file:</p> <pre><code>HETATM10910 C4B NAD A 363 60.856 -58.575 149.282 1.00 40.44 C HETATM10911 O4B NAD A 363 61.320 -59.488 148.275 1.00 43.48 O HETATM10912 C3B NAD A 363 60.243 -57.426 148.473 1.00 40.37 C HETATM10914 C2B NAD A 363 60.167 -57.970 147.054 1.00 40.90 C HETATM10916 C1B NAD A 363 61.394 -58.766 147.056 1.00 43.29 C HETATM10954 C4B NAD B 363 41.496 -54.407 140.932 1.00 39.26 C HETATM10955 O4B NAD B 363 41.936 -54.715 139.568 1.00 41.96 O HETATM10956 C3B NAD B 363 42.061 -55.476 141.894 1.00 37.13 C HETATM10958 C2B NAD B 363 42.883 -56.336 140.942 1.00 38.13 C HETATM10960 C1B NAD B 363 42.233 -56.127 139.593 1.00 42.92 C </code></pre> <p>I want to print data as per following: </p> <pre><code>HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C HETATM 3792 C2B NAI A 302 54.537 14.748 7.190 1.00 50.93 C HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O HETATM 3790 C3B NAI A 302 54.225 15.525 8.465 1.00 52.99 C HETATM 3788 C4B NAI A 302 52.695 15.486 8.535 1.00 57.28 C HETATM 3789 O4B NAI A 302 52.258 14.631 7.456 1.00 56.26 O HETATM 3794 C1B NAI A 302 53.348 13.816 7.022 1.00 53.44 C </code></pre> <p>same lie that for each chain. Chain ID may be A to H. Code: </p> <pre><code>import os import sys d = {} chainIDs = ('A', 'B', 'C', 'D',) atomIDs = ('C4B', 'O4B', 'C1B', 'C2B', 'C3B', 'C4B') with open('1A7K.pdb') as pdbfile: for line in map(str.rstrip, pdbfile): if line[:6] != "HETATM": continue chainID = line[21:22] atomID = line[13:16].strip() if chainID not in chainIDs: continue if atomID not in atomIDs: continue try: d[chainID][atomID] = line except KeyError: d[chainID] = {atomID: line} n = 4 for chain, atoms in d.items(): for atom, line in atoms.items(): for i in range(len(atom)-n+1): for j in range(n): print d[chain][atomIDs[i+j]] print </code></pre> <p>Msg is:</p> <pre><code>runfile('C:/Users/Desktop/test_python_2.py', wdir='C:/Users/Desktop') </code></pre>
0
2016-10-15T06:38:41Z
40,055,953
<p>In your code</p> <pre><code>for i in range(len(atomIDs)-n+1): for j in range(len(i)-n+1): for k in range(len((j))-n+1): for l in range(n): </code></pre> <p>you take the length of <code>i</code> and <code>j</code>. These are integers (obtained from range), and as the error you receive states, <code>int</code> objects do not have a length as such (at least as far as Python's <code>len</code> function is concerned).</p> <p>What precisely are you trying to do with these for loops? If you wish to print each line for each chain and atom, would something like the following would work?</p> <pre><code>for chain, atoms in d.items(): for atom, line in atoms.items(): print line </code></pre>
0
2016-10-15T06:49:45Z
[ "python", "python-2.7", "python-3.x", "bioinformatics" ]
Playing MP3s in Python - Automatically handling varied sampling frequencies
40,056,024
<p>I am writing a python program to practice and test my Mandarin oral comprehension. It selects a random mp3 from my designated directory and plays it (then does more stuff after). I am using pygame to play these mp3s, but my problem is my current setup requires explicit declaration of the sampling frequency of the mp3 in order for it to play properly. But, I have a mixture of 48 kHz and 44.1 kHz mp3s, and would like to be able to play them without distorting the sound.</p> <pre><code>import pygame import random import os filenames = [x[:-4] for x in os.listdir(filepath) if x.endswith(suffix)] pygame.mixer.init(48000, -16, 2, 4096) selected_filename = random.choice(filenames) selected_filename_full = filepath + selected_filename + suffix pygame.mixer.music.load(selected_filename_full) pygame.mixer.music.set_volume(volume) pygame.mixer.music.play() </code></pre> <p>Is there a way to detect the sampling frequency of an mp3? Or somehow play an mp3 properly some other way? It seems like a weird issue, whenever I double click an mp3, my music player will always play it properly, so what can I do to get the same behavior in my python code?</p>
0
2016-10-15T06:57:37Z
40,056,701
<p>You can use <a href="http://eyed3.nicfit.net/" rel="nofollow">eyeD3</a>:</p> <pre><code>import eyed3 e = eyed3.load(filename) print e.info.sample_freq </code></pre>
1
2016-10-15T08:09:54Z
[ "python", "pygame", "mp3", "frequency", "sampling" ]
python program freezes after client connects
40,056,046
<p>I have this python program which uses flask for video streaming( sequence of independent JPEG pictures). I know I should debug this myself first but as soon as the client connects index.html only shows a broken image icon and the computer freezes. I have tried -</p> <ul> <li>Running it on linux where it runs fine.</li> <li>disabling or enabling threading but it has no effect.<br><br></li> </ul> <p><strong>edit 2</strong> : </p> <p>It worked on Linux because it had python 2.7 installed. In python 3 it doesn't show any error but doesn't work. Tried it on four systems(both windows and linux) and it seems to be a compatibility problem because it failed on all computers with python 3 but not with python 2.How can it be made to work in python 3?</p> <p><strong>edit 1</strong> : The freezing has been fixed by adding <code>time.sleep(1)</code> inside the loop in <code>gen()</code> but there is still no output in the browser.Recorded the network activity in chrome developer tools. Here's a screenshot - <a href="https://i.stack.imgur.com/xRuzC.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/xRuzC.jpg" alt="enter image description here"></a></p> <p>Here is the code :<br><br></p> <p>app.py(server)</p> <pre><code>#!/usr/bin/env python from flask import Flask, render_template, Response # emulated camera from camera import Camera app = Flask(__name__) @app.route('/') def index(): """Video streaming home page.""" return render_template('index.html') def gen(camera): """Video streaming generator function.""" while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') @app.route('/video_feed') def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=False, threaded=False) </code></pre> <p>camera.py</p> <pre><code>from time import time class Camera(object): """An emulated camera implementation that streams a repeated sequence of files 1.jpg, 2.jpg and 3.jpg at a rate of one frame per second.""" def __init__(self): self.frames = [open(f + '.jpg', 'rb').read() for f in ['1', '2', '3']] def get_frame(self): return self.frames[int(time()) % 3] </code></pre> <p>index.py(client)</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Video Streaming Demonstration&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Video Streaming Demonstration&lt;/h1&gt; &lt;img src="{{ url_for('video_feed') }}"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As I have already mentioned I can't use a debugger because the whole computer freezes immediately.python version - 3.5 and os - windows 10.<br> How can I fix it?</p>
0
2016-10-15T06:59:57Z
40,056,948
<p>It appears that you might want to double check the routes to the image files from app.py, i.e. make sure they're in the same directory or if they're in an /images directory, double check the path to the files or that they are there to begin with.</p> <p>As a test, (git) clone Miguel's project and run it and see whether you get the same result.</p> <p><a href="https://blog.miguelgrinberg.com/post/video-streaming-with-flask" rel="nofollow">https://blog.miguelgrinberg.com/post/video-streaming-with-flask</a></p>
0
2016-10-15T08:43:56Z
[ "python", "windows", "python-3.x", "flask", "mjpeg" ]
Maximum distance between points in a convex hull
40,056,061
<p>I am solving a problem in which I need to find the maximum distance between two points on a plane (2D) .So there is an O(n^2) approach in which I calculate distance between every point in the graph . I also implemented a convex hull algorithm now my approach is I compute convex hull in O(nlogn) and then use the O(n^2) algorithm to compute maximum distance between points in the convex hull. Is there a better approach than this to compute the max distance in convex hull</p> <p>Here are my algorithm :</p> <blockquote> <p>O(n^2)</p> </blockquote> <pre><code> def d(l1,l2): return ((l2[0]-l1[0])**2+(l2[1]-l1[1])**2) def find_max_dist(L): max_dist = d(L[0], L[1]) for i in range(0, len(L)-1): for j in range(i+1, len(L)): max_dist = max(d(L[i], L[j]), max_dist) return max_dist </code></pre> <blockquote> <p>convex hull</p> </blockquote> <pre><code>def convex_hull(points): """Computes the convex hull of a set of 2D points. Input: an iterable sequence of (x, y) pairs representing the points. Output: a list of vertices of the convex hull in counter-clockwise order, starting from the vertex with the lexicographically smallest coordinates. Implements Andrew's monotone chain algorithm. O(n log n) complexity. """ # Sort the points lexicographically (tuples are compared lexicographically). # Remove duplicates to detect the case we have just one unique point. points = sorted(set(points)) # Boring case: no points or a single point, possibly repeated multiple times. if len(points) &lt;= 1: return points # 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product. # Returns a positive value, if OAB makes a counter-clockwise turn, # negative for clockwise turn, and zero if the points are collinear. def cross(o, a, b): return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]) # Build lower hull lower = [] for p in points: while len(lower) &gt;= 2 and cross(lower[-2], lower[-1], p) &lt;= 0: lower.pop() lower.append(p) # Build upper hull upper = [] for p in reversed(points): while len(upper) &gt;= 2 and cross(upper[-2], upper[-1], p) &lt;= 0: upper.pop() upper.append(p) # Concatenation of the lower and upper hulls gives the convex hull. # Last point of each list is omitted because it is repeated at the beginning of the other list. return lower[:-1] + upper[:-1] </code></pre> <blockquote> <p>overall algorithm</p> </blockquote> <pre><code> l=[] for i in xrange(int(raw_input())): # takes input denoting number of points in the plane n=tuple(int(i) for i in raw_input().split()) #takes each point and makes a tuple l.append(n) # appends to n if len(l)&gt;=10: print find_max_dist(convex_hull(l)) else: print find_max_dist(l) </code></pre> <p>Now how do I improve the running time of my approach and is there a better way to compute this ?</p>
2
2016-10-15T07:00:56Z
40,057,533
<p>Once you have a convex hull, you can find two furthest points in linear time. </p> <p>The idea is to keep two pointers: one of them points to the current edge (and is always incremented by one) and the other one points to a vertex.</p> <p>The answer is the maximum distance between end points of an edge and the vertex for all edges.</p> <p>It is possible to show (the proof is neither short nor trivial, so I will not post it here) that if we keep incrementing the second pointer every time after moving the first one as long as it increases the distance between the line that goes through the edge and a vertex, we will find the optimal answer. </p>
1
2016-10-15T09:50:36Z
[ "python", "algorithm", "python-2.7", "convex-hull" ]
Did numpy override == operator, because i can't understand follow python code
40,056,209
<pre><code>image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) </code></pre> <p>What does this line mean?</p> <pre><code>labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) </code></pre> <p>code is from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/2_fullyconnected.ipynb" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/2_fullyconnected.ipynb</a></p>
1
2016-10-15T07:15:28Z
40,056,270
<p>In numpy, the <code>==</code> operator means something different when comparing two numpy arrays (as is being done in that line of note), so yes, it is overloaded in that sense. It compares the two numpy arrays elementwise and returns a boolean numpy array of the same size as the two inputs. The same is true for other comparisons like <code>&gt;=</code>, <code>&lt;</code>, etc.</p> <p>E.g. </p> <pre><code>import numpy as np print(np.array([5,8,2]) == np.array([5,3,2])) # [True False True] print((np.array([5,8,2]) == np.array([5,3,2])).astype(np.float32)) # [1. 0. 1.] </code></pre>
3
2016-10-15T07:21:47Z
[ "python", "numpy" ]
Did numpy override == operator, because i can't understand follow python code
40,056,209
<pre><code>image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) </code></pre> <p>What does this line mean?</p> <pre><code>labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) </code></pre> <p>code is from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/2_fullyconnected.ipynb" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/2_fullyconnected.ipynb</a></p>
1
2016-10-15T07:15:28Z
40,056,282
<p>For Numpy arrays the <code>==</code> operator is a element-wise operation which returns a boolean array. The <code>astype</code> function transforms the boolean values <code>True</code> to <code>1.0</code> and <code>False</code> to <code>0.0</code> as stated in the comment.</p>
1
2016-10-15T07:22:54Z
[ "python", "numpy" ]
Did numpy override == operator, because i can't understand follow python code
40,056,209
<pre><code>image_size = 28 num_labels = 10 def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) print('Training set', train_dataset.shape, train_labels.shape) print('Validation set', valid_dataset.shape, valid_labels.shape) print('Test set', test_dataset.shape, test_labels.shape) </code></pre> <p>What does this line mean?</p> <pre><code>labels = (np.arange(num_labels) == labels[:,None]).astype(np.float32) </code></pre> <p>code is from <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/2_fullyconnected.ipynb" rel="nofollow">https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/udacity/2_fullyconnected.ipynb</a></p>
1
2016-10-15T07:15:28Z
40,061,909
<p><a href="https://docs.python.org/3/reference/expressions.html#value-comparisons" rel="nofollow">https://docs.python.org/3/reference/expressions.html#value-comparisons</a> describes value comparisons like <code>==</code>. While the default comparison is an <code>identity</code> <code>x is y</code>, it first checks if either argument implements an <code>__eq__</code> method. Numbers, lists, and dictionaries implement their own version. And so does <code>numpy</code>.</p> <p>What's unique about the <code>numpy</code> <code>__eq__</code> is that it does, if possible an element by element comparison, and returns a boolean array of the same size.</p> <pre><code>In [426]: [1,2,3]==[1,2,3] Out[426]: True In [427]: z1=np.array([1,2,3]); z2=np.array([1,2,3]) In [428]: z1==z2 Out[428]: array([ True, True, True], dtype=bool) In [432]: z1=np.array([1,2,3]); z2=np.array([1,2,4]) In [433]: z1==z2 Out[433]: array([ True, True, False], dtype=bool) In [434]: (z1==z2).astype(float) # change bool to float Out[434]: array([ 1., 1., 0.]) </code></pre> <p>A common SO question is 'why do I get this ValueError?'</p> <pre><code>In [435]: if z1==z2: print('yes') ... ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() </code></pre> <p>That's because the comparison produces this array which has more than one True/False value.</p> <p>Comparison of floats is also a common problem. Check out <code>isclose</code> and <code>allclose</code> it that issue comes up.</p>
0
2016-10-15T17:08:30Z
[ "python", "numpy" ]
How does numpy broadcasting perform faster?
40,056,275
<p>In the following question, <a href="http://stackoverflow.com/a/40056135/5714445">http://stackoverflow.com/a/40056135/5714445</a></p> <p>Numpy's broadcasting provides a solution that's almost 6x faster than using np.setdiff1d() paired with np.view(). How does it manage to do this?</p> <p>And using <code>A[~((A[:,None,:] == B).all(-1)).any(1)]</code> speeds it up even more. Interesting, but raises yet another question. How does this perform even better?</p>
6
2016-10-15T07:22:13Z
40,057,999
<p>I would try to answer the second part of the question.</p> <p>So, with it we are comparing :</p> <pre><code>A[np.all(np.any((A-B[:, None]), axis=2), axis=0)] (I) </code></pre> <p>and </p> <pre><code>A[~((A[:,None,:] == B).all(-1)).any(1)] </code></pre> <p>To compare with a matching perspective against the first one, we could write down the second approach like this -</p> <pre><code>A[(((~(A[:,None,:] == B)).any(2))).all(1)] (II) </code></pre> <p>The major difference when considering performance, would be the fact that with the first one, we are getting non-matches with subtraction and then checking for non-zeros with <code>.any()</code>. Thus, <code>any()</code> is made to operate on an array of non-boolean dtype array. In the second approach, instead we are feeding it a boolean array obtained with <code>A[:,None,:] == B</code>.</p> <p>Let's do a small runtime test to see how <code>.any()</code> performs on <code>int</code> dtype vs <code>boolean array</code> -</p> <pre><code>In [141]: A = np.random.randint(0,9,(1000,1000)) # An int array In [142]: %timeit A.any(0) 1000 loops, best of 3: 1.43 ms per loop In [143]: A = np.random.randint(0,9,(1000,1000))&gt;5 # A boolean array In [144]: %timeit A.any(0) 10000 loops, best of 3: 164 µs per loop </code></pre> <p>So, with close to <strong><code>9x</code></strong> speedup on this part, we see a huge advantage to use <code>any()</code> with boolean arrays. This I think was the biggest reason to make the second approach faster.</p>
5
2016-10-15T10:39:59Z
[ "python", "numpy" ]