title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Unexpected number of decimal places and Syntactical Query
39,577,927
<p>I'm trying to find the intersection between the curves $ y= x^2+3x+2 $ and $ y=x^2+2x+1$. For this, I have written the following python program:</p> <pre><code>from numpy import * import numpy as np for x in np.arange(-100, 100, 0.0001): y_1=x**2+3*x+2 y_2=x**2+2*x+1 if round(y_1, 5)==round(y_2,5): print x print 'end' </code></pre> <p>The console displays:</p> <pre><code>-0.999999996714 end </code></pre> <p>I have three questions. </p> <p>1) Why must I include <code>y_1=x**2+3*x+2</code> and <code>y_2=x**2+2*x+1</code> in the for statement? Why can I not simply include them after the line <code>from numpy import*</code>?</p> <p>2) Why is the output to 12 decimal places when I have specified the step in <code>np.arange</code> to be 4 decimal places?</p> <p>3) Why is -1.0000 not outputted?</p> <p>Please go easy on me, I'm just starting to use python and thought I would try and solve some simultaneous equations with it.</p> <p>Thanks,</p> <p>Jack</p>
1
2016-09-19T16:33:45Z
39,578,038
<ol> <li>Because the <code>y_1</code> and <code>y_2</code> lines are computing specific values, not defining functions. Plain Python does not have a built-in concept of symbolic equations. (Although you can implement symbolic equations various ways.)</li> <li>Because binary floating-point, as used in Python, cannot exactly represent 0.0001 (base 10). Therefore, the step is rounded, so your steps are not exactly ten-thousandths. The Python <code>print</code> statement does not round, absent specific instructions to do so, so you get exactly the value the system is using, even though that's not quite the value you asked for.</li> <li>Same reason: Since the steps are not exactly ten-thousandths, the point at which the functions are close enough to test as equal under rounding is not exactly at -1.</li> </ol>
2
2016-09-19T16:39:12Z
[ "python", "numpy" ]
Unexpected number of decimal places and Syntactical Query
39,577,927
<p>I'm trying to find the intersection between the curves $ y= x^2+3x+2 $ and $ y=x^2+2x+1$. For this, I have written the following python program:</p> <pre><code>from numpy import * import numpy as np for x in np.arange(-100, 100, 0.0001): y_1=x**2+3*x+2 y_2=x**2+2*x+1 if round(y_1, 5)==round(y_2,5): print x print 'end' </code></pre> <p>The console displays:</p> <pre><code>-0.999999996714 end </code></pre> <p>I have three questions. </p> <p>1) Why must I include <code>y_1=x**2+3*x+2</code> and <code>y_2=x**2+2*x+1</code> in the for statement? Why can I not simply include them after the line <code>from numpy import*</code>?</p> <p>2) Why is the output to 12 decimal places when I have specified the step in <code>np.arange</code> to be 4 decimal places?</p> <p>3) Why is -1.0000 not outputted?</p> <p>Please go easy on me, I'm just starting to use python and thought I would try and solve some simultaneous equations with it.</p> <p>Thanks,</p> <p>Jack</p>
1
2016-09-19T16:33:45Z
39,578,105
<p>1) First you have (probably) redundant import statements:</p> <pre><code>from numpy import * import numpy as np </code></pre> <p>The first statement imports the <code>__all__</code> variable from the package the second statement imports the numpy package then aliases it as <code>np</code>. The normal convention is to import numpy as <code>np</code>, so I would delete your first line and keep the second. </p> <p>Now to more clearly answer your question, you need to include your equations in the for loop because <code>x</code> is representing each element in the <code>np.array</code> using the <code>for</code> loop.</p> <p>2 and 3) The value is probably being interpreted as a float in your equations. The rounding error is inherent to how python (and most programing languages) interpret fractions. <a href="https://docs.python.org/3/tutorial/floatingpoint.html" rel="nofollow">See more here</a>. </p>
1
2016-09-19T16:43:23Z
[ "python", "numpy" ]
Bokeh line graph looping
39,577,944
<p>I’ve been working on bokeh plots and I’m trying to plot a line graph taking values from a database. But the plot kind of traces back to the initial point and I don’t want that. I want a plot which starts at one point and stops at a certain point (and circle back). I’ve tried plotting it on other tools like SQLite browser and Excel and the plot seems ok which means I must be doing something wrong with the bokeh stuff and that the data points itself are not in error.</p> <p>I’ve attached the images for reference and the line of code doing the line plot. Is there something I’ve missed?</p> <pre><code>&gt;&gt;&gt; image = fig.line(“x”, “y”, color=color, source=something) </code></pre> <p>(Assume <code>x</code> and <code>y</code> are integer values and I’ve specified <code>x</code> and <code>y</code> ranges as <code>DataRange1d(bounds=(0,None))</code>)</p> <p><a href="http://i.stack.imgur.com/wpPiU.png" rel="nofollow"><img src="http://i.stack.imgur.com/wpPiU.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/shVqI.png" rel="nofollow"><img src="http://i.stack.imgur.com/shVqI.png" alt="enter image description here"></a></p>
0
2016-09-19T16:34:33Z
39,578,847
<p>Bokeh does not "auto-close" lines. You can see this is the case by looking at any number of examples in the docs and repository, but here is one in particular:</p> <p><a href="http://bokeh.pydata.org/en/latest/docs/gallery/stocks.html" rel="nofollow">http://bokeh.pydata.org/en/latest/docs/gallery/stocks.html</a></p> <p>Bokeh's <code>.line</code> method will only "close up" if that is what is in the data (i.e., if the last point in the data is a repeat of the first point). I suggest you actually inspect the data values in <code>source.data</code> and I believe you will find this to be the case. Then the question is why is that the case and how to prevent it from doing that, but that is not really a Bokeh question. </p>
0
2016-09-19T17:27:56Z
[ "python", "bokeh" ]
How to multiply without the * sign using recursion?
39,577,950
<p>so as homework for a programming class on python we're supposed to multiply to integers (n,m) with each other WITHOUT using the * sign (or another multiplication form). We're supposed to use recursion to solve this problem, so i tried just adding n with itself, m number of times. I think my problem is with using recursion itself. I have searched on the internet for recursion usage, no results. Here is my code. Could someone point me in the right direction?</p> <pre><code> def mult(n,m): """ mult outputs the product of two integers n and m input: any numbers """ if m &gt; 0: return n + n return m - 1 else: return 1 </code></pre>
-4
2016-09-19T16:35:00Z
39,578,224
<p>I don't want to give you the answer to your homework here so instead hopefully I can provide an example of recursion that may help you along :-). </p> <pre><code># Here we define a normal function in python def count_down(val): # Next we do some logic, in this case print the value print(val) # Now we check for some kind of "exit" condition. In our # case we want the value to be greater than 1. If our value # is less than one we do nothing, otherwise we call ourself # with a new, different value. if val &gt; 1: count_down(val-1) count_down(5) </code></pre> <p>How can you apply this to what you're currently working on? Maybe, instead of printing something you could have it return something instead...</p>
1
2016-09-19T16:50:02Z
[ "python", "recursion" ]
How to multiply without the * sign using recursion?
39,577,950
<p>so as homework for a programming class on python we're supposed to multiply to integers (n,m) with each other WITHOUT using the * sign (or another multiplication form). We're supposed to use recursion to solve this problem, so i tried just adding n with itself, m number of times. I think my problem is with using recursion itself. I have searched on the internet for recursion usage, no results. Here is my code. Could someone point me in the right direction?</p> <pre><code> def mult(n,m): """ mult outputs the product of two integers n and m input: any numbers """ if m &gt; 0: return n + n return m - 1 else: return 1 </code></pre>
-4
2016-09-19T16:35:00Z
39,579,125
<p>You have the right mechanics, but you haven't internalized the basics you found in your searches. A recursive function usually breaks down to two cases:</p> <ol> <li>Base Case -- How do you know when you're done? What do you want to do at that point?</li> </ol> <p>Here, you've figured out that your base case is when the multiplier is 0. What do you want to return at this point? Remember, you're doing this as an additive process: I believe you want the additive identity element <strong>0</strong>, not the multiplicative <strong>1</strong>.</p> <ol start="2"> <li>Recursion Case -- Do something trivial to simplify the problem, then recur with this simplified version.</li> </ol> <p>Here, you've figured out that you want to enhance the running sum and reduce the multiplier by 1. However, you haven't called your function again. You haven't properly enhanced any sort of accumulative sum; you've doubled the multiplicand. Also, you're getting confused about recursion: <strong>return</strong> is to go back to whatever called this function. For recursion, you'll want something like</p> <pre><code>mult(n, m-1) </code></pre> <p>Now remember that this is a function: it returns a value. Now, what do you need to do with this value? For instance, if you're trying to compute 4*3, the statement above will give you the value of 4*2, What do you do with that, so that you can return the correct value of 4*3 to whatever called this instance? You'll want something like</p> <pre><code>result = mult(n, m-1) return [...] result </code></pre> <p>... where you have to fill in that <strong>[...]</strong> spot. If you want, you can combine these into a single line of code; I'm just trying to make it easier for you.</p>
0
2016-09-19T17:44:27Z
[ "python", "recursion" ]
How to multiply without the * sign using recursion?
39,577,950
<p>so as homework for a programming class on python we're supposed to multiply to integers (n,m) with each other WITHOUT using the * sign (or another multiplication form). We're supposed to use recursion to solve this problem, so i tried just adding n with itself, m number of times. I think my problem is with using recursion itself. I have searched on the internet for recursion usage, no results. Here is my code. Could someone point me in the right direction?</p> <pre><code> def mult(n,m): """ mult outputs the product of two integers n and m input: any numbers """ if m &gt; 0: return n + n return m - 1 else: return 1 </code></pre>
-4
2016-09-19T16:35:00Z
39,579,172
<p>Thanks guys, i figured it out!!! i had to return 0 instead of 1, otherwise the answer would always be one higher than what we wanted. and i understand how you have to call upon the function, which is the main thing i missed. Here's what i did:</p> <pre><code> def mult(n,m): """ mult outputs the product of two integers n and m input: any numbers """ if m == 0: return 0 else: return n + mult(n, m - 1) </code></pre>
0
2016-09-19T17:47:12Z
[ "python", "recursion" ]
Raspberry LCD IP display format
39,577,970
<p>I'm working on a little project with a Raspberry Pi, and I need to display the IP adress of the PI on an LCD screen. </p> <p>I followed this tutorial : <a href="https://learn.adafruit.com/drive-a-16x2-lcd-directly-with-a-raspberry-pi/python-code" rel="nofollow">https://learn.adafruit.com/drive-a-16x2-lcd-directly-with-a-raspberry-pi/python-code</a></p> <p>It seems to work fine, however there is a problem displaying the IP. Instead of displaying "192.168.0.68", it shows "fe80::779b:a7a1:9282:f4d5". It shows the time just fine ("Sep 19 18:20:41"). </p> <p>Being new to programming, I couldn't find the problem, so here I am asking for help </p> <p>Thanks in advance !</p>
1
2016-09-19T16:35:55Z
39,583,212
<p>I found the <code>netifaces</code> package to be useful for obtaining the IP address. The link below explains well about its basic usage</p> <p><a href="https://pypi.python.org/pypi/netifaces" rel="nofollow">https://pypi.python.org/pypi/netifaces</a></p> <p>Below is an example to obtain the ip address in the python interpreter.</p> <pre><code>&gt;&gt;&gt;import netifaces &gt;&gt;&gt;addr = netifaces.ifaddresses('en1') &gt;&gt;&gt;addr {18: [{'addr': 'e4:ce:8f:30:98:0c'}], 2: [{'broadcast': '192.168.1.255', 'addr': '192.168.1.22', 'netmask': '255.255.255.0'}], 30: [{'addr': 'fe80::e6ce:8fff:fe30:980c%en1', 'netmask': 'ffff:ffff:ffff:ffff::'}]} &gt;&gt;&gt;addr[netifaces.AF_INET][0]['addr'] '192.168.1.22' </code></pre> <p>Note: I use <code>'en1'</code> because I'm on a Mac. In the Pi typically this would be <code>'eth0'</code></p>
0
2016-09-19T22:49:42Z
[ "python", "raspberry-pi", "ip", "lcd" ]
What is "pkg-resources==0.0.0" in output of pip freeze command
39,577,984
<p>When I run <code>pip freeze</code> I see (among other expected packages) <code>pkg-resources==0.0.0</code>. I have seen a few posts mentioning this package (including <a href="https://stackoverflow.com/questions/38992194/why-does-pip-freeze-list-pkg-resources-0-0-0">this one</a>), but none explaining what it is, or why it is included in the output of <code>pip freeze</code>. The main reason I am wondering is out of curiosity, but also, it seems to break things in some cases when trying to install packages with a <code>requirements.txt</code> file generated with <code>pip freeze</code> that includes the <code>pkg-resources==0.0.0</code> line (for example when <a href="https://travis-ci.org/" rel="nofollow">Travis CI</a> tries to install dependencies through <code>pip</code> and finds this line).</p> <p><strong>What is <code>pkg-resources</code>, and is it OK to remove this line from <code>requirements.txt</code>?</strong></p> <h1>Update:</h1> <p>I have found that this line only seems to exist in the output of <code>pip freeze</code> when I am in a <code>virtualenv</code>. I am still not sure what it is or what it does, but I will investigate further knowing that it is likely related to <code>virtualenv</code>.</p>
4
2016-09-19T16:36:39Z
39,638,060
<p>As for the part of your question "is it OK to remove this line":</p> <p>I have the same issue here developing on an ubuntu 16.04 with that very line in the requirements. When deploying on a debian 8.5 running <code>"pip install -r requirements.txt"</code> pip complains that pkg-resources is "not found" but there is a global package installed "python-pkg-resources" so the dependency should be satisfied. Same on ubuntu: The package exists there as well.</p> <p>As stated <a href="http://stackoverflow.com/questions/38992194/why-does-pip-freeze-list-pkg-resources-0-0-0">here</a> it seems to be some "implicitly installed package". </p> <p>So: If you are on a Debian/Ubuntu having python-pkg-resources installed <strong>it should be safe to remove that line</strong>. I did so and everything is running fine. However since I am no expert on this you should keep in mind that this might lead to complications when deploying on another machine.</p>
1
2016-09-22T11:42:41Z
[ "python", "python-3.x", "pip", "ubuntu-16.04" ]
Dropdown menus in python / selenium
39,578,022
<p>Trying to autofill a form using python and selenium. Dropdown menu html is:</p> <pre><code>&lt;select id="typeOfTeacher" class="chosen-select-no-single ng-untouched ng-dirty ng-valid-parse ng-valid ng-valid-required" required="" ng-class="{ 'has-error' : positionDetailForm.typeOfTeacher.$invalid &amp;&amp; !positionDetailForm.typeOfTeacher.$pristine }" ng-change="vm.setRequired()" tabindex="-1" ng-model="vm.data.typeOfTeacher" name="typeOfTeacher" data-placeholder="Select" style="display: none;"&gt; &lt;option value="" disabled="" selected=""&gt;Select&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="1" ng-repeat="teacherType in vm.teacherTypes"&gt;No position at the moment&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="2" ng-repeat="teacherType in vm.teacherTypes"&gt;Supply&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="3" ng-repeat="teacherType in vm.teacherTypes"&gt;Permanent&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Python code is:</p> <pre><code>elem = Select(browser.find_element_by_id('typeOfTeacher')) elem.select_by_value("1") </code></pre> <p>Error is "element is not currently visible and may not be interacted with".</p>
0
2016-09-19T16:38:25Z
39,578,280
<p>I have not used the python Select method, but I would guess that the error message means that the menu is not being opened, and therefore an element in the menu is still hidden and cannot be interacted with.</p> <p>Try something like this:</p> <pre><code>element = driver.find_element_by_id('typeOfTeacher').click() driver.find_element_by_css_selector("[value=\"1\"]").click() </code></pre>
0
2016-09-19T16:53:44Z
[ "python", "selenium", "selenium-webdriver" ]
Dropdown menus in python / selenium
39,578,022
<p>Trying to autofill a form using python and selenium. Dropdown menu html is:</p> <pre><code>&lt;select id="typeOfTeacher" class="chosen-select-no-single ng-untouched ng-dirty ng-valid-parse ng-valid ng-valid-required" required="" ng-class="{ 'has-error' : positionDetailForm.typeOfTeacher.$invalid &amp;&amp; !positionDetailForm.typeOfTeacher.$pristine }" ng-change="vm.setRequired()" tabindex="-1" ng-model="vm.data.typeOfTeacher" name="typeOfTeacher" data-placeholder="Select" style="display: none;"&gt; &lt;option value="" disabled="" selected=""&gt;Select&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="1" ng-repeat="teacherType in vm.teacherTypes"&gt;No position at the moment&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="2" ng-repeat="teacherType in vm.teacherTypes"&gt;Supply&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="3" ng-repeat="teacherType in vm.teacherTypes"&gt;Permanent&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Python code is:</p> <pre><code>elem = Select(browser.find_element_by_id('typeOfTeacher')) elem.select_by_value("1") </code></pre> <p>Error is "element is not currently visible and may not be interacted with".</p>
0
2016-09-19T16:38:25Z
39,578,581
<p>This would work</p> <pre><code>element = driver.find_element_by_id('typeOfTeacher').click() element.find_element_by_xpath(".//option[@value='1']").click() </code></pre>
0
2016-09-19T17:12:19Z
[ "python", "selenium", "selenium-webdriver" ]
Dropdown menus in python / selenium
39,578,022
<p>Trying to autofill a form using python and selenium. Dropdown menu html is:</p> <pre><code>&lt;select id="typeOfTeacher" class="chosen-select-no-single ng-untouched ng-dirty ng-valid-parse ng-valid ng-valid-required" required="" ng-class="{ 'has-error' : positionDetailForm.typeOfTeacher.$invalid &amp;&amp; !positionDetailForm.typeOfTeacher.$pristine }" ng-change="vm.setRequired()" tabindex="-1" ng-model="vm.data.typeOfTeacher" name="typeOfTeacher" data-placeholder="Select" style="display: none;"&gt; &lt;option value="" disabled="" selected=""&gt;Select&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="1" ng-repeat="teacherType in vm.teacherTypes"&gt;No position at the moment&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="2" ng-repeat="teacherType in vm.teacherTypes"&gt;Supply&lt;/option&gt; &lt;option class="ng-binding ng-scope" value="3" ng-repeat="teacherType in vm.teacherTypes"&gt;Permanent&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Python code is:</p> <pre><code>elem = Select(browser.find_element_by_id('typeOfTeacher')) elem.select_by_value("1") </code></pre> <p>Error is "element is not currently visible and may not be interacted with".</p>
0
2016-09-19T16:38:25Z
39,579,423
<p>It looks like timing issue. You should try using <a href="http://selenium-python.readthedocs.io/waits.html#waits" rel="nofollow">Waits</a>. </p> <p>I would suggest you, use <code>WebDriverWait</code> to wait until dropdown visible before interaction as below :-</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "typeOfTeacher"))) select = Select(element) select.select_by_value("1") </code></pre>
0
2016-09-19T18:02:25Z
[ "python", "selenium", "selenium-webdriver" ]
How to delete existing file when user uploads a new one
39,578,087
<p>I've just successfully implemented a method similar to the one that Giles suggested for saving new images with a filename of the primary key of the model here: <a href="http://stackoverflow.com/a/16574947/5884437">http://stackoverflow.com/a/16574947/5884437</a></p> <p>Actual code used:</p> <pre><code>class Asset(models.Model): asset_id = models.AutoField(primary_key=True) asset_image = models.ImageField(upload_to = 'images/temp', max_length=255, null=True, blank=True) def save( self, *args, **kwargs ): # Call save first, to create a primary key super( Asset, self ).save( *args, **kwargs ) asset_image = self.asset_image if asset_image: # Create new filename, using primary key and file extension oldfile = self.asset_image.name dot = oldfile.rfind( '.' ) newfile = 'images/' + str( self.pk ) + oldfile[dot:] # Create new file and remove old one if newfile != oldfile: self.asset_image.storage.delete( newfile ) self.asset_image.storage.save( newfile, asset_image ) self.asset_image.name = newfile self.asset_image.close() self.asset_image.storage.delete( oldfile ) # Save again to keep changes super( Asset, self ).save( *args, **kwargs ) def __str__(self): return self.asset_description </code></pre> <p>e.g. User submits "MyPicture.jpg" on a blank 'new asset' form. Server first pre-saves the new asset to generate an (asset_id) primary key, then renames the file as [asset_id].[original_extension] (e.g. "26.jpg") and moves it to the correct folder. </p> <p>Unfortunately I've just found that this doesn't take into account files with different extensions, e.g. a user first uploads an image that gets renamed "26.jpg", but then when a user uploads a new image for that asset with a different extension (e.g. ".png"), both "26.jpg" &amp; "26.png" will be saved alongside each other.</p> <p>How can I change this so that an existing image is always deleted when a new image is uploaded for that asset / primary key? </p>
3
2016-09-19T16:42:20Z
39,578,883
<p>You can attempt to delete the old image when it doens't match the newly sumbitted image:</p> <pre><code>class Asset(models.Model): asset_id = models.AutoField(primary_key=True) asset_image = models.ImageField(upload_to = 'images/temp', max_length=255, null=True, blank=True) def save( self, *args, **kwargs ): # Delete the old image try: asset = Asset.objects.get(id=self.id) if asset.asset_image and self.image and asset.asset_image != self.image: # Delete the old file if it doesn't match the newly submitted one asset.asset_image.delete(save=False); except Asset.DoesNotExist: # Do nothing when a new image is submitted pass # Call save first, to create a primary key super( Asset, self ).save( *args, **kwargs ) ... </code></pre> <p>A better solution might be to take a look at <a href="https://pypi.python.org/pypi/django-cleanup" rel="nofollow">django-cleanup</a> which automatically deletes files for FileField, ImageField and subclasses. It will delete the old file on model deletion or when a new file is being updated.</p>
2
2016-09-19T17:30:27Z
[ "python", "django", "django-models" ]
Killing stdout in python breaks get_line_buffer()
39,578,088
<p>So I'm using some libraries that (unfortunately and much to my chagrin) print to stdout for certain debug info. Okay, no problem, I just disabled it with:</p> <pre><code>import sys,os sys.stdout = open(os.devnull,'wb') </code></pre> <p>I've recently added code for getting user input and printing output in the terminal, which of course needs stdout. But again, no problem, instead of <code>print</code> I can just do:</p> <pre><code>sys.__stdout__.write('text\n') </code></pre> <p>Finally, since I'm doing <code>raw_input</code> in a separate thread and the program's output can interrupt the user typing, I wanted to re-echo the test as described <a href="http://stackoverflow.com/a/4653306/2258915">in the first part of this answer</a> to make it more or less seamless using <code>readline.get_line_buffer()</code>. For example, if the user entered <code>foobar</code>:</p> <pre><code>&gt; foobar </code></pre> <p>And then another thread says <code>Interrupting text!</code> it should look like:</p> <pre><code>Interrupting text! &gt; foobar </code></pre> <p>But instead I observe:</p> <pre><code>Interrupting text! &gt; </code></pre> <p>It turns out that <code>readline.get_line_buffer()</code> is always blank, and the code fails to re-echo what the user had typed. If I remove the <code>sys.stdout</code> override, everything works as expected (except now the debug output from libraries isn't blocked).</p> <p>I'm using Python 2.7 on Linux if that matters. Perhaps what I want to do is impossible, but I'd really like to know why this is happening. In my mind, doing things with <code>stdout</code> shouldn't affect the <code>stdin</code> line buffer, but I'm admittedly not familiar with the underlying libraries or implementation.</p> <p>A minimum working example is below. Just type something and wait for the interrupting text. The prompt <code>"&gt; "</code> will be re-echoed, but the text you entered won't be. Simply comment out the second line to see it work correctly. When the thread prints, it logs the line buffer to <code>stdin.log</code>.</p> <pre><code>import time,readline,thread,sys,os sys.stdout = open(os.devnull,'wb') # comment this line! def noisy_thread(): while True: time.sleep(5) line = readline.get_line_buffer() with open('stdin.log','a') as f: f.write(time.asctime()+' | "'+line+'"\n') sys.__stdout__.write('\r'+' '*(len(line)+2)+'\r') sys.__stdout__.write('Interrupting text!\n') sys.__stdout__.write('&gt; ' + line) sys.__stdout__.flush() thread.start_new_thread(noisy_thread, ()) while True: sys.__stdout__.write('&gt; ') s = raw_input() </code></pre> <p>I've also tried <code>sys.stdout = sys.__stdout__</code> right before the <code>get_line_buffer()</code> call, but that doesn't work either. Any help or explanation is greatly appreciated.</p>
4
2016-09-19T16:42:21Z
39,844,597
<p>Its the <code>raw_input()</code> that stops working when you redirect the stdout. If you try <code>sys.stdout = sys.__stdout__</code> just before the <code>raw_input()</code> it works again. Both <code>stdin</code> and <code>stdout</code> need to be connected to the terminal in order for <code>raw_input</code> to work.</p>
1
2016-10-04T05:13:22Z
[ "python", "multithreading", "stdout", "raw-input" ]
Nested For Loop with Unequal Entities
39,578,130
<p>I would like to scrape the contents of a website with a similar structure to</p> <p><a href="https://www.wellstar.org/locations/pages/default.aspx" rel="nofollow">https://www.wellstar.org/locations/pages/default.aspx</a></p> <p>Using the provided website as a framework, I would like to extract the location's name and the heading associated with that location. I want to be able to produce the following:</p> <p>WellStar Hospitals</p> <p>WELLSTAR ATLANTA MEDICAL CENTER</p> <p>WellStar Hospitals</p> <p>WELLSTAR ATLANTA MEDICAL CENTER SOUTH</p> <p>...</p> <p>WellStar Health Parks</p> <p>ACWORTH HEALTH PARK</p> <p>...</p> <p>Thus far I have attempted a nested for loop:</p> <pre><code>for type in soup.find_all("h3",class_="WebFont SpotBodyGreen"): for name in soup.find_all("div",class_="PurpleBackgroundHeading"): print(type.text, name.text) </code></pre> <p>The above <code>for loop</code> returns duplicates due to each name being paired with each type regardless of presentation on the website. Any help whether in the form of code and/or recommended resources for dealing with this task would be greatly appreciated. </p>
0
2016-09-19T16:44:49Z
39,578,499
<p>You need a way to group the locations by name. For this, we separate each block, get the title and locations collected into a dictionary:</p> <pre><code>from pprint import pprint import requests from bs4 import BeautifulSoup url = "https://www.wellstar.org/locations/pages/default.aspx" response = requests.get(url) soup = BeautifulSoup(response.content, "html.parser") d = {} for row in soup.select(".WS_Content &gt; .WS_LeftContent &gt; table &gt; tr"): title = row.h3.get_text(strip=True) d[title] = [item.get_text(strip=True) for item in row.select(".PurpleBackgroundHeading a")] pprint(d) </code></pre> <p>Prints (pretty-printed with <code>pprint()</code>):</p> <pre><code>{'WellStar Community Hospice': ['Tranquility at Cobb Hospital', 'Tranquility at Kennesaw Mountain'], 'WellStar Health Parks': ['Acworth Health Park', 'East Cobb Health Park'], 'WellStar Hospitals': ['WellStar Atlanta Medical Center', 'WellStar Atlanta Medical Center South', 'WellStar Cobb Hospital', 'WellStar Douglas Hospital', 'WellStar Kennestone Hospital', 'WellStar North Fulton Hospital', 'WellStar Paulding Hospital', 'WellStar Spalding Regional Hospital', 'WellStar Sylvan Grove Hospital', 'WellStar West Georgia Medical Center', 'WellStar Windy Hill Hospital'], 'WellStar Urgent Care Centers': ['WellStar Urgent Care in Acworth', 'WellStar Urgent Care in Kennesaw', 'WellStar Urgent Care in Marietta - Delk ' 'Road', 'WellStar Urgent Care in Marietta - East ' 'Cobb', 'WellStar Urgent Care in Marietta - ' 'Kennestone', 'WellStar Urgent Care in Marietta - Sandy ' 'Plains Road', 'WellStar Urgent Care in Smyrna', 'WellStar Urgent Care in Woodstock']} </code></pre>
1
2016-09-19T17:07:46Z
[ "python", "web-scraping", "beautifulsoup" ]
Python How to print dictionary in one line?
39,578,141
<p>Hi I am new to Python and I am struggling regarding how to print dictionary.</p> <p>I have a dictionary as shown below.</p> <pre><code>dictionary = {a:1,b:1,c:2} </code></pre> <p>How can I print dictionary in one line as shown below?</p> <pre><code>a1b1c2 </code></pre> <p>I want to print keys and values in one line but could not figure out by myself.</p> <p>I would appreciate your advice!</p>
-1
2016-09-19T16:45:34Z
39,578,258
<p>With a dictionary, e.g. </p> <pre><code>dictionary = {'a':1,'b':1,'c':2} </code></pre> <p>You could try:</p> <pre><code>print ''.join(['{0}{1}'.format(k, v) for k,v in dictionary.iteritems()]) </code></pre> <p>Resulting in</p> <blockquote> <p>a1c2b1</p> </blockquote> <p>If order matters, try using an <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow">OrderedDict</a>, as described by <a href="http://stackoverflow.com/questions/9001509/how-can-i-sort-a-dictionary-by-key">this</a> post.</p>
1
2016-09-19T16:51:43Z
[ "python", "python-2.7", "dictionary", "printing" ]
Python How to print dictionary in one line?
39,578,141
<p>Hi I am new to Python and I am struggling regarding how to print dictionary.</p> <p>I have a dictionary as shown below.</p> <pre><code>dictionary = {a:1,b:1,c:2} </code></pre> <p>How can I print dictionary in one line as shown below?</p> <pre><code>a1b1c2 </code></pre> <p>I want to print keys and values in one line but could not figure out by myself.</p> <p>I would appreciate your advice!</p>
-1
2016-09-19T16:45:34Z
39,578,281
<p>If you want a string to contain the answer, you could do this:</p> <pre><code>&gt;&gt;&gt; dictionary = {'a':1,'b':1,'c':2} &gt;&gt;&gt; result = "".join(str(key) + str(value) for key, value in dictionary.items()) &gt;&gt;&gt; print(result) c2b1a1 </code></pre> <p>This uses the join method on an empty string. Dict's are not ordered, so the order of the output may vary.</p>
1
2016-09-19T16:53:46Z
[ "python", "python-2.7", "dictionary", "printing" ]
Django return JSON with Logged in Cookie
39,578,430
<p>I want to design a simple Django "RESTful" API without the need of using django-rest-framework.</p> <p>The endpoint is <code>/api/login</code> which accept only POST method with <code>username</code> and <code>password</code> in json. I want it to return <code>{"status" : 0}</code> for success with the session cookie to be used later at my other endpoints. Only when the user successfully logged in, the cookie will be set.</p> <p>I have imported the <code>JsonResponse</code> object from <code>django.http</code> but not very sure how to set the session for the user.</p> <pre><code>def login(request): # some code omitted, like if request.method == "POST" credential = json.loads(request.body) username = credential['username'] password = credential['password'] user = authenticate(username=username, password=password) if user: if user.is_active: auth_login(request, user) else: return JsonResponse({"status" : 1, "err" : "Your account has been disabled"}) # TODO: Now return what? </code></pre> <p>I have browsed the <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#jsonresponse-objects" rel="nofollow">document</a> but failed to find any useful tip.</p>
0
2016-09-19T17:03:20Z
39,581,113
<p>I tested it out, that I can just use <code>return JsonResponse({'status' : 0})</code> because the cookies are registered with Django because of <code>authenticate</code>.</p>
0
2016-09-19T19:59:12Z
[ "python", "json", "django", "cookies" ]
pandas date to string
39,578,466
<p>i have a datetime <code>pandas.Series</code>. One column called "dates". I want to get 'i' element in loop like string.</p> <p><code>s.apply(lambda x: x.strftime('%Y.%m.%d'))</code> or <code>astype(str).tail(1).reset_index()['date']</code> or many other solutions don't work.</p> <p>I just want a string like <code>'2016-09-16'</code> (first datetime element in series) and not what is currently returned, which is:</p> <pre><code> ss = series_of_dates.astype(str).tail(1).reset_index()['date'] "lol = %s" % ss </code></pre> <blockquote> <p><code>lol = 0 2016-09-16\nName: date, dtype: object</code></p> </blockquote> <p>I need just:</p> <blockquote> <p><code>lol = 2016-09-16</code></p> </blockquote> <p>because I need </p> <blockquote> <p><strong><code>some string</code></strong> % a , b , s ,d</p> </blockquote> <p>..... without even '/n' in a, b ,s ...</p>
1
2016-09-19T17:05:50Z
39,578,549
<p>In order to extract the value, you can try:</p> <pre><code>ss = series_of_dates.astype(str).tail(1).reset_index().loc[0, 'date'] </code></pre> <p>using <code>loc</code> will give you the contents just fine.</p>
1
2016-09-19T17:10:42Z
[ "python", "datetime", "pandas", "time-series" ]
pandas date to string
39,578,466
<p>i have a datetime <code>pandas.Series</code>. One column called "dates". I want to get 'i' element in loop like string.</p> <p><code>s.apply(lambda x: x.strftime('%Y.%m.%d'))</code> or <code>astype(str).tail(1).reset_index()['date']</code> or many other solutions don't work.</p> <p>I just want a string like <code>'2016-09-16'</code> (first datetime element in series) and not what is currently returned, which is:</p> <pre><code> ss = series_of_dates.astype(str).tail(1).reset_index()['date'] "lol = %s" % ss </code></pre> <blockquote> <p><code>lol = 0 2016-09-16\nName: date, dtype: object</code></p> </blockquote> <p>I need just:</p> <blockquote> <p><code>lol = 2016-09-16</code></p> </blockquote> <p>because I need </p> <blockquote> <p><strong><code>some string</code></strong> % a , b , s ,d</p> </blockquote> <p>..... without even '/n' in a, b ,s ...</p>
1
2016-09-19T17:05:50Z
39,578,709
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>strftime</code></a> for convert <code>datetime</code> column to <code>string</code> column:</p> <pre><code>import pandas as pd start = pd.to_datetime('2015-02-24 10:00') rng = pd.date_range(start, periods=10) df = pd.DataFrame({'dates': rng, 'a': range(10)}) print (df) a dates 0 0 2015-02-24 10:00:00 1 1 2015-02-25 10:00:00 2 2 2015-02-26 10:00:00 3 3 2015-02-27 10:00:00 4 4 2015-02-28 10:00:00 5 5 2015-03-01 10:00:00 6 6 2015-03-02 10:00:00 7 7 2015-03-03 10:00:00 8 8 2015-03-04 10:00:00 9 9 2015-03-05 10:00:00 s = df.dates print (s.dt.strftime('%Y.%m.%d')) 0 2015.02.24 1 2015.02.25 2 2015.02.26 3 2015.02.27 4 2015.02.28 5 2015.03.01 6 2015.03.02 7 2015.03.03 8 2015.03.04 9 2015.03.05 Name: dates, dtype: object </code></pre> <p>Loop with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iteritems.html" rel="nofollow"><code>Series.iteritems</code></a>:</p> <pre><code>for idx, val in s.dt.strftime('%Y.%m.%d').iteritems(): print (val) 2015.02.24 2015.02.25 2015.02.26 2015.02.27 2015.02.28 2015.03.01 2015.03.02 2015.03.03 2015.03.04 2015.03.05 </code></pre>
1
2016-09-19T17:19:39Z
[ "python", "datetime", "pandas", "time-series" ]
Using `apply` on datetime64 series in pandas
39,578,495
<p>I have a Series of <code>datetime64[ns]</code> objects. I would like to apply <code>strftime('%d-%m-%Y')</code> to all of them, for reversing the order of year,day,month. I tried using:</p> <pre><code>series.apply(time.strftime('%d-%m-%Y')) </code></pre> <p>But I get the error:</p> <blockquote> <p>TypeError: 'str' object is not callable</p> </blockquote> <p>Any idea on the right way to do this elegantly?</p>
2
2016-09-19T17:07:31Z
39,578,511
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>Series.dt.strftime</code></a>:</p> <pre><code>series.dt.strftime('%d-%m-%Y') </code></pre> <p>Or if is necessary convert <code>Series</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> first:</p> <pre><code>pd.to_datetime(series).dt.strftime('%d-%m-%Y') </code></pre>
3
2016-09-19T17:08:25Z
[ "python", "python-3.x", "pandas", "numpy", "strftime" ]
issue with create_user.py in django-cms
39,578,498
<p>I just started using django-cms and am facing issues. I used virtualenv.please help.The following is the error:</p> <pre><code>Traceback (most recent call last): File "create_user.py", line 4, in &lt;module&gt; from django.contrib.auth import get_user_model File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/contrib/auth/__init__.py", line 7, in &lt; module&gt; from django.middleware.csrf import rotate_token File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/middleware/csrf.py", line 14, in &lt;module&gt; from django.utils.cache import patch_vary_headers File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/utils/cache.py", line 26, in &lt;module&gt; from django.core.cache import caches File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/core/cache/__init__.py", line 34, in &lt;module&gt; if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/conf/__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. </code></pre> <p>Can somebody tell me which specific files to edit and what edits should i make </p>
2
2016-09-19T17:07:45Z
39,608,259
<p>Try running this command instead:</p> <pre><code>djangocms -w web </code></pre> <p>This will start the djangocms-installer wizard and run you through various settings, dependencies, and create a superuser for you to log in with. When it finishes, you should have a running instance of django-cms within <code>./web/</code>.</p> <p>You can access the new instance by going into <code>./web/</code> and running <code>runserver</code> as usual:</p> <pre><code>$ source venv/bin/activate (venv) $ python manage.py runserver </code></pre>
1
2016-09-21T05:35:00Z
[ "python", "django", "virtualenv", "django-cms" ]
issue with create_user.py in django-cms
39,578,498
<p>I just started using django-cms and am facing issues. I used virtualenv.please help.The following is the error:</p> <pre><code>Traceback (most recent call last): File "create_user.py", line 4, in &lt;module&gt; from django.contrib.auth import get_user_model File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/contrib/auth/__init__.py", line 7, in &lt; module&gt; from django.middleware.csrf import rotate_token File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/middleware/csrf.py", line 14, in &lt;module&gt; from django.utils.cache import patch_vary_headers File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/utils/cache.py", line 26, in &lt;module&gt; from django.core.cache import caches File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/core/cache/__init__.py", line 34, in &lt;module&gt; if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/home/mayankmodi/SSAD18/Source/env/local/lib/python2.7/site-packages /django/conf/__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting CACHES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. </code></pre> <p>Can somebody tell me which specific files to edit and what edits should i make </p>
2
2016-09-19T17:07:45Z
39,628,304
<p>I have same problem from a few week ago. I assume the new version(djangocms-installer==0.9.x) have problem because when I created a project using default djangocms-installer(==0.9.0) like "djangcms -p . mysite", there was no questions about DB, django version, or etc, then error...</p> <p>Try old version "pip install djangocms-installer==0.8.x"(x=12,11,10,...)</p> <p>Now, I am using "djangocms-installer==0.8.12" without any error.</p>
1
2016-09-22T00:09:17Z
[ "python", "django", "virtualenv", "django-cms" ]
Parallel random distribution
39,578,568
<p>I have two iterators in python and both should follow the same "random" distribution <strong>(both should run in parallel)</strong>. For instance:</p> <pre><code>class Iter1(object): def __iter__(self): for i in random_generator(): yield i class Iter2(object): def __iter__(self): for i in random_generator(): yield i for el1, el2 in zip(Iter1(), Iter2()): print '{} {}'.format(el1, el2) </code></pre> <p>output should be somethig like:</p> <pre><code>0.53534 0.53534 0.12312 0.12312 0.19238 0.19238 </code></pre> <p>How can I define <code>random_generator()</code> in a way that it creates the same random distributions <strong>in parallel</strong> for both iterators. </p> <p>Note:</p> <ul> <li>They should run in parallel</li> <li>I can't generate the sequence in advance (it is a streaming, so I don't know the size of the sequence)</li> </ul> <p>Thanks.</p>
0
2016-09-19T17:11:39Z
39,578,737
<p>There is no way to control the random generation number in this way. If you want to do that you should create your own random function. But as another pythonic and simpler way you can just create one object and use <code>itertools.tee</code> in order to copy your iterator object to having the same result for your random sequences:</p> <pre><code>In [28]: class Iter1(object): def __init__(self, number): self.number = number def __iter__(self): for _ in range(self.number): yield random.random() ....: In [29]: In [29]: num = Iter1(5) In [30]: from itertools import tee In [31]: num, num2 = tee(num) In [32]: list(zip(num, num2)) Out[32]: [(0.485400998727448, 0.485400998727448), (0.8801649381536764, 0.8801649381536764), (0.9684025615967844, 0.9684025615967844), (0.9980073706742334, 0.9980073706742334), (0.1963579685642387, 0.1963579685642387)] </code></pre>
0
2016-09-19T17:20:49Z
[ "python", "random", "iterator", "generator" ]
Parallel random distribution
39,578,568
<p>I have two iterators in python and both should follow the same "random" distribution <strong>(both should run in parallel)</strong>. For instance:</p> <pre><code>class Iter1(object): def __iter__(self): for i in random_generator(): yield i class Iter2(object): def __iter__(self): for i in random_generator(): yield i for el1, el2 in zip(Iter1(), Iter2()): print '{} {}'.format(el1, el2) </code></pre> <p>output should be somethig like:</p> <pre><code>0.53534 0.53534 0.12312 0.12312 0.19238 0.19238 </code></pre> <p>How can I define <code>random_generator()</code> in a way that it creates the same random distributions <strong>in parallel</strong> for both iterators. </p> <p>Note:</p> <ul> <li>They should run in parallel</li> <li>I can't generate the sequence in advance (it is a streaming, so I don't know the size of the sequence)</li> </ul> <p>Thanks.</p>
0
2016-09-19T17:11:39Z
39,579,168
<p>Specify the same seed to each call of <code>random_generator</code>:</p> <pre><code>import random def random_generator(l, seed=None): r = random.Random(seed) for i in range(l): yield r.random() class Iter1(object): def __init__(self, seed): self.seed = seed def __iter__(self): for i in random_generator(10, self.seed): yield i class Iter2(object): def __init__(self, seed): self.seed = seed def __iter__(self): for i in random_generator(10, self.seed): yield i # The seed can be any hashable object, but don't use None; that # tells random.seed() to use the current time. But make sure that # Python itself isn't using hash randomization. common_seed = object() for el1, el2 in zip(Iter1(common_seed), Iter2(common_seed)): print '{} {}'.format(el1, el2) </code></pre>
2
2016-09-19T17:46:59Z
[ "python", "random", "iterator", "generator" ]
Update Pandas dataframe value based on present value
39,578,656
<p>I have a Pandas dataframe with values which should lie between, say, <code>11-100</code>. However, sometimes I'll have values between <code>1-10</code>, and this is because the person who was entering that row used a convention that the value in question should be multiplied by 10. So what I'd like to do is run a Pandas command which will fix those particular rows by multiplying their value by <code>10</code>.</p> <p>I can reference the values in question by doing something like </p> <pre><code>my_dataframe[my_dataframe['column_name']&lt;10] </code></pre> <p>and I could set them all to a particular value, like 50, like so</p> <pre><code>my_dataframe[my_dataframe['column_name']&lt;10] = 50 </code></pre> <p>but how do I set them to a value which is 10* the value of that particular row?</p>
1
2016-09-19T17:16:47Z
39,578,688
<p>I think you can use:</p> <pre><code>my_dataframe[my_dataframe['column_name']&lt;10] *= 10 </code></pre>
3
2016-09-19T17:18:35Z
[ "python", "pandas", "indexing", "dataframe", "multiplying" ]
Python Battleship random number generator
39,578,807
<p>I'm fairly new to classes in Python. While coding a battleship game I ran into a problem with choosing random x,y coordinates for the locations of computer's ships and the computer's attack coordinates. I am confused about whether to generate random numbers as a local variable in one of the functions or as Class attribute or instance attribute. </p> <p>Initially I thought to create an instance attribute (below), but i got rand_x is not defined. I tried creating a Battleship function that generated random numbers, but it returned the same pair of coordinates every time it was called. Is the only way to do this to create a local variable for random #s? Because I will be using the random generator more than once it would be nice not to have to repeat that code.</p> <p>Thanks for your patience.</p> <p>EDIT: I've included more code with the randomness function, and replaced <code>size</code> in randomness function with <code>self.size</code>. </p> <p>For example, Battleship(4,2,0,0) might give me a <code>hitlist</code> of [[2,1],[2,1]] I would like random #s inside <code>hitlist</code>.</p> <pre><code>import random hitlist=[]; #a global variable class Battleship(object): """ Ship object container. A game where the user tries to destroy the enemy's ships User tries to guess computer's position x and y """ def __init__(self, size, numberships,position_x,position_y): self.position_x=position_x self.position_y=position_y self.numberships=numberships self.size = size def plotships(self,r): """input is integer coordinates for ships and output is an array of arrays with battleship locations CREATES THE HITLIST DONT REPEAT""" print('plotships function running') for i in range(self.numberships): hitlist.append(r) #random number from function randomness print(hitlist) return hitlist def randomness(self): rand_x=random.choice(range(self.size)) rand_y=random.choice(range(self.size)) randcoord=[rand_x,rand_y] return randcoord #Game Interface size=int(input('Gameboard size')) numberships=int(input('Waiting for Number of enemy ships')) b=Battleship(size,numberships,0,0) random=b.randomness() #create a random x y coordinate b.plotships(random) #create a hitlist </code></pre>
0
2016-09-19T17:25:38Z
39,579,079
<p>To get a random number maybe you could import the random library.</p> <p>You could use it to initialize your (X, Y) coordenates on an instance of your class.</p> <pre><code>import random Battleship(size, numberships, random.randint(0, WIDTH), random.randint(0, HEIGHT)) </code></pre> <p>I'm assuming you have the screen's widht and Height available. Hope it helps. </p>
0
2016-09-19T17:41:58Z
[ "python" ]
Python Battleship random number generator
39,578,807
<p>I'm fairly new to classes in Python. While coding a battleship game I ran into a problem with choosing random x,y coordinates for the locations of computer's ships and the computer's attack coordinates. I am confused about whether to generate random numbers as a local variable in one of the functions or as Class attribute or instance attribute. </p> <p>Initially I thought to create an instance attribute (below), but i got rand_x is not defined. I tried creating a Battleship function that generated random numbers, but it returned the same pair of coordinates every time it was called. Is the only way to do this to create a local variable for random #s? Because I will be using the random generator more than once it would be nice not to have to repeat that code.</p> <p>Thanks for your patience.</p> <p>EDIT: I've included more code with the randomness function, and replaced <code>size</code> in randomness function with <code>self.size</code>. </p> <p>For example, Battleship(4,2,0,0) might give me a <code>hitlist</code> of [[2,1],[2,1]] I would like random #s inside <code>hitlist</code>.</p> <pre><code>import random hitlist=[]; #a global variable class Battleship(object): """ Ship object container. A game where the user tries to destroy the enemy's ships User tries to guess computer's position x and y """ def __init__(self, size, numberships,position_x,position_y): self.position_x=position_x self.position_y=position_y self.numberships=numberships self.size = size def plotships(self,r): """input is integer coordinates for ships and output is an array of arrays with battleship locations CREATES THE HITLIST DONT REPEAT""" print('plotships function running') for i in range(self.numberships): hitlist.append(r) #random number from function randomness print(hitlist) return hitlist def randomness(self): rand_x=random.choice(range(self.size)) rand_y=random.choice(range(self.size)) randcoord=[rand_x,rand_y] return randcoord #Game Interface size=int(input('Gameboard size')) numberships=int(input('Waiting for Number of enemy ships')) b=Battleship(size,numberships,0,0) random=b.randomness() #create a random x y coordinate b.plotships(random) #create a hitlist </code></pre>
0
2016-09-19T17:25:38Z
39,579,293
<p>I think it's because you're calling <code>random.choice</code> with <code>size</code> and not <code>self.size</code>.</p> <p>i.e.</p> <pre><code>rand_x = random.choice(range(self.size)) </code></pre> <p>Also, where are you defining <code>self.rand</code>? Surely you're getting problems in the constructor trying to print it?</p> <p>EDIT - IN RESPONSE TO COMMENT BELOW:</p> <p>If you want <code>hitlist</code> to be populated with <code>self.numberships</code> pairs of independent random number pairs, the write the <code>plotships</code> method as:</p> <pre><code>def plotships(self): """input is integer coordinates for ships and output is an array of arrays with battleship locations CREATES THE HITLIST DONT REPEAT""" print('plotships function running') for i in range(self.numberships): hitlist.append(randomness()) #random number from function randomness print(hitlist) return hitlist </code></pre>
2
2016-09-19T17:54:26Z
[ "python" ]
how to add a row to a Datetime Multiindex Panda Dataframe
39,578,866
<blockquote> <p>How would I go about adding a row to the top of this dataframe. This is downloaded data. I cannot use a specific row index in the formula because the first Datetime indice changes all the time. I cannot also use a specific label for the inner index as it could be Datetime. Is there a way to generalize this?</p> <p>I tried this</p> </blockquote> <pre><code>df[df.index.min()[0])) - dt.timedelta(minutes=5), :] = [list to add] </code></pre> <blockquote> <p>however it only add a row at the end of the Dataframe. Sorting,</p> </blockquote> <pre><code>df.sort_index(inplace=True) </code></pre> <blockquote> <p>did not help because I guess I am dealing with 2 levels of index here; which would explain why the row sticks to the bottom of the frame. </p> </blockquote> <pre><code> A B C D E 2006-04-28 00:00:00 A 69.62 69.62 6.518 65.09 69.62 B C 2006-05-01 00:00:00 A 71.5 71.5 6.522 65.16 71.5 B C 2006-05-02 00:00:00 A 72.34 72.34 6.669 66.55 72.34 B C </code></pre> <p>The final result should look like this: <code>X</code>'s being the elements in the list/array to be added.</p> <pre><code> A B C D E NEWROW X1 X2 X3 X4 X5 2006-04-28 00:00:00 A 69.62 69.62 6.518 65.09 69.62 B C 2006-05-01 00:00:00 A 71.5 71.5 6.522 65.16 71.5 B C 2006-05-02 00:00:00 A 72.34 72.34 6.669 66.55 72.34 B C </code></pre>
1
2016-09-19T17:29:14Z
39,580,332
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sortlevel.html" rel="nofollow"><code>sortlevel</code></a> for me does <strong>not</strong> work with <code>Multiindex</code>:</p> <p>So you can use little <code>hack</code> - first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> with second level <code>Stats</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> back with parameter <code>append=True</code>:</p> <pre><code>df1 = df1.sort_index() df1.loc[((df1.index.min()[0]) - dt.timedelta(minutes=5), 'SUM'),:] = df1.loc[(slice(None), slice('price')),:].sum() df1 = df1.reset_index('Stats') df1 = df1.sort_index(axis=0).set_index('Stats', append=True) print (df1) A B C D E Date Stats 2006-04-27 23:55:00 SUM 213.46 213.46 19.709 196.80 213.46 2006-04-28 00:00:00 price 69.62 69.62 6.518 65.09 69.62 std NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN 2006-05-01 00:00:00 price 71.50 71.50 6.522 65.16 71.50 std NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN 2006-05-02 00:00:00 price 72.34 72.34 6.669 66.55 72.34 std NaN NaN NaN NaN NaN weight NaN NaN NaN NaN NaN </code></pre>
1
2016-09-19T19:04:28Z
[ "python", "pandas", "dataframe", "append", "multi-index" ]
Calculation/manipulation of numpy array
39,578,974
<p>Looking to make the this calculation as quickly as possible. I have X as n x m numpy array. I want to define Y to be the following:</p> <p><code>Y_11 = 1 / (exp(X_11-X_11) + exp(X_11-X_12) + ... exp(X_11 - X_1N) ).</code></p> <p>or for Y_00</p> <p><code>1/np.sum(np.exp(X[0,0]-X[0,:]))</code></p> <p>So basically, Y is also n x m where the i,j element is the 1 / sum_j' exp(X_ij - X_ij') </p> <p>Any tips would be great! Thanks.</p> <p><em>Sample code as requested:</em></p> <pre><code>np.random.seed(111) J,K = 110,120 X = np.random.rand(J,K) Y = np.zeros((J,K)) for j in range(J): for k in range(K): Y[j,k] = 1/np.sum(np.exp(X[j,k]-X[j,:])) # note each row will sum to 1 under this operation np.sum(Y,axis=1) </code></pre>
3
2016-09-19T17:35:25Z
39,580,554
<p>Here's a first step at reducing the double loop:</p> <pre><code>def foo2(X): Y = np.zeros_like(X) for k in range(X.shape[1]): Y[:,k]=1/np.exp(X[:,[k]]-X[:,:]).sum(axis=1) return Y </code></pre> <p>I suspect I can also remove the <code>k</code> loop, but I have to spend more time figuring out just what it is doing. That <code>X[:,[k]]-X[:,:]</code> isn't obvious (in the big picture).</p> <p>Another step:</p> <pre><code>Z = np.stack([X[:,[k]]-X for k in range(X.shape[1])],2) Y = 1/np.exp(Z).sum(axis=1) </code></pre> <p>which can be further refined (with too much trial and error) with</p> <pre><code>Z = X[:,None,:]-X[:,:,None] </code></pre>
2
2016-09-19T19:20:26Z
[ "python", "performance", "numpy", "sum", "numpy-einsum" ]
Calculation/manipulation of numpy array
39,578,974
<p>Looking to make the this calculation as quickly as possible. I have X as n x m numpy array. I want to define Y to be the following:</p> <p><code>Y_11 = 1 / (exp(X_11-X_11) + exp(X_11-X_12) + ... exp(X_11 - X_1N) ).</code></p> <p>or for Y_00</p> <p><code>1/np.sum(np.exp(X[0,0]-X[0,:]))</code></p> <p>So basically, Y is also n x m where the i,j element is the 1 / sum_j' exp(X_ij - X_ij') </p> <p>Any tips would be great! Thanks.</p> <p><em>Sample code as requested:</em></p> <pre><code>np.random.seed(111) J,K = 110,120 X = np.random.rand(J,K) Y = np.zeros((J,K)) for j in range(J): for k in range(K): Y[j,k] = 1/np.sum(np.exp(X[j,k]-X[j,:])) # note each row will sum to 1 under this operation np.sum(Y,axis=1) </code></pre>
3
2016-09-19T17:35:25Z
39,580,804
<p>Here are few fully vectorized approaches -</p> <pre><code>def vectorized_app1(X): return 1/np.exp(X[:,None] - X[...,None]).sum(1) def vectorized_app2(X): exp_vals = np.exp(X) return 1/(exp_vals[:,None]/exp_vals[...,None]).sum(1) def vectorized_app3(X): exp_vals = np.exp(X) return 1/np.einsum('ij,ik-&gt;ij',exp_vals,1/exp_vals) </code></pre> <p><strong>Tricks used and lessons learnt</strong></p> <ul> <li><p>Extend dimensions with <code>None/np.newaxis</code> to bring in broadcasting and perform everything in a vectorized manner.</p></li> <li><p><code>np.exp</code> is an expensive operation. So, using it on broadcasted huge array would be costly. So, the trick used is : <code>exp(A-B) = exp(A)/exp(B)</code>. Thus, we perform <code>np.exp(X)</code> upfront and then perform broadcasted divisions.</p></li> <li><p>Those sum-reductions could be implemented with <code>np.einsum</code>. This brings in memory-efficiency as we won't have to create huge broadcasted arrays and this effects in massive performance boost.</p></li> </ul> <p>Runtime test -</p> <pre><code>In [111]: # Setup input, X ...: np.random.seed(111) ...: J,K = 110,120 ...: X = np.random.rand(J,K) ...: In [112]: %timeit original_approach(X) 1 loop, best of 3: 322 ms per loop In [113]: %timeit vectorized_app1(X) 10 loops, best of 3: 124 ms per loop In [114]: %timeit vectorized_app2(X) 100 loops, best of 3: 14.6 ms per loop In [115]: %timeit vectorized_app3(X) 100 loops, best of 3: 3.01 ms per loop </code></pre> <p>Looks like <code>einsum</code> showed its magic again with <strong><code>100x+</code></strong> speedup!</p>
5
2016-09-19T19:37:40Z
[ "python", "performance", "numpy", "sum", "numpy-einsum" ]
ret2libc strcpy not working
39,578,987
<p>I am trying to solve a CTF challenge in wich I need to use ret2libc. The problem is that when I try to use strcpy to put some text inside a buffer for latter use, it does not seems to work. The challenge box still vulnerable to "ulimit -s unlimited" so we can fix libc addresses. Here is my current python code:</p> <pre><code>from pwn import * def r2lc_print(write_buff,read_buff): strcpy_addr=0x55607a40 pop2ret=0x55643876 return p32(strcpy_addr)+p32(pop2ret)+p32(write_buff)+p32(read_buff) buffer_size=172 execlp_addr=0x55643970 c00_str_addr=0x55575d37 a00_str_addr=0x55575d5e t00_str_addr=0x55575440 write_buff=0x55576858 print cyclic(buffer_size)+r2lc_print(write_buff,c00_str_addr)+r2lc_print(write_buff,a00_str_addr)+r2lc_print(write_buff,t00_str_addr)+"A"*4 </code></pre> <p>I got strcpy address by issuing "p strcpy" inside gdb.</p> <p>The problem is that strcpy does not seem to be complete, as neither of the instructions or calls do any data movement:</p> <pre><code> 0x55608320 &lt;strncpy&gt;: push ebx 0x55608321 &lt;strncpy+1&gt;: call 0x556b5c63 0x55608326 &lt;strncpy+6&gt;: add ebx,0x127cce 0x5560832c &lt;strncpy+12&gt;: cmp DWORD PTR [ebx+0x368c],0x0 0x55608333 &lt;strncpy+19&gt;: jne 0x5560833a &lt;strncpy+26&gt; 0x55608335 &lt;strncpy+21&gt;: call 0x555a48b0 0x5560833a &lt;strncpy+26&gt;: lea eax,[ebx-0x120e54] 0x55608340 &lt;strncpy+32&gt;: test DWORD PTR [ebx+0x36a0],0x4000000 0x5560834a &lt;strncpy+42&gt;: je 0x55608370 &lt;strncpy+80&gt; 0x5560834c &lt;strncpy+44&gt;: lea eax,[ebx-0x117f14] 0x55608352 &lt;strncpy+50&gt;: test DWORD PTR [ebx+0x36bc],0x10 0x5560835c &lt;strncpy+60&gt;: jne 0x55608370 &lt;strncpy+80&gt; 0x5560835e &lt;strncpy+62&gt;: test DWORD PTR [ebx+0x369c],0x200 0x55608368 &lt;strncpy+72&gt;: je 0x55608370 &lt;strncpy+80&gt; 0x5560836a &lt;strncpy+74&gt;: lea eax,[ebx-0x11f554] 0x55608370 &lt;strncpy+80&gt;: pop ebx 0x55608371 &lt;strncpy+81&gt;: ret </code></pre>
0
2016-09-19T17:36:12Z
39,579,993
<p>I <em>think</em> the code you're seeing at glibc's <code>strncpy</code> symbol does the runtime CPU dispatching during lazy dynamic linking. It looks like the asm in <a href="http://repo.or.cz/glibc.git/blob/1850ce5a2ea3b908b26165e7e951cd4334129f07:/sysdeps/i386/i686/multiarch/strcpy.S" rel="nofollow"><code>sysdeps/i386/i686/multiarch/strcpy.S</code></a>. This file is built multiple times (via a #include into other files), with the STRCPY macro defined to strcpy, strncpy, and maybe others.</p> <p>I think it just returns a function pointer for the version of str[n]cpy that should be used, and the dynamic linker code that called it stores that pointer into the PLT and then calls it.</p> <hr> <p>If you compile a tiny C program that calls strncpy twice, you can single-step into the second call and lazy dynamic linking will already be done.</p> <pre><code>#include &lt;string.h&gt; int main(int argc, char**argv) { strncpy(argv[0], argv[1], 5); strncpy(argv[1], argv[2], 5); } </code></pre> <p>compile with <code>gcc -m32 -Og foo.c -g</code>.</p> <p>In Ubuntu 15.10's libc-2.21.0.so, the PLT jump takes you a function outside of any symbol, according to gdb. (I put <code>set disassembly-flavor intel</code> and <code>layout reg</code> in my <code>~/.gdbinit</code> to get TUI register and asm "windows".)</p> <pre><code> &gt;|0xf7e68fa0 push ebx | |0xf7e68fa1 mov edx,DWORD PTR [esp+0x8] | |0xf7e68fa5 mov ecx,DWORD PTR [esp+0xc] | |0xf7e68fa9 mov ebx,DWORD PTR [esp+0x10] | |0xf7e68fad cmp ebx,0x8 | |0xf7e68fb0 jbe 0xf7e6ba40 | |0xf7e68fb6 cmp BYTE PTR [ecx],0x0 | |0xf7e68fb9 je 0xf7e6aef0 | |0xf7e68fbf cmp BYTE PTR [ecx+0x1],0x0 | |0xf7e68fc3 je 0xf7e6af10 | </code></pre> <p>... eventually a movaps / pcmpeqb / pmovmskb loop. This function is the real strncpy implementation, and doesn't dispatch to anything else.</p>
0
2016-09-19T18:41:03Z
[ "python", "assembly", "exploit" ]
How to use pytmx in pygame?
39,579,000
<p>There was a question similar to this but the persons question wasn't regarding the same way I'm trying to implement <code>pytmx</code>, so this is the first time I've worked with <code>tiled</code>, or <code>pytmx</code> and I'm having trouble with the docs on <code>pytmx</code>.</p> <p>I just cannot get the code to execute right. What is the position parameter in the <code>gameScreen.blit(image, position)</code>? and what is the layer parameter in reference to in this module?</p> <pre><code>import pygame import time import random import pyganim import sys import os import pytmx from pytmx import load_pygame pygame.init() display_width = 800 display_height = 800 white = (255, 255, 255) gameScreen = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('2d Game') clock = pygame.time.Clock() def game_loop(): gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True gameMap = pytmx.TiledMap('gamemap.tmx') image = gameMap.get_tile_image(0, 0, 0) gameScreen.blit(image, position) pygame.display.update() clock.tick(30) game_loop() pygame.quit() quit() </code></pre>
0
2016-09-19T17:37:11Z
39,584,184
<p>There are a lot of things wrong with this code. - did you write it or get it from somewhere else? It may be that you need to make sure you understand Pygame better before you try to do something as advanced as using a Tiled map. Also, is this the whole code, or did you leave some out?</p> <p>To address the biggest issues:</p> <p>1) You are loading your Tiled map every frame, which is a huge problem:</p> <pre><code>gameMap = pytmx.TiledMap('gamemap.tmx') </code></pre> <p>You only need to load the map data once. Do this before the game loop.</p> <p>2) The only drawing happening in your code is this:</p> <pre><code>image = gameMap.get_tile_image(0, 0, 0) gameScreen.blit(image, position) </code></pre> <p>This gets the tile at position (0, 0) on layer 0 of your map and blits it at the coordinates specified by a variable called "position" that doesn't seem to exist. So even if it worked it would only draw one tile on the screen.</p> <p>3) "what is the layer parameter in reference to"</p> <p>Have you used Tiled before? Tiled is a map editor that lets you draw in multiple layers, so that you can have tiles on top of other tiles. Layer 0 would be the first (bottom) layer of your map.</p> <p>4) If you're using PyTMX with Pygame, you need to use the load_pygame() function, which it looks like you imported, but didn't use. In fact, there are a ton of imports - what are they all there for?</p> <p>A simple working version of this code would load the map, and then blit all the tiles on the screen, like so:</p> <pre><code>import pygame import pytmx pygame.init() display_width = 800 display_height = 800 white = (255, 255, 255) gameScreen = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('2d Game') clock = pygame.time.Clock() # load map data gameMap = pytmx.load_pygame('gamemap.tmx') def game_loop(): gameExit = False while not gameExit: for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True # draw map data on screen for layer in gameMap.visible_layers: for x, y, gid, in layer: tile = gameMap.get_tile_image_by_gid(gid) gameScreen.blit(tile, (x * gameMap.tilewidth, y * gameMap.tileheight)) pygame.display.update() clock.tick(30) game_loop() pygame.quit() </code></pre> <p>Note, this is not the best way of doing it, but it is the simplest. I encourage you to look for some Pygame and PyTMX tutorials and work your way up. It can be very frustrating to try and learn too many new things at the same time. As you can tell from the PyTMX docs, it's not really targeted at the beginner level.</p>
0
2016-09-20T00:58:59Z
[ "python", "python-3.x", "pygame" ]
How do I request a zipfile, extract it, then create pandas dataframes from the csv files?
39,579,073
<p>Load in these CSV files from the Sean Lahman's Baseball Database. For this assignment, we will use the 'Salaries.csv' and 'Teams.csv' tables. Read these tables into a pandas DataFrame and show the head of each table.</p> <pre><code> #Here's the code I have so far: import requests import io import zipfile url = 'http://seanlahman.com/files/database/lahman-csv_2014-02-14.zip r = requests.get(url,auth=('user','pass')) #These were lines of code I looked up but am not sure to use: #with zipfile.ZipFile('/path/to/file', 'r') as z: #f = z.open('member.csv') #table = pd.io.parsers.read_table(f, ...) #salariesData = pd.read_csv('Salaries.csv') #teamsData = pd.read_csv('Teams.csv') </code></pre>
0
2016-09-19T17:41:45Z
39,579,321
<p>Request returns a bytes file, so first convert bytes to zip file:</p> <pre><code>mlz = zipfile.ZipFile(io.BytesIO(r.content)) </code></pre> <p>To see what's in the zipfile, type:</p> <pre><code>mlz.namelist() </code></pre> <p>Then you can extract and read the CSV corresponding to the index, x:</p> <pre><code>df1 = pd.read_csv(mlz.open(mlz.namelist()[0])) df2 = pd.read_csv(mlz.open(mlz.namelist()[1])) </code></pre> <p>In your specific case, this will likely be:</p> <pre><code>salariesData = pd.read_csv(mlz.open('Salaries.csv')) teamsData = pd.read_csv(mlz.open('Teams.csv')) </code></pre> <p>(All of this ^ assumes you're using Python 3.x)</p>
0
2016-09-19T17:56:14Z
[ "python", "csv", "pandas", "python-requests", "zipfile" ]
Django: Where should I put queries about User which is in relation with other models
39,579,145
<p>I am writing a Django app which define groups of user. A user can be part of many groups.</p> <p>I want to be able to retrieve, from a list of groups, users which are members of at least one of those groups and with no duplicate.</p> <p>So i wrote a query to accomplish that. That method will take a list of group_id and simply returns a list of users. My question is: where is the best place to put that method?</p> <p>I was thinking to create a custom manager for my Group model. But it don't seems logical as my method will return to me a list of Users.</p> <p>According to the doc: <a href="https://docs.djangoproject.com/en/1.8/topics/db/managers/" rel="nofollow">https://docs.djangoproject.com/en/1.8/topics/db/managers/</a></p> <p>Manager of a model should contains queries about that model.</p> <p>After some research, I've seen that is not advised to extends the django.auth.models.User manager (at least in my case).</p> <p>For the moment, i will just put my method in a 'service.py' file, but I was wondering if there is not a more elegant way to accomplish what i am trying to do.</p> <p>Thanks by advance for your suggestions!</p>
0
2016-09-19T17:46:02Z
39,580,629
<p>I assume there is a <code>ManyToManyField</code> relation from <code>User</code> to <code>Group</code>, like the following?</p> <pre><code>class Group(models.Model): users = models.ManyToManyField('auth.User') </code></pre> <p>I don't think there's a reason to write a method to achieve this, it's just a one-line call to <code>filter</code>:</p> <pre><code>User.objects.filter(groups__in=group_ids) </code></pre> <p>If you must make it a method, I don't think there's an "official" place to put this. The <code>User</code> manager would probably be closest, but as you say, adding a custom manager to <code>User</code> is a pain. Django apps are just python code, and aren't very prescriptive about where non-framework methods go, so put it where it makes sense for your code/team.</p> <p>Note that <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#permissions-and-authorization" rel="nofollow">Django already provides all of this functionality</a>, and even names the model <code>Group</code>, so it seems like you're reinventing the wheel writing your own.</p>
0
2016-09-19T19:25:54Z
[ "python", "django", "django-models", "django-orm", "django-managers" ]
Django: Where should I put queries about User which is in relation with other models
39,579,145
<p>I am writing a Django app which define groups of user. A user can be part of many groups.</p> <p>I want to be able to retrieve, from a list of groups, users which are members of at least one of those groups and with no duplicate.</p> <p>So i wrote a query to accomplish that. That method will take a list of group_id and simply returns a list of users. My question is: where is the best place to put that method?</p> <p>I was thinking to create a custom manager for my Group model. But it don't seems logical as my method will return to me a list of Users.</p> <p>According to the doc: <a href="https://docs.djangoproject.com/en/1.8/topics/db/managers/" rel="nofollow">https://docs.djangoproject.com/en/1.8/topics/db/managers/</a></p> <p>Manager of a model should contains queries about that model.</p> <p>After some research, I've seen that is not advised to extends the django.auth.models.User manager (at least in my case).</p> <p>For the moment, i will just put my method in a 'service.py' file, but I was wondering if there is not a more elegant way to accomplish what i am trying to do.</p> <p>Thanks by advance for your suggestions!</p>
0
2016-09-19T17:46:02Z
39,581,002
<p>In your views.py you can use the below function and call it in your view:</p> <pre><code>def get_groups_users(*groups): users = User.objects.filter(groups__name__in=list(groups)) return list(set(users)) </code></pre>
0
2016-09-19T19:51:22Z
[ "python", "django", "django-models", "django-orm", "django-managers" ]
How do I create a directory to assign values to similar items in a list.
39,579,265
<p>I need to create a dictionary where I can assign a value that classifies the same object in the list. Note that I don't have a preexisting value, I want python to assign one. Here is what I have:</p> <pre><code> In [38]: post_title_list Out[38]: [u'the rfe master list', u'the rfe master list', u'the rfe master list', ...] </code></pre> <p>the rfe master list goes on for about 700 more times until we begin the next title which is u'the co problem'. I want to assign one number for each new phrase in the list, so the rfe master list is assigned 1 until we get to the co problem which would be assigned 2 and so on.</p> <p>I have tried the following codes with no luck:</p> <pre><code> In [39]: d = dict(zip(post_title_list, range(len(post_title_list))) Out[39]: {u'the rfe master list': '491818'} In [40]: {item: str(i) for i, item in enumerate(post_title_list)} Out[40]: {u'the rfe master list': '491818'} In [41]: dict.fromkeys(post_title_list) Out[41]: {u'the rfe master list': None} </code></pre> <p>Desired output:</p> <pre><code> Out[42]: {u'the rfe master list': 1, u'the rfe master list': 1, u'the rfe master list': 1, u'the co problem' : 2, u'the co problem' : 2, u'expecting delays' : 3, u'denied help : 4, ...} </code></pre> <p>Thank you.</p>
0
2016-09-19T17:52:55Z
39,580,000
<p>As it was already pointed out in the comments to your question, you can't have multiple entries for the same key in a dictionary.</p> <p>One way to go would be a dictionary in which every title occurs only once and maps to the corresponding number:</p> <pre><code>d = {} next_id = 1 for title in post_title_list: if title not in d: d[title] = next_id next_id += 1 </code></pre> <p>Alternatively, you can create a list with a tuple <code>(title,id)</code>for every element in your list:</p> <pre><code>l = [] next_id = 0 last = None for title in post_title_list: if title != last: next_id += 1 l.append((title,next_id)) last = title </code></pre>
1
2016-09-19T18:41:23Z
[ "python", "dictionary" ]
How do I create a directory to assign values to similar items in a list.
39,579,265
<p>I need to create a dictionary where I can assign a value that classifies the same object in the list. Note that I don't have a preexisting value, I want python to assign one. Here is what I have:</p> <pre><code> In [38]: post_title_list Out[38]: [u'the rfe master list', u'the rfe master list', u'the rfe master list', ...] </code></pre> <p>the rfe master list goes on for about 700 more times until we begin the next title which is u'the co problem'. I want to assign one number for each new phrase in the list, so the rfe master list is assigned 1 until we get to the co problem which would be assigned 2 and so on.</p> <p>I have tried the following codes with no luck:</p> <pre><code> In [39]: d = dict(zip(post_title_list, range(len(post_title_list))) Out[39]: {u'the rfe master list': '491818'} In [40]: {item: str(i) for i, item in enumerate(post_title_list)} Out[40]: {u'the rfe master list': '491818'} In [41]: dict.fromkeys(post_title_list) Out[41]: {u'the rfe master list': None} </code></pre> <p>Desired output:</p> <pre><code> Out[42]: {u'the rfe master list': 1, u'the rfe master list': 1, u'the rfe master list': 1, u'the co problem' : 2, u'the co problem' : 2, u'expecting delays' : 3, u'denied help : 4, ...} </code></pre> <p>Thank you.</p>
0
2016-09-19T17:52:55Z
39,580,010
<p>As stated in the comments, dictionaries need to have unique keys. So I would suggest a list of tuples. To generate a similar form of the desired output, I suggest something like:</p> <pre><code>ctr = 1 l = [ 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'c', 'c', ] out = [] for idx, element in enumerate(l): if idx == 0: out.append((element, ctr)) else: if element != l[idx-1]: ctr = ctr + 1 out.append((element, ctr)) print(out) </code></pre> <p>giving</p> <pre><code>[('a', 1), ('a', 1), ('a', 1), ('a', 1), ('a', 1), ('a', 1), ('a', 1), ('a', 1), ('b', 2), ('b', 2), ('b', 2), ('b', 2), ('b', 2), ('b', 2), ('c', 3), ('c', 3), ('c', 3), ('c', 3), ('c', 3)] </code></pre> <hr> <p><em>Update due to comment</em></p> <p>The way lists are printed depends on which development environment you're using. However, to have something IDE-independent, this should to the job:</p> <pre><code>for t in out: print(t) </code></pre>
1
2016-09-19T18:42:09Z
[ "python", "dictionary" ]
How to read contents of a large csv file and write them to another file with an operator in Python?
39,579,292
<p>I have a csv file of data from a LiDAR sensor that looks like this, but with a bagillion more lines:</p> <pre><code>scan_0,scan_1,scan_2 timestamp_0,timestamp_1,timestamp_2 7900200,7900225,7900250 logTime_0,logTime_1,logTime_2 27:46.8,27:46.8,27:46.8 distance_0,distance_0,distance_0 132,141,139 136,141,155 139,141,155 138,143,155 138,143,142 139,143,136 138,143,136 </code></pre> <p>This is data from a planar sensor. So Scan_0 is a list or "radial" coordinates for the specific scan at a time stamp. </p> <p>My plan is to:</p> <ol> <li>Read the CSV file into a list</li> <li>Create Separate Array's for each scan (columns)</li> <li><p>Turn each element of the scan array into a xyz format like the example below.</p> <pre><code>scan_0 -----&gt; scan_0 timestamp_0-&gt; timestamp_0 7900200-----&gt; 7900200 logTime_0---&gt; logTime_0 27:46.8-----&gt; 27:46.8 distance_0--&gt; distance_0 132---------&gt; [132*cos(1),132*sin(1),7900200] 136---------&gt; [136*cos(2),136*sin(2),7900200] 139---------&gt; [139*cos(3),139*sin(3),7900200] 138---------&gt; . . 138---------&gt; . . 139---------&gt; . . 138---------&gt; [138*cos(7),139*sin(7),7900200] </code></pre></li> <li><p>Write the array of xyz coordinates to a new csv file with one coordinate per line'</p></li> <li><p>eventually use a trajectory instead of timestamp for the z coordinate from another csv file.</p></li> </ol> <p>I tell you all of this, so you have some context for my motivation. To start this little project, I've decided to simply try and read the csv file into a list and output each of the lines to another csv file... start small right?</p> <p>here is what I have so far:</p> <pre><code>import csv with open("2016_09_16_14_29_09_953.csv", 'r') as f: with open("out.csv", "a") as f1: x = csv.reader(f) my_list = list(x) thedatawriter = csv.writer(f1) for row in my_list: thedatawriter.write(row) </code></pre> <p>This creates an empty csv file. What am I doing wrong here? I feel like an ant climbing mount Everest. Any help, advice, and guidance is greatly appreciated. </p>
3
2016-09-19T17:54:23Z
39,579,464
<p>I am not sure why this isn't blowing up on you. csv.writer objects don't have a write function. Try thedatawriter.writerow(row) instead.</p>
1
2016-09-19T18:05:01Z
[ "python" ]
How to read contents of a large csv file and write them to another file with an operator in Python?
39,579,292
<p>I have a csv file of data from a LiDAR sensor that looks like this, but with a bagillion more lines:</p> <pre><code>scan_0,scan_1,scan_2 timestamp_0,timestamp_1,timestamp_2 7900200,7900225,7900250 logTime_0,logTime_1,logTime_2 27:46.8,27:46.8,27:46.8 distance_0,distance_0,distance_0 132,141,139 136,141,155 139,141,155 138,143,155 138,143,142 139,143,136 138,143,136 </code></pre> <p>This is data from a planar sensor. So Scan_0 is a list or "radial" coordinates for the specific scan at a time stamp. </p> <p>My plan is to:</p> <ol> <li>Read the CSV file into a list</li> <li>Create Separate Array's for each scan (columns)</li> <li><p>Turn each element of the scan array into a xyz format like the example below.</p> <pre><code>scan_0 -----&gt; scan_0 timestamp_0-&gt; timestamp_0 7900200-----&gt; 7900200 logTime_0---&gt; logTime_0 27:46.8-----&gt; 27:46.8 distance_0--&gt; distance_0 132---------&gt; [132*cos(1),132*sin(1),7900200] 136---------&gt; [136*cos(2),136*sin(2),7900200] 139---------&gt; [139*cos(3),139*sin(3),7900200] 138---------&gt; . . 138---------&gt; . . 139---------&gt; . . 138---------&gt; [138*cos(7),139*sin(7),7900200] </code></pre></li> <li><p>Write the array of xyz coordinates to a new csv file with one coordinate per line'</p></li> <li><p>eventually use a trajectory instead of timestamp for the z coordinate from another csv file.</p></li> </ol> <p>I tell you all of this, so you have some context for my motivation. To start this little project, I've decided to simply try and read the csv file into a list and output each of the lines to another csv file... start small right?</p> <p>here is what I have so far:</p> <pre><code>import csv with open("2016_09_16_14_29_09_953.csv", 'r') as f: with open("out.csv", "a") as f1: x = csv.reader(f) my_list = list(x) thedatawriter = csv.writer(f1) for row in my_list: thedatawriter.write(row) </code></pre> <p>This creates an empty csv file. What am I doing wrong here? I feel like an ant climbing mount Everest. Any help, advice, and guidance is greatly appreciated. </p>
3
2016-09-19T17:54:23Z
39,579,531
<p>When running your code, I get the following error: </p> <pre><code>AttributeError: '_csv.writer' object has no attribute 'write' </code></pre> <p>Are you sure you are not getting the same kind of error? Because based on <a href="https://docs.python.org/3/library/csv.html#csv.writer" rel="nofollow">the documentation of csv</a>, the method seems to be <code>writerow</code> instead of <code>write</code>.</p> <p>So, like Rob Davis already seems to have answered, <code>thedatawriter.writerow(row)</code></p>
2
2016-09-19T18:09:13Z
[ "python" ]
Maximum Recursion in LCS Recursive Function
39,579,361
<p>I'm trying to execute an LCS function that utilizes recursion to give me the number of positions the LCS is valid, along with the place of LCS depicted here:</p> <pre><code>input: LCS("smile", "tile") output: [3, "##ile", "#ile"] </code></pre> <p>Whenever I try and execute it, it tells me that there is a recursion error, as follows:</p> <pre><code>RecursionError: maximum recursion depth exceeded in comparison </code></pre> <p>What is wrong with my code? I tried to replace the areas where LCS didn't apply through recursion, but where does the function exceed its depth?</p> <pre><code>def LCS(s1, s2): if s1 == "" or s2 == "": return 0 else: if s1[0] == s2[0]: s1 = s1 + s1[0] s2 = s2 + s2[0] count = 1 + LCS(s1[1:], s2[1:]) else: s1 = s1 + '#' count = max(LCS(s1, s2[1:]), LCS(s1[1:], s2)) array = [count] + [s1] + [s2] print(array) </code></pre>
2
2016-09-19T17:58:32Z
39,579,472
<p>In your first recursive call (<code>count = 1 + LCS(s1[1:], s2[1:])</code>), since you just added an element to the end of each of <code>s1</code> and <code>s2</code>, the sizes of strings being passed are the same as in the call, so you are making no progress towards termination</p> <p>Inside of <code>max</code>, the second recursive call has the same problem: you added an element to <code>s1</code>, so the sizes of the string being passed are the same as in the call.</p>
1
2016-09-19T18:05:33Z
[ "python", "recursion", "lcs" ]
Maximum Recursion in LCS Recursive Function
39,579,361
<p>I'm trying to execute an LCS function that utilizes recursion to give me the number of positions the LCS is valid, along with the place of LCS depicted here:</p> <pre><code>input: LCS("smile", "tile") output: [3, "##ile", "#ile"] </code></pre> <p>Whenever I try and execute it, it tells me that there is a recursion error, as follows:</p> <pre><code>RecursionError: maximum recursion depth exceeded in comparison </code></pre> <p>What is wrong with my code? I tried to replace the areas where LCS didn't apply through recursion, but where does the function exceed its depth?</p> <pre><code>def LCS(s1, s2): if s1 == "" or s2 == "": return 0 else: if s1[0] == s2[0]: s1 = s1 + s1[0] s2 = s2 + s2[0] count = 1 + LCS(s1[1:], s2[1:]) else: s1 = s1 + '#' count = max(LCS(s1, s2[1:]), LCS(s1[1:], s2)) array = [count] + [s1] + [s2] print(array) </code></pre>
2
2016-09-19T17:58:32Z
39,579,543
<p>I'm not at all clear about your logic: on each iteration, you either move the first character to the end of the string, or you drop it and append a <strong>#</strong>. The <em>only</em> reduction step in this is shortening s2 in the lower branch, but you'll get caught in infinite recursion before you get there. I added a simple tracing print to the top of the routine:</p> <pre><code>def LCS(s1, s2): print("ENTER s1=", s1, "\ts2=", s2) </code></pre> <p>Here's how it gets stuck:</p> <pre><code>ENTER s1= smile s2= tile ENTER s1= smile# s2= ile ENTER s1= smile## s2= le ENTER s1= smile### s2= e ENTER s1= smile#### s2= ENTER s1= mile#### s2= e ENTER s1= mile##### s2= ENTER s1= ile##### s2= e ENTER s1= ile###### s2= ENTER s1= le###### s2= e ENTER s1= le####### s2= ENTER s1= e####### s2= e ENTER s1= #######e s2= e ENTER s1= #######e# s2= ENTER s1= ######e# s2= e ENTER s1= ######e## s2= ENTER s1= #####e## s2= e ENTER s1= #####e### s2= ENTER s1= ####e### s2= e ENTER s1= ####e#### s2= ENTER s1= ###e#### s2= e ENTER s1= ###e##### s2= ENTER s1= ##e##### s2= e ENTER s1= ##e###### s2= ENTER s1= #e###### s2= e ENTER s1= #e####### s2= ENTER s1= e####### s2= e ENTER s1= #######e s2= e </code></pre> <hr> <p>When you fail in a run, you need to reset <strong>s2</strong> to its original value. Your present code backs up with one more character on each string, leaving <strong>s2</strong> permanently bouncing between its last character and NULL.</p>
0
2016-09-19T18:09:53Z
[ "python", "recursion", "lcs" ]
Maximum Recursion in LCS Recursive Function
39,579,361
<p>I'm trying to execute an LCS function that utilizes recursion to give me the number of positions the LCS is valid, along with the place of LCS depicted here:</p> <pre><code>input: LCS("smile", "tile") output: [3, "##ile", "#ile"] </code></pre> <p>Whenever I try and execute it, it tells me that there is a recursion error, as follows:</p> <pre><code>RecursionError: maximum recursion depth exceeded in comparison </code></pre> <p>What is wrong with my code? I tried to replace the areas where LCS didn't apply through recursion, but where does the function exceed its depth?</p> <pre><code>def LCS(s1, s2): if s1 == "" or s2 == "": return 0 else: if s1[0] == s2[0]: s1 = s1 + s1[0] s2 = s2 + s2[0] count = 1 + LCS(s1[1:], s2[1:]) else: s1 = s1 + '#' count = max(LCS(s1, s2[1:]), LCS(s1[1:], s2)) array = [count] + [s1] + [s2] print(array) </code></pre>
2
2016-09-19T17:58:32Z
39,579,914
<p>As stated by others you are adding a character to your string variable, and chop one off in the next recursive call. This way there will always be recursive calls with a string that has the initial length, leading to infinite recursion.</p> <p>And with a closer look, this does not make sense:</p> <pre><code> if s1[0] == s2[0]: s1 = s1 + s1[0] </code></pre> <p>Here you add the <em>first</em> character to the <em>end</em> of the string again. This cannot be right.</p> <p>Also, the function has the ability to return only 0 (or <code>None</code>), but nothing else. This also cannot be right. Whatever the function does, it should always return a value.</p> <p>As you are interested in the count of matching characters and the <code>#</code> filled versions of both original strings, you could let your function return three values (a list) instead of one.</p> <p>The code could then be made to work like this:</p> <pre><code>def LCS(s1, s2): if s1 == "" or s2 == "": return 0, '#' * len(s1), '#' * len(s2) else: if s1[0] == s2[0]: count, r1, r2 = LCS(s1[1:], s2[1:]) return count+1, s1[0] + r1, s2[0] + r2 else: count1, r11, r12 = LCS(s1, s2[1:]) count2, r21, r22 = LCS(s1[1:], s2) if count2 &gt; count1: return count2, '#' + r21, r22 else: return count1, r11, '#' + r12 print (LCS ('smile', 'tile')) </code></pre> <p>Output:</p> <pre><code>(3, '##ile', '#ile') </code></pre> <p>See it run on <a href="https://repl.it/Dbix/2" rel="nofollow">repl.it</a>.</p>
0
2016-09-19T18:35:24Z
[ "python", "recursion", "lcs" ]
extract div tag entries that are part of a table using python scrapy
39,579,386
<p>Im trying to extract some data on a webpage using python scrapy. I don't know enough HTML/CSS to know if this is well formatted, but it doesn't appear to be. The target information I am interested in has a pattern as shown below. A Table contains a set of entries (Name, Year, Int1, Int2) that I am interested in extracting. But these are not in the standard TD tags, instead they are part of DIV tags. here's an example:</p> <pre><code>&lt;table width='100%'&gt; &lt;tr&gt; &lt;td width='50%'&gt; &lt;div style='width: 10px; float: left'&gt;&amp;nbsp;&lt;/div&gt; &lt;div style='width: 232px; float: left'&gt;Mr. Richard D. Hanson&lt;/div&gt; &lt;div style='width: 40px; float: left'&gt;1989&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;1&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;27&lt;/div&gt;&lt;/td&gt;&lt;td width='50%'&gt;&lt;div style='width: 10px; float: left'&gt;&amp;nbsp;&lt;/div&gt; &lt;div style='width: 232px; float: left'&gt;Alison G. Mills, CPA&lt;/div&gt; &lt;div style='width: 40px; float: left'&gt;1989&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;8&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;12&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width='50%'&gt;&lt;div style='width: 10px; float: left'&gt;&amp;nbsp;&lt;/div&gt; &lt;div style='width: 232px; float: left'&gt;Mr. Timothy D. Harrell&lt;/div&gt; &lt;div style='width: 40px; float: left'&gt;1989&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;28&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;28&lt;/div&gt;&lt;/td&gt;&lt;td width='50%'&gt;&lt;div style='width: 10px; float: left'&gt;&amp;nbsp;&lt;/div&gt; &lt;div style='width: 232px; float: left'&gt;Debora R. Mitchell, PhD&lt;/div&gt; &lt;div style='width: 40px; float: left'&gt;1989&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;20&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;21&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td width='50%'&gt;&lt;div style='width: 10px; float: left'&gt;&amp;nbsp;&lt;/div&gt; &lt;div style='width: 232px; float: left'&gt;Mr. Tim J. Scoggins&lt;/div&gt; &lt;div style='width: 40px; float: left'&gt;1989&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;1&lt;/div&gt; &lt;div style='width: 88px; float: left; text-align: right'&gt;9&lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Here's what I have tried so far using the Scrapy Shell</p> <p>Attempt 1:</p> <p>This works, but then I need to co-relate the entries - ie get the Year and Int1 and Int2 for each Name that is accessed below</p> <pre><code>&gt;&gt;&gt; response.xpath('//div[@style="width: 232px; float: left"]/text()').extract() [u'Mr. Richard D. Hanson', u'Alison G. Mills, CPA', u'Mr. Timothy D. Harrell', u'Debora R. Mitchell, PhD', u'Mr. Tim J. Scoggins'] </code></pre> <p>Attempt 2: In this attempt I am hoping to make one call to then iterate over each entry and store it in a dictionary. Unfortunately, Im not sure whats happening here</p> <pre><code>&gt;&gt;&gt; response.xpath('//table[@width="100%"]/tr/td[@width="50%"]/div[@style="width: 10px; float: left"]/text()').extract() [u'\xa0', u'\xa0', u'\xa0', u'\xa0', u'\xa0'] </code></pre> <p>Any ideas?</p>
2
2016-09-19T18:00:16Z
39,579,524
<p>You can get the texts of every inner <code>div</code> and then <a href="http://stackoverflow.com/q/9671224/771848">split the extracted list into chunks</a>:</p> <pre><code>In [1]: data = response.xpath("//table/tr/td/div/text()").extract() In [2]: [data[x+1:x+5] for x in xrange(0, len(data), 5)] Out[2]: [[u'Mr. Richard D. Hanson', u'1989', u'1', u'27'], [u'Alison G. Mills, CPA', u'1989', u'8', u'12'], [u'Mr. Timothy D. Harrell', u'1989', u'28', u'28'], [u'Debora R. Mitchell, PhD', u'1989', u'20', u'21'], [u'Mr. Tim J. Scoggins', u'1989', u'1', u'9']] </code></pre>
1
2016-09-19T18:08:49Z
[ "python", "xpath", "scrapy" ]
Matplotlib python animation not showing line
39,579,419
<p>The windows for plotting shows up but nothing appears and i get this ValueError: x and y must have same first dimension </p> <pre><code>import psutil import matplotlib.pyplot as plt import matplotlib.animation as animation a = [i for i in range(1000)] ram_avaliable = [] fig, ax = plt.subplots() def update(n): ram = psutil.virtual_memory() ram_avaliable.append(float(ram[1])/1073741824) print (a[n],ram_avaliable[n]) ax.plot(a[n],ram_avaliable[n]) ani = animation.FuncAnimation(fig,update,interval=100) plt.show() </code></pre>
2
2016-09-19T18:02:09Z
39,579,636
<p>Your code as posted runs without errors for me. The only change I had to make for points to show up was add a marker style to the <code>plot</code> command.</p> <p>This is because when you call <code>plot</code> you are plotting a <em>new line</em>. The reason it wasn't showing up before is because the default line style is to connect points with lines - since there is only one point per plotted line, there's nothing to connect to. Changing the marker style to one that shows points fixes this, e.g.</p> <pre><code>ax.plot(a[n],ram_avaliable[n], 'ro') </code></pre> <p>causes points to be plotted in red circles.</p>
0
2016-09-19T18:16:11Z
[ "python", "matplotlib" ]
Counting frequencies in two lists, Python
39,579,431
<p>I'm new to programming in python so please bear over with my newbie question...</p> <p>I have one initial list (list1) , which I have cleaned for duplicates and ended up with a list with only one of each value (list2): </p> <p>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],</p> <p>list2 = [13, 19, 2, 16, 6, 5, 20, 21]</p> <p>What I want is to count how many times each of the values in "list2" appears in "list1", but I can't figure out how to do that without getting it wrong. </p> <p>The output I am looking for is something similar to this: </p> <p>Number 13 is represented 1 times in list1. ........ Number 16 is represented 2 times in list1. </p>
4
2016-09-19T18:02:41Z
39,579,465
<pre><code>visited = [] for i in list2: if i not in visited: print "Number", i, "is presented", list1.count(i), "times in list1" visited.append(i) </code></pre>
6
2016-09-19T18:05:03Z
[ "python", "list", "frequency", "counting" ]
Counting frequencies in two lists, Python
39,579,431
<p>I'm new to programming in python so please bear over with my newbie question...</p> <p>I have one initial list (list1) , which I have cleaned for duplicates and ended up with a list with only one of each value (list2): </p> <p>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],</p> <p>list2 = [13, 19, 2, 16, 6, 5, 20, 21]</p> <p>What I want is to count how many times each of the values in "list2" appears in "list1", but I can't figure out how to do that without getting it wrong. </p> <p>The output I am looking for is something similar to this: </p> <p>Number 13 is represented 1 times in list1. ........ Number 16 is represented 2 times in list1. </p>
4
2016-09-19T18:02:41Z
39,579,512
<p>The easiest way is to use a counter:</p> <pre><code>from collections import Counter list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16] c = Counter(list1) print(c) </code></pre> <p>giving</p> <pre><code>Counter({2: 1, 5: 1, 6: 1, 13: 4, 16: 2, 19: 3, 20: 2, 21: 1}) </code></pre> <p>So you can access the key-value-pairs of the counter representing the items and its occurrences using the same syntax used for acessing dicts:</p> <pre><code>for k, v in c.items(): print('- Element {} has {} occurrences'.format(k, v)) </code></pre> <p>giving:</p> <pre><code>- Element 16 has 2 occurrences - Element 2 has 1 occurrences - Element 19 has 3 occurrences - Element 20 has 2 occurrences - Element 5 has 1 occurrences - Element 6 has 1 occurrences - Element 13 has 4 occurrences - Element 21 has 1 occurrences </code></pre>
7
2016-09-19T18:08:11Z
[ "python", "list", "frequency", "counting" ]
Counting frequencies in two lists, Python
39,579,431
<p>I'm new to programming in python so please bear over with my newbie question...</p> <p>I have one initial list (list1) , which I have cleaned for duplicates and ended up with a list with only one of each value (list2): </p> <p>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],</p> <p>list2 = [13, 19, 2, 16, 6, 5, 20, 21]</p> <p>What I want is to count how many times each of the values in "list2" appears in "list1", but I can't figure out how to do that without getting it wrong. </p> <p>The output I am looking for is something similar to this: </p> <p>Number 13 is represented 1 times in list1. ........ Number 16 is represented 2 times in list1. </p>
4
2016-09-19T18:02:41Z
39,579,549
<p><strong>Simplest</strong>, <strong>easiest</strong> to understand, <strong>no-magic-approach</strong> is to create an object(associative array) and just count the numbers in list1:</p> <pre><code>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16] frequency_list = {} for l in list1: if l in frequency_list: frequency_list[l] += 1 else: frequency_list[l] = 1 print(frequency_list) </code></pre> <p>prints out this:</p> <pre><code>{ 16: 2, 2: 1, 19: 3, 20: 2, 5: 1, 6: 1, 13: 4, 21: 1 } </code></pre> <p>meaning 16 is there twice, 2 is there once...</p>
1
2016-09-19T18:10:18Z
[ "python", "list", "frequency", "counting" ]
Counting frequencies in two lists, Python
39,579,431
<p>I'm new to programming in python so please bear over with my newbie question...</p> <p>I have one initial list (list1) , which I have cleaned for duplicates and ended up with a list with only one of each value (list2): </p> <p>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],</p> <p>list2 = [13, 19, 2, 16, 6, 5, 20, 21]</p> <p>What I want is to count how many times each of the values in "list2" appears in "list1", but I can't figure out how to do that without getting it wrong. </p> <p>The output I am looking for is something similar to this: </p> <p>Number 13 is represented 1 times in list1. ........ Number 16 is represented 2 times in list1. </p>
4
2016-09-19T18:02:41Z
39,579,633
<p>You can also use operator</p> <pre><code>&gt;&gt;&gt; list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16], &gt;&gt;&gt; list2 = [13, 19, 2, 16, 6, 5, 20, 21] &gt;&gt;&gt; import operator &gt;&gt;&gt; for s in list2: ... print s, 'appearing in :', operator.countOf(list1, s) </code></pre>
0
2016-09-19T18:16:03Z
[ "python", "list", "frequency", "counting" ]
Counting frequencies in two lists, Python
39,579,431
<p>I'm new to programming in python so please bear over with my newbie question...</p> <p>I have one initial list (list1) , which I have cleaned for duplicates and ended up with a list with only one of each value (list2): </p> <p>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],</p> <p>list2 = [13, 19, 2, 16, 6, 5, 20, 21]</p> <p>What I want is to count how many times each of the values in "list2" appears in "list1", but I can't figure out how to do that without getting it wrong. </p> <p>The output I am looking for is something similar to this: </p> <p>Number 13 is represented 1 times in list1. ........ Number 16 is represented 2 times in list1. </p>
4
2016-09-19T18:02:41Z
39,579,635
<p>In technical terms, <code>list</code> is a "type" of "object". Python has a number of built in types like strings (<code>str</code>), integers (<code>int</code>), and a few others that can be easily found on google. The reason this is important is because each object type has its own "methods". You can think of these methods as functions that complete common programming tasks and make your life easier. </p> <p>Counting the number of occurrences in a list is an example of a common programing task. We can accomplish it with the <code>count()</code> method. For example, to count the number of times 13 appears in list1: </p> <pre><code>count_13 = list1.count(13) </code></pre> <p>We can also use a for loop to iterate over the whole list:</p> <pre><code>for x in list2: print(list1.count(x)) #This is for python version 3 and up </code></pre> <p>or for python versions older than 3:</p> <pre><code>for x in list2: print list1.count(x) #This is for python version 3 and up </code></pre>
0
2016-09-19T18:16:07Z
[ "python", "list", "frequency", "counting" ]
Counting frequencies in two lists, Python
39,579,431
<p>I'm new to programming in python so please bear over with my newbie question...</p> <p>I have one initial list (list1) , which I have cleaned for duplicates and ended up with a list with only one of each value (list2): </p> <p>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16],</p> <p>list2 = [13, 19, 2, 16, 6, 5, 20, 21]</p> <p>What I want is to count how many times each of the values in "list2" appears in "list1", but I can't figure out how to do that without getting it wrong. </p> <p>The output I am looking for is something similar to this: </p> <p>Number 13 is represented 1 times in list1. ........ Number 16 is represented 2 times in list1. </p>
4
2016-09-19T18:02:41Z
39,581,682
<p>You don't need to remove duplicates. When you add to a dictionary, automatically, the duplicates will be considered as single values.</p> <pre><code>list1 = [13, 19, 13, 2, 16, 6, 5, 19, 20, 21, 20, 13, 19, 13, 16] counts = {s:list1.count(s) for s in list1} print counts {2: 1, 5: 1, 6: 1, 13: 4, 16: 2, 19: 3, 20: 2, 21: 1} </code></pre>
0
2016-09-19T20:35:56Z
[ "python", "list", "frequency", "counting" ]
TypeError: unsupported operand type(s) for +: 'function' and 'int'
39,579,448
<p>Why this function call is giving me the above error?</p> <pre><code>count=0 def returncall(): for i,j in enumerate(range(count,count+3),0): print i,j return j count=returncall print count() </code></pre>
-3
2016-09-19T18:03:41Z
39,579,571
<p>The problem is here:</p> <pre><code>for i,j in enumerate(range(count,count+3),0): </code></pre> <p><code>count</code> is another name for <code>returncall</code> because you have done <code>count = returncall</code>. <code>returncall</code> is a function; in fact, it's the very function that statement is in. You can't add an integer to a function (<code>count+3</code>) because that is meaningless.</p> <p>I don't really understand what you're attempting to do here, so can't really offer further advice. But that's what the error message means.</p>
4
2016-09-19T18:11:24Z
[ "python", "python-2.7" ]
visit all elements in nested lists and dicts without recursion
39,579,513
<p>I have a structure consisting of nested lists and dicts. I want to apply a function to every element. How to do it without recursion.</p> <pre><code>def visit(data, func): if isinstance(data, dict): for k, v in data.items(): data[k] = visit(v, func) return data elif isinstance(data, list): for i, v in enumerate(data): data[i] = visit(v, func) return data else: return func(data) </code></pre> <p>The recursive version works for small data, but I hit the RecursionError exception when the data is big.</p> <p>I looked for general ways to eliminate recursion, the ones I found rely on first transforming the recursive call to a tail call, my problem with this is the recursive call in my example is inside a loop.</p>
2
2016-09-19T18:08:11Z
39,579,995
<p>This approach will work. For the record, though, I agree with Sven Marnach that there is something <em>definitely fishy</em> going on with your data structures if you have nesting that is breaking the recursion limit. If as Sven conjectures,you have cycles in your data, this approach will also break. </p> <pre><code>data = [1,2, {'a':1, 'b':{'a':[1,2,3]}},3] def apply(data, f): stack = [] stack.append(data) while stack: data = stack.pop() if isinstance(data, dict): for k,v in data.items(): if isinstance(v, (dict,list)): stack.append(v) else: data[k] = f(v) if isinstance(data, list): for i,e in enumerate(data): if isinstance(e, (dict,list)): stack.append(e) else: data[i] = f(e) </code></pre> <p>In the interpreter shell:</p> <pre><code>$ python -i apply.py &gt;&gt;&gt; apply(data, lambda x: x + 1) &gt;&gt;&gt; data [2, 3, {'a': 2, 'b': {'a': [2, 3, 4]}}, 4] &gt;&gt;&gt; </code></pre>
2
2016-09-19T18:41:03Z
[ "python", "recursion", "data-structures" ]
Check for Dead Links on soundcloud using text file with Python
39,579,517
<p>Python 2.7</p> <h2>Windows 10 x64</h2> <p>I have a .txt file full of soundcloud links and was wondering how I can use this txt file as input and loop through the links checking for the error that the header displays. And then printing those that do not give the error.</p> <p>This what I have but it keeps giving me 404.</p> <pre><code># Test Dead Link # https://soundcloud.com/nightsanity-793590747/the-xx-intro # Working Link # https://soundcloud.com/madeleinepeyroux/everything-i-do-gonna-be-funky import requests filename = 'data.txt' with open(filename) as f: data = f.readlines() for row in data: r = requests.get(row) r.status_code if r.status_code == 404: print 'The Link is Dead' else: print 'The Link is Alive' </code></pre>
1
2016-09-19T18:08:29Z
39,579,845
<p>The problem is caused by carriage return / line feed at the end of your row variable.</p> <p>Use</p> <pre><code>r = requests.get(row.strip()) </code></pre> <p>to get rid of blanks and the beginning and end of your url. You may also have to handle exceptions:</p> <pre><code># Test Dead Link # https://soundcloud.com/nightsanity-793590747/the-xx-intro # Working Link # https://soundcloud.com/madeleinepeyroux/everything-i-do-gonna-be-funky import requests filename = 'data.txt' with open(filename) as f: data = f.readlines() for row in data: print row try: r = requests.get(row.strip()) print 'The Link is Alive' except: print 'The Link is Dead' print </code></pre> <p>Some more information how to handle exceptions for requests can be found <a href="http://stackoverflow.com/questions/16511337/correct-way-to-try-except-using-python-requests-module">here</a>.</p> <p>Works well with the following file text.txt:</p> <pre><code>http://www.cnn.com http://www.jkawhegcbkqjwzetrc.com http://www.google.com </code></pre>
1
2016-09-19T18:30:27Z
[ "python", "testing", "hyperlink" ]
Align ListBox in Frame wxpython
39,579,580
<p>I'm trying to figure out how to align a ListBox properly. As soon as i insert the lines of ListBox, the layout transforms into a mess.</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import wx oplist=[] with open("options.txt","r") as f: for line in f: oplist.append(line.rstrip('\n')) print(oplist) class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title = title, size=(200,300)) self.InitUI() self.Centre() self.Show() def InitUI(self): p = wx.Panel(self) vbox= wx.BoxSizer(wx.VERTICAL) self.l1 = wx.StaticText(p, label="Enter number", style=wx.ALIGN_CENTRE) vbox.Add(self.l1, -1, wx.ALIGN_CENTER_HORIZONTAL, 200) self.b1 = wx.Button(p, label="Buton 1") vbox.Add(self.b1, -1, wx.ALIGN_CENTER_HORIZONTAL,100) self.flistbox= wx.ListBox(self,choices=oplist, size=(100,100), name="Field", wx.ALIGN_CENTER_HORIZONTAL) vbox.Add(self.flistbox, -1, wx.CENTER, 10) p.SetSizer(vbox) app = wx.App() Example(None, title="BoxSizer") app.MainLoop() </code></pre> <p>Here the outputs with and without: <a href="http://i.stack.imgur.com/52j71.png" rel="nofollow"><img src="http://i.stack.imgur.com/52j71.png" alt="With ListBox"></a> <a href="http://i.stack.imgur.com/15VkA.png" rel="nofollow"><img src="http://i.stack.imgur.com/15VkA.png" alt="Without"></a></p>
2
2016-09-19T18:12:01Z
39,580,647
<p>The listbox is being parented to the frame by using self.</p> <pre><code>self.flistbox= wx.ListBox( self,choices=oplist, size=(100,100), name="Field", wx.ALIGN_CENTER_HORIZONTAL) </code></pre> <p>It should be parented to the panel by using p like the other controls.</p> <pre><code>self.flistbox= wx.ListBox( p,choices=oplist, size=(100,100), name="Field", wx.ALIGN_CENTER_HORIZONTAL) </code></pre>
1
2016-09-19T19:27:38Z
[ "python", "listbox", "wxpython", "boxsizer" ]
Imagemagick Draw text, draws past the border of the image. How to fix?
39,579,655
<p>When I use Imagemagick's draw function to write text it will write beyond the border of the image. For example if the image is 200px width and the text I need to write will take up 300px, it continues off the edge and the rest of the text isn't shown.</p> <p>I checked the manual and didnt find anything on how to set some type of constraint for it to stay within. Any ideas?</p>
1
2016-09-19T18:17:30Z
39,581,603
<p>If you have a known area which you want to put text in, you should probably use <code>caption:</code> and not specify a font size, then ImageMagick will use the largest font commensurate with that size:</p> <pre><code>convert -size 200x100 -background blue -fill white caption:"Here is some funky text." result.png </code></pre> <p>See also <a href="http://stackoverflow.com/a/39557083/2836621/">here</a>.</p>
0
2016-09-19T20:30:45Z
[ "python", "image", "imagemagick" ]
Flask background-image not showing
39,579,666
<p>My background-image works only for this template that has @app.route('/').</p> <pre><code> &lt;header class="intro-header" style="background-image: url('static/img/home.jpg')"&gt; </code></pre> <p>This works perfectly fine when:</p> <pre><code>@app.route('/') def home(): return render_template('post.html') </code></pre> <p>Everything works. I get this:</p> <pre><code>127.0.0.1 - - [19/Sep/2016 21:07:11] "GET /static/img/home.jpg HTTP/1.1" 304 </code></pre> <p>But when I use same template with:</p> <pre><code>@app.route('/post/') def post(): return render_template('post.html') </code></pre> <p>I get this:</p> <pre><code>127.0.0.1 - - [19/Sep/2016 21:15:23] "GET /post/static/img/home.jpg HTTP/1.1" 404 - </code></pre> <p>And background-image is blank.</p>
3
2016-09-19T18:18:14Z
39,579,747
<blockquote> <p>Partial URLs are interpreted relative to the source of the style sheet, not relative to the document - <a href="https://www.w3.org/TR/REC-CSS1/#url" rel="nofollow">w3 CSS</a> </p> </blockquote> <p>This means that you need to change your <code>url()</code> a bit, to include the leading <code>/</code>. </p> <pre><code>"background-image: url('/static/img/home.jpg')" </code></pre>
1
2016-09-19T18:24:25Z
[ "python", "html", "css", "flask" ]
Flask background-image not showing
39,579,666
<p>My background-image works only for this template that has @app.route('/').</p> <pre><code> &lt;header class="intro-header" style="background-image: url('static/img/home.jpg')"&gt; </code></pre> <p>This works perfectly fine when:</p> <pre><code>@app.route('/') def home(): return render_template('post.html') </code></pre> <p>Everything works. I get this:</p> <pre><code>127.0.0.1 - - [19/Sep/2016 21:07:11] "GET /static/img/home.jpg HTTP/1.1" 304 </code></pre> <p>But when I use same template with:</p> <pre><code>@app.route('/post/') def post(): return render_template('post.html') </code></pre> <p>I get this:</p> <pre><code>127.0.0.1 - - [19/Sep/2016 21:15:23] "GET /post/static/img/home.jpg HTTP/1.1" 404 - </code></pre> <p>And background-image is blank.</p>
3
2016-09-19T18:18:14Z
39,579,810
<p><a href="http://flask.pocoo.org/docs/0.11/quickstart/#static-files" rel="nofollow">This is a simple problem can solved by Flask documentation</a></p> <p>Anyway, you should use something like this in your template:</p> <pre><code>background-image: url({{ url_for('static', filename='img/home.jpg') }}) </code></pre> <p>but if you don't want to use Flask methods use :</p> <pre><code>url('/static/img/home.jpg') </code></pre> <p>or use another web server instead of flask default web server for your files like Apache and access via <code>http://yoursite/static/img/home.jpg</code></p>
4
2016-09-19T18:28:33Z
[ "python", "html", "css", "flask" ]
Execute python script with output from php
39,579,673
<p>Is there any special permission or setting in order to execute a python script that create a new file or image? This is my code:</p> <pre><code>&lt;? function py(){ exec( 'python my_script.py'); echo "ok"; } py(); ?&gt; </code></pre> <p>And this is my python script (an example):</p> <pre><code>#!/usr/bin/python import sys f = open('out.txt', 'w') print &gt;&gt; f, 'thats all' f.close() </code></pre> <p>Running php i get "ok" message but no file is created. What am i doing wrong?</p>
3
2016-09-19T18:18:49Z
39,581,371
<p>You need to call <code>shell_exec()</code> not <code>exec()</code> if you want to be able to capture the output:</p> <p><a href="http://php.net/manual/en/ref.exec.php" rel="nofollow">Refernce: PHP Manual</a></p>
0
2016-09-19T20:16:04Z
[ "php", "python" ]
Execute python script with output from php
39,579,673
<p>Is there any special permission or setting in order to execute a python script that create a new file or image? This is my code:</p> <pre><code>&lt;? function py(){ exec( 'python my_script.py'); echo "ok"; } py(); ?&gt; </code></pre> <p>And this is my python script (an example):</p> <pre><code>#!/usr/bin/python import sys f = open('out.txt', 'w') print &gt;&gt; f, 'thats all' f.close() </code></pre> <p>Running php i get "ok" message but no file is created. What am i doing wrong?</p>
3
2016-09-19T18:18:49Z
39,588,384
<p>Setting the right permissions to file and folders did the trick.</p> <p><a href="http://i.stack.imgur.com/fuXCb.png" rel="nofollow"><img src="http://i.stack.imgur.com/fuXCb.png" alt="enter image description here"></a></p> <p>On Mac OS: Alt + Click on "+", then search for _www and add World Wide Web Server to users giving read and write permission. Same for the root folder.</p>
1
2016-09-20T07:42:35Z
[ "php", "python" ]
Python Script Error in Windows 7
39,579,713
<p>I am trying to run this following script in here and getting this NameError. I have added path variable in Windows 7. </p> <pre><code>C:\Users\myname&gt;python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; script.py Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'script' is not defined </code></pre> <p>This is the script I am trying to run : </p> <pre><code>#!/usr/bin/python import sys, string, time from socket import * host = "192.168.0.98" port = 80 print "Open TCP connections to: %s, port %s" % (host, port) while (1): s = socket(AF_INET,SOCK_STREAM) s.connect((host, port)) s.send("abc") ### test: donot close. s.close() time.sleep(0.1) print ".", </code></pre> <p>Thank you all. </p>
1
2016-09-19T18:21:38Z
39,579,741
<p>You need to do <code>python script.py</code> instead, from the command prompt <em>not</em> from the Python interpreter. </p> <p>However, if you are in the Python interactive interpretor in the same directory as your script, as <strong>@Tuan333</strong> points out, you can do:</p> <pre><code>&gt;&gt;&gt; import script </code></pre> <p>or </p> <pre><code>&gt;&gt;&gt; from script import something </code></pre> <p>to get access to functions and classes defined in the script (note that it is <code>script</code> in this case, not <code>script.py</code> because you are treating it as a module). However, as <strong>@ŁukaszRogalski</strong> points out, this is not equivalent to running the script from the command prompt as described above.</p>
4
2016-09-19T18:24:19Z
[ "python", "python-3.x" ]
Python Script Error in Windows 7
39,579,713
<p>I am trying to run this following script in here and getting this NameError. I have added path variable in Windows 7. </p> <pre><code>C:\Users\myname&gt;python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; script.py Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'script' is not defined </code></pre> <p>This is the script I am trying to run : </p> <pre><code>#!/usr/bin/python import sys, string, time from socket import * host = "192.168.0.98" port = 80 print "Open TCP connections to: %s, port %s" % (host, port) while (1): s = socket(AF_INET,SOCK_STREAM) s.connect((host, port)) s.send("abc") ### test: donot close. s.close() time.sleep(0.1) print ".", </code></pre> <p>Thank you all. </p>
1
2016-09-19T18:21:38Z
39,579,744
<p>You need to call the script all on one line</p> <pre><code>C:\Users\myname&gt;python C:\path\to\script.py </code></pre>
1
2016-09-19T18:24:23Z
[ "python", "python-3.x" ]
Python Script Error in Windows 7
39,579,713
<p>I am trying to run this following script in here and getting this NameError. I have added path variable in Windows 7. </p> <pre><code>C:\Users\myname&gt;python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; script.py Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'script' is not defined </code></pre> <p>This is the script I am trying to run : </p> <pre><code>#!/usr/bin/python import sys, string, time from socket import * host = "192.168.0.98" port = 80 print "Open TCP connections to: %s, port %s" % (host, port) while (1): s = socket(AF_INET,SOCK_STREAM) s.connect((host, port)) s.send("abc") ### test: donot close. s.close() time.sleep(0.1) print ".", </code></pre> <p>Thank you all. </p>
1
2016-09-19T18:21:38Z
39,579,765
<p>you have to run your script by using this command in command prompt <br /> <em>python [Address of your script]</em></p>
1
2016-09-19T18:25:16Z
[ "python", "python-3.x" ]
Obtain device path from pyudev with python
39,579,727
<p>Using pydev with <code>python-2.7</code>, I wish obtain the device path of connected devices. </p> <p>Now I use this code:</p> <pre><code>from pyudev.glib import GUDevMonitorObserver as MonitorObserver def device_event(observer, action, device): print 'event {0} on device {1}'.format(action, device) </code></pre> <p>but <code>device</code> return a string like this:</p> <blockquote> <p>(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2')</p> </blockquote> <p>How can I obtain a path like <code>/dev/ttyUSB1</code> ?</p>
1
2016-09-19T18:22:53Z
39,885,881
<p><code>Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2')</code> is a <em>USB device</em> (i.e. <code>device.device_type == 'usb_device'</code>). At the time of its enumeration the <code>/dev/tty*</code> file does not exist yet as it gets assigned to its <em>child</em> <em>USB interface</em> later during its own enumeration. So you need to wait for a separate <em>device added</em> event for the <code>Device(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2:1.0')</code> which would have <code>device.device_type == 'usb_interface'</code>.</p> <p>Then you could just do <code>print [os.path.join('/dev', f) for f in os.listdir(device.sys_path) if f.startswith('tty')]</code> in its <code>device_added()</code>:</p> <pre><code>import os import glib import pyudev import pyudev.glib context = pyudev.Context() monitor = pyudev.Monitor.from_netlink(context) monitor.filter_by(subsystem='usb') observer = pyudev.glib.GUDevMonitorObserver(monitor) def device_added(observer, device): if device.device_type == "usb_interface": print device.sys_path, [os.path.join('/dev', f) for f in os.listdir(device.sys_path) if f.startswith('tty')] observer.connect('device-added', device_added) monitor.start() mainloop = glib.MainLoop() mainloop.run() </code></pre>
1
2016-10-06T00:57:10Z
[ "python", "usb", "glib", "pyudev" ]
Obtain device path from pyudev with python
39,579,727
<p>Using pydev with <code>python-2.7</code>, I wish obtain the device path of connected devices. </p> <p>Now I use this code:</p> <pre><code>from pyudev.glib import GUDevMonitorObserver as MonitorObserver def device_event(observer, action, device): print 'event {0} on device {1}'.format(action, device) </code></pre> <p>but <code>device</code> return a string like this:</p> <blockquote> <p>(u'/sys/devices/pci0000:00/pci0000:00:01.0/0000.000/usb1/1-2')</p> </blockquote> <p>How can I obtain a path like <code>/dev/ttyUSB1</code> ?</p>
1
2016-09-19T18:22:53Z
39,897,510
<p>I find this solution:</p> <pre><code>def device_event (observer, action, device): if action == "add": last_dev = os.popen('ls -ltr /dev/ttyUSB* | tail -n 1').read() print "Last device: " + last_dev </code></pre> <p>I know... is horrible. </p>
0
2016-10-06T13:34:31Z
[ "python", "usb", "glib", "pyudev" ]
Checking if string contains unicode using standard Python
39,579,745
<p>I have some strings of roughly 100 characters and I need to detect if each string contains an unicode character. The final purpose is to check if some particular emojis are present, but initially I just want a filter that catches all emojis (as well as potentially other special characters). This method should be fast.</p> <p>I've seen <a href="http://stackoverflow.com/questions/1832893/python-regex-matching-unicode-properties">Python regex matching Unicode properties</a>, but I cannot use any custom packages. I'm using Python 2.7. Thanks!</p>
0
2016-09-19T18:24:24Z
39,579,944
<p>There is no point is testing 'if a string contains Unicode characters', because <strong>all</strong> characters in a string are Unicode characters. The Unicode standard encompasses all codepoints that Python supports, including the ASCII range (Unicode codepoints U+0000 through to U+007F).</p> <p>If you want to test for Emoji code, test for specific ranges, as outlined by the <a href="http://unicode.org/Public/emoji/latest/emoji-data.txt" rel="nofollow">Unicode Emoji class specification</a>:</p> <pre><code>re.compile( u'[\u231A-\u231B\u2328\u23CF\23E9-\u23F3...\U0001F9C0]', flags=re.UNICODE) </code></pre> <p>where you'll have to pick and choose what codepoints <em>you</em> consider to be Emoji. I personally would not include <a href="https://codepoints.net/U+0023" rel="nofollow">U+0023 NUMBER SIGN</a> in that category for example, but apparently the Unicode standard <em>does</em>.</p> <p>Note: To be explicit, the above expression is not complete. There are 209 separate entries in the Emoji category and I didn't feel like writing them <em>all</em> out.</p> <p>Another note: the above uses a <code>\Uhhhhhhhh</code> wide Unicode escape sequence; its use is only supported in a regex pattern in Python 3.3 and up, or in a <a href="http://stackoverflow.com/questions/1446347/how-to-find-out-if-python-is-compiled-with-ucs-2-or-ucs-4"><em>wide</em> (UCS-4) build</a> for earlier versions of Python. For a narrow Python build, you'll have to <a href="https://stackoverflow.com/questions/26568722/remove-unicode-emoji-using-re-in-python">match on surrogate pairs</a> for codepoints over U+FFFF.</p>
1
2016-09-19T18:37:34Z
[ "python", "regex", "unicode" ]
Can't get program to print "not in sentence" when word not in sentence
39,579,770
<p>I have a program that asks for input of a sentence, then asks for a word, and tells you the position of that word:</p> <pre><code>sentence = input("enter sentence: ").lower() askedword = input("enter word to locate position: ").lower() words = sentence.split(" ") for i, word in enumerate(words): if askedword == word : print(i+1) #elif keyword != words : #print ("this not") </code></pre> <p>However I cannot get the program to work correctly when I edit it to say that if the input word is not in the sentence, then print "this isn't in the sentence"</p>
1
2016-09-19T18:25:35Z
39,579,838
<p>Lists are sequences, as such you can use <a href="https://docs.python.org/3.5/library/stdtypes.html#common-sequence-operations" rel="nofollow">the <code>in</code> operation</a> on them to test for membership in the <code>words</code> list. If inside, find the position inside the sentence with <code>words.index</code>:</p> <pre><code>sentence = input("enter sentence: ").lower() askedword = input("enter word to locate position: ").lower() words = sentence.split(" ") if askedword in words: print('Position of word: ', words.index(askedword)) else: print("Word is not in the given sentence.") </code></pre> <p>With sample input:</p> <pre><code>enter sentence: hello world enter word to locate position: world Position of word: 1 </code></pre> <p>and, a false case:</p> <pre><code>enter sentence: hello world enter word to locate position: worldz Word is not in the given sentence. </code></pre> <p>If you're looking to check against multiple matches then a list-comprehension with <code>enumerate</code> is the way to go:</p> <pre><code>r = [i for i, j in enumerate(words, start=1) if j == askedword] </code></pre> <p>Then check on whether the list is empty or not and print accordingly:</p> <pre><code>if r: print("Positions of word:", *r) else: print("Word is not in the given sentence.") </code></pre>
5
2016-09-19T18:30:05Z
[ "python", "python-3.x", "words", "enumerate", "sentence" ]
Can't get program to print "not in sentence" when word not in sentence
39,579,770
<p>I have a program that asks for input of a sentence, then asks for a word, and tells you the position of that word:</p> <pre><code>sentence = input("enter sentence: ").lower() askedword = input("enter word to locate position: ").lower() words = sentence.split(" ") for i, word in enumerate(words): if askedword == word : print(i+1) #elif keyword != words : #print ("this not") </code></pre> <p>However I cannot get the program to work correctly when I edit it to say that if the input word is not in the sentence, then print "this isn't in the sentence"</p>
1
2016-09-19T18:25:35Z
39,580,062
<p>Jim's answer—combining a test for <code>askedword in words</code> with a call to <code>words.index(askedword)</code>—is the best and most Pythonic approach in my opinion.</p> <p>Another variation on the same approach is to use <code>try</code>-<code>except</code>:</p> <pre><code>try: print(words.index(askedword) + 1) except ValueError: print("word not in sentence") </code></pre> <p>However, I just thought I'd point out that the structure of the OP code looks like you might have been attempting to adopt the following pattern, which also works:</p> <pre><code>for i, word in enumerate(words): if askedword == word : print(i+1) break else: # triggered if the loop runs out without breaking print ("word not in sentence") </code></pre> <p>In an unusual twist unavailable in most other programming languages, this <code>else</code> binds to the <code>for</code> loop, not to the <code>if</code> statement (that's right, get your editing hands off my indents). <a href="https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">See the python.org documentation here.</a></p>
3
2016-09-19T18:46:05Z
[ "python", "python-3.x", "words", "enumerate", "sentence" ]
Create wheel without building dependencies
39,579,804
<p>I have a sample project:</p> <pre><code>test/ - __init__.py - module.py - setup.py </code></pre> <p>setup.py is just</p> <pre><code>from setuptools import setup setup(name='test', install_requires=['numpy']) </code></pre> <p>Then when I call <code>pip wheel .</code>, it automatically makes a wheel for numpy. Can I make it not do that? It's my understanding that when you install a wheel, it will automatically go download and install any missing dependencies. Is the numpy wheel needed for making my test wheel?</p>
2
2016-09-19T18:28:19Z
39,579,922
<p>That's just the way that pip rolls, but if you wheely want to omit the numpy build then you can turn around and give this command a spin:</p> <pre><code>pip wheel --no-deps . </code></pre> <p><em>Note:</em> if the correct numpy wheel was already existing, it would be skipped anyway. No need to reinvent the thing...</p>
1
2016-09-19T18:36:06Z
[ "python", "setup.py", "python-wheel" ]
Combine multiple time-series rows into one row with Pandas
39,579,875
<p>I am using a recurrent neural network to consume time-series events (click stream). My data needs to be formatted such that a each row contains all the events for an id. My data is one-hot encoded, and I have already grouped it by the id. Also I limit the total number of events per id (ex. 2), so final width will always be known (#one-hot cols x #events). I need to maintain the order of the events, because they are ordered by time. </p> <p>Current data state: </p> <pre><code> id page.A page.B page.C 0 001 0 1 0 1 001 1 0 0 2 002 0 0 1 3 002 1 0 0 </code></pre> <p>Required data state: </p> <pre><code> id page.A1 page.B1 page.C1 page.A2 page.B2 page.C2 0 001 0 1 0 1 0 0 1 002 0 0 1 1 0 1 </code></pre> <p>This looks like a <code>pivot</code> problem to me, but my resulting dataframes are not in the format I need. Any suggestions on how I should approach this? </p>
3
2016-09-19T18:32:54Z
39,580,051
<p>The idea here is to <code>reset_index</code> within each group of <code>'id'</code> to get a count which row of that particular <code>'id'</code> we are at. Then follow that up with <code>unstack</code> and <code>sort_index</code> to get columns where they are supposed to be.</p> <p>Finally, flatten the multiindex.</p> <pre><code>df1 = df.set_index('id').groupby(level=0) \ .apply(lambda df: df.reset_index(drop=True)) \ .unstack().sort_index(axis=1, level=1) # Thx @jezrael for sort reminder df1.columns = ['{}{}'.format(x[0], int(x[1]) + 1) for x in df1.columns] df1 </code></pre> <p><a href="http://i.stack.imgur.com/yzHdw.png" rel="nofollow"><img src="http://i.stack.imgur.com/yzHdw.png" alt="enter image description here"></a></p>
3
2016-09-19T18:45:25Z
[ "python", "pandas", "numpy" ]
Combine multiple time-series rows into one row with Pandas
39,579,875
<p>I am using a recurrent neural network to consume time-series events (click stream). My data needs to be formatted such that a each row contains all the events for an id. My data is one-hot encoded, and I have already grouped it by the id. Also I limit the total number of events per id (ex. 2), so final width will always be known (#one-hot cols x #events). I need to maintain the order of the events, because they are ordered by time. </p> <p>Current data state: </p> <pre><code> id page.A page.B page.C 0 001 0 1 0 1 001 1 0 0 2 002 0 0 1 3 002 1 0 0 </code></pre> <p>Required data state: </p> <pre><code> id page.A1 page.B1 page.C1 page.A2 page.B2 page.C2 0 001 0 1 0 1 0 0 1 002 0 0 1 1 0 1 </code></pre> <p>This looks like a <code>pivot</code> problem to me, but my resulting dataframes are not in the format I need. Any suggestions on how I should approach this? </p>
3
2016-09-19T18:32:54Z
39,580,054
<p>You can first create new column with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> for new column name, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a>. Then you need sort columns in level <code>1</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a>, remove <code>MultiIndex</code> from columns by <code>list comprehension</code> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a>:</p> <pre><code>df['g'] = (df.groupby('id').cumcount() + 1).astype(str) df1 = df.set_index(['id','g']).unstack() df1.sort_index(axis=1,level=1, inplace=True) df1.columns = [''.join(col) for col in df1.columns] df1.reset_index(inplace=True) print (df1) id page.A1 page.B1 page.C1 page.A2 page.B2 page.C2 0 1 0 1 0 1 0 0 1 2 0 0 1 1 0 0 </code></pre>
2
2016-09-19T18:45:33Z
[ "python", "pandas", "numpy" ]
wxPython - "Uknown accel modifier: num/numpad" on Ubuntu
39,579,954
<p>I am trying to hookup some keybindings for a program I am developing on Ubuntu. The keybindings themselves are working, however the wxPython menu cannot seem to map the Numpad keys to the accelerator table so that the hotkey combination appears next to the menu item.</p> <p>I have tried the few logical variations of the word Numpad that I can think of, including:</p> <pre><code>menu_item = wx.MenuItem(self._menu, wx.ID_ANY, "&amp;Function 1\tNum+") menu_item = wx.MenuItem(self._menu, wx.ID_ANY, "&amp;Function 1\tNumpad+") </code></pre> <p>I have also tried with spaces in between Num/Numpad and the specific key. Note that I have tested on Windows and it seems to recognize them, or it simply doesn't care and adds them anyways.</p> <p>So does anyone have any idea what the correct string is so that wxPython can recognize the accel modifier?</p>
1
2016-09-19T18:38:43Z
39,857,678
<p>Just in case anyone comes across this and was wondering, a list of all the different label accelerators can be found at the bottom of the following page:</p> <p><a href="http://docs.wxwidgets.org/trunk/classwx_menu_item.html" rel="nofollow">http://docs.wxwidgets.org/trunk/classwx_menu_item.html</a></p>
0
2016-10-04T16:44:01Z
[ "python", "ubuntu", "wxpython" ]
MariaDB SQL syntax near error paranthesis ')' for python
39,579,996
<p>I am trying to insert some data into my MariaDB using python script. when I do the following in console it works perfectly.</p> <pre><code>INSERT INTO `Failure` (`faillure_id`, `testrun_id`, `failed_at`, `log_path`, `node`) VALUES (2, 1, 'STEP8:RUN:RC=1', '/var/fail_logs','NodeA') </code></pre> <p>shows me a query ok. and I can see the table being populated. no problem there.</p> <p>However when I do the same SQL query using python I get some error. Here's my code</p> <pre><code>conn = MySQLdb.connect("localhost","user","","DB") cursor = conn.cursor() cursor.execute("""INSERT INTO `Failure` (`testrun_id`, `failed_at`, `log_path`, `node`) VALUES (%s, %s, %s, %s)""",(testrun_id, failed_at, log_path, node)) conn.commit() </code></pre> <p>this yields the following error</p> <blockquote> <p>check the manual that corresponds to your MariaDB server version for the right syntax to use near '),</p> </blockquote> <p>Can someone please help me understand where the error is coming from. Thanks in advance.</p>
2
2016-09-19T18:41:06Z
39,581,444
<p>As a work-around I'm building the query string like this </p> <pre><code>sql_query = "INSERT INTO `Failure` (`testrun_id`, `failed_at`, `log_path`, `node`) VALUES " + "( '" + str(testrun_id) + "', '" + str(failed_at) + "', '"+ log_path + "', '" + node + "')" cursor.execute(sql_query) </code></pre> <p>not very efficient but does the job for now.</p>
0
2016-09-19T20:19:53Z
[ "python", "mysql", "mariadb" ]
Writing a list of lists to a seperate text file, one file per a list with in that list
39,580,015
<p>so I am trying to write a list of lists to seperate files. Each list contains 100 string objects or less. The goal is keep a text file less than 100 lines no more than that.</p> <p>To do that, i split a list but now i am having an issue writing them to a file. So essentialy write a list within a list to its own separate file. There are total of 275 strings objects in total</p> <pre><code>size=100 list_ofList_flows=[parameter_list[i:i+size] for i in range(0,len(parameter_list), size)] #above list_ofList_flows contains [100][100][75] in terms of length fileNumbers = int(math.ceil((len(parameter_list) / 100))) #fileNumbers is 3, because we have 3 sets of lists[100, 100, 75] i = 0 while i &lt; fileNumbers: for flowGroup in list_ofList_flows: f = open("workFlow_sheet" + str(i) + ".txt", "w") for flo in flowGroup: f.write(flo + '\n') i = i + 1 </code></pre>
0
2016-09-19T18:42:29Z
39,580,289
<p>Something like this would work. I had to use <code>random</code> to generate some data, into a list that was 275 elements long. </p> <pre><code>import random def chunks(l, n): n = max(1, n) return [l[i:i + n] for i in range(0, len(l), n)] data = [random.randint(0, 10) for x in range(275)] chunked_data = chunks(data, 100) for file_num, sublist in enumerate(chunked_data): with open("workFlow_sheet{}.txt".format(file_num), 'w') as outfile: for item in sublist: outfile.write(str(item) + '\n') </code></pre> <p>Essentially, sub-divide your data into nested lists of maximum length of 100, and then write the contents of each nested list to a unique file.</p> <p><strong>EDIT</strong></p> <p>I couldn't actually reproduce your problem in terms of each file containing the same data. However, you incremented <code>i</code> in the wrong scope (it needs an extra level of indentation, I think you overwrote each file multiple times in your code) and you did not <code>close()</code> the files on each iteration. The use of <code>with</code> (the Python <a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow">context manager</a>) just means that it automatically closes the file once the operations are complete. I <em>think</em> this is a working tweak of your original code... albeit with a random list generated.</p> <pre><code>import random import math parameter_list = [random.randint(0, 10) for x in range(275)] size=100 list_ofList_flows=[parameter_list[i:i+size] for i in range(0,len(parameter_list), size)] #above list_ofList_flows contains [100][100][75] in terms of length fileNumbers = int(math.ceil((len(parameter_list) / 100))) #fileNumbers is 3, because we have 3 sets of lists[100, 100, 75] i = 0 while i &lt; fileNumbers: for flowGroup in list_ofList_flows: f = open("workFlow_sheet" + str(i) + ".txt", "w") for flo in flowGroup: f.write(str(flo) + '\n') f.close() i = i + 1 </code></pre>
1
2016-09-19T19:01:04Z
[ "python" ]
Remove the first N items that match a condition in a Python list
39,580,063
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p> <p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?</p> <pre><code>n = 3 def condition(x): return x &lt; 5 data = [1, 10, 2, 9, 3, 8, 4, 7] out = do_remove(data, n, condition) print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains) </code></pre>
58
2016-09-19T18:46:05Z
39,580,319
<p>Write a generator that takes the iterable, a condition, and an amount to drop. Iterate over the data and yield items that don't meet the condition. If the condition is met, increment a counter and don't yield the value. Always yield items once the counter reaches the amount you want to drop.</p> <pre><code>def iter_drop_n(data, condition, drop): dropped = 0 for item in data: if dropped &gt;= drop: yield item continue if condition(item): dropped += 1 continue yield item data = [1, 10, 2, 9, 3, 8, 4, 7] out = list(iter_drop_n(data, lambda x: x &lt; 5, 3)) </code></pre> <p>This does not require an extra copy of the list, only iterates over the list once, and only calls the condition once for each item. Unless you actually want to see the whole list, leave off the <code>list</code> call on the result and iterate over the returned generator directly.</p>
31
2016-09-19T19:03:49Z
[ "python", "list", "list-comprehension" ]
Remove the first N items that match a condition in a Python list
39,580,063
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p> <p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?</p> <pre><code>n = 3 def condition(x): return x &lt; 5 data = [1, 10, 2, 9, 3, 8, 4, 7] out = do_remove(data, n, condition) print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains) </code></pre>
58
2016-09-19T18:46:05Z
39,580,552
<p>If mutation is required:</p> <pre><code>def do_remove(ls, N, predicate): i, delete_count, l = 0, 0, len(ls) while i &lt; l and delete_count &lt; N: if predicate(ls[i]): ls.pop(i) # remove item at i delete_count, l = delete_count + 1, l - 1 else: i += 1 return ls # for convenience assert(do_remove(l, N, matchCondition) == [10, 9, 8, 4, 7]) </code></pre>
4
2016-09-19T19:20:12Z
[ "python", "list", "list-comprehension" ]
Remove the first N items that match a condition in a Python list
39,580,063
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p> <p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?</p> <pre><code>n = 3 def condition(x): return x &lt; 5 data = [1, 10, 2, 9, 3, 8, 4, 7] out = do_remove(data, n, condition) print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains) </code></pre>
58
2016-09-19T18:46:05Z
39,580,621
<p>One way using <a href="https://docs.python.org/3/library/itertools.html#itertools.filterfalse"><code>itertools.filterfalse</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.count"><code>itertools.count</code></a>:</p> <pre><code>from itertools import count, filterfalse data = [1, 10, 2, 9, 3, 8, 4, 7] output = filterfalse(lambda L, c=count(): L &lt; 5 and next(c) &lt; 3, data) </code></pre> <p>Then <code>list(output)</code>, gives you:</p> <pre><code>[10, 9, 8, 4, 7] </code></pre>
59
2016-09-19T19:25:17Z
[ "python", "list", "list-comprehension" ]
Remove the first N items that match a condition in a Python list
39,580,063
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p> <p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?</p> <pre><code>n = 3 def condition(x): return x &lt; 5 data = [1, 10, 2, 9, 3, 8, 4, 7] out = do_remove(data, n, condition) print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains) </code></pre>
58
2016-09-19T18:46:05Z
39,580,831
<p>The accepted answer was a little too magical for my liking. Here's one where the flow is hopefully a bit clearer to follow:</p> <pre><code>def matchCondition(x): return x &lt; 5 def my_gen(L, drop_condition, max_drops=3): count = 0 iterator = iter(L) for element in iterator: if drop_condition(element): count += 1 if count &gt;= max_drops: break else: yield element yield from iterator example = [1, 10, 2, 9, 3, 8, 4, 7] print(list(my_gen(example, drop_condition=matchCondition))) </code></pre> <p>It's similar to logic in <a href="http://stackoverflow.com/a/39580319/674039">davidism</a> answer, but instead of checking the drop count is exceeded on every step, we just short-circuit the rest of the loop.</p> <p><em>Note:</em> If you don't have <a href="https://docs.python.org/3/whatsnew/3.3.html"><code>yield from</code></a> available, just replace it with another for loop over the remaining items in <code>iterator</code>. </p>
24
2016-09-19T19:39:12Z
[ "python", "list", "list-comprehension" ]
Remove the first N items that match a condition in a Python list
39,580,063
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p> <p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?</p> <pre><code>n = 3 def condition(x): return x &lt; 5 data = [1, 10, 2, 9, 3, 8, 4, 7] out = do_remove(data, n, condition) print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains) </code></pre>
58
2016-09-19T18:46:05Z
39,596,598
<p>Straightforward Python:</p> <pre><code>N = 3 data = [1, 10, 2, 9, 3, 8, 4, 7] def matchCondition(x): return x &lt; 5 c = 1 l = [] for x in data: if c &gt; N or not matchCondition(x): l.append(x) else: c += 1 print(l) </code></pre> <p>This can easily be turned into a generator if desired:</p> <pre><code>def filter_first(n, func, iterable): c = 1 for x in iterable: if c &gt; n or not func(x): yield x else: c += 1 print(list(filter_first(N, matchCondition, data))) </code></pre>
1
2016-09-20T14:19:19Z
[ "python", "list", "list-comprehension" ]
Remove the first N items that match a condition in a Python list
39,580,063
<p>If I have a function <code>matchCondition(x)</code>, how can I remove the first <code>n</code> items in a Python list that match that condition?</p> <p>One solution is to iterate over each item, mark it for deletion (e.g., by setting it to <code>None</code>), and then filter the list with a comprehension. This requires iterating over the list twice and mutates the data. Is there a more idiomatic or efficient way to do this?</p> <pre><code>n = 3 def condition(x): return x &lt; 5 data = [1, 10, 2, 9, 3, 8, 4, 7] out = do_remove(data, n, condition) print(out) # [10, 9, 8, 4, 7] (1, 2, and 3 are removed, 4 remains) </code></pre>
58
2016-09-19T18:46:05Z
39,630,844
<p>Using list comprehensions:</p> <pre><code>n = 3 data = [1, 10, 2, 9, 3, 8, 4, 7] count = 0 def counter(x): global count count += 1 return x def condition(x): return x &lt; 5 filtered = [counter(x) for x in data if count &lt; n and condition(x)] </code></pre> <p>This will also stop checking the condition after <em>n</em> elements are found thanks to boolean short-circuiting.</p>
1
2016-09-22T05:22:55Z
[ "python", "list", "list-comprehension" ]
how to insert new row in pandas data frame at desired index
39,580,066
<p>I have a data frame which has missing dates </p> <pre><code>print data Date Longitude Latitude Elevation Max Temperature \ 4/11/1979 83.75 24.197701 238 44.769 20.007 4/12/1979 83.75 24.197701 238 41.967 18.027 4/13/1979 83.75 24.197701 238 43.053 20.549 4/15/1979 83.75 24.197701 238 40.826 20.189 </code></pre> <p>How do I insert <code>4/14/1979</code> at the <code>4th</code> row</p> <p>print data </p> <pre><code>Date Longitude Latitude Elevation Max Temperature \ 4/11/1979 83.75 24.197701 238 44.769 20.007 4/12/1979 83.75 24.197701 238 41.967 18.027 4/13/1979 83.75 24.197701 238 43.053 20.549 4/14/1979 0.0 0.0 0 0.0 0.0 4/15/1979 83.75 24.197701 238 40.826 20.189 </code></pre>
4
2016-09-19T18:46:10Z
39,580,178
<p>First convert column <code>Date</code> <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> for resampling.</p> <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a> by <code>D</code> (<code>days</code>) and then need fill <code>NaN</code> to <code>0</code>, one posible solution is <a href="http://stackoverflow.com/q/39452095/2901002"><code>replace({np.nan:0})</code></a>:</p> <pre><code>df['Date'] = pd.to_datetime(df.Date) df.set_index('Date', inplace=True) df = df.resample('D').replace({np.nan:0}).reset_index() print (df) Date Longitude Latitude Elevation Max Temperature 0 1979-04-11 83.75 24.197701 238.0 44.769 20.007 1 1979-04-12 83.75 24.197701 238.0 41.967 18.027 2 1979-04-13 83.75 24.197701 238.0 43.053 20.549 3 1979-04-14 0.00 0.000000 0.0 0.000 0.000 4 1979-04-15 83.75 24.197701 238.0 40.826 20.189 </code></pre>
3
2016-09-19T18:53:46Z
[ "python", "pandas", "dataframe", null, "resampling" ]
How to Skip Numbers In Each Iteration Loop String in Python?
39,580,069
<p>I'm very new to this: but I have this string:</p> <pre><code>urls = ['http://example.com/page_%s.html' % page for page in xrange(0,50)] </code></pre> <p>which runs from 0,1,2,3 ... 50. </p> <p>The question is how can i make run by skipping 5 number in each iteration? </p> <p>The number should run like this: 0, 5, 10, 15 ... 50.</p>
0
2016-09-19T18:46:24Z
39,580,094
<p>Just adding the 5 as another argument to xrange should do that</p> <pre><code>urls = ['http://example.com/page_%s.html' % page for page in xrange(0,50,5)] </code></pre>
3
2016-09-19T18:48:14Z
[ "python" ]
How to Skip Numbers In Each Iteration Loop String in Python?
39,580,069
<p>I'm very new to this: but I have this string:</p> <pre><code>urls = ['http://example.com/page_%s.html' % page for page in xrange(0,50)] </code></pre> <p>which runs from 0,1,2,3 ... 50. </p> <p>The question is how can i make run by skipping 5 number in each iteration? </p> <p>The number should run like this: 0, 5, 10, 15 ... 50.</p>
0
2016-09-19T18:46:24Z
39,580,111
<p>You can try this:</p> <pre><code>urls = map('http://example.com/page_{}.html'.format, range(0, 50, 5)) </code></pre> <p><code>range</code> and <code>xrange</code> take an optional <code>step</code> argument as the third parameter.</p>
3
2016-09-19T18:49:13Z
[ "python" ]
Can't print contents after scraping site
39,580,090
<p>I am unable to print contents after scraping a website using selenium. I need to scrape a table. Here's what I am trying to do:</p> <pre><code>table = driver.find_element_by_xpath('//div[@class="line-chart"]/div/div[1]/div/div/table/tbody') print table.text </code></pre> <p>But I am just getting a blank line!! </p> <p>I know I am selecting the correct contents because when I save an html file it works fine:</p> <pre><code>source_code = table.get_attribute("outerHTML") f = open('html_source.html', 'w') f.write(source_code.encode('utf-8')) f.close() </code></pre> <p>And I get:</p> <pre><code>&lt;tbody&gt;&lt;tr&gt;&lt;td&gt;‪Jun 19‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 20‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 21‬&lt;/td&gt;&lt;td&gt;27&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 22‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 23‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 24‬&lt;/td&gt;&lt;td&gt;57&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 25‬&lt;/td&gt;&lt;td&gt;11&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 26‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 27‬&lt;/td&gt;&lt;td&gt;39&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 28‬&lt;/td&gt;&lt;td&gt;31&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 29‬&lt;/td&gt;&lt;td&gt;29&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jun 30‬&lt;/td&gt;&lt;td&gt;28&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 1‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 2‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 3‬&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 4‬&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 5‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 6‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 7‬&lt;/td&gt;&lt;td&gt;22&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 8‬&lt;/td&gt;&lt;td&gt;23&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 9‬&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 10‬&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 11‬&lt;/td&gt;&lt;td&gt;27&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 12‬&lt;/td&gt;&lt;td&gt;27&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 13‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 14‬&lt;/td&gt;&lt;td&gt;28&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 15‬&lt;/td&gt;&lt;td&gt;25&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 16‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 17‬&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 18‬&lt;/td&gt;&lt;td&gt;28&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 19‬&lt;/td&gt;&lt;td&gt;28&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 20‬&lt;/td&gt;&lt;td&gt;30&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 21‬&lt;/td&gt;&lt;td&gt;29&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 22‬&lt;/td&gt;&lt;td&gt;30&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 23‬&lt;/td&gt;&lt;td&gt;9&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 24‬&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 25‬&lt;/td&gt;&lt;td&gt;35&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 26‬&lt;/td&gt;&lt;td&gt;92&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 27‬&lt;/td&gt;&lt;td&gt;100&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 28‬&lt;/td&gt;&lt;td&gt;50&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 29‬&lt;/td&gt;&lt;td&gt;39&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 30‬&lt;/td&gt;&lt;td&gt;9&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Jul 31‬&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 1‬&lt;/td&gt;&lt;td&gt;32&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 2‬&lt;/td&gt;&lt;td&gt;35&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 3‬&lt;/td&gt;&lt;td&gt;31&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 4‬&lt;/td&gt;&lt;td&gt;33&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 5‬&lt;/td&gt;&lt;td&gt;33&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 6‬&lt;/td&gt;&lt;td&gt;10&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 7‬&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 8‬&lt;/td&gt;&lt;td&gt;29&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 9‬&lt;/td&gt;&lt;td&gt;32&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 10‬&lt;/td&gt;&lt;td&gt;30&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 11‬&lt;/td&gt;&lt;td&gt;29&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 12‬&lt;/td&gt;&lt;td&gt;27&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 13‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 14‬&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 15‬&lt;/td&gt;&lt;td&gt;34&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 16‬&lt;/td&gt;&lt;td&gt;33&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 17‬&lt;/td&gt;&lt;td&gt;29&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 18‬&lt;/td&gt;&lt;td&gt;27&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 19‬&lt;/td&gt;&lt;td&gt;25&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 20‬&lt;/td&gt;&lt;td&gt;12&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 21‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 22‬&lt;/td&gt;&lt;td&gt;23&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 23‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 24‬&lt;/td&gt;&lt;td&gt;24&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 25‬&lt;/td&gt;&lt;td&gt;23&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 26‬&lt;/td&gt;&lt;td&gt;21&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 27‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 28‬&lt;/td&gt;&lt;td&gt;3&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 29‬&lt;/td&gt;&lt;td&gt;24&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 30‬&lt;/td&gt;&lt;td&gt;43&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Aug 31‬&lt;/td&gt;&lt;td&gt;27&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 1‬&lt;/td&gt;&lt;td&gt;23&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 2‬&lt;/td&gt;&lt;td&gt;23&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 3‬&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 4‬&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 5‬&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 6‬&lt;/td&gt;&lt;td&gt;26&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 7‬&lt;/td&gt;&lt;td&gt;72&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 8‬&lt;/td&gt;&lt;td&gt;53&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 9‬&lt;/td&gt;&lt;td&gt;37&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 10‬&lt;/td&gt;&lt;td&gt;9&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 11‬&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 12‬&lt;/td&gt;&lt;td&gt;30&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 13‬&lt;/td&gt;&lt;td&gt;35&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 14‬&lt;/td&gt;&lt;td&gt;44&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 15‬&lt;/td&gt;&lt;td&gt;54&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;‪Sep 16‬&lt;/td&gt;&lt;td&gt;53&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt; </code></pre>
0
2016-09-19T18:47:31Z
39,584,950
<p>It's hard to say, why <code>.text</code> is not working in your case, may be its designing issue. But you can try also using <code>get_attribute()</code> to scrap text as below :-</p> <pre><code>table.get_attribute("textContent") </code></pre>
0
2016-09-20T02:47:47Z
[ "python", "selenium", "web-scraping", "html-table" ]
numpy binary notation quick generation
39,580,110
<p>Suppose, I have a <code>numpy</code> vector with <code>n</code> elements, so I'd like to encode numbers in this vector as a binary notation, so resulting shape will be <code>(n,m)</code> where <code>m</code> is <code>log2(maxnumber)</code> for example:</p> <pre><code>x = numpy.array([32,5,67]) </code></pre> <p>Because max number I have is <code>67</code>, I need <code>numpy.ceil(numpy.log2(67)) == 7</code> bits to encode this vector, so shape of the result will be <code>(3,7)</code></p> <pre><code>array([[1, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 0, 1], [0, 1, 0, 0, 0, 0, 0]]) </code></pre> <p>The problem rises because I have no quick way to move binary notation from<br> function <code>numpy.binary_repr</code> to numpy array. Now I have to iterate over result, and put each bit severally: </p> <pre><code>brepr = numpy.binary_repr(x[i],width=7) j = 0 for bin in brepr: X[i][j] = bin j += 1 </code></pre> <p>It's very timecost and stupid way, how to make it efficient?</p>
3
2016-09-19T18:49:12Z
39,580,269
<p>Here us one way using <code>np.unpackbits</code> and broadcasting:</p> <pre><code>&gt;&gt;&gt; max_size = np.ceil(np.log2(x.max())).astype(int) &gt;&gt;&gt; np.unpackbits(x[:,None].astype(np.uint8), axis=1)[:,-max_size:] array([[0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1]], dtype=uint8) </code></pre>
3
2016-09-19T19:00:08Z
[ "python", "numpy" ]
numpy binary notation quick generation
39,580,110
<p>Suppose, I have a <code>numpy</code> vector with <code>n</code> elements, so I'd like to encode numbers in this vector as a binary notation, so resulting shape will be <code>(n,m)</code> where <code>m</code> is <code>log2(maxnumber)</code> for example:</p> <pre><code>x = numpy.array([32,5,67]) </code></pre> <p>Because max number I have is <code>67</code>, I need <code>numpy.ceil(numpy.log2(67)) == 7</code> bits to encode this vector, so shape of the result will be <code>(3,7)</code></p> <pre><code>array([[1, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 1, 0, 1], [0, 1, 0, 0, 0, 0, 0]]) </code></pre> <p>The problem rises because I have no quick way to move binary notation from<br> function <code>numpy.binary_repr</code> to numpy array. Now I have to iterate over result, and put each bit severally: </p> <pre><code>brepr = numpy.binary_repr(x[i],width=7) j = 0 for bin in brepr: X[i][j] = bin j += 1 </code></pre> <p>It's very timecost and stupid way, how to make it efficient?</p>
3
2016-09-19T18:49:12Z
39,580,272
<p>You can use numpy byte string.</p> <p>For the case you have in hand:</p> <pre><code>res = numpy.array(len(x),dtype='S7') for i in range(len(x)): res[i] = numpy.binary_repr(x[i]) </code></pre> <p>Or more compactly</p> <pre><code>res = numpy.array([numpy.binary_repr(val) for val in x]) </code></pre>
1
2016-09-19T19:00:18Z
[ "python", "numpy" ]
Constructing an edge list from the second column of a two columnar file with relationships derived from the first column
39,580,130
<p>I have a problem, I have a file with several million lines arranged like so:</p> <pre><code>1 Protein_A 1 Protein_B 2 Protein_A 3 Protein_C 4 Protein_A 4 Protein_B 4 Protein_C 4 Protein_D 5 Protein_C 5 Protein_D </code></pre> <p>Where column 1 indicates an interaction pathway and column 2 indicates the protein's ID. Can anyone recommend an effective way I can sort this into an edge list of only (non reciprocal) interactions per network eg:</p> <pre><code>1 Protein_A,Protein_B 4 Protein_A,Protein_B 4 Protein_A,Protein_C 4 Protein_A,Protein_D 4 Protein_B,Protein_C 5 Protein_C,Protein_D 5 Protein_C,Protein_D </code></pre> <p>Or give me an indication of where to look for such data? </p> <p>I tried a shell script which slowly iterates through the file and deletes the new line at the end of the file which results in the following:</p> <pre><code>1 Protein_A 1 Protein_B </code></pre> <p>This can then be processed into an edge, however this doesn't work if there is more than 2 proteins in a network. I'm drawing a blank. Can anyone please help?</p> <p>Thank you in advance.</p>
1
2016-09-19T18:49:54Z
39,580,297
<p>Rather easy using python and some smart modules. I have embedded the file contents in a string. Just replace by <code>data = open("input.txt")</code> to read from a file (iterable as well).</p> <p>I create a dictionary with number as key and list of proteins matching the number as values.</p> <p>Once built, I use <code>itertools.combinations</code> of size 2 to generate the list, printing the key along the way.</p> <pre><code>import re import collections,itertools data="""1 Protein_A 1 Protein_B 2 Protein_A 3 Protein_C 4 Protein_A 4 Protein_B 4 Protein_C 4 Protein_D 5 Protein_C 5 Protein_D""".split("\n") d = collections.defaultdict(lambda : list()) for l in data: fields = re.split("\s+",l.strip()) d[int(fields[0])].append(fields[1]) for k,v in d.items(): for a,b in itertools.combinations(v,2): print(k,a,b) </code></pre> <p>result:</p> <pre><code>(1, 'Protein_A', 'Protein_B') (4, 'Protein_A', 'Protein_B') (4, 'Protein_A', 'Protein_C') (4, 'Protein_A', 'Protein_D') (4, 'Protein_B', 'Protein_C') (4, 'Protein_B', 'Protein_D') (4, 'Protein_C', 'Protein_D') (5, 'Protein_C', 'Protein_D') </code></pre>
1
2016-09-19T19:01:41Z
[ "python", "bash", "shell", "unix" ]
Elasticsearch-py date malformed
39,580,217
<p>I am trying to index some data but I keep getting the error </p> <pre><code>error: reason: failed to parse [date] type: mapper_parsing_exception, caused_by: Invalid format: 2016-08-12\t17:35:26 is malformed at \t17:35:26 </code></pre> <p>My mapping looks like</p> <pre><code>'date': { 'type': 'date', 'format': 'dateOptionalTime' }, </code></pre> <p>Is there a different way to create the date mapping?</p> <p>EDIT: Here is a line from the document. I can get it to index just fine when I set time to string and date to date but the date shows a bogus time attached to it. So it looks like ES is taking my date (2016/9/20) and adding a time to it. In my case it adds 19:00:00. Which is why I can't figure out why it doesnt like the time.</p> <pre><code>2016-06-14 18:12:35 1.1.1.1 GET /origin-www.origin.com/Images/pipe-gray.png? 200 1442 0 "http://www.origin.com/Main.css" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36" "__qca=P0-920525163; s_fid=4CDFF16906A35CC4; __CSCookie=z5ayStQYdIbcPTxGKyhsjRIi0peP5GAP6K; icxid=1459286804904; icxid=1459286804904; ASP.NET_SessionId=dzg3esjzp4tpg; __SessionCookie=gXA9BuDiF245ZJeuh; dtCookie=0C05828501CE759D; s_vi=[CS]v1|2A069D04051D2E2A; __CSUserIbcIDCookie=NL7VeN+rh05z5FWSCgTnzTC6G;" </code></pre>
1
2016-09-19T18:56:37Z
39,603,908
<p>Before adding the date to hashtable or before u feed it to json, convert the date "2016-02-10\t10:25:30" to this "2016-02-10T10:25:30" </p> <p>If you give elasticsearch this format, you should be able to use the original mapping - dateOptionalTime. </p>
1
2016-09-20T21:20:49Z
[ "python", "elasticsearch" ]
doc2vec - How to infer vectors of documents faster?
39,580,232
<p>I have trained paragraph vectors for around 2300 paragraphs(between 2000-12000 words each) each with vector size of 300. Now, I need to infer paragraph vectors of around 100,000 sentences which I have considered as paragraphs(each sentence is around 10-30 words each corresponding to the earlier 2300 paragraphs already trained).</p> <p>So, am using </p> <p><code>model.infer_vector(sentence)</code></p> <p>But, the problem is it is taking too long, and it does not take any arguments such as "workers" .! Is there a way I can speed up the process by threading or some other way? I am using a machine with 8gb ram and when I checked the available cores using</p> <pre><code>cores = multiprocessing.cpu_count() </code></pre> <p>it comes out to be 8.</p> <p>I need this for answering multiple choice questions. Also, are there any other libraries/models such as doc2vec which can help in this task?</p> <p>Thanks in advance for your time.</p>
1
2016-09-19T18:57:36Z
39,715,902
<p>You might get a slight speedup from calling <code>infer_vector()</code> from multiple threads, on different subsets of the new data on which you need to infer vectors. There would still be quite a bit of thread-contention, preventing full use of all cores, due to the Python Global Interpreter Lock ('GIL'). </p> <p>If your RAM is large enough to do so without swapping, you could save the model to disk, then load it into 8 separate processes, and have each do inference on 1/8th of the new data. That'd be the best way to saturate all CPUs. </p> <p>Any faster speedups would require making optimizations to the <code>infer_vector()</code> implementation in gensim – which is an <a href="https://github.com/RaRe-Technologies/gensim/issues/515" rel="nofollow">open issue</a> on the project that would accept contributed improvements. </p>
1
2016-09-27T04:19:40Z
[ "python", "gensim", "word2vec", "doc2vec" ]
Recognizing cx_Oracle install within PyDev
39,580,275
<p>I am on Windows 10 Pro 64-bit Anniversary Edition using Python 3.5.2 (Anaconda 4.1.1). I download the latest Oracle 12c Instant Client <code>instantclient-basic-windows.x64-12.1.0.2.0.zip</code> and <code>instantclient-sdk-windows.x64-12.1.0.2.0.zip</code> into <code>C:\instantclient</code> and put <code>C:\instantclient</code> on my <code>PATH</code>. Then I download the installer <code>cx_Oracle-5.2.1-12c.win-amd64-py3.5.exe</code> <a href="https://pypi.python.org/pypi/cx_Oracle/5.2.1" rel="nofollow">directly from <code>PyPI</code></a>.</p> <p>Now I can start an Anaconda <code>python</code> prompt and type <code>import cx_Oracle</code> and it is successful.</p> <pre><code>&gt;&gt;&gt; import cx_Oracle &gt;&gt;&gt; </code></pre> <p>By when I go into my PyDev installation on Eclipse Neon (4.6), the <code>import cx_Oracle</code> line in my source file still shows an error as an unresolved import.</p> <ul> <li>I went into <strong>Windows > Preferences > PyDev > Interpreters > Python Interpreter</strong> and removed the Anaconda interpreter (<code>C:\bin\anaconda3\python.exe</code>) and added it back. I restarted Eclipse, but no luck.</li> <li>I issued a <strong>Project > Clean</strong> on all my projects and restarted Eclipse. It still shows <code>import cx_Oracle</code> as an unresolved import.</li> </ul> <p>How can I get <code>PyDev</code> to see my <code>cx_Oracle</code> package installation?</p> <p>Note that there are a lot of supposed answers that do not work for me; I've tried all the suggestions, as indicated above.</p> <ul> <li><a href="http://stackoverflow.com/q/26235307/421049">PyDev does not recognize imports</a></li> <li><a href="http://stackoverflow.com/q/3732093/421049">How To Make Eclipse Pydev Plugin Recognize Newly Installed Python Modules?</a></li> <li><a href="http://stackoverflow.com/q/8318103/421049">Force eclipse to reload Python modules</a></li> <li><a href="http://stackoverflow.com/q/3610272/421049">pydev doesn&#39;t find python library after installation</a></li> </ul>
6
2016-09-19T19:00:21Z
39,778,288
<p>You can try this (after the steps that you already report in your question)</p> <ol> <li><p>Check if the installation in PyDev is ok (besides showing an error marker for <code>import cx_Oracle</code>)</p> <pre><code>import cx_Oracle conn = cx_Oracle.connect('hr/hr@pdborcl') cur = conn.cursor() cur.execute('select 13 from dual') for r in cur.fetchall(): print(r) </code></pre> <p>If this works, and prints <code>(13,)</code> the installation is correct. Likely some part of completion could work as well. In addition, Shift+Click on <code>cx_Oracle</code> should report <code>The definition of ... was found at ...</code>.</p></li> <li><p>Go to <strong>Windows > Preferences > PyDev > Interpreters > Python Interpreter</strong> and on the tab <strong>Forced builtins</strong> add <code>cx_Oracle</code></p> <p>After rebuilding the project, the error markers on the import should go away. (In the little test program I just did a trivial edit and saved.)</p></li> </ol> <p>For the record: </p> <pre><code>Eclipse Version: 4.6.0 (Neon) PyDev Version: 5.2.0 Python: 3.5.2 (from a virtualenv) </code></pre>
1
2016-09-29T19:15:22Z
[ "python", "windows", "anaconda", "pydev", "cx-oracle" ]
py2neo.database.status.Unauthorized in Neo4j 3.0.3
39,580,406
<p>I've tried to access from a python program to the Neo4j 3.0 database but the following error is shown: </p> <p>File "C:\Python27\lib\py2neo\database\http.py", line 157, in get raise Unauthorized(self.uri.string) py2neo.database.status.Unauthorized: <a href="http://localhost:7474/db/data/" rel="nofollow">http://localhost:7474/db/data/</a></p> <p>There is already a post of the same topic opened, but it's in version 2.2. </p> <p>My code is:</p> <pre><code>authenticate("localhost:7474", "neo4j", "neo4j") graph_db = Graph("http://localhost:7474/db/data/") </code></pre> <p>Which is exactly the same as in version 2.2, as it is specified in <a href="http://py2neo.org/v3/database.html" rel="nofollow">http://py2neo.org/v3/database.html</a>.</p> <p>I've also tried to do it like this:</p> <pre><code>graph_db = Graph("http://localhost:7474/db/data/", user="neo4j", password="neo4j") </code></pre> <p>But I get the same result.</p> <p>Does anyone know where is the problem?</p> <p>Thanks in advanced.</p>
0
2016-09-19T19:09:27Z
39,581,177
<p>Access the database through the web interface (<a href="http://localhost:7474/browser/" rel="nofollow">http://localhost:7474/browser/</a>), you have to set a new password at the first log in.</p> <p>Then, this should work:</p> <pre><code>from py2neo g = Graph('http://localhost:7474/db/data', user='neo4j', password='new_password') </code></pre>
1
2016-09-19T20:02:57Z
[ "python", "neo4j", "py2neo" ]
How does TensorFlow calculate the gradients for the tf.train.GradientDescentOptimizer?
39,580,427
<p>I am trying to understand how TensorFlow computes the gradients for the <code>tf.train.GradientDescentOptimizer</code>.</p> <p>If I understand section 4.1 in the TensorFlow whitepaper correct, it computes the gradients based on backpropagation by adding nodes to the TensorFlow graph which compute the derivation of a node in the original graph. </p> <blockquote> <p>When TensorFlow needs to compute the gradient of a tensor C with respect to some tensor I on which C depends, it first finds the path in the computation graph from I to C. Then it backtracks from C to I, and for each operation on the backward path it adds a node to the TensorFlow graph, composing the partial gradients along the backwards path using the chain rule. The newly added node computes the “gradient function” for the corresponding operation in the forward path. A gradient function may be registered by any operation. This function takes as input not only the partial gradients computed already along the backward path, but also, optionally, the inputs and outputs of the forward operation.<a href="http://download.tensorflow.org/paper/whitepaper2015.pdf" rel="nofollow"> [Section 4.1 TensorFlow whitepaper]</a></p> </blockquote> <p><strong>Question 1:</strong> Is there a second node implementation for each TensorFlow node which represents the derivation of the original TensorFlow node?</p> <p><strong>Question 2:</strong> Is there a way to visualize which derivation nodes get added to the graph (or any logs)?</p>
0
2016-09-19T19:10:42Z
39,583,022
<p>Each node gets corresponding method that computes backprop values (registered using something like @ops.RegisterGradient("Sum") in Python)</p> <p>You can visualize the graph using method <a href="http://stackoverflow.com/questions/38189119/simple-way-to-visualize-a-tensorflow-graph-in-jupyter">here</a></p> <p>However, note that since automatic differentiation code is meant to work for a range of conditions, the graph it creates is quite complicated and not very useful to look at. It's not uncommon to have 10 ops nodes for a simple gradient calculation that could be implemented with 1-2 nodes</p>
1
2016-09-19T22:27:34Z
[ "python", "optimization", "tensorflow", "gradient" ]
Pyglet Player.seek() function not working?
39,580,438
<p>I am trying to build a simple media tool in Pyglet, which requires a seek feature. Files are loaded, paused, and then told to seek to a specific time; however, the file does not seek when Player.seek() is called. Below is the test code I am using:</p> <pre><code>import os import pyglet from os.path import abspath, isfile def loadsong(filename): # check for file print("Attempting to load "+filename) filename = abspath(filename) if not ( isfile(filename) ): raise Exception(filename+" not found.") # create a player for this file song = pyglet.media.load(filename) source = song.play() source.eos_action = source.EOS_LOOP source.pause() return source music = loadsong("test.mp3") music.seek(57) music.play() pyglet.app.run() </code></pre> <p>What am I doing wrong here? I am using Python 3.5.2, Pyglet 1.2 alpha 1, and AVBin 11 alpha 4.</p>
2
2016-09-19T19:10:51Z
39,745,404
<p>First of all, the error you're getting is quite important.<br> But I'll assume it's a <code>Segmentation fault (core dumped)</code> on the row:</p> <pre><code>music.seek(12) </code></pre> <p>Another quick note, fix your indentation! You're using 3 spaces and whether you are a space guy or a tab guy - 3 spaces is just odd -</p> <p>The reason for you getting a segmentation fault when trying to seek is most likely because of AVbin, it's an old (and dead afaik) project.</p> <p>I hacked together something more similar to a music player and here's an example on how you can use <code>Seek</code> with wav files:</p> <pre><code>import pyglet from pyglet.gl import * from os.path import abspath, isfile pyglet.options['audio'] = ('pulseaudio', 'alsa', 'openal', 'silent') pyglet.have_avbin=False key = pyglet.window.key def loadsong(filename): # check for file filename = abspath(filename) # create a player for this file player = pyglet.media.Player() player.queue(pyglet.media.load(filename, streaming=False)) #player.play() #song.eos_action = song.EOS_LOOP #song.pause() return player class main(pyglet.window.Window): def __init__ (self): super(main, self).__init__(300, 300, fullscreen = False) self.alive = 1 self.player = loadsong('./test.wav') def on_draw(self): self.render() def on_close(self): self.alive = 0 def on_key_press(self, symbol, modifiers): if symbol == key.ESCAPE: # [ESC] self.alive = 0 elif symbol == key.SPACE: if self.player.playing: self.player.pause() else: self.player.play() elif symbol == key.RIGHT: print('Skipping to:',self.player.time+2) self.player.source.seek(self.player.time+2) elif symbol == key.LEFT: print('Rewinding to:',self.player.time-2) self.player.source.seek(self.player.time-2) def render(self): self.clear() #source = pyglet.text.Label(str(self.player.source.info.title.decode('UTF-8')), x=20, y=300-30) volume = pyglet.text.Label(str(self.player.volume*100)+'% volume', x=20, y=40) p_time = pyglet.text.Label(str(self.player.time), x=20, y=20) #source.draw() volume.draw() p_time.draw() self.flip() def run(self): while self.alive == 1: self.render() # -----------&gt; This is key &lt;---------- # This is what replaces pyglet.app.run() # but is required for the GUI to not freeze # event = self.dispatch_events() x = main() x.run() </code></pre> <p>A few important notes:</p> <pre><code>pyglet.have_avbin=False </code></pre> <p>This will turn off AVbin completely, there is probably a way to turn it off for individual sources.. But since I rarely play around with it I honestly have no idea of how to.. So off it goes :)</p> <p>Secondly:</p> <pre><code>streaming=False </code></pre> <p>On the <code>media.load()</code> call is quite important, otherwise you might get weird artifacts in your sound and or no sound at all. I got instance to a super high pitched scratching noise that almost made me deaf without that flag.</p> <p>Other than that, the code is quite straight forward.</p> <pre><code>self.player.source.seek(&lt;time&gt;) </code></pre> <p>Is called on the player object that is a instance of <code>pyglet.media.Player()</code>. And it works brilliantly.</p> <p>Another work-around would be to manually install <a href="https://code.google.com/archive/p/avbin/" rel="nofollow">AVbin 7</a> which <strong>appears</strong> to be working better, but I'm reluctant to install it on this machine just for testing purposes.. But the overall info i've gathered over the years is that that old library works better with Mp3 files.</p>
0
2016-09-28T10:52:12Z
[ "python", "python-3.x", "media", "pyglet" ]
Pandas/python and working with a column, in a dataframe, with a date
39,580,450
<p>I am currently working on a Python/Pandas data science project for fun. The data that I am looking at has a Date column where the date looks like the following: 2016-07-16. The data type is also an object. What I want to do is go through each date and pull data from across that row. Now, some rows may have the same date because two separate attacks occurred on that date. (I am looking at terrorism data.) What I currently have done is the following:</p> <pre><code>dates = [] start = 0; while start &lt; 300: date = data.iat[start, 1] dates.append(date) start += 1 </code></pre> <p>This will get me ALMOST what I want. However, I have two problems, the start variable is set to 0 but I cannot go to 365 since, like I said, each date may have multiple attacks. So one year may have like 400 attacks. Is there a way that I could end the data collection at 2016-12-31 or 2017-01-01 for example? Basically, is there a way to quickly determine the number of attacks, per year for year after year? Thank you for any help! </p> <p>Oh I will say that I was trying something like:</p> <pre><code>newDate = pd.to_datetime(startdate) + pd.DateOffset(days=1) </code></pre> <p>or </p> <pre><code>data['Date']) + timedelta(days=1) </code></pre> <p>to add one to the date to end at the year. Not getting what I wanted plus, there could be more than one entry per day. </p> <p>to explain further I could have something like this:</p> <pre><code>Date Deaths Country 2002-01-01 2 India 2002-01-02 0 Pakistan 2001-01-02 1 France </code></pre> <p>The data has about 20,000 points and I need to find a way to stop it at the end of each year. That is my main issue. I cannot go to 365 because there may be multiple terrorist attacks on the same date around the world. </p>
1
2016-09-19T19:11:54Z
39,581,149
<p>IMO there is no need to add a new column:</p> <pre><code>In [132]: df Out[132]: Date Deaths Country 0 2002-01-01 2 India 1 2002-01-02 0 Pakistan 2 2001-01-02 1 France In [217]: df.groupby(df.Date.dt.year)['Deaths'].sum() Out[217]: Date 2001 1 2002 2 Name: Deaths, dtype: int64 </code></pre> <p>or:</p> <pre><code>In [218]: df.groupby(pd.TimeGrouper(freq='AS', key='Date'))['Deaths'].sum() Out[218]: Date 2001-01-01 1 2002-01-01 2 Freq: AS-JAN, Name: Deaths, dtype: int64 In [219]: df.groupby(pd.TimeGrouper(freq='A', key='Date'))['Deaths'].sum() Out[219]: Date 2001-12-31 1 2002-12-31 2 Freq: A-DEC, Name: Deaths, dtype: int64 </code></pre> <p>and you can always access different parts (year, month, day, weekday, hour, etc.) of your DateTime column:</p> <pre><code>In [137]: df.Date.dt.year Out[137]: 0 2002 1 2002 2 2001 Name: Date, dtype: int64 In [138]: df.Date.dt. df.Date.dt.ceil df.Date.dt.freq df.Date.dt.microsecond df.Date.dt.strftime df.Date.dt.weekday df.Date.dt.date df.Date.dt.hour df.Date.dt.minute df.Date.dt.time df.Date.dt.weekday_name df.Date.dt.day df.Date.dt.is_month_end df.Date.dt.month df.Date.dt.to_period df.Date.dt.weekofyear df.Date.dt.dayofweek df.Date.dt.is_month_start df.Date.dt.nanosecond df.Date.dt.to_pydatetime df.Date.dt.year df.Date.dt.dayofyear df.Date.dt.is_quarter_end df.Date.dt.normalize df.Date.dt.tz df.Date.dt.days_in_month df.Date.dt.is_quarter_start df.Date.dt.quarter df.Date.dt.tz_convert df.Date.dt.daysinmonth df.Date.dt.is_year_end df.Date.dt.round df.Date.dt.tz_localize df.Date.dt.floor df.Date.dt.is_year_start df.Date.dt.second df.Date.dt.week </code></pre>
1
2016-09-19T20:01:12Z
[ "python", "date", "pandas" ]
Pandas/python and working with a column, in a dataframe, with a date
39,580,450
<p>I am currently working on a Python/Pandas data science project for fun. The data that I am looking at has a Date column where the date looks like the following: 2016-07-16. The data type is also an object. What I want to do is go through each date and pull data from across that row. Now, some rows may have the same date because two separate attacks occurred on that date. (I am looking at terrorism data.) What I currently have done is the following:</p> <pre><code>dates = [] start = 0; while start &lt; 300: date = data.iat[start, 1] dates.append(date) start += 1 </code></pre> <p>This will get me ALMOST what I want. However, I have two problems, the start variable is set to 0 but I cannot go to 365 since, like I said, each date may have multiple attacks. So one year may have like 400 attacks. Is there a way that I could end the data collection at 2016-12-31 or 2017-01-01 for example? Basically, is there a way to quickly determine the number of attacks, per year for year after year? Thank you for any help! </p> <p>Oh I will say that I was trying something like:</p> <pre><code>newDate = pd.to_datetime(startdate) + pd.DateOffset(days=1) </code></pre> <p>or </p> <pre><code>data['Date']) + timedelta(days=1) </code></pre> <p>to add one to the date to end at the year. Not getting what I wanted plus, there could be more than one entry per day. </p> <p>to explain further I could have something like this:</p> <pre><code>Date Deaths Country 2002-01-01 2 India 2002-01-02 0 Pakistan 2001-01-02 1 France </code></pre> <p>The data has about 20,000 points and I need to find a way to stop it at the end of each year. That is my main issue. I cannot go to 365 because there may be multiple terrorist attacks on the same date around the world. </p>
1
2016-09-19T19:11:54Z
39,582,046
<p>Another way of dealing with the problem is through a dictionary</p> <pre><code># Get column with the dates dates = df.iloc[:,0].values year_attacks = {} for date in dates: # Get year from the date year=str(date).split('-')[0] # If year is already in the dictionary increase number of attacks by 1 if year in year_attacks: year_attacks[year]=year_attacks[year]+1 # Else create new key else: year_attacks[year]=1 </code></pre>
0
2016-09-19T21:02:04Z
[ "python", "date", "pandas" ]
calculate the totall number of uniqe words of the first column of a list
39,580,452
<p>I have a file that consists of many Persian sentences. each line contains a sentence, then a "tab", then a word, again a "tab" and then an English word. I have to know just the number of unique words of the sentences (the words after tabs should not be in calculation). For that I changed the file to a list, so I have a list that contains a lot of lines and each line contains three indices; the sentence, a Persian word, an English word. Now I can achieve the sentences. The problem is that, the code I wrote returns the number of unique words of each line separately. For example if the file has 100 lines it returns 100 numbers, each in a new line. But I want the summation of all the numbers and have just one number which shows the total number of unique words. How can I change the code?</p> <pre><code>from hazm import* def WordsProbs (file): with open (file, encoding = "utf-8") as f1: normalizer = Normalizer() for line in f1: tmp = line.strip().split("\t") tmp[0] = normalizer.normalize(tmp[0]) corpus.append(tmp) for row in corpus: UniqueWords = len(set(row[0].split())) print (UniqueWords) </code></pre> <p>The sample data:</p> <p>باد بارش برف وزش باد، کولاک یخبندان سطح wind</p>
0
2016-09-19T19:11:59Z
39,580,583
<p>There is a simple solution. As you said you have list of lines. So the following code should get you what you want</p> <pre><code>sample_data = """This is One sentence word1 word2 This is Second sentence word1 word2""" lines = sample_data.split("\n") word_list = [] for line in lines: line = line.split("\t")[0] word_list.extend(line.split(" ")) print len(set(word_list)) </code></pre>
1
2016-09-19T19:22:35Z
[ "python", "nlp" ]
calculate the totall number of uniqe words of the first column of a list
39,580,452
<p>I have a file that consists of many Persian sentences. each line contains a sentence, then a "tab", then a word, again a "tab" and then an English word. I have to know just the number of unique words of the sentences (the words after tabs should not be in calculation). For that I changed the file to a list, so I have a list that contains a lot of lines and each line contains three indices; the sentence, a Persian word, an English word. Now I can achieve the sentences. The problem is that, the code I wrote returns the number of unique words of each line separately. For example if the file has 100 lines it returns 100 numbers, each in a new line. But I want the summation of all the numbers and have just one number which shows the total number of unique words. How can I change the code?</p> <pre><code>from hazm import* def WordsProbs (file): with open (file, encoding = "utf-8") as f1: normalizer = Normalizer() for line in f1: tmp = line.strip().split("\t") tmp[0] = normalizer.normalize(tmp[0]) corpus.append(tmp) for row in corpus: UniqueWords = len(set(row[0].split())) print (UniqueWords) </code></pre> <p>The sample data:</p> <p>باد بارش برف وزش باد، کولاک یخبندان سطح wind</p>
0
2016-09-19T19:11:59Z
39,580,682
<p>You an use <code>collections.Counter</code> in order to count the number of words after splitting:</p> <pre><code>from collections import Counter from itertools import chain def WordsProbs (file_name): with open (file_name, encoding = "utf-8") as f1: all_words = chain.from_iterable(word_tokenizer(line.split(None, 1)[0]) for line in f1) return Counter(all_words) </code></pre> <p>The <code>chain.from_iterable</code> will chain the splitted words together as an integrated iterator, so that the <code>Counter</code> can create a counter object from all of the words.</p> <p>If you just want the number of all unique words <code>len(WordsProbs(file_name))</code> will give you that, but another way is using a set on the iterator that we created with <code>cahin.from_iterable</code>:</p> <pre><code>def WordsProbs (file_name): with open (file_name, encoding = "utf-8") as f1: all_words = chain.from_iterable(word_tokenizer(line.split(None, 1)[0]) for line in f1) return len(set(all_words)) </code></pre> <p>And if you want the number of unique words for each line:</p> <pre><code>def WordsProbs (file_name): with open (file_name, encoding = "utf-8") as f1: each_line_numbers = [len(set(word_tokenizer(line.split(None, 1)[0]))) for line in f1) return each_line_numbers </code></pre>
0
2016-09-19T19:29:58Z
[ "python", "nlp" ]
calculate the totall number of uniqe words of the first column of a list
39,580,452
<p>I have a file that consists of many Persian sentences. each line contains a sentence, then a "tab", then a word, again a "tab" and then an English word. I have to know just the number of unique words of the sentences (the words after tabs should not be in calculation). For that I changed the file to a list, so I have a list that contains a lot of lines and each line contains three indices; the sentence, a Persian word, an English word. Now I can achieve the sentences. The problem is that, the code I wrote returns the number of unique words of each line separately. For example if the file has 100 lines it returns 100 numbers, each in a new line. But I want the summation of all the numbers and have just one number which shows the total number of unique words. How can I change the code?</p> <pre><code>from hazm import* def WordsProbs (file): with open (file, encoding = "utf-8") as f1: normalizer = Normalizer() for line in f1: tmp = line.strip().split("\t") tmp[0] = normalizer.normalize(tmp[0]) corpus.append(tmp) for row in corpus: UniqueWords = len(set(row[0].split())) print (UniqueWords) </code></pre> <p>The sample data:</p> <p>باد بارش برف وزش باد، کولاک یخبندان سطح wind</p>
0
2016-09-19T19:11:59Z
39,581,184
<p>Assuming tmp[0] contains the sentence from each line, the individual words in the sentence can be counted without building a corpus.</p> <pre><code>from hazm import* def WordsProbs (file): words = set() with open (file, encoding = "utf-8") as f1: normalizer = Normalizer() for line in f1: tmp = line.strip().split("\t") words.update(set(normalizer.normalize(tmp[0].split()))) print(len(words), "unique words") </code></pre> <p>I can't test it because on my machine, the English word "wind" shows up in the first column after cutting and pasting your sample data.</p>
0
2016-09-19T20:03:16Z
[ "python", "nlp" ]
PyQt - Dialog in another thread
39,580,473
<p>my program has a main window and in this window it runs a thread to read the power from a photodetector then it sends a signal, which is captured by a slot in the main window that updates the main window's gui. </p> <p>Then I have another widget (let's call it programming widget) that pops from the main window, which is basically a plain text into which the user can insert commands so the program will execute them. Now the issue comes:</p> <p>When I just open the programming widget with "show", the main window keeps updating the photodetector. However, when I start executing a sequence from the programming widget the main window freezes and the photodetector readings stops with it while is executing the commands (I guess it keeps reading because is in another thread but it stops updating the main window's gui).</p> <p>My question is: The programming widget is already, by default, in another thread since the main window keeps working when it's popped. So, why it (main window)freezes when the programming widget is in a loop?</p> <p>Here is the Thread code:</p> <pre><code>class PDThread(QtCore.QThread): valueupdate = QtCore.pyqtSignal(float) state = 1 def __init__(self, state, port): QtCore.QThread.__init__(self) self.photodetector = PM100D() self.port = port def run(self): while True: try: self.photodetector.connect(self.port) break except: self.dialog = dialog_classes.DialogPort() self.dialog.set_instrument('PM100D') self.dialog.exec_() ret = self.dialog.pm100d.itemText(self.dialog.pm100d.currentIndex()) if ret == QtGui.QDialog.Accepted: self.port = str(ret) else: self.photodetector.__del__() self.quit() return window.PDState = 1 window.startpd.setText('Stop PD') while self.state == 1: time.sleep(0.1) value = self.photodetector.get_pow() self.valueupdate.emit(value) </code></pre> <p>Here is the function that creates the thread and the slot in the main window:</p> <pre><code>def ActionConnect_PM100D(self): if self.PDState == 0: self.PD = PDThread(self.PDState, self.PDport) self.PD.valueupdate.connect(self.PDHandler) self.threads = [] self.threads.append(self.PD) self.PD.start() else: self.PDState = 0 self.PD.state = 0 self.startpd.setText('Start PD') def PDHandler(self, value): ref = float(self.refpd.value()) self.outputpd.setText(str(value-ref)) </code></pre> <p>Here also in the main window, the function that creates the widget:</p> <pre><code> def ActionSetup(self): self.program = dialog_classes.Programming(self.newport, self.output, self.outputpd) self.program.show() </code></pre> <p>Finally, the widget code:</p> <pre><code>class Programming(QtGui.QDialog, Ui_Programming_Dialog, gui.MyApp): def __init__(self, ESP300, output, outputpd): QtGui.QDialog.__init__(self) self.setupUi(self) self.setWindowTitle('Programming Setup') self.openbuttom.clicked.connect(self.Open) self.save.clicked.connect(self.Save) self.execute.clicked.connect(self.Execute) self.newport = ESP300 self.output = output self.outputpd = outputpd def Open(self): self.fileName = QtGui.QFileDialog.getOpenFileName(self, 'OpenFile', '', '*.txt') try: text = open(self.fileName).read() except: None else: self.program.setPlainText(text) def Save(self): self.fileName = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '', '*.txt') try: open(self.fileName, 'w').write(str(self.program.toPlainText())) except: None def Execute(self): text = str(self.program.toPlainText()) lines = text.split('\n') for line in lines: arg = [] List = line.split(',') for word in List: arg.append(word.strip()) if arg[0].lower() == 'move': if arg[1].lower() == 'x': self.newport.move_x(float(arg[2])) elif arg[1].lower() == 'y': self.newport.move_y(float(arg[2])) elif arg[1].lower() == 'z': self.newport.move_z(float(arg[2])) elif arg[0].lower() == 'wait': self.newport.wait() elif arg[0].lower() == 'home': self.newport.home() while True: try: self.GetPosition() except: time.sleep(0.5) else: if self.newport.x == 0 and self.newport.y == 0 and self.newport.z == 0: break elif arg[0].lower() == 'power on': self.newport.power_on(arg[1]) elif arg[0].lower() == 'power off': self.newport.power_off(arg[1]) elif arg[0].lower() == 'pos': self.newport.pos_x(arg[1]) self.newport.pos_y(arg[2]) self.newport.pos_z(arg[3]) while True: try: self.GetPosition() except: time.sleep(0.5) else: time.sleep(1) break elif arg[0].lower() == 'get pos': self.GetPosition() elif arg[0].lower() == 'get error': self.GetError() elif arg[0].lower() == 'get pow': print(self.outputpd.toPlainText()) time.sleep(2) def closeIt(self): self.close() </code></pre> <p>Thank you for your support.</p>
0
2016-09-19T19:13:28Z
39,583,114
<p>Generally, the way this is done is to create a class derived from <code>QObject</code> that handles all the non-Qt data collection and move that into a separate thread using the <a href="http://stackoverflow.com/a/38003561/1547004">worker model</a>.</p> <p>Then, you can use signals to pass data back and forth between the main (GUI) thread and the Worker thread, and to trigger events (like popping up a dialog in the main thread because of an event in the worker thread).</p>
0
2016-09-19T22:38:11Z
[ "python", "multithreading", "qt", "dialog", "pyqt" ]
PyQt - Dialog in another thread
39,580,473
<p>my program has a main window and in this window it runs a thread to read the power from a photodetector then it sends a signal, which is captured by a slot in the main window that updates the main window's gui. </p> <p>Then I have another widget (let's call it programming widget) that pops from the main window, which is basically a plain text into which the user can insert commands so the program will execute them. Now the issue comes:</p> <p>When I just open the programming widget with "show", the main window keeps updating the photodetector. However, when I start executing a sequence from the programming widget the main window freezes and the photodetector readings stops with it while is executing the commands (I guess it keeps reading because is in another thread but it stops updating the main window's gui).</p> <p>My question is: The programming widget is already, by default, in another thread since the main window keeps working when it's popped. So, why it (main window)freezes when the programming widget is in a loop?</p> <p>Here is the Thread code:</p> <pre><code>class PDThread(QtCore.QThread): valueupdate = QtCore.pyqtSignal(float) state = 1 def __init__(self, state, port): QtCore.QThread.__init__(self) self.photodetector = PM100D() self.port = port def run(self): while True: try: self.photodetector.connect(self.port) break except: self.dialog = dialog_classes.DialogPort() self.dialog.set_instrument('PM100D') self.dialog.exec_() ret = self.dialog.pm100d.itemText(self.dialog.pm100d.currentIndex()) if ret == QtGui.QDialog.Accepted: self.port = str(ret) else: self.photodetector.__del__() self.quit() return window.PDState = 1 window.startpd.setText('Stop PD') while self.state == 1: time.sleep(0.1) value = self.photodetector.get_pow() self.valueupdate.emit(value) </code></pre> <p>Here is the function that creates the thread and the slot in the main window:</p> <pre><code>def ActionConnect_PM100D(self): if self.PDState == 0: self.PD = PDThread(self.PDState, self.PDport) self.PD.valueupdate.connect(self.PDHandler) self.threads = [] self.threads.append(self.PD) self.PD.start() else: self.PDState = 0 self.PD.state = 0 self.startpd.setText('Start PD') def PDHandler(self, value): ref = float(self.refpd.value()) self.outputpd.setText(str(value-ref)) </code></pre> <p>Here also in the main window, the function that creates the widget:</p> <pre><code> def ActionSetup(self): self.program = dialog_classes.Programming(self.newport, self.output, self.outputpd) self.program.show() </code></pre> <p>Finally, the widget code:</p> <pre><code>class Programming(QtGui.QDialog, Ui_Programming_Dialog, gui.MyApp): def __init__(self, ESP300, output, outputpd): QtGui.QDialog.__init__(self) self.setupUi(self) self.setWindowTitle('Programming Setup') self.openbuttom.clicked.connect(self.Open) self.save.clicked.connect(self.Save) self.execute.clicked.connect(self.Execute) self.newport = ESP300 self.output = output self.outputpd = outputpd def Open(self): self.fileName = QtGui.QFileDialog.getOpenFileName(self, 'OpenFile', '', '*.txt') try: text = open(self.fileName).read() except: None else: self.program.setPlainText(text) def Save(self): self.fileName = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '', '*.txt') try: open(self.fileName, 'w').write(str(self.program.toPlainText())) except: None def Execute(self): text = str(self.program.toPlainText()) lines = text.split('\n') for line in lines: arg = [] List = line.split(',') for word in List: arg.append(word.strip()) if arg[0].lower() == 'move': if arg[1].lower() == 'x': self.newport.move_x(float(arg[2])) elif arg[1].lower() == 'y': self.newport.move_y(float(arg[2])) elif arg[1].lower() == 'z': self.newport.move_z(float(arg[2])) elif arg[0].lower() == 'wait': self.newport.wait() elif arg[0].lower() == 'home': self.newport.home() while True: try: self.GetPosition() except: time.sleep(0.5) else: if self.newport.x == 0 and self.newport.y == 0 and self.newport.z == 0: break elif arg[0].lower() == 'power on': self.newport.power_on(arg[1]) elif arg[0].lower() == 'power off': self.newport.power_off(arg[1]) elif arg[0].lower() == 'pos': self.newport.pos_x(arg[1]) self.newport.pos_y(arg[2]) self.newport.pos_z(arg[3]) while True: try: self.GetPosition() except: time.sleep(0.5) else: time.sleep(1) break elif arg[0].lower() == 'get pos': self.GetPosition() elif arg[0].lower() == 'get error': self.GetError() elif arg[0].lower() == 'get pow': print(self.outputpd.toPlainText()) time.sleep(2) def closeIt(self): self.close() </code></pre> <p>Thank you for your support.</p>
0
2016-09-19T19:13:28Z
39,616,388
<p>I tried moving the Execute method to another thread using the <strong>worker model</strong> as suggested but it also froze the gui, I don't know why. Probably I did something wrong.</p> <p>However, when I created another thread directly in the Class implemented to execute the loop and it worked. I followed this example: <a href="https://nikolak.com/pyqt-threading-tutorial/" rel="nofollow">https://nikolak.com/pyqt-threading-tutorial/</a></p> <p>In addition, here is my code. I hope it can help others as well, thank you.</p> <pre><code>self.worker_thread = [] def Execute(self): self.execution = ProgramExecution(self.newport, self.output, self.outputpd, self.program) self.worker_thread.append(self.execution) self.execution.start() </code></pre> <p>And here is the Thread Class:</p> <pre><code>class ProgramExecution(QtCore.QThread): _signalStatus = QtCore.pyqtSignal(str) def __init__(self, ESP300, output, outputpd, program): QtCore.QThread.__init__(self) self.newport = ESP300 self.output = output self.outputpd = outputpd self.program = program def __del__(self): self.wait() def run(self): text = str(self.program.toPlainText()) lines = text.split('\n') for line in lines: arg = [] List = line.split(',') for word in List: arg.append(word.strip()) if arg[0].lower() == 'move': if arg[1].lower() == 'x': self.newport.move_x(float(arg[2])) elif arg[1].lower() == 'y': self.newport.move_y(float(arg[2])) elif arg[1].lower() == 'z': self.newport.move_z(float(arg[2])) elif arg[0].lower() == 'wait': self.newport.wait() elif arg[0].lower() == 'home': self.newport.home() while True: try: self.GetPosition() except: time.sleep(0.5) else: if self.newport.x == 0 and self.newport.y == 0 and self.newport.z == 0: break elif arg[0].lower() == 'power on': self.newport.power_on(arg[1]) elif arg[0].lower() == 'power off': self.newport.power_off(arg[1]) elif arg[0].lower() == 'pos': self.newport.pos_x(arg[1]) self.newport.pos_y(arg[2]) self.newport.pos_z(arg[3]) while True: try: self.GetPosition() except: time.sleep(0.5) else: time.sleep(1) break elif arg[0].lower() == 'get pos': self.GetPosition() elif arg[0].lower() == 'get error': self.GetError() elif arg[0].lower() == 'get pow': print(self.outputpd.toPlainText()) time.sleep(2) </code></pre>
0
2016-09-21T12:19:18Z
[ "python", "multithreading", "qt", "dialog", "pyqt" ]
Levenshtein edit distance Python
39,580,488
<p>This piece of code returns the Levenshtein edit distance of 2 terms. How can i make this so that insertion and deletion only costs 0.5 instead of 1 ? substitution should still costs 1.</p> <pre><code>def substCost(x,y): if x == y: return 0 else: return 1 def levenshtein(target, source): i = len(target); j = len(source) if i == 0: return j elif j == 0: return i return(min(levenshtein(target[:i-1],source)+1, levenshtein(target, source[:j-1])+1, levenshtein(target[:i-1], source[:j-1])+substCost(source[j-1],target[i-1]))) </code></pre>
0
2016-09-19T19:15:32Z
39,582,342
<p>There are two places you need to account for the reduced cost of adding or removing a vowel. They are the <code>return j</code> and <code>return i</code> lines in the base cases of your function, and the <code>+1</code>s in the <code>min</code> call after the first two recursive calls.</p> <p>We need to change each of those to use a "ternary" expression: <code>0.5 if ch in 'aeiou' else 1</code> in place of assuming a cost of <code>1</code> per character added or removed.</p> <p>For the base cases, we can replace the return values with <code>sum</code> calls on a generator expression that includes the ternary expression:</p> <pre><code>if i == 0: return sum(0.5 if ch in 'aeiou' else 1 for ch in source) elif j == 0: return sum(0.5 if ch in 'aeiou' else 1 for ch in target) </code></pre> <p>For later cases, we can replace the <code>+1</code> with the ternary expression itself (with an index rather than the <code>ch</code> iteration variable):</p> <pre><code>return min(levenshtein(target[:i-1],source) + (0.5 if target[-1] in 'aeiou' else 1), levenshtein(target, source[:j-1]) + (0.5 if source[-1] in 'aeiou' else 1), levenshtein(target[:i-1], source[:j-1])+substCost(source[j-1],target[i-1])) </code></pre> <p>If you wanted to generalize this, you could move the ternary expression out into its own function, named something like <code>addCost</code>, and call it from the code in the <code>levenshtein</code> function.</p>
1
2016-09-19T21:23:00Z
[ "python", "levenshtein-distance" ]