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
How to do calculation on pandas dataframe that require processing multiple rows?
39,919,672
<p>I have a dataframe from which I need to calculate a number of features from. The dataframe <code>df</code> looks something like this for a object and an event:</p> <pre><code>id event_id event_date age money_spent rank 1 100 2016-10-01 4 150 2 2 100 2016-09-30 5 10 4 1 101 2015-12-28 3 350 3 2 102 2015-10-25 5 400 5 3 102 2015-10-25 7 500 2 1 103 2014-04-15 2 1000 1 2 103 2014-04-15 3 180 6 </code></pre> <p>From this I need to know for each id and event_id (basically each row), what was the number of days since the last event date, total money spend upto that date, avg. money spent upto that date, rank in last 3 events etc.</p> <p>What is the best way to work with this kind of problem in pandas where for each row I need information from all rows with the same <code>id</code> before the date of that row, and so the calculations? I want to return a new dataframe with the corresponding calculated features like</p> <pre><code>id event_id event_date days_last_event avg_money_spent total_money_spent 1 100 2016-10-01 278 500 1500 2 100 2016-09-30 361 196.67 590 1 101 2015-12-28 622 675 1350 2 102 2015-10-25 558 290 580 3 102 2015-10-25 0 500 500 1 103 2014-04-15 0 1000 1000 2 103 2014-04-15 0 180 180 </code></pre>
1
2016-10-07T14:28:29Z
39,922,162
<p>Sort the <code>event_date</code> column in ascending order and choose the first date which corresponds to the earliest date and compute the results(in days) after subtracting it with the other dates:</p> <pre><code>min_date = df.sort_values(by=['event_date'])['event_date'].iloc[0] df['days_last_event'] = (df['event_date'] - min_date).dt.days </code></pre> <p>Sort the <code>DF</code> by the number of days and making sure it starts from 0 at the very top:</p> <pre><code>df.sort_values(['days_last_event'], inplace=True) </code></pre> <p>Grouping with key as the <code>id</code> column and taking <code>money_spent</code> as our selection and taking it's cumulative sum across groups:</p> <pre><code>grp_1 = df.groupby('id')['money_spent'] df['total_money_spent'] = grp_1.apply(lambda x: x.cumsum()).sort_index() </code></pre> <p>Grouping with key as the <code>id</code> column and taking <code>total_money_spent</code> as our selection and dividing with the cumulative count of the previous groupby object to compute the cumulative average/mean.</p> <pre><code>grp_2 = df.groupby(['id'])['total_money_spent'] df['avg_money_spent'] = (grp_2.head()).div(grp_1.cumcount()+1) </code></pre> <p>Finally, drop off the unwanted columns to get:</p> <pre><code>df.sort_index().drop(['age', 'rank', 'money_spent'], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/VMz0V.png" rel="nofollow"><img src="http://i.stack.imgur.com/VMz0V.png" alt="Image"></a></p>
0
2016-10-07T16:40:21Z
[ "python", "python-2.7", "pandas" ]
How can I use unittest.mock to remove side effects from code?
39,919,699
<p>I have a function with several points of failure:</p> <pre><code>def setup_foo(creds): """ Creates a foo instance with which we can leverage the Foo virtualization platform. :param creds: A dictionary containing the authorization url, username, password, and version associated with the Foo cluster. :type creds: dict """ try: foo = Foo(version=creds['VERSION'], username=creds['USERNAME'], password=creds['PASSWORD'], auth_url=creds['AUTH_URL']) foo.authenticate() return foo except (OSError, NotFound, ClientException) as e: raise UnreachableEndpoint("Couldn't find auth_url {0}".format(creds['AUTH_URL'])) except Unauthorized as e: raise UnauthorizedUser("Wrong username or password.") except UnsupportedVersion as e: raise Unsupported("We only support Foo API with major version 2") </code></pre> <p>and I'd like to test that all the relevant exceptions are caught (albeit not handled well currently).</p> <p>I have an initial test case that passes:</p> <pre><code>def test_setup_foo_failing_auth_url_endpoint_does_not_exist(self): dummy_creds = { 'AUTH_URL' : 'http://bogus.example.com/v2.0', 'USERNAME' : '', #intentionally blank. 'PASSWORD' : '', #intentionally blank. 'VERSION' : 2 } with self.assertRaises(UnreachableEndpoint): foo = osu.setup_foo(dummy_creds) </code></pre> <p>but how can I make my test framework believe that the AUTH_URL is actually a valid/reachable URL?</p> <p>I've created a mock class for <code>Foo</code>:</p> <pre><code>class MockFoo(Foo): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) </code></pre> <p>and my thought is mock the call to <code>setup_foo</code> and remove the side effect of raising an <code>UnreachableEndpoint</code> exception. I know how to <em>add</em> side-effects to a <code>Mock</code> with <code>unittest.mock</code>, but how can I remove them?</p>
3
2016-10-07T14:29:13Z
39,920,128
<p>Assuming your exceptions are being raised from <code>foo.authenticate()</code>, what you want to realize here is that it does not necessarily matter whether the data is in fact <em>really</em> valid in your tests. What you are trying to say really is this: </p> <p>When this external method raises with something, my code should behave accordingly based on that something. </p> <p>So, with that in mind, what you want to do is have different test methods where you pass what <em>should</em> be valid data, and have your code react accordingly. The data itself does not matter, but it provides a documented way of showing how the code should behave with data that is passed in that way. </p> <p>Ultimately, you should not care how the nova client handles the data you give it (nova client is tested, and you should not care about it). What you care about is what it spits back at you and how you want to handle it, regardless of what you gave it. </p> <p>In other words, for the sake of your tests, you can actually pass a dummy url as: </p> <pre><code>"this_is_a_dummy_url_that_works" </code></pre> <p>For the sake of your tests, you can let that pass, because in your <code>mock</code>, you will raise accordingly. </p> <p>For example. What you should be doing here is actually mocking out <code>Client</code> from <code>novaclient</code>. With that mock in hand, you can now manipulate whatever call within novaclient so you can properly test your code.</p> <p>This actually brings us to the root of your problem. Your first exception is catching the following:</p> <pre><code>except (OSError, NotFound, ClientException) </code></pre> <p>The problem here, is that you are now catching <code>ClientException</code>. Almost every exception in <code>novaclient</code> inherits from <code>ClientException</code>, so no matter what you try to test beyond that exception line, you will never reach those exceptions. You have two options here. Catch <code>ClientException</code>, and just raise a custom exception, or, remote <code>ClientException</code>, and be more explicit (like you already are).</p> <p>So, let us go with removing <code>ClientException</code> and set up our example accordingly. </p> <p>So, in your <em>real</em> code, you should be now setting your first exception line as:</p> <pre><code>except (OSError, NotFound) as e: </code></pre> <p>Furthermore, the next problem you have is that you are not mocking properly. You are supposed to mock with respect to where you are testing. So, if your <code>setup_nova</code> method is in a module called <code>your_nova_module</code>. It is with respect to that, that you are supposed to mock. The example below illustrates all this. </p> <pre><code>@patch("your_nova_module.Client", return_value=Mock()) def test_setup_nova_failing_unauthorized_user(self, mock_client): dummy_creds = { 'AUTH_URL': 'this_url_is_valid', 'USERNAME': 'my_bad_user. this should fail', 'PASSWORD': 'bad_pass_but_it_does_not_matter_what_this_is', 'VERSION': '2.1', 'PROJECT_ID': 'does_not_matter' } mock_nova_client = mock_client.return_value mock_nova_client.authenticate.side_effect = Unauthorized(401) with self.assertRaises(UnauthorizedUser): setup_nova(dummy_creds) </code></pre> <p>So, the main idea with the example above, is that it does not matter what data you are passing. What really matters is that you are wanting to know how your code will react when an external method raises.</p> <p>So, our goal here is to actually raise something that will get your second exception handler to be tested: <code>Unauthorized</code></p> <p>This code was tested against the code you posted in your question. The only modifications were made were with module names to reflect my environment.</p>
2
2016-10-07T14:51:34Z
[ "python", "unit-testing", "python-3.x", "exception-handling", "python-unittest.mock" ]
How can I use unittest.mock to remove side effects from code?
39,919,699
<p>I have a function with several points of failure:</p> <pre><code>def setup_foo(creds): """ Creates a foo instance with which we can leverage the Foo virtualization platform. :param creds: A dictionary containing the authorization url, username, password, and version associated with the Foo cluster. :type creds: dict """ try: foo = Foo(version=creds['VERSION'], username=creds['USERNAME'], password=creds['PASSWORD'], auth_url=creds['AUTH_URL']) foo.authenticate() return foo except (OSError, NotFound, ClientException) as e: raise UnreachableEndpoint("Couldn't find auth_url {0}".format(creds['AUTH_URL'])) except Unauthorized as e: raise UnauthorizedUser("Wrong username or password.") except UnsupportedVersion as e: raise Unsupported("We only support Foo API with major version 2") </code></pre> <p>and I'd like to test that all the relevant exceptions are caught (albeit not handled well currently).</p> <p>I have an initial test case that passes:</p> <pre><code>def test_setup_foo_failing_auth_url_endpoint_does_not_exist(self): dummy_creds = { 'AUTH_URL' : 'http://bogus.example.com/v2.0', 'USERNAME' : '', #intentionally blank. 'PASSWORD' : '', #intentionally blank. 'VERSION' : 2 } with self.assertRaises(UnreachableEndpoint): foo = osu.setup_foo(dummy_creds) </code></pre> <p>but how can I make my test framework believe that the AUTH_URL is actually a valid/reachable URL?</p> <p>I've created a mock class for <code>Foo</code>:</p> <pre><code>class MockFoo(Foo): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) </code></pre> <p>and my thought is mock the call to <code>setup_foo</code> and remove the side effect of raising an <code>UnreachableEndpoint</code> exception. I know how to <em>add</em> side-effects to a <code>Mock</code> with <code>unittest.mock</code>, but how can I remove them?</p>
3
2016-10-07T14:29:13Z
39,920,186
<p>If you wish to mock out http servers from bogus urls, I suggest you check out <a href="https://github.com/gabrielfalcao/HTTPretty" rel="nofollow">HTTPretty</a>. It mocks out urls at a socket level so it can trick most Python HTTP libraries that it's a valid url.</p> <p>I suggest the following setup for your unittest:</p> <pre><code>class FooTest(unittest.TestCase): def setUp(self): httpretty.register_uri(httpretty.GET, "http://bogus.example.com/v2.0", body='[{"response": "Valid"}]', content_type="application/json") @httpretty.activate def test_test_case(self): resp = requests.get("http://bogus.example.com/v2.0") self.assertEquals(resp.status_code, 200) </code></pre> <p>Note that the mock will only apply to stacks that are decorated with <code>http.activate</code> decorator, so it won't leak to other places in your code that you don't want to mock. Hope that makes sense.</p>
0
2016-10-07T14:53:50Z
[ "python", "unit-testing", "python-3.x", "exception-handling", "python-unittest.mock" ]
UnicodeDecodeError Help: Data needs to be in ascii for seaborn but source code is in utf-8
39,919,704
<p>Context: I'm trying to build a seaborn heatmap in order to map the following type of data (in a dataframe):</p> <p><a href="http://i.stack.imgur.com/NFZAj.png" rel="nofollow"><img src="http://i.stack.imgur.com/NFZAj.png" alt="enter image description here"></a></p> <p>(This can be up to 50 fruits and 5500 stores)</p> <p>My problem (I think) is that seaborn appears to want to use ascii but my data is in utf-8. When I read the csv file, I can't do the following:</p> <pre><code>df = pd.read_csv('data.csv', encoding = 'ascii') </code></pre> <p>without getting the following error:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 3: ordinal not in range(128) </code></pre> <p>When I bring it in using utf-8, it will read and I can reshape it to heatmap-friendly form but then when trying to run:</p> <pre><code>sns.heatmap(df2) </code></pre> <p>I get a similar UnicodeDecodeError</p> <p>I do have simple special characters (colons, backspaces, etc.) in either my store or fruit fields so I'm wondering what the best approach is here. </p> <ul> <li>Should I run something on my dataframe to remove the utf-8 character then encode in ascii? </li> <li>Should I be doing something to my source .csv file to remove the utf-8 characters?</li> <li>Can I run seaborn another way to let is accept the encoding I have?</li> </ul> <p>If anybody has a preferred method, can they help me with the proper code to get it done?</p> <p>Python version 2.7.12 :: Anaconda 4.1.1 (64-bit) Pandas (0.18.1) Seaborn (0.7.1)</p>
2
2016-10-07T14:29:22Z
39,920,926
<p>Your configuration (Python 2.7, Pandas 0.18.1, Seaborn 0.7.1) should certainly be able to handle utf-8. Even if the font used in the plot doesn't support these unicode characters, the heatmap should still be displayed. Here is a test case:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd import seaborn as sns df = pd.DataFrame( {'Fruit': ['Apple', 'Banana', 'Orange', 'Kiwi'] * 2, 'Store': [u'Kr\xf6ger'] * 4 + [u'F\u0254\u0254d Li\u01ebn'] * 4, 'Stock': [6, 1, 3, 4, 1, 7, 7, 9]}) sns.heatmap(df.pivot("Fruit", "Store", "Stock")) </code></pre> <p>The problem, therefore, is somewhere in your data frame <code>df2</code>. Your comment states that <code>df2</code> is created by reshaping another data frame, probably also by something like <code>pivot()</code> or <code>crosstab()</code>. </p> <p>Let's assume that this original data frame contains the columns <code>Store</code> and <code>Fruit</code>, and that it was read from your file like so, i.e. with default encoding:</p> <pre><code>raw = pd.read_csv('data.csv') </code></pre> <p>For testing, this is the content of that file <code>data.csv</code>:</p> <pre class="lang-none prettyprint-override"><code>Store,Fruit,Stock Kröger,Apple,6 Kröger,Banana,1 Kröger,Orange,3 Kröger,Kiwi,4 Fɔɔd Liǫn,Apple,1 Fɔɔd Liǫn,Banana,7 Fɔɔd Liǫn,Orange,7 Fɔɔd Liǫn,Kiwi,9 </code></pre> <p>Now, in order to fix the encoding of columns <code>Store</code> and <code>Fruit</code> so that they contain valid Unicode strings, use the <a href="https://docs.python.org/2/library/stdtypes.html#str.decode" rel="nofollow"><code>decode()</code></a> string method, like so:</p> <pre><code>raw["Store"] = raw["Store"].apply(lambda x: x.decode("utf-8")) raw["Fruit"] = raw["Fruit"].apply(lambda x: x.decode("utf-8")) </code></pre> <p>Now, <code>heatmap()</code> should work happily with the data frame:</p> <pre><code>sns.heatmap(raw.pivot("Fruit", "Store", "Stock")) </code></pre>
1
2016-10-07T15:31:42Z
[ "python", "pandas", "unicode", "encoding", "seaborn" ]
Click through pagination with Selenium in Python
39,919,744
<p>I'm working on building an automation framework using Selenium in Python where I am trying to loop through landing pages on HubSpot.com by clicking on the "Next" button.</p> <p>The Next button is located in the following HTML according to the Chrome Inspector:</p> <pre><code>&lt;a class="next" data-reactid=".0.1.0.0.2.1.0.0.1.0.$next.0"&gt; &lt;span data-reactid=".0.1.0.0.2.1.0.0.1.0.$next.0.1"&gt;Next&lt;/span&gt; &lt;span class="right" data-reactid=".0.1.0.0.2.1.0.0.1.0.$next.0.2"&gt;&lt;/span&gt; &lt;/a&gt; </code></pre> <p>And I'm clicking the button using the following Python code:</p> <pre><code>time.sleep(3) wait(self.driver, """//a[@class="next" and not(@disabled)]""") nextButton = self.driver.find_element(By.XPATH, """//a[@class="next" and not(@disabled)]""") hov = ActionChains(self.driver).move_to_element(nextButton) hov.click().perform() </code></pre> <p>where my wait() function is defined as:</p> <pre><code>def wait(dr, x): element = WebDriverWait(dr, 5).until( EC.presence_of_element_located((By.XPATH, x)) ) return element </code></pre> <p>This works perfectly fine on the first page. But for some reason when I get to page two, it's not able to click the button. No errors, it just starts doing what it should on page three - but on page two. Also, if I stop the script just before it's supposed to click on the Next button on page two, I can see that the button is highlighted in the Chromedriver.</p> <p>The Next button is located in the following HTML on page 2 according to the Chrome Inspector::</p> <pre><code>&lt;a class="next" data-reactid=".0.1.0.0.2.1.0.0.1.0.$next.0"&gt; &lt;span data-reactid=".0.1.0.0.2.1.0.0.1.0.$next.0.1"&gt;Next&lt;/span&gt; &lt;span class="right" data-reactid=".0.1.0.0.2.1.0.0.1.0.$next.0.2"&gt;&lt;/span&gt; &lt;/a&gt; </code></pre> <p>Any suggestions? I am out of ideas.</p>
0
2016-10-07T14:30:57Z
39,922,786
<p>I have managed to find a workaround. Instead of trying to click the next button I click the relevant page-button. I define j=2 to begin with, and then use the following code:</p> <pre><code>if self.driver.find_elements(By.XPATH, """//a[@class="next" and not(@disabled)]""") != 0: xpathstring = """//div[@class="hs-pagination"]/ul/li/a[text()="%s"]""" % (j) waitclick(self.driver, xpathstring) nextButton = self.driver.find_element(By.XPATH, xpathstring) hov = ActionChains(self.driver).move_to_element(nextButton) hov.click().perform() time.sleep(3) j = j + 1 </code></pre> <p>I still do not understand why the first solution does not work, but this is a working solution to clicking through pagination.</p>
0
2016-10-07T17:21:44Z
[ "python", "selenium", "onclick", "click" ]
Pyside setData flags on QStandardItem
39,919,748
<p>I have two questions here.</p> <ol> <li><p>Where can I find a list of all the available flags/properties I can set using the setData method of a QstandardItem? I only know of the one below because i came across it online.</p></li> <li><p>How do I set the Font of my QStandardItem to be bold?</p></li> </ol> <p><strong>Python</strong></p> <pre><code>doors = QtGui.QStandardItem("Doors") doors.setData(QtGui.QBrush(QtGui.QColor(200, 10, 255, 255)), role=QtCore.Qt.ForegroundRole) </code></pre>
0
2016-10-07T14:31:12Z
39,923,605
<ol> <li><p>The Qt Documentation lists the <a href="http://doc.qt.io/qt-4.8/qt.html#ItemDataRole-enum" rel="nofollow">item data roles</a>.</p></li> <li><p>The font can be changed like this:</p> <pre><code>font = item.font() font.setBold(True) item.setFont(font) </code></pre></li> </ol>
1
2016-10-07T18:21:22Z
[ "python", "pyside", "qstandarditem" ]
pyplot plot shows a window with no graph
39,919,761
<p>I have several arrays for which I calculate the Frobenius norm. Then I simply draw a graph of these calculated norms vs the index of their corresponding arrays. The problem is that when the plot window pops out, there is no graph on it. But, when I add a styling for my plot, it shows the graph. I also tried to use save figure, but the saved figure just shows a window without any graph on it. The last thing that I tried was to print out the array of the calculated norms, defining it as a numpy array and draw it vs the array of the corresponding indices and it shows me the graph! So, my question is why I cannot draw the graph with pylot plot function. This is what I get when I print out the array of calculated norms:</p> <pre><code>FrobNorm=[[ -3.27415727e-01 2.83421670e+00 -2.59669415e+00 -3.83713705e+00 -1.11064367e+00 -9.83842479e+00 9.64202990e+00 -3.66747069e+00 9.49022713e+00 -3.58659316e+00 4.28355911e+00 -4.58104577e+00 -4.26765959e+00 -6.54306600e-01 4.31816208e+00 1.08043604e+01 3.36647201e+01 -9.47369163e+00 1.41183067e+01 1.75464238e+00 6.84732164e+00 -1.13034176e+01 -1.83641151e+01 -6.07528575e+01 -2.11765783e+01 -3.46253416e+01 -3.50911001e+01 -1.78855570e+01 2.00630855e+01 1.90068192e+01 3.33858144e-01 -1.75526132e+01 -1.34355117e+01 -8.39318642e+00 -1.96338714e+01 -5.80396650e+01 -1.52712614e+01 -7.95109842e+00 -1.14383666e+01 -4.29497153e+00 -1.97874688e+01 -1.32635215e+01 3.10595354e+00 3.30488466e-01 1.24957569e+00 2.32608957e+01 -5.12962561e-01 3.23879652e+00 1.80536181e+01 1.64091731e+01 2.46815567e+01 2.01190758e+01 2.25210602e+01 1.92789009e+01 4.32809711e+01 1.24060317e+02 5.11700004e+00 2.56249967e+00 3.27317719e+01 3.01294858e+01 2.96865339e+01 2.01666494e+01 -1.75473758e+00 -9.73091969e+00 -1.51961382e+01 8.11369952e+00 -1.74469244e+01 5.94097932e+00 -5.43142631e+00 -4.40072150e+00 -1.51168549e+01 -5.58957352e+00 -2.34872324e+04 9.19836593e+02 6.76833045e+03 7.59304882e+03 1.77573454e+03 9.71109062e+02 1.63742243e+03 3.70221807e+02 1.01405251e+03 4.06811235e+02 1.45049823e+02 1.43212472e+02 8.88928849e+01 3.10859242e+02 4.79435420e+01 6.86347162e+01 2.14372829e+01 5.43555421e+01 1.39810283e+01 9.51714116e+00 4.98563968e+01 4.02058896e+01 1.61359027e+02 7.91939932e+00 1.73949723e+01 5.19412047e+01 1.89645369e+01 2.25526021e+01 1.36734416e+01 3.13646035e+01 2.02633125e+01 5.16259077e+01 7.34024536e+01 2.01376746e+01 8.50796026e+00 1.76689397e+01 5.32159344e+01 1.75182361e+01 2.38797434e+01 2.21623152e+01 2.15496171e+01 1.56287225e+01 7.12160153e+01 1.20319418e+01 -2.14376043e-01 -2.16844613e+00 7.31383577e+00 9.60358643e+00 1.53346738e+01 -1.75376507e+01 -4.23607412e+01 -1.34004685e+01 -5.74096286e+01 -1.88056408e+01 1.24411854e+00 -2.20228598e+00 -1.44691587e+01 -4.02906454e+00 -7.06859151e+00 -9.28329296e-01 3.97785623e+00 -1.17290825e+01 5.30538782e+00 -1.30573008e+00 2.57332085e-01 -5.03652416e+00 -8.01889243e+00 -4.21210481e+00 7.97575488e+00 1.33063141e+01 1.94559898e+01 1.30643051e+01 1.39963350e+00 1.31746057e+01 4.87291463e-01 7.62221548e+00 1.90832548e+00 -9.17783469e+00 -6.74190235e+00 -5.18322407e+00 2.08694160e+00 -8.32251763e+00 -3.41052019e+01 -4.07077413e+00 -5.35572194e+00 -1.00300755e+01 -1.85180723e+00 -2.85137343e+00 -2.92087149e+00 5.82955457e+00 4.00575111e+00 1.17418771e+01 2.13152055e+01 6.74130687e+00 2.89890044e+00 9.56403257e+00 9.49920338e+00 -4.90698086e+00 -4.31125932e-01 7.43422603e+00 -1.36522668e+00 6.71239870e+00 2.97819245e+01 2.70232682e+00 1.43525496e+01 7.69774164e-01 6.11231825e+00 1.48208154e+00 -2.23136432e+00 4.61075719e+00 -3.59137897e+01 -1.62455157e+01 -6.07367620e+01 -2.62556836e+00 -1.64717047e-01 -1.33588774e+01 -8.23873116e+00 -4.69412397e+00 -8.64679071e+00 -7.05601974e+00 9.42962930e+00 -1.08717341e+01 -5.27810809e+01 -8.69225245e+00 -4.99076301e+00]] </code></pre> <p>When I plot the graph vs its indices array, I only get the window with no graph:</p> <pre><code>plt.plot(numVec,FrobNorm) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/5eWky.png" rel="nofollow"><img src="http://i.stack.imgur.com/5eWky.png" alt="enter image description here"></a></p> <p>But, when I use a styling for the plot it shows the graph (something like scatter plot, which I am not interested in):</p> <pre><code>plt.plot(numVec,FrobNorm,'ro') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/BOZwZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/BOZwZ.png" alt="enter image description here"></a></p> <p>Now, I print the array of calculated norms. comma separate it, and define a numpy array with its elements and simply draw the graph of this numpy array and the corresponding array of indices and I get:</p> <p><a href="http://i.stack.imgur.com/azQx3.png" rel="nofollow"><img src="http://i.stack.imgur.com/azQx3.png" alt="enter image description here"></a></p> <p>I want to get the same thing in the first place. My question is why I cannot get any graph when I plot the calculated norms. As, I said I am not looking for the scatter graph, like in the second figure, which surprisingly is something that I can get only by changing the styling of the figure.</p>
0
2016-10-07T14:31:50Z
39,934,108
<p>I think I got it. I used squeeze and it works. So, the plot line should be changed like this:</p> <pre><code>plt.plot(np.squeeze(NumVec),np.squeeze(FrobNorm)) </code></pre> <p>I still don't understand why, but this is what I guess; I think somehow the format of the numpy arrays that were produced, was in the way that plot function could only see the range of the values without having access to every single element of the arrays. When I didn't use the squeeze function, I got the window without the plot, but the range of the x and y axis were the same as when I could draw the plot in the second and third figures. This is only a guess, I hope someone could help me with the real reason. Thank you for all the feedback!</p>
0
2016-10-08T15:26:53Z
[ "python", "matplotlib", "plot" ]
summation of values in pandas
39,919,828
<p>There is a pandas dataframe with two columns 'key' and 'value'. I want summation of values corresponding to the rows with key in range(key-3,key-1) to be put in a new column 'new_value' in the original dataframe. for eg:</p> <p>df:</p> <pre><code>key value 1 2 2 1 3 1 5 1 7 1 </code></pre> <p>output would be:</p> <pre><code>key value new_value 1 2 0 2 1 2 3 1 3 5 1 2 7 1 1 </code></pre>
-2
2016-10-07T14:35:28Z
39,920,533
<p>You can take a look at this :</p> <pre><code>In [52]: df Out[52]: key value 0 1 2 1 2 1 2 3 1 3 5 1 4 7 1 In [53]: df['new_value'] = df.apply(lambda x: df[(df['key'] &gt;= x['key'] - 3) &amp; (df['key'] &lt;= x['key'] - 1)]['value'].sum(), axis=1) In [54]: df Out[54]: key value new_value 0 1 2 0 1 2 1 2 2 3 1 3 3 5 1 2 4 7 1 1 </code></pre> <p>I'm using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow"><code>apply</code></a> to compute the new value for each row.</p>
0
2016-10-07T15:11:05Z
[ "python", "pandas" ]
Failed ndb transaction attempt not rolling back all changes?
39,919,928
<p>I have some trouble understanding a sequence of events causing a bug in my appplication which can only be seen <strong>intermittently</strong> in the app deployed on GAE, and never when running with the local <code>devserver.py</code>.</p> <p>All the related code snippets below (trimmed for MCV, hopefully I didn't lose anything significant) are executed during handling of <strong>the same</strong> task queue request.</p> <p>The entry point:</p> <pre><code>def job_completed_task(self, _): # running outside transaction as query is made if not self.all_context_jobs_completed(self.context.db_key, self): # this will transactionally enqueue another task self.trigger_job_mark_completed_transaction() else: # this is transactional self.context.jobs_completed(self) </code></pre> <p>The corresponding <code>self.context.jobs_completed(self)</code> is:</p> <pre><code>@ndb.transactional(xg=True) def jobs_completed(self, job): if self.status == QAStrings.status_done: logging.debug('%s jobs_completed %s NOP' % (self.lid, job.job_id)) return # some logic computing step_completed here if step_completed: self.status = QAStrings.status_done # includes self.db_data.put() # this will transactionally enqueue another task job.trigger_job_mark_completed_transaction() </code></pre> <p>The <code>self.status</code> setter, hacked to obtain a traceback for debugging this scenario:</p> <pre><code>@status.setter def status(self, new_status): assert ndb.in_transaction() status = getattr(self, self.attr_status) if status != new_status: traceback.print_stack() logging.info('%s status change %s -&gt; %s' % (self.name, status, new_status)) setattr(self, self.attr_status, new_status) </code></pre> <p>The <code>job.trigger_job_mark_completed_transaction()</code> eventually enqueues a new task like this:</p> <pre><code> task = taskqueue.add(queue_name=self.task_queue_name, url=url, params=params, transactional=ndb.in_transaction(), countdown=delay) </code></pre> <p>The GAE log for the occurence, split as it doesn't fit into a single screen:</p> <p><a href="http://i.stack.imgur.com/kN5ei.png" rel="nofollow"><img src="http://i.stack.imgur.com/kN5ei.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/ktDLu.png" rel="nofollow"><img src="http://i.stack.imgur.com/ktDLu.png" alt="enter image description here"></a></p> <p>My expectation from the <code>jobs_completed</code> transaction is to either see the <code>... jobs_completed ... NOP</code> debug message and no task enqueued or to at least see the <code>status change running -&gt; done</code> info message and a task enqueued by <code>job.trigger_job_mark_completed_transaction()</code>.</p> <p>What I'm actually seeing is both messages and no task enqueued.</p> <p>The logs appears to indicate the transaction is attempted twice:</p> <ul> <li><p>1st time it finds the status not <code>done</code>, so it executes the logic, sets the status to <code>done</code> (and displays the traceback and the info msg) and should transactionally enqueue the new task - but it doesn't</p></li> <li><p>2nd time it finds the status <code>done</code> and just prints the debug message</p></li> </ul> <p>My question is - if the 1st transaction attempt fails shouldn't the status change be rolled back as well? What am I missing?</p>
3
2016-10-07T14:40:01Z
40,059,476
<p>I found a workaround: specifying no retries to the <code>jobs_completed()</code> transaction:</p> <pre><code>@ndb.transactional(xg=True, retries=0) def jobs_completed(self, job): </code></pre> <p>This prevents the automatic repeated execution, instead causing an exception:</p> <blockquote> <p>TransactionFailedError(The transaction could not be committed. Please try again.)</p> </blockquote> <p>Which is acceptable as I already have in place a back-off/retry safety net for the entire <code>job_completed_task()</code>. Things are OK now.</p> <p>As for why the rollback didn't happen, the only thing that crosses my mind is that somehow the entity was read (and cached in my object attribute) prior to entering the transaction, thus not being considered part of the (same) transaction. But I couldn't find a code path that would do that, so it's just speculation.</p>
0
2016-10-15T13:16:35Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
SQL query doesn't select the data that I need with 'where' conditions
39,919,990
<p>I am trying to get the records from my database where studentID, and lessonDate are equal to specific results. The StudentID seems to work fine, but lessonDate does not. Because of date formats, I have converted all dates to strings to be put into the database. I have set up database file so that the field is text field. I am trying to get the lesson name and rating that a student got for all exercises that they performed on a particular date. Database diagram: <a href="https://docs.google.com/drawings/d/16IqlDN2iqzVCeaUUGgeCe1R98yhUI7vQswH0tK39cAk/edit?usp=sharing" rel="nofollow">https://docs.google.com/drawings/d/16IqlDN2iqzVCeaUUGgeCe1R98yhUI7vQswH0tK39cAk/edit?usp=sharing</a></p> <p>I am certain that the StudentID is correct, as I use it in other parts of this function. I am certain that the date is correct, as the 'date' variable used in the 4th line results in the correct output written to the file, and I originally had the date in the SQL query as this variable, but it didn't work. I have tried printing the lessons where this student is the foreign key, and the date is '8-10-2016'. I really have no idea why this is happening. Any suggestion or hypothesis from anyone would be greatly appreciated.</p> <pre><code>template = ("{0:50}{1:50} \n") print(lessonDateSet) for date in list(lessonDateSet): target.write("Lesson date: {} \n".format(date)) target.write("\n") target.write(template.format("Exercise name:","rating:")) self.cur.execute("""SELECT b.roadExerciseName, a.rating FROM lessonExercises a LEFT JOIN roadExerciseInfo b ON a.roadExerciseID=b.roadExerciseID LEFT JOIN lessons c ON c.lessonID=a.lessonID WHERE c.StudentID = {0} AND c.lessonDate = {1}""".format(studentInfo[0][0],"8-10-2016")) fetch = self.cur.fetchall() print(fetch, "fetch") </code></pre> <p>'fetch' is an empty list. after this. I have double and tripple checked my data. my data is definitely correct.</p>
0
2016-10-07T14:43:44Z
39,920,079
<p>Your parameters are not being quoted correctly.</p> <p>This is why you should not use string interpolation to add data into your queries. You should use the db-api's parameter substitution instead:</p> <pre><code>self.cur.execute("""SELECT b.roadExerciseName, a.rating FROM lessonExercises a LEFT JOIN roadExerciseInfo b ON a.roadExerciseID=b.roadExerciseID LEFT JOIN lessons c ON c.lessonID=a.lessonID WHERE c.StudentID = ? AND c.lessonDate = ?""", [studentInfo[0][0], "8-10-2016"]) </code></pre>
2
2016-10-07T14:49:08Z
[ "python", "sqlite" ]
else-like clause when PIR motion sensors not sensing using Raspberry Pi
39,920,019
<p>I'm working on a Raspberry Pi project which displays a different video-loop depending on which of the 3 PIR motion sensors are "sensing motion". When no sensors are sensing anything, I want to display an additional video. So all in all there are 4 videos: left, middle, right, not-active.</p> <p>Using Python 3.4.2 , I have managed to get videos playing when sensors are activated, but I am having difficulties getting a video to play when none of the sensors are active. I thought it would be a simple 'else' like clause, but apparently it is not. I've tried many different methods, but have ran out of ideas. Can someone help me integrate a "no motion detected" return to the code? The code is as below:</p> <pre><code>''' Import required stuff ''' import RPi.GPIO as GPIO #GPIO import time #for delay import subprocess #for omxplayer ''' GPIO setup ''' GPIO.setmode(GPIO.BCM) #GPIO setmode PIR_PIN_L = 23 #define left pin PIR_PIN_R = 24 #define right pin PIR_PIN_M = 25 #define middle pin GPIO.setup(PIR_PIN_L, GPIO.IN) #set left pin GPIO.setup(PIR_PIN_R, GPIO.IN) #set right pin GPIO.setup(PIR_PIN_M, GPIO.IN) #set middle pin '''Definitions ''' def MOTIONL(PIR_PIN_L): #define motion on left print("Motion Detected on Left!") #output if motion detected def MOTIONR(PIR_PIN_R): #define motion on right print("Motion Detected on Right!") #output if motion detected def MOTIONM(PIR_PIN_M): #define motion in middle print("Motion Detected at Middle!") #output if motion detected ''' Initiation ''' print("PIR Module Test (CTRL+C to exit)") time.sleep(4) print("Ready") ''' Sensing ''' try: GPIO.add_event_detect(PIR_PIN_L, GPIO.RISING, callback=MOTIONL) GPIO.add_event_detect(PIR_PIN_M, GPIO.RISING, callback=MOTIONM) GPIO.add_event_detect(PIR_PIN_R, GPIO.RISING, callback=MOTIONR) while 1: time.sleep(100) except KeyboardInterrupt: print("Quit") GPIO.cleanup() </code></pre> <p>I've replaced the video parts with <code>print("Motion detected ...")</code> for simplicity. If you can add a <code>print("No motion detected")</code> when no sensors are activated, it would be very helpful.</p>
0
2016-10-07T14:45:41Z
39,928,589
<p>I managed to solve the issue, and thought I'll post it in case someone wants to use it. Note that the code has been changed quite considerably. It still uses very low CPU. The only difference is that this code is more efficient at picking up motions, but at the cost of higher false readings. That may be fixed by adjusting the knobs on the PIR sensor. The same concept can be applied to the code above. </p> <pre><code>''' Import required stuff ''' import RPi.GPIO as GPIO #GPIO import time #for delay ''' GPIO setup ''' GPIO.setmode(GPIO.BCM) #GPIO setmode PIR_PIN_L = 23 #define left pin PIR_PIN_R = 24 #define right pin PIR_PIN_M = 25 #define middle pin GPIO.setup(PIR_PIN_L, GPIO.IN) #set left pin GPIO.setup(PIR_PIN_R, GPIO.IN) #set right pin GPIO.setup(PIR_PIN_M, GPIO.IN) #set middle pin '''Definitions ''' def MOTIONL(): #define motion on left if GPIO.input(PIR_PIN_L)==1 : #trigger condtion left being active print("Motion Detected on Left") #output time.sleep(3) def MOTIONR(): #define motion on right if GPIO.input(PIR_PIN_R)==1 : #trigger condtion right being active print("Motion Detected on Right") #output time.sleep(3) def MOTIONM(): #define motion in middle if GPIO.input(PIR_PIN_M)==1 : #trigger condtion middle being active print("Motion Detected on Middle") #output time.sleep(3) def NOMOTION() : if GPIO.input(PIR_PIN_L)==0 and GPIO.input(PIR_PIN_R)==0 and GPIO.input(PIR_PIN_M)==0 : #above trigger condition is no sensor being active print("No Motion Detected") #output time.sleep(3) ''' Initiation ''' print("PIR Module Test (CTRL+C to exit)") time.sleep(4) print("Ready") ''' Sensing ''' try: while 1: #calls defined functions simulatanously NOMOTION() MOTIONR() MOTIONL() MOTIONM() except KeyboardInterrupt: #CTRL and C will reset shell print("Quit") GPIO.cleanup() </code></pre> <p>the <code> print </code> commands can be replaced with whatever function you wish to call.</p>
0
2016-10-08T04:10:18Z
[ "python", "python-3.x", "raspberry-pi3" ]
HSM using label of key object in PKCS11
39,920,023
<p>This block of code is loading a cryptoki.so library and retrieving slot info. This is getting a list of objects in slot num. 0. I don't need to access all the keys to perform a few functions, just a specific key pair. Is there a way to get a single desired token by using the label name, object ID, or handle?</p> <pre><code>pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load(lib) pkcs11.initialize() info = pkcs11.getInfo() i = pkcs11.getSlotInfo(0) pkcs11.openSession(0) print "Library manufacturerID: " + info.manufacturerID slots = pkcs11.getSlotList() print "Available Slots:", len(slots) for s in slots: try: i = pkcs11.getSlotInfo(s) print "Slot no:", s print format_normal % ("slotDescription", i.slotDescription.strip()) print format_normal % ("manufacturerID", i.manufacturerID.strip()) t = pkcs11.getTokenInfo(s) print "TokenInfo" print format_normal % ("label", t.label.strip()) print format_normal % ("manufacturerID", t.manufacturerID.strip()) print format_normal % ("model", t.model.strip()) session = pkcs11.openSession(s) print "Opened session 0x%08X" % session.session.value() if pin_available: try: session.login(pin=pin) except: print "login failed, exception:", str(sys.exc_info()[1]) objects = session.findObjects() print print "Found %d objects: %s" % (len(objects), [x.value() for x in objects]) </code></pre> <p>The specific script i'm running only has a few commands defined, such as <code>-pin --sign --decrypt --lib</code> do i need to define a common <code>pkcs11-tool</code> such as <code>--init-token or --token-label</code> to pass it as an argument when executing my script ? Or can i directly assign a variable to the desired LabelName within the python script?</p> <p>So from command line i'm running </p> <p><code>$./Test.py --pin=pass</code> and getting the following</p> <pre><code>Library manufacturerID: Safenet, Inc. Available Slots: 4 Slot no: 0 slotDescription: ProtectServer K5E:00045 manufacturerID: SafeNet Inc. TokenInfo label: CKM manufacturerID: SafeNet Inc. model: K5E:PL25 Opened session 0x00000002 Found 52 objects: [5021, 5022, 5014, 5016, 4, 5, 6, 7, 8, 9, 16, 18, 23, 24, 26, 27, 29, 30, 32, 33, 35, 36, 38, 39, 5313, 5314, 4982, 5325, 5326, 5328, 5329, 5331, 5332, 5335, 5018, 4962, 5020, 4963, 5357, 5358, 5360, 5361, 5363, 5364, 5366, 5367, 5369, 5370, 5372, 5373, 5375, 5376] </code></pre> <p>I'm ultimately trying to get only one of these objects to run some tests.For instance <code>objectID = 201603040001</code> contains a private/cert file. I want to specify this particular handle. The actual label is something like <code>000103...3A0</code>. How can I define this so I don't get the rest of the objects inside the library.</p> <p>Here's the a list of just a couple of the HSM objects </p> <pre><code> HANDLE LABEL TYPE OBJECT-ID 5314 00000103000003A1 X509PublicKeyCertificate 201603040001 5313 00000103000003A1 RSAPrivateKey 201603040001 </code></pre> <p>I'm trying to pull just one of the Labels.</p> <p>Here's the defined usage </p> <pre><code>def usage(): print "Usage:", sys.argv[0], print "[-p pin][--pin=pin]", print "[-s slot][--slot=slot]", print "[-c lib][--lib=lib]", print "[-h][--help]", print "[-o][--opensession]" try: opts, args = getopt.getopt(sys.argv[1:], "p:c:Sd:h:s", ["pin=", "lib=", "sign", "decrypt", "help","slot="]) except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) </code></pre> <p>I'm not aware of how I can add an argument so I can use <code>--sign</code> with just a specific label. End game I want to use <code>$./Test.py --pin=pass --sign --label "00000103000003A4"</code> or by handle <code>$./Test.py --pin=pass --sign --handle=5313</code></p> <p><strong>UPDATED</strong> <strong>from suggested comments below. still having trouble getting attributes for rsa private key and cert. Using the specific token has worked but those objects inside of it are returning bad attribute types</strong></p> <pre><code> t = pkcs11.getTokenInfo(s) print "TokenInfo" if 'CKM' == t.label.decode('ascii').strip(): tokenInfo = pkcs11.getTokenInfo(slot) if '00000103000003A1' == tokenInfo.label.decode('ascii').strip(): print format_normal % ("label", t.label.strip()) print format_normal % ("manufacturerID", t.manufacturerID.strip()) print format_normal % ("model", t.model.strip()) session = pkcs11.openSession(s) print("Opened session 0x%08X" % session.session.value()) if pin_available: try: if (pin is None) and \ (PyKCS11.CKF_PROTECTED_AUTHENTICATION_PATH &amp; t.flags): print("\nEnter your PIN for %s on the pinpad" % t.label.strip()) session.login(pin=pin) except: print("login failed, exception:", str(sys.exc_info()[1])) break objects = session.findObjects([(CKA_LABEL, "00000103000003A4")]) print() print("Found %d objects: %s" % (len(objects), [x.value() for x in objects])) all_attributes = list(PyKCS11.CKA.keys()) # only use the integer values and not the strings like 'CKM_RSA_PKCS' all_attributes.remove(PyKCS11.CKA_PRIVATE_EXPONENT) all_attributes.remove(PyKCS11.CKA_PRIME_1) all_attributes.remove(PyKCS11.CKA_PRIME_2) all_attributes.remove(PyKCS11.CKA_EXPONENT_1) all_attributes.remove(PyKCS11.CKA_EXPONENT_2) all_attributes.remove(PyKCS11.CKA_COEFFICIENT) all_attributes = [e for e in all_attributes if isinstance(e, int)] n_obj = 1 for o in objects: print() print((red + "==================== Object: %d ====================" + normal) % o.value()) n_obj += 1 try: attributes = session.getAttributeValue(o, all_attributes) except PyKCS11.PyKCS11Error as e: continue attrDict = dict(zip(all_attributes, attributes)) if attrDict[PyKCS11.CKA_CLASS] == PyKCS11.CKO_PRIVATE_KEY \ and attrDict[PyKCS11.CKA_KEY_TYPE] == PyKCS11.CKK_RSA: m = attrDict[PyKCS11.CKA_MODULUS] e = attrDict[PyKCS11.CKA_PUBLIC_EXPONENT] if m and e: mx = eval(b'0x' + ''.join("%02X" %c for c in m)) ex = eval(b'0x' + ''.join("%02X" %c for c in e)) if sign: try: toSign = "12345678901234567890123456789012" # 32 bytes, SHA256 digest print("* Signing with object 0x%08X following data: %s" % (o.value(), toSign)) signature = session.sign(o, toSign) sx = eval(b'0x' + ''.join("%02X" % c for c in signature)) print("Signature:") print(dump(''.join(map(chr, signature)))) if m and e: print("Verifying using following public key:") print("Modulus:") print(dump(''.join(map(chr, m)))) print("Exponent:") print(dump(''.join(map(chr, e)))) decrypted = pow(sx, ex, mx) # RSA print("Decrypted:") d = binascii.unhexlify(hexx(decrypted)) print(dump(d)) if toSign == d[-20:]: print("*** signature VERIFIED!\n") </code></pre> <p><strong>the following is what prints. nothing seems to be working using the specific objects, there are no error messages</strong> </p> <pre><code>Slot no: 0 slotDescription: ProtectServer K5E:00045 manufacturerID: SafeNet Inc. TokenInfo Opened session 0x00000002 Found 2 objects: [5328, 5329] ==================== Object: 5328 ==================== ==================== Object: 5329 ==================== </code></pre>
1
2016-10-07T14:45:57Z
39,954,836
<p>You can work only with one token by checking its label before use, e.g.:</p> <pre><code>tokenInfo = pkcs11.getTokenInfo(slot) if 'DesiredTokenLabel' == tokenInfo.label.decode('ascii').strip(): # Start working with this particular token session = pkcs11.openSession(s) </code></pre> <p>You can enumerate only specific object using a template argument for the <code>findObjects</code> call, e.g.:</p> <pre><code># get objects labelled "PRIV" objects = session.findObjects([(CKA_LABEL, "PRIV")]) # get all private key objects objects = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY)]) # get all private key objects labelled "PRIV" objects = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY),(CKA_LABEL, "PRIV")]) # get all RSA private key objects labelled "PRIV" objects = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY),(CKA_KEY_TYPE, CKK_RSA),(CKA_LABEL, "PRIV")]) </code></pre> <p>Below is an example code with hard-coded parameters:</p> <pre><code>from PyKCS11 import * pkcs11 = PyKCS11.PyKCS11Lib() pkcs11.load("your module path...") slots = pkcs11.getSlotList() for s in slots: t = pkcs11.getTokenInfo(s) if 'CKM' == t.label.decode('ascii').strip(): session = pkcs11.openSession(s) objects = session.findObjects([(CKA_LABEL, "00000103000003A1")]) print ("Found %d objects: %s" % (len(objects), [x.value() for x in objects])) </code></pre> <p>Please note that it is Python 3 as I can't use PyKCS11 in Python 2.x right now.</p> <p>Soma additional (random) notes:</p> <ul> <li><p>do not rely on handles -- they may (and will) be different for different program runs</p></li> <li><p>your program's command line arguments are up to you -- you must decide yourself if your program needs arguments like <code>--token-label</code></p></li> </ul> <p>Disclaimer: I am not that into python so please do validate my thoughts</p> <p>Good luck!</p> <p>EDIT(Regarding you recent edit)></p> <p>No error is (most probably) shown because the exception is caught and ignored:</p> <pre><code>try: attributes = session.getAttributeValue(o, all_attributes) except PyKCS11.PyKCS11Error as e: continue </code></pre>
1
2016-10-10T09:07:04Z
[ "python", "encryption", "cryptography", "pkcs#11", "hsm" ]
xml.etree.ElementTree search tag by variable
39,920,099
<p>I have a problem with the xml.etree.ElementTree Module in Python. I tried to search for a tag in the XML Tree using a variable:</p> <pre><code>i = "Http_Https" print(xmldoc_ports.findall(".//*application-set/[name=i]/application/")) </code></pre> <p>But it looks like that it did not resolve the variable <code>i</code>.</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File "test.py", line 223, in &lt;module&gt; print(xmldoc_ports.findall(".//*application-set/[name=i]/application/")) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 749, in findall return self._root.findall(path, namespaces) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 390, in findall return ElementPath.findall(self, path, namespaces) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 293, in findall return list(iterfind(elem, path, namespaces)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 263, in iterfind selector.append(ops[token[0]](next, token)) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementPath.py", line 224, in prepare_predicate raise SyntaxError("invalid predicate") </code></pre> <p>Is it possible to use a variable in the findall function?</p>
0
2016-10-07T14:50:07Z
39,920,154
<p>The <code>.//*application-set/[name=i]/application/</code> is not valid. I think you meant:</p> <pre><code>xpath = ".//application-set[@name='%s']/application" % i print(xmldoc_ports.findall(xpath)) </code></pre> <p>Note that <code>@</code> before the name - this is how you show access the <code>name</code> attribute. Also, I've removed the <code>/</code> after the <code>application-set</code> and <code>*</code> before it.</p> <p>Also, in order to have variable <code>i</code> inside the XPath, you should/can use string formatting. The <code>%s</code> is a placeholder for <code>%</code> operator to fill.</p>
1
2016-10-07T14:52:37Z
[ "python", "xml-parsing" ]
Riak Search 2 not indexing bucket
39,920,110
<p>I'm using Riak as a key-value store backend for a graph database implemented in Python.</p> <p>I created a custom <a href="https://github.com/linkdd/link.graph/blob/master/etc/link/graph/schemas/node.xml" rel="nofollow">search schema</a> named <code>nodes</code>. I created and activated a bucket type <code>nodes</code> with the <code>search_index</code> property set to <code>nodes</code> and the <code>datatype</code> property set to <code>map</code>.</p> <p>I inserted the following data into the bucket <code>default</code> (with bucket type <code>nodes</code>):</p> <pre><code>key: node1 value: { "type_set": {"n1"}, "foo_set": {"bar", "baz"} } </code></pre> <p><strong>NB:</strong> the data is automatically transformed into a Map datatype.</p> <p>I can fetch the data correctly, but I tried the following fulltext searches and no document is returned:</p> <pre><code>type_set:n1 type_set:*n1* type_set:* foo_set:* _yz_rk:node1 _yz_rk:* </code></pre> <p>It seems that my document is not indexed.</p> <p>I also tried to set the <code>search_type</code> property to <code>nodes</code> on the bucket <code>default</code>, but I got the same result.</p> <p>The parameter <code>search</code> is set to <code>on</code> in the configuration file (<code>/etc/riak/riak.conf</code>) and the OpenJDK 7 is installed.</p> <p>I have no idea what I'm doing wrong, if anyone can help me, thanks in advance.</p>
1
2016-10-07T14:50:32Z
39,925,036
<p>First, you should take into account that Riak automatically adds suffix <code>_set</code>, so that you don't have to name yours <code>type_set</code> but <code>type</code>. Otherwise you will have to query for <code>type_set_set:*</code> instead of <code>type_set:*</code>.</p> <p>Second, according to <a href="https://docs.basho.com/riak/kv/2.0.0/developing/usage/searching-data-types/#data-type-schemas" rel="nofollow">Data Type Schemas</a>, embedded schemas (as opposed to top-level ones) must use dynamic fields. Apparently Riak prepends field names with some internal identifier of the top-level map. Unfortunately, this also means that you cannot index one set without indexing the other as well.</p> <p>I've run some tests and found out that <code>&lt;dynamicField name="*_set" type="string" indexed="true" stored="true" multiValued="true"/&gt;</code> works fine, while <code>&lt;dynamicField name="*type_set" type="string" indexed="true" stored="true" multiValued="true"/&gt;</code> does not.</p>
1
2016-10-07T20:09:07Z
[ "python", "solr", "riak" ]
Error MSVCP140.dll not found on python Geopandas installation
39,920,116
<p>I've installed Geopandas (a library that doesn't have a specific wheel for Windows). The pip install ran without problems but when I execute the script, it shows me an 'MSVCP140.dll not found' error.</p> <p>The dll seems to be there and the permission on the temp for full control is ok too (as another post suggests in this web).</p> <p>On the other hand, I read on a Python forum that this dll is causing problems because the numerous non compatible versions.</p> <p>More info: this error is happening now, in a win 7 64 bits machine with py 3.5 32 bits, but in my last one it worked very well (win7 - 32 bits // python 3.4 - 32 bits).</p> <p>I don't know what i'm missing.</p> <p>Thanks in advance for your help :)</p>
0
2016-10-07T14:50:57Z
39,981,177
<p>As <a href="http://stackoverflow.com/users/205580/eryksun">eryksun</a> said in his comment, </p> <blockquote> <p>then MSVCP140.dll needs to be installed to the System32 directory or a PATH directory. Installing <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48145" rel="nofollow">vc_redist.x86.exe</a> should resolve your issue.</p> </blockquote> <p>I post it here, because it solved my problem.</p> <p>The fact that I change <strong>from win 64 to 32</strong> bits, but <strong>I keep my python 32 bits</strong> has caused the error.</p> <p>You</p>
0
2016-10-11T15:37:28Z
[ "python", "windows", "dll", "geopandas" ]
How to preprocess twitter text data using python
39,920,183
<p>I have text data after retrieval from a <code>mongoDB</code> in this format: </p> <p>**</p> <pre><code>[u'In', u'love', u'#Paralympics?\U0001f60d', u"We've", u'got', u'nine', u'different', u'sports', u'live', u'streams', u'https://not_a_real_link', u't_https://anotherLink'] [u't_https://somelink'] [u'RT', u'@sportvibz:', u'African', u'medal', u'table', u'#Paralympics', u't_https://somelink', u't_https://someLink'] </code></pre> <p>**</p> <p>However I would like to replace all URLs in the list with the word 'URL' while preserving other texts in the list, i.e to something like this:</p> <pre><code>[u'In', u'love', u'#Paralympics?\U0001f60d', u"We've", u'got', u'nine', u'different', u'sports', u'live', u'streams', u'URL', u'URL'] </code></pre> <p>But when I run the code for stopword removal and also perform regular expression I get this result sample : </p> <p>**</p> <pre><code>In URL RT </code></pre> <p>**</p> <p>Please could anyone help with this, as I'm finding this difficult.</p> <p>Here is the code I have at the moment: </p> <pre><code>def stopwordsRemover(self, rawText): stop = stopwords.words('english') ##remove stop words from the rawText argument and store the result list in processedText variable processedText = [i for i in rawText.split() if i not in stop] return processedText def clean_text(self, rawText): temp_raw = rawText for i, text in enumerate(temp_raw): temp = re.sub(r'https?:\/\/.*\/[a-zA-Z0-9]*', 'URL', text) return temp </code></pre>
0
2016-10-07T14:53:45Z
39,920,256
<p>This is wrong:</p> <pre><code>def clean_text(self, rawText): temp_raw = rawText for i, text in enumerate(temp_raw): temp = re.sub(r'https?:\/\/.*\/[a-zA-Z0-9]*', 'URL', text) return temp </code></pre> <p>you return the last substituted string instead of a list, that should replace your <code>rawText</code> input list (I must admit I'm puzzled by the fast that you seem to get the <em>first</em> item, but I'm still confident on the explanation)</p> <p>do that instead:</p> <pre><code>def clean_text(self, rawText): temp = list() for text in rawText: temp.append(re.sub(r'https?:\/\/.*\/\w*', 'URL', text)) # simpler regex with \w return temp </code></pre> <p>with a listcomp:</p> <pre><code>def clean_text(self, rawText): return [re.sub(r'https?:\/\/.*\/\w*', 'URL', text) for text in rawText] </code></pre> <p>you could also work in-place, modifying <code>rawText</code> directly:</p> <pre><code>def clean_text(self, rawText): rawText[:] = [re.sub(r'https?:\/\/.*\/\w*', 'URL', text) for text in rawText] </code></pre>
0
2016-10-07T14:58:05Z
[ "python", "regex" ]
Pygame: Flipping horizontally
39,920,237
<p>I'm making a game for my program and I'm trying to flip the image horizontally when I press the left key or right key. I found out about the function </p> <pre><code>pygame.transform.flip </code></pre> <p>however I am unsure as to where to insert it in my code. It would be appreciated if someone could help me. Here is my code. Also could somebody also tell me how I could prevent the image from moving out of the screen?</p> <pre><code>import pygame import os img_path = os.path.join('C:\Python27', 'player.png') class Player(object): def __init__(self): self.image = pygame.image.load("player1.png") self.x = 0 self.y = 0 def handle_keys(self): """ Handles Keys """ key = pygame.key.get_pressed() dist = 5 if key[pygame.K_DOWN]: self.y += dist elif key[pygame.K_UP]: self.y -= dist if key[pygame.K_RIGHT]: self.x += dist elif key[pygame.K_LEFT]: self.x -= dist ) def draw(self, surface): surface.blit(self.image, (self.x, self.y)) pygame.init() screen = pygame.display.set_mode((640, 400)) player = Player() clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() # quit the screen running = False player.handle_keys() # movement keys screen.fill((255,255,255)) # fill the screen with white player.draw(screen) # draw the player to the screen pygame.display.update() # update the screen clock.tick(60) # Limits Frames Per Second to 60 or less </code></pre>
0
2016-10-07T14:56:38Z
39,920,577
<p>I would do the image processing stuff when Player is instantiated like so:</p> <pre><code>class Player(object): def __init__(self): self.image = pygame.image.load("player1.png") self.image2 = pygame.transform.flip(self.image, True, False) self.flipped = False self.x = 0 self.y = 0 </code></pre> <p>Handle keys would changed the state of self.flipped.</p> <pre><code> if key[pygame.K_RIGHT]: self.x += dist self.flipped = False elif key[pygame.K_LEFT]: self.x -= dist self.flipped = True </code></pre> <p>Then self.draw decides which image to display.</p> <pre><code>def draw(self, surface): if self.flipped: image = self.image2 else: image = self.image surface.blit(image, (self.x, self.y)) </code></pre> <p>This is the approach I take with all animated game objects.</p>
2
2016-10-07T15:12:52Z
[ "python", "python-2.7", "pygame" ]
knn with custom distance function in R
39,920,387
<p>I want to apply k nearest neighbour with a custom distance function. I have not found a way to pass this function using packages like FNN or class. Is there a way to pass a function or distance matrix to an existing knn algorithm in some R package or do I have to write it from scratch?</p> <h2>Background</h2> <p>To elaborate on my problem: my data includes columns for</p> <ul> <li>start latitude</li> <li>start longitude</li> <li>start country</li> <li>end latitude</li> <li>end longitude</li> <li>end country</li> <li>start+end country</li> <li>means of transportation</li> <li>distance</li> <li>price</li> </ul> <p>and I want to estimate the price based on the other factors. The distance function needs to include the haversine distance to measure the similarity of start and end points' latitude and longitude, so I cannot use a built-in distance like euclidean or minkowski.</p> <h2>Open for Python suggestions</h2> <p>If somebody believes that for some reason this would be much easier to do in Python (provided the same programming skills in both languages) using some fancy package, I am also very open to additional information about this.</p>
1
2016-10-07T15:03:45Z
39,963,292
<p>After searching a bit, I found a package called KODAMA that <strong>does cross validation</strong> 10 fold for instance and seems to have a knn prediction function <code>knn.predict</code> working with a distance matrix calculated separately by the <code>knn.dist</code> function.</p> <p>It appears that the output of the <code>knn.dist</code> function is nothing but a standard distance matrix with symmetric values and diagonal set to zero, of class Matrix. So we can create one separately, those lines of code are equivalent:</p> <pre><code>kdist &lt;- KODAMA::knn.dist(x) kdist &lt;- dist(x, upper=T, diag=T) %&gt;% as.matrix # it also works knn.predict(train, test, y ,kdist, k=3, agg.meth="majority") </code></pre> <p>You might try it with your custom distance matrix. hope it helps. </p>
1
2016-10-10T17:04:17Z
[ "python", "machine-learning", "distance", "knn" ]
Segmentation fault using python layer in caffe
39,920,438
<p>I'm trying to use python layer as described <a href="http://chrischoy.github.io/research/caffe-python-layer/" rel="nofollow">here</a>. But I am getting this exception:</p> <pre><code>I1007 17:48:31.366592 30357 layer_factory.hpp:77] Creating layer loss *** Aborted at 1475851711 (unix time) try "date -d @1475851711" if you are using GNU date *** PC: @ 0x7f32895f1156 (unknown) *** SIGSEGV (@0x0) received by PID 30357 (TID 0x7f328b07fa40) from PID 0; stack trace: *** @ 0x7f328883ecb0 (unknown) @ 0x7f32895f1156 (unknown) @ 0x7f3289b43dfe (unknown) @ 0x7f32429d0d9c google::protobuf::MessageLite::ParseFromArray() @ 0x7f3242a1f652 google::protobuf::EncodedDescriptorDatabase::Add() @ 0x7f32429da012 google::protobuf::DescriptorPool::InternalAddGeneratedFile() @ 0x7f3242a2b33e google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fdescriptor_2eproto() @ 0x7f3242a5aa75 google::protobuf::StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto::StaticDescriptorInitializer_google_2fprotobuf_2fdescriptor_2eproto() @ 0x7f3242a56beb __static_initialization_and_destruction_0() @ 0x7f3242a56c00 _GLOBAL__sub_I_descriptor.pb.cc @ 0x7f328aeca10a (unknown) @ 0x7f328aeca1f3 (unknown) @ 0x7f328aecec30 (unknown) @ 0x7f328aec9fc4 (unknown) @ 0x7f328aece37b (unknown) @ 0x7f327d91b02b (unknown) @ 0x7f328aec9fc4 (unknown) @ 0x7f327d91b62d (unknown) @ 0x7f327d91b0c1 (unknown) @ 0x7f3288f412ae (unknown) @ 0x7f3288f09dae (unknown) @ 0x7f3288f88729 (unknown) @ 0x7f3288ebccbf (unknown) @ 0x7f3288f81d66 (unknown) @ 0x7f3288e47a3f (unknown) @ 0x7f3288f12d43 (unknown) @ 0x7f3288f8b577 (unknown) @ 0x7f3288f6dc13 (unknown) @ 0x7f3288f7154d (unknown) @ 0x7f3288f71682 (unknown) @ 0x7f3288f71a2c (unknown) @ 0x7f3288f88016 (unknown) Segmentation fault (core dumped) </code></pre> <p>I am using Ubuntu 14.04, GPU caffe installation. Python layer and prototxt are <a href="https://gist.github.com//shelhamer/8d9a94cf75e6fb2df221" rel="nofollow">here</a>. Could anybody suggest anything? I don't know what I am doing wrong.</p>
0
2016-10-07T15:06:00Z
39,920,765
<p>From my experience, this is one of the most prevalent weaknesses in Caffe: this SegFault without an error message. I generally get this when I haven't connected the data layer properly. For instance, I haven't started the data server, or there's a severe mismatch in format.</p>
0
2016-10-07T15:22:58Z
[ "python", "caffe" ]
generate mouse velocity when only integer steps are allowed
39,920,445
<p>I write a simple program in python which includes moving my mouse (I do his with <a href="https://github.com/PyUserInput/PyUserInput" rel="nofollow">PyUserInput</a>). However: It is only allowed to move the mouse in integer steps (say pixels). So <code>mouse.move(250.3,300.2)</code> won't work.</p> <p>I call the move function about 30 times in a second and move the mouse a few pixels. The speed with which I move the mouse varies from 0.5-2.5px/call. Rounding gives me 1-3 (move only want ints) which does not really represent the speed.</p> <p>I search for a solution (maybe generator?) which takes my current speed (e.g. 0.7px) and gives me back a pattern (like a PWM Signal) out of 0 and 1 (e.g. <code>1,1,0,1,1,0...</code>) which yields the 0.7px in average. However this generator has to be adaptive because speed is constantly changing.</p> <p>I am quite new to python and stuck with the last point: The variability of the generator function.</p> <p>Here is what I have so far:</p> <pre><code># for 0.75px/call def getPWM(n): nums = [1,0,1,1] yield nums[n%4] </code></pre>
1
2016-10-07T15:06:26Z
39,921,155
<p>What you need to do is keep track of the previous position and the desired current position, and hand out the rounded coordinate. You could track the previous position in a function but it's much easier to do it in a class.</p> <pre><code>class pwm: def __init__(self): self.desired_position = 0.0 self.actual_position = 0 def nextPWM(self, speed): self.desired_position += speed movement = round(self.desired_position - self.actual_position) self.actual_position += movement return movement </code></pre>
1
2016-10-07T15:44:15Z
[ "python" ]
When is a decorator (class) object destroyed?
39,920,525
<p>I am using a decorator to open and close a neo4j database session (and allow my decorated functions to run queries within that session). At first I used a decorator function :</p> <pre><code> from neo4j.v1 import GraphDatabase, basic_auth def session(func,url="bolt://localhost:7474", user="neo4j",pwd="neo4j", *args, **kwargs): def operate(*args, **kwargs): driver = GraphDatabase.driver(url, auth=basic_auth(user,pwd)) session=driver.session() kwargs["session"]=session result=func(*args, **kwargs) session.close() return result return operate </code></pre> <p>and for example I then call this function:</p> <pre><code>@session def RUN(command,session): result=session.run(command) return(result) </code></pre> <p>However, this opens and closes the session for every query which is resource consuming. Thus, I tried to create a decorator class, and store the session:</p> <pre><code>class session(object): def __init__(self, func, url="bolt://localhost", user="neo4j", pwd="neo4j"): try: driver = GraphDatabase.driver(url, auth=basic_auth(user, pwd)) print("session opened") except: print("Exception during authentification") self.__exit__() else: session=driver.session() self.func=func self.SESSION=session def __call__(self, *args, **kwargs): kwargs["session"]=self.SESSION result=self.func(*args, **kwargs) return result def __del__(self): print("del") try: self.SESSION.close() print("session closed") except: print("could not close session") </code></pre> <p>This seems to work, as the "session opened" appears only once. But the session does not seem to close ("session close" is never printed).</p> <p>So my first question is the following, how can I call the self.SESSION.close() at the destruction of the decorator ?</p> <p>I'm also wondering if I understood well what my code is doing. When I call a decorated function such as <code>RUN</code>, is only one session object created? And what if I were to have an other decorated function <code>MATCH</code></p> <pre><code>@session def MATCH(*args,**kwargs): pass </code></pre> <p>would the session object be the same ?</p>
0
2016-10-07T15:10:47Z
39,920,984
<h2>How to</h2> <p>Here is a template to create a decorator with parameters using a function:</p> <pre><code>def decorator_maker(param1, param2): print("The parameters of my decorator are: {0} and {1}".format(param1, param2)) def my_decorator(function_to_decorate): def wrapper(arg1, arg2): print("before call") result = function_to_decorate(arg1, arg2) print("after call") return result return wrapper return my_decorator </code></pre> <p>The usage is as follow:</p> <pre><code>@decorator_maker("hello", "How are you?") def my_function(arg1, arg2): print("The parameters of my function are: {0} and {1}".format(arg1, arg2)) return arg1 + "-" + arg2 </code></pre> <p>With a class, it is more straightforward:</p> <pre><code>class decorator_maker(object): def __init__(self, param1, param2): print("The parameters of my decorator are: {0} and {1}".format(param1, param2)) self.param1 = param1 self.param2 = param2 def __call__(self, function_to_decorate): def wrapper(arg1, arg2): print("before call") result = function_to_decorate(arg1, arg2) print("after call") return result return wrapper </code></pre> <h2>Answer</h2> <p>To open and close your session before/after the function call, you have to implement it in the wrapped function, like this:</p> <pre><code>class with_session(object): def __init__(self, url="bolt://localhost", user="neo4j", pwd="neo4j"): self.url = url self.user = user self.pwd = pwd def __call__(self, f): def wrapper(*args, **kwargs): driver = GraphDatabase.driver(self.url, auth=basic_auth(self.user, self.pwd)) kwargs["session"] = session = driver.session() try: return f(*args, **kwargs) finally: session.close() return wrapper </code></pre> <p>Notes:</p> <ul> <li>You can let the exception raises...</li> <li>You should rename the decorator (like I did) to avoid shadowing the name "session".</li> <li>This decorator is not a a context manager. For that you need to use <code>__enter__</code> and <code>__exit__</code>, this is another use case...</li> </ul> <h2>Reference</h2> <p>See: <a href="http://stackoverflow.com/questions/739654">How to make a chain of function decorators in Python?</a></p>
1
2016-10-07T15:34:38Z
[ "python", "database-connection", "decorator", "python-decorators" ]
How does one create a dense vector from a sentence as input to a neural net?
39,920,528
<p>I'm having trouble figuring out how one converts a sentence into a dense vector as input to a neural network, specifically to test whether or not a sentence is '<strong><em>liked</em></strong>' or '<strong><em>not liked</em></strong>' given a training set. </p> <p>I've had some luck with Support Vector Machines. Using NLTK and scikit-learn I worked out that, by default, scikit-learn uses <code>sklearn.feature_extraction.DictVectorizer</code>. This seems to create a large matrix with a rank the same size as the number of unique words in the dataset and a 1.0 if that word appears in the sample, or a 0.0 if not.</p> <p>Here is the code I have already. It seems to work 'reasonably' well but I'm looking at training some kind of Recurrent or Convolutional Neural Network to do the same sort of thing.</p> <pre><code>''' A small example of training a support vector machine classifier to detect whether or not I like or dislike a particular tweet ''' import sqlite3 import nltk from sklearn.svm import LinearSVC, NuSVC, SVC, SVR from nltk.classify.scikitlearn import SklearnClassifier liked_ngrams = [] disliked_ngrams = [] # Limits on the dataset. Dividing into training vs test pos_cutoff = 0 neg_cutoff = 0 # Prep a tweet from our db, setting the features def prep_tweet(row): tokens = nltk.word_tokenize(row[0]) tokens = [token.lower() for token in tokens if len(token) &gt; 1] bi_tokens = nltk.bigrams(tokens) tri_tokens = nltk.trigrams(tokens) a =[(word, True) for word in tokens] #a += [(word, True) for word in bi_tokens] #a += [(word, True) for word in tri_tokens] return dict(a) # test out classifier on some existing tweets def test_classifier(classifier): conn = sqlite3.connect('fuchikoma.db') cursor = conn.cursor() # start with likes idx = 0 total_positive = 0 total_negative = 0 for row in cursor.execute('SELECT * FROM likes ORDER BY date(date) DESC').fetchall(): if idx &gt; pos_cutoff: test_set = [] try: a = prep_tweet(row) if len(a) &gt; 0: if classifier.classify(a) == 'neg': total_negative += 1 else: total_positive += 1 except UnicodeDecodeError: pass idx += 1 print("Checking positive Tweets") p = float(total_positive) / float(total_positive + total_negative) * 100.0 print ("Results: Positive: " + str(total_positive) + " Negative: " + str(total_negative) + " Percentage Correct: " + str(p) + "%") idx = 0 total_positive = 0 total_negative = 0 for row in cursor.execute('SELECT * FROM dislikes ORDER BY date(date) DESC').fetchall(): if idx &gt; neg_cutoff: test_set = [] try: a = prep_tweet(row) if len(a) &gt; 0: if classifier.classify(a) == 'pos': total_negative += 1 else: total_positive += 1 except UnicodeDecodeError: pass idx += 1 print("Checking negative Tweets") p = float(total_positive) / float(total_positive + total_negative) * 100.0 print ("Results: Positive: " + str(total_positive) + " Negative: " + str(total_negative) + " Percentage Correct: " + str(p) + "%") # http://streamhacker.com/2010/10/25/training-binary-text-classifiers-nltk-trainer/ # http://streamhacker.com/2010/05/10/text-classification-sentiment-analysis-naive-bayes-classifier/comment-page-2/ def train_classifier(): conn = sqlite3.connect('fuchikoma.db') cursor = conn.cursor() # start with likes for row in cursor.execute('SELECT * FROM likes ORDER BY date(date) DESC').fetchall(): try: a = prep_tweet(row) if len(a) &gt; 0: liked_ngrams.append(a) except UnicodeDecodeError: pass #from sklearn.feature_extraction import DictVectorizer #v = DictVectorizer(sparse=True) #X = v.fit_transform(liked_ngrams) #print(X) #print(v.inverse_transform(X)) # now dislikes for row in cursor.execute('SELECT * FROM dislikes ORDER BY date(date) DESC').fetchall(): try: a = prep_tweet(row) if len(a) &gt; 0: disliked_ngrams.append(a) except UnicodeDecodeError: pass pos_cutoff = int(len(liked_ngrams)*0.75) neg_cutoff = int(len(disliked_ngrams)*0.75) training_set = [ (feat, 'pos') for feat in liked_ngrams[:pos_cutoff] ] training_set += [ (feat, 'neg') for feat in disliked_ngrams[:neg_cutoff]] # Finally, train the classifier and return # By default, this appears to create clusters and vectors using # sklearn.feature_extraction.DictVectorizer with a sparse feature set it would appear classif = SklearnClassifier(LinearSVC()) classif.train(training_set) return classif if __name__ == "__main__": test_classifier(train_classifier()) </code></pre> <p>I've been pointed at <a href="http://www.aclweb.org/anthology/P14-1062" rel="nofollow">http://www.aclweb.org/anthology/P14-1062</a> but its a bit too hard for me to understand fully. I've seen plenty of neural nets and deep learning for images, but comparatively little on text. Can someone please point me at some easier, introductory work for this sort of thing please? Cheers Ben</p>
0
2016-10-07T15:10:55Z
39,925,634
<p>You might find this blog helpful:</p> <p><a href="http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/" rel="nofollow">http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/</a></p>
1
2016-10-07T20:52:53Z
[ "python", "nlp", "svm", "deep-learning" ]
How does one create a dense vector from a sentence as input to a neural net?
39,920,528
<p>I'm having trouble figuring out how one converts a sentence into a dense vector as input to a neural network, specifically to test whether or not a sentence is '<strong><em>liked</em></strong>' or '<strong><em>not liked</em></strong>' given a training set. </p> <p>I've had some luck with Support Vector Machines. Using NLTK and scikit-learn I worked out that, by default, scikit-learn uses <code>sklearn.feature_extraction.DictVectorizer</code>. This seems to create a large matrix with a rank the same size as the number of unique words in the dataset and a 1.0 if that word appears in the sample, or a 0.0 if not.</p> <p>Here is the code I have already. It seems to work 'reasonably' well but I'm looking at training some kind of Recurrent or Convolutional Neural Network to do the same sort of thing.</p> <pre><code>''' A small example of training a support vector machine classifier to detect whether or not I like or dislike a particular tweet ''' import sqlite3 import nltk from sklearn.svm import LinearSVC, NuSVC, SVC, SVR from nltk.classify.scikitlearn import SklearnClassifier liked_ngrams = [] disliked_ngrams = [] # Limits on the dataset. Dividing into training vs test pos_cutoff = 0 neg_cutoff = 0 # Prep a tweet from our db, setting the features def prep_tweet(row): tokens = nltk.word_tokenize(row[0]) tokens = [token.lower() for token in tokens if len(token) &gt; 1] bi_tokens = nltk.bigrams(tokens) tri_tokens = nltk.trigrams(tokens) a =[(word, True) for word in tokens] #a += [(word, True) for word in bi_tokens] #a += [(word, True) for word in tri_tokens] return dict(a) # test out classifier on some existing tweets def test_classifier(classifier): conn = sqlite3.connect('fuchikoma.db') cursor = conn.cursor() # start with likes idx = 0 total_positive = 0 total_negative = 0 for row in cursor.execute('SELECT * FROM likes ORDER BY date(date) DESC').fetchall(): if idx &gt; pos_cutoff: test_set = [] try: a = prep_tweet(row) if len(a) &gt; 0: if classifier.classify(a) == 'neg': total_negative += 1 else: total_positive += 1 except UnicodeDecodeError: pass idx += 1 print("Checking positive Tweets") p = float(total_positive) / float(total_positive + total_negative) * 100.0 print ("Results: Positive: " + str(total_positive) + " Negative: " + str(total_negative) + " Percentage Correct: " + str(p) + "%") idx = 0 total_positive = 0 total_negative = 0 for row in cursor.execute('SELECT * FROM dislikes ORDER BY date(date) DESC').fetchall(): if idx &gt; neg_cutoff: test_set = [] try: a = prep_tweet(row) if len(a) &gt; 0: if classifier.classify(a) == 'pos': total_negative += 1 else: total_positive += 1 except UnicodeDecodeError: pass idx += 1 print("Checking negative Tweets") p = float(total_positive) / float(total_positive + total_negative) * 100.0 print ("Results: Positive: " + str(total_positive) + " Negative: " + str(total_negative) + " Percentage Correct: " + str(p) + "%") # http://streamhacker.com/2010/10/25/training-binary-text-classifiers-nltk-trainer/ # http://streamhacker.com/2010/05/10/text-classification-sentiment-analysis-naive-bayes-classifier/comment-page-2/ def train_classifier(): conn = sqlite3.connect('fuchikoma.db') cursor = conn.cursor() # start with likes for row in cursor.execute('SELECT * FROM likes ORDER BY date(date) DESC').fetchall(): try: a = prep_tweet(row) if len(a) &gt; 0: liked_ngrams.append(a) except UnicodeDecodeError: pass #from sklearn.feature_extraction import DictVectorizer #v = DictVectorizer(sparse=True) #X = v.fit_transform(liked_ngrams) #print(X) #print(v.inverse_transform(X)) # now dislikes for row in cursor.execute('SELECT * FROM dislikes ORDER BY date(date) DESC').fetchall(): try: a = prep_tweet(row) if len(a) &gt; 0: disliked_ngrams.append(a) except UnicodeDecodeError: pass pos_cutoff = int(len(liked_ngrams)*0.75) neg_cutoff = int(len(disliked_ngrams)*0.75) training_set = [ (feat, 'pos') for feat in liked_ngrams[:pos_cutoff] ] training_set += [ (feat, 'neg') for feat in disliked_ngrams[:neg_cutoff]] # Finally, train the classifier and return # By default, this appears to create clusters and vectors using # sklearn.feature_extraction.DictVectorizer with a sparse feature set it would appear classif = SklearnClassifier(LinearSVC()) classif.train(training_set) return classif if __name__ == "__main__": test_classifier(train_classifier()) </code></pre> <p>I've been pointed at <a href="http://www.aclweb.org/anthology/P14-1062" rel="nofollow">http://www.aclweb.org/anthology/P14-1062</a> but its a bit too hard for me to understand fully. I've seen plenty of neural nets and deep learning for images, but comparatively little on text. Can someone please point me at some easier, introductory work for this sort of thing please? Cheers Ben</p>
0
2016-10-07T15:10:55Z
39,928,490
<p>There are many ways:</p> <p>1) Vector space model, after you have that dense vector, you can apply a SVD eg with 300 components , then you will have a vector in 300 dimensions. Do check out <a href="https://github.com/StevenLOL/aicyber_semeval_2016_ivector/blob/master/System_1/system_1_baseline.py#L32" rel="nofollow">this example, written by me for Semeval 2016</a>.</p> <p>2) Using CNN with word embedding layer(randomized or <a href="https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html" rel="nofollow">pretrained</a>) , check out Keras's <a href="https://keras.io/preprocessing/text/" rel="nofollow">docs</a> and examples:</p> <ol> <li><p><a href="https://github.com/fchollet/keras/blob/master/examples/imdb_cnn.py" rel="nofollow"> cnn</a></p></li> <li><p><a href="https://github.com/fchollet/keras/blob/master/examples/imdb_cnn_lstm.py" rel="nofollow">cnn lstm</a></p></li> <li><p><a href="https://github.com/fchollet/keras/blob/master/examples/imdb_fasttext.py" rel="nofollow">fasttext</a></p></li> <li><a href="https://github.com/fchollet/keras/blob/master/examples/pretrained_word_embeddings.py" rel="nofollow">pretrained embeddings</a></li> </ol>
1
2016-10-08T03:50:56Z
[ "python", "nlp", "svm", "deep-learning" ]
Testing with a txt file
39,920,551
<p>I created a input.txt file. There several sets of testing input date in input.txt. Then I run in the terminal <code>python Filename.py &lt;input.txt &gt;output.txt</code>. After running I only get output of first set input date. How can I get all the output date automatically in output.txt? </p> <pre><code># GET amount of money in bank amount_in_bank = input( "How much money is in the bank? $" ) # GET amount of income amount_of_income = input( "How much income is expected? $" ) # GET amount of expenses amount_of_expenses = input( "How much money is going to be spent on expenses? $" ) # CALCULATE money in bank + income - expenses # SET amount available to result of previous calculation amount_available = int( amount_in_bank ) + int( amount_of_income ) - int( amount_of_expenses ) # DISPLAY amount available message = "Bobbie will have $" + str( amount_available ) + " left at the end of the month." print ( message ) </code></pre>
0
2016-10-07T15:11:41Z
39,923,403
<p>I feel that you have not added any loop in order to traverse all the inputs in txt file. This might help:</p> <p>Start with <code>fp = open('input.txt')</code>. Add a <code>for</code> loop like <code>for i, line in enumerate(fp.readlines()):</code> and then type the code you had added for getting the values and printing the message.</p>
0
2016-10-07T18:06:17Z
[ "python" ]
Pythonanywhere Moviepy
39,920,663
<p>What is problem?</p> <p>I'm running on Pythonanywhere.com</p> <blockquote> <p>This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or.that the path you specified is incorrect</p> </blockquote> <pre><code>[MoviePy] This command returned an error !Traceback (most recent call last):, File "deneme.py", line 6, in &lt;module&gt; txt_clip = TextClip("My Holidays 2013",fontsize=70,color='white') File "/home/pirali/.local/lib/python2.7/site-packages/moviepy/video/VideoClip.py", line 1145, in __init__ raise IOError(error) IOError: MoviePy Error: creation of None failed because of the following error: Youtube Foto Galeri: not authorized `@/tmp/tmpxjn5vu.txt' @ error/property.c/InterpretImageProperties/2959. Youtube Foto Galeri: no images defined `PNG32:/tmp/tmp3lNxp8.png' @ error/convert.c/ConvertImageCommand/3044... This error can be due to the fact that ImageMagick is not installed on your computer, or (for Windows users) that you didn't specify the path to the ImageMagick binary in file conf.py, or.that the path you specified is incorrect </code></pre>
1
2016-10-07T15:17:09Z
39,979,774
<p>PythonAnywhere admin here. For anyone else that might come across the problem, it was due to the ImageMagick security vulnerability that was discovered a few weeks ago:</p> <p><a href="https://www.imagemagick.org/discourse-server/viewtopic.php?t=29588" rel="nofollow">https://www.imagemagick.org/discourse-server/viewtopic.php?t=29588</a></p> <p>Certain features in imagemagick are therefore disabled, pending security patches.</p>
2
2016-10-11T14:35:33Z
[ "python", "imagemagick", "moviepy" ]
Selenium With Python-Firefox always loading blank page
39,920,691
<p>I've got an issue setting up and running Selenium with Python at first. My system- Windows 8.1, Python 3.4.4 </p> <p>When I try to call a browser with python code inside console or even running py doc with this particular code all I get-nothing but a blank page in browser. After some time I have errors in console.</p> <pre><code> `C:\Python34\selenium\Tests&gt;new1.py Traceback (most recent call last): File "C:\Python34\selenium\Tests\new1.py", line 2, in &lt;module&gt; browser=webdriver.Firefox() File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 80, in __init__ self.binary, timeout) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\extension_conne ction.py", line 52, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_binary. py", line 68, in launch_browser self._wait_until_connectable(timeout=timeout) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_binary. py", line 108, in _wait_until_connectable % (self.profile.path)) selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: C:\Users\Admin\AppData\Local\Temp\tmpxr3qxv83 If you specified a lo g_file in the FirefoxBinary constructor, check it for details. ` </code></pre> <p>It would be really great if you may help me.</p> <p>P.S. Pip version is the latest-8.1.2 Firefox version 49.0.1</p> <p>Here is the code where I've set the environment </p> <pre><code>C:\Python34\Scripts&gt;pip.exe install selenium Requirement already satisfied (use --upgrade to upgrade): selenium in c:\python3 4\lib\site-packages </code></pre> <p>It have been already installed before</p> <p>Small update,guys</p> <p>I have created Firefox profile especially for selenium tests. But I have the same problem with exception again.</p> <pre><code>&gt;&gt;&gt; from selenium import webdriver &gt;&gt;&gt; from selenium.webdriver.common.keys import Keys &gt;&gt;&gt; fp = webdriver.FirefoxProfile('C:/Users/Admin/AppData/Roaming/Mozilla/Firefo x/Profiles/2byxc9l6.selenium') &gt;&gt;&gt; browser = webdriver.Firefox(fp) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 80, in __init__ self.binary, timeout) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\extension_conne ction.py", line 52, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_binary. py", line 68, in launch_browser self._wait_until_connectable(timeout=timeout) File "C:\Python34\lib\site-packages\selenium\webdriver\firefox\firefox_binary. py", line 108, in _wait_until_connectable % (self.profile.path)) selenium.common.exceptions.WebDriverException: Message: Can't load the profile. Profile Dir: C:\Users\Admin\AppData\Local\Temp\tmpe1dfmxt_\webdriver-py-profilec opy If you specified a log_file in the FirefoxBinary constructor, check it for d etails. &gt;&gt;&gt; </code></pre> <p>What I did wrong if selenium is searching PATH in another directory?</p> <p>P.S. Selenium version is 2.53.6. Firefox is 49.0.1</p>
0
2016-10-07T15:18:44Z
39,921,840
<p>This is a problem with loading a Firefox profile. In order to avoid that, you should use a <strong>custom profile</strong> for your tests. </p> <p>Create a custom profile: Close all instances of Firefox and then start it from command line with <code>firefox -P</code>. Follow the steps to create a profile with some meaningful name (like 'selenium') and make sure you the directory where the profile is saved. Details are explained <a href="https://support.mozilla.org/en-US/kb/profile-manager-create-and-remove-firefox-profiles" rel="nofollow">here</a>.</p> <p>Replace the code in <code>new1.py</code> to create a firefox driver instance with custom profile, e.g. if your profile is located in folder "C:\Users\Admin\AppData\Roaming\Mozilla\Firefox\Profiles\cmx3h2wi.selenium", replace the line <code>browser=webdriver.Firefox()</code> with this (note the forward slashes even on Windows, as explained <a href="http://stackoverflow.com/questions/11095294/using-the-default-firefox-profile-with-selenium-webdriver-in-python">here</a></p> <pre><code>fp = webdriver.FirefoxProfile('C:/Users/Admin/AppData/Roaming/Mozilla/Firefox/Profiles/cmx3h2wi.selenium') browser = webdriver.Firefox(fp) </code></pre> <p>That way FirefoxDriver should load a profile exclusively for your selenium tests.</p>
0
2016-10-07T16:21:31Z
[ "python", "selenium" ]
Plot polar scatter plot with images as markers, matplotlib: cannot convert NaN to integer
39,920,705
<p>Given a pandas dataframe I have some code that will create a scatter plot and place a specified png at each point:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.image import BboxImage from matplotlib.transforms import Bbox, TransformedBbox threshold = 0.05 fig = plt.figure(figsize=(20,20)) ax = fig.add_subplot(111) bound = 0.2 ax.set_xlim([-bound,bound]) ax.set_ylim([-bound,0.25]) ax.set_axis_bgcolor('white') for index, row in high_low.iterrows(): x = row['row1'] y = row['row2'] if abs(x) &gt; threshold or abs(y) &gt; threshold: im = plt.imread('/path/to/my/image_' + str(index) + '.png') bb = Bbox.from_bounds(x,y,.01,.01) bb2 = TransformedBbox(bb,ax.transData) bbox_image = BboxImage(bb2, norm = None, origin=None, clip_on=False, alpha=0.75) bbox_image.set_data(im) ax.add_artist(bbox_image) ax.grid(True, color="black", linestyle="--") plt.savefig("myfig.svg", dpi=300, format='svg') </code></pre> <p>I want to change this plot to polar coordinates, so I added the following function</p> <pre><code>def cart2pol(x, y): rho = np.sqrt(x**2 + y**2) phi = np.arctan2(y, x) return(rho, phi) </code></pre> <p>and changed my code to:</p> <pre><code>ax = fig.add_subplot(111, polar=True) # &lt;- CHANGE HERE ax.set_axis_bgcolor('white') for index, row in high_low.iterrows(): x = row['row1'] y = row['row2'] if abs(x) &gt; threshold or abs(y) &gt; threshold: rho, phi = cart2pol(x, y) # &lt;- CHANGE HERE im = plt.imread('/path/to/my/image_' + str(index) + '.png') bb = Bbox.from_bounds(rho,phi,.01,.01) # &lt;- CHANGE HERE bb2 = TransformedBbox(bb,ax.transData) bbox_image = BboxImage(bb2, norm = None, origin=None, clip_on=False, alpha=0.75) bbox_image.set_data(im) ax.add_artist(bbox_image) ax.grid(True, color="black", linestyle="--") plt.savefig("myfigPolar.pdf", dpi=300, format='pdf') </code></pre> <p>The loop runs:</p> <pre><code>... &lt;matplotlib.image.BboxImage object at 0x7f6b805fb390&gt; &lt;matplotlib.image.BboxImage object at 0x7f6b805fb6d0&gt; &lt;matplotlib.image.BboxImage object at 0x7f6b805fba10&gt; ... </code></pre> <p>but I get the following error when plotting: </p> <pre><code>&gt;&gt;&gt; plt.savefig("myfigPolar.pdf", dpi=300, format='pdf') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 561, in savefig return fig.savefig(*args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1421, in savefig self.canvas.print_figure(*args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 2220, in print_figure **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/backend_bases.py", line 1952, in print_pdf return pdf.print_pdf(*args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_pdf.py", line 2352, in print_pdf self.figure.draw(renderer) File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1034, in draw func(*args) File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2086, in draw a.draw(renderer) File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1182, in draw im = self.make_image(renderer, image_mag) File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1172, in make_image im.resize(int(widthDisplay), int(heightDisplay), ValueError: cannot convert float NaN to integer </code></pre> <p>Not sure what I'm doing wrong. Neither <code>rho</code> nor <code>phi</code> are <code>Nan</code>, nor are they super small floats (which I've seen causing this error in other Stackoverflow answers). </p> <p><strong>Edit</strong>: In response to the comment asking for <code>plt.show()</code></p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1489, in __call__ return self.func(*args) File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 276, in resize self.show() File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 348, in draw FigureCanvasAgg.draw(self) File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 451, in draw self.figure.draw(self.renderer) File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1034, in draw func(*args) File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 2086, in draw a.draw(renderer) File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper draw(artist, renderer, *args, **kwargs) File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1182, in draw im = self.make_image(renderer, image_mag) File "/usr/lib/pymodules/python2.7/matplotlib/image.py", line 1172, in make_image im.resize(int(widthDisplay), int(heightDisplay), ValueError: cannot convert float NaN to integer </code></pre> <p>Min and max values of <code>rho</code> and <code>phi</code></p> <pre><code>&gt;&gt;&gt; min(rho), max(rho) (0.10336371748137782, 0.22005286472537541) &gt;&gt;&gt; min(phi), max(phi) (-2.9088677009635697, 1.3618299263576035) </code></pre>
1
2016-10-07T15:19:45Z
39,922,273
<p>You need to pass positive angles to Bbox, apparently. This should work:</p> <pre><code>def cart2pol(x, y): rho = np.sqrt(x**2 + y**2) phi = np.arctan2(y, x) if phi &lt; 0: phi += 2 * np.pi return(rho, phi) </code></pre>
1
2016-10-07T16:46:52Z
[ "python", "matplotlib" ]
Python, connect menu to functions
39,920,727
<p>I have got a menu and a couple of functions to continue working with.My task is to add more functions. The menu code right now, looks like this.</p> <pre><code>def menu(): """ Display the menu with the options that The Goddamn Batman can do. """ print(chr(27) + "[2J" + chr(27) + "[;H") print(meImage()) print("Hi, I'm The Goddamn Batman. There is nothing I can't do. What can I do you for?") print("1) Present yourself to The Goddamn Batman.") print("2) Tell me your age. I'm going to show you a neat trick.") print("q) Quit.") </code></pre> <p>The problem is print2. I get the alternative to show up in Cygwin but I when I press "2", I get an error. The function (not complete) looks like this:</p> <pre><code>def Age(): """ Ask the user's age and calculate for how many seconds the user has lived """ age = input("How old are you? ") if choice == int: print ("Ah, %s, that is old." % age) result = (input * (int)31 556 926) return result print("You know what? Your age actually makes ",result, "seconds.") else: print("That is not a valid choice. Please write a number.") </code></pre> <p>The previous functions, print 1 (name) and print q (the quit everything one), works fine. For example, print 1 looks like this:</p> <pre><code>def myNameIs(): """ Read the users name and say hello to The Goddamn Batman. """ name = input("What is your name? ") print("\nThe Goddamn Batman says:\n") print("Hello %s - you're something special." % name) print("What can I do for you?") </code></pre> <p>Why won't the print 2 (age) respond? The other ones work fine but I just can't add more functions and get them to work. Hopefully this helps other people to learn how to properly connect functions to a menu. I'm just stuck.</p> <p>So, to clarify, my problem is that the function <code>def myNameIs():</code> responds as a menu option in Cygwin. The function <code>def Age():</code> doesn't. I don't know why.</p> <p>Thanks in advance, I'm very grateful for any help you can provide. </p> <p>EDIT:</p> <p>Ok, after request. This is ALL the code there is. I'm very sorry for not providing just a fiddle but I don't know any fiddles I can use for python. I only find jsfiddle and it doesn't seem to have anything meant for python in it. </p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Marvin with a simple menu to start up with. Marvin doesnt do anything, just presents a menu with some choices. You should add functinoality to Marvin. """ def meImage(): """ Store my ascii image in a separat variabel as a raw string """ return r""" _==/ i i \==_ /XX/ |\___/| \XX\ /XXXX\ |XXXXX| /XXXX\ |XXXXXX\_ _XXXXXXX_ _/XXXXXX| XXXXXXXXXXXxxxxxxxXXXXXXXXXXXxxxxxxxXXXXXXXXXXX |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX |XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX| XXXXXX/^^^^"\XXXXXXXXXXXXXXXXXXXXX/^^^^^\XXXXXX |XXX| \XXX/^^\XXXXX/^^\XXX/ |XXX| \XX\ \X/ \XXX/ \X/ /XX/ "\ " \X/ " /" """ def menu(): """ Display the menu with the options that The Goddamn Batman can do. """ print(chr(27) + "[2J" + chr(27) + "[;H") print(meImage()) print("Hi, I'm The Goddamn Batman. There is nothing I can't do. What can I do for you?") print("1) Present yourself to The Goddamn Batman.") print("2) Tell me your age. I'm going to show you a neat trick.") print("q) Quit.") def myNameIs(): """ Read the users name and say hello to The Goddamn Batman. """ name = input("What is your name? ") print("\nThe Goddamn Batman says:\n") print("Hello %s - you're something special." % name) print("What can I do for you?") def Age(): """ Ask the user's age and calculate for how many seconds the user has lived """ age = input("How old are you? ") if choice == int: print ("Ah, %s, that is old." % age) result = (input * (int)31 556 926) return result print("You know what? Your age actually makes ",result, "seconds.") else: print("That is not a valid choice. Please write a number.") def main(): """ This is the main method, I call it main by convention. Its an eternal loop, until q is pressed. It should check the choice done by the user and call a appropriate function. """ while True: menu() choice = input("--&gt; ") if choice == "q": print("Bye, bye - and welcome back anytime!") return elif choice == "1": myNameIs() else: print("That is not a valid choice. You can only choose from the menu.") input("\nPress enter to continue...") if __name__ == "__main__": main() </code></pre>
0
2016-10-07T15:21:17Z
39,921,738
<p>You are converting years to seconds?</p> <p>1) In python <code>int()</code> is a function that takes a parameter, it doesn't cast values like <code>(int)31 556 926</code><br> 2) integer values don't have spaces in them<br> 3) You can't put code after a <code>return</code> statement and expect it to run<br> 4) <code>choice</code> is not probably not accessible in the <code>Age</code> function. You could add it as a parameter<br> 5) Check for <code>int</code> with <code>isinstance(choice, int)</code> instead of <code>==</code>, because you want to check for the <em>type</em> of the variable, not against the <code>int</code> class itself. </p> <pre><code>def Age(): """ Ask the user's age and calculate for how many seconds the user has lived """ age = input("How old are you? ") print("Ah, %s, that is old." % age) result = int(input) * 31556926 # Fixed this line print("You know what? Your age actually makes ",result, "seconds.") return result # Moved this line down </code></pre> <p>Regarding your menu, you never executed your functions, or prompted for <code>input</code>, but here's a trick you can do </p> <pre><code>menu_funcs = {'1': myNameIs, '2': Age} # map the options to functions while True: menu() choice = input("Enter an option: ") if choice == 'q': return # exit if choice in menu_funcs: menu_funcs[val]() # call the function else: print("That is not a valid choice. You can only choose from the menu.") </code></pre>
1
2016-10-07T16:15:32Z
[ "python" ]
unable to fetch updated variable from an active python module
39,920,833
<p>I am new to python and trying to create a module that would fetch a specific variable from an active module preferably as read only. I have tried importing the file in test2 but the print statement displays the length as 0. Cant understand why it is not able to get the current status of the variable and only reading the initialization.</p> <p>Below is what I have tried, any help would be greatly appreciated.</p> <p>Thanks.</p> <p>test1.py</p> <pre><code>from datetime import datetime,timedelta import time data=[] stop=datetime.now()+timedelta(minutes=5) while datetime.now()&lt;stop: time.sleep(1) data.append(datetime.now().time()) </code></pre> <p>test2.py:</p> <pre><code>from test1 import * print len(data) </code></pre>
1
2016-10-07T15:26:41Z
39,921,029
<p>When you wrap statements in:</p> <pre><code>if __name__ == "__main__" </code></pre> <p>The code within only gets executed when you execute that specific module from the Python interpreter. So your Main function won't get executed, and consequently your data variable won't be initialized, unless you run:</p> <pre><code>python test2.py </code></pre> <p>You can actually just remove that clause and it will work as expected.</p>
0
2016-10-07T15:37:06Z
[ "python" ]
model selection for GaussianMixture by using GridSearch
39,920,862
<p>I'd like to use the function GaussianMixture by scikit-learn, and I have to perform model selection. I want to do it by using GridSearchCV, and I would like to use for the selection the BIC and the AIC. Both these values are implemented into GaussianMixture(), but I don't know how to insert them into the definition of my custom scorer, since the function </p> <pre><code>make_scorer(score_func, greater_is_better=True, needs_proba=False, needs_threshold=False, **kwargs) </code></pre> <p>that I am using to create my custom scorer takes as input a function score_funct, that has to be defined as </p> <pre><code>score_func(y, y_pred, **kwargs) </code></pre> <p>Can someone help me?</p>
1
2016-10-07T15:28:02Z
39,921,941
<p>Using the BIC/AIC is an <em>alternative</em> to using cross validation. <code>GridSearchCV</code> selects models using cross validation. To perform model selection using the BIC/AIC we have to do something a little different. Let's take an example where we generate samples from two Gaussians, and then try to fit them using scikit-learn. </p> <pre><code>import numpy as np X1 = np.random.multivariate_normal([0.,0.],[[1.,0.],[0.,1.]],10000) X2 = np.random.multivariate_normal([10.,10.],[[1.,0.],[0.,1.]],10000) X = np.vstack((X1,X2)) np.random.shuffle(X) </code></pre> <p><a href="http://i.stack.imgur.com/3SxTu.png" rel="nofollow"><img src="http://i.stack.imgur.com/3SxTu.png" alt="enter image description here"></a></p> <p><strong>Method 1: Cross-validation</strong></p> <p><a href="https://en.wikipedia.org/wiki/Cross-validation_%28statistics%29" rel="nofollow">Cross validation</a> involves splitting the data into pieces. One then fits the model on some of the pieces ('training') and tests how well it performs on the remaining pieces ('validating'). This guards against over-fitting. Here we will use two-fold cross validation, where we split the data in half.</p> <pre><code>from sklearn.mixture import GaussianMixture from sklearn.model_selection import GridSearchCV import matplotlib.pyplot as plt #check 1-&gt;4 components tuned_parameters = {'n_components': np.array([1,2,3,4])} #construct grid search object that uses 2 fold cross validation clf = GridSearchCV(GaussianMixture(),tuned_parameters,cv=2) #fit the data clf.fit(X) #plot the number of Gaussians against their rank plt.scatter(clf.cv_results_['param_n_components'],\ clf.cv_results_['rank_test_score']) </code></pre> <p>We can see that 2-fold cross validation favours two Gaussian components, as we expect.</p> <p><a href="http://i.stack.imgur.com/oQ9cg.png" rel="nofollow"><img src="http://i.stack.imgur.com/oQ9cg.png" alt="enter image description here"></a> </p> <p><strong>Method 2: BIC/AIC</strong></p> <p>Instead of using cross-validation, we can evaluate the <a href="https://en.wikipedia.org/wiki/Bayesian_information_criterion" rel="nofollow">BIC</a> using the best-fit model given each number of Gaussians. We then choose the model that has the lowest BIC. The procedure would be identical if one used the AIC (although it is a different statistic, and can provide different answers: but your code structure would be identical to below).</p> <pre><code>bic = np.zeros(4) n = np.arange(1,5) models = [] #loop through each number of Gaussians and compute the BIC, and save the model for i,j in enumerate(n): #create mixture model with j components gmm = GaussianMixture(n_components=j) #fit it to the data gmm.fit(X) #compute the BIC for this model bic[i] = gmm.bic(X) #add the best-fit model with j components to the list of models models.append(gmm) </code></pre> <p>After carrying out this procedure, we can plot the number of Gaussians against the BIC.</p> <pre><code>plt.plot(n,bic) </code></pre> <p><a href="http://i.stack.imgur.com/SwZ2R.png" rel="nofollow"><img src="http://i.stack.imgur.com/SwZ2R.png" alt="enter image description here"></a></p> <p>So we can see that the BIC is minimised for two Gaussians, so the best model according to this method also has two components.</p> <p>Because I took 10000 samples from two very well-separated Gaussians (i.e. the distance between their centres is much larger than either of their dispersions), the answer was very clear-cut. This is not always the case, and often neither of these methods will confidently tell you which number of Gaussians to use, but rather some sensible range.</p>
0
2016-10-07T16:27:22Z
[ "python", "scikit-learn", "grid-search" ]
Writing a program that creates a particular pattern using the number sign
39,920,886
<p>How can this particular pattern be created using the number sign. <strong>Note</strong>, the first line must be indented.</p> <p><strong><em>Write a program that creates a pattern like the one below. Let the user input a nonnegative integer to determine the number of lines of the pattern.</em></strong></p> <p>I am currently at this step, confused on how to indent the first line. </p> <pre><code> for row in range(5): print('# #') # # # # # # # # # # </code></pre>
-3
2016-10-07T15:29:47Z
39,921,636
<p>Print the first line before the loop.</p> <pre><code>print " # #" for row in range(4): print "# #" </code></pre> <p>Or use an <code>if</code> statement</p> <pre><code>for row in range(5): if row == 0: print " ", # trailing comma prints without a newline print "# " </code></pre>
0
2016-10-07T16:10:09Z
[ "python" ]
Python Function Return Statement is Confusing and Complex
39,920,930
<p>Could any body explain what do the 'and' and 'or' statements are doing in the return statement of the function below ? the function seems to be returning the largest common denominator of a and b. </p> <p> <code>def gcd(a,b): return b and gcd(b, a % b) or a</code></p> <p>Thank you !</p>
-1
2016-10-07T15:31:54Z
39,921,014
<p>The first thing we can do is put in some parenthesis:</p> <pre><code>((b and gcd(b, a % b)) or a) </code></pre> <p>Now lets take this piece by piece:</p> <pre><code>b and gcd(b, a % b) </code></pre> <p>This will give <code>b</code> if <code>b</code> is falsy. Otherwise it'll give you <code>gcd(b, a % b)</code>. In other words, it's equivalent to the following conditional expression:</p> <pre><code>b if not b else gcd(b, a % b) </code></pre> <p>The next part of the expression is:</p> <pre><code>(...) or a </code></pre> <p>Which will give you <code>a</code> if the previous expression has a falsy result, otherwise it'll give you the previous expression.</p> <p>Note that this <em>might</em> not be what you're expecting if you come from a language like <code>C</code> where boolean operations return booleans :-). In python, the only boolean operation that is <em>guaranteed</em> to return a boolean is <code>not</code>. This all tends to "just work" however because python knows how to get an object's "truth value" when it needs it. e.g.:</p> <pre><code>if obj: ... </code></pre> <p>will actually check <code>bool(obj)</code> implicitly.</p> <hr> <p>So, if I were to write out the whole thing using <code>if</code> suites, it would look like:</p> <pre><code>def gcd(a, b): if not b: # Likely `b == 0`. This is the recursion base-case. val = b else: val = gcd(b, a % d) if val: return val else: return a </code></pre>
6
2016-10-07T15:36:19Z
[ "python", "python-2.7", "function", "python-3.x" ]
Python Function Return Statement is Confusing and Complex
39,920,930
<p>Could any body explain what do the 'and' and 'or' statements are doing in the return statement of the function below ? the function seems to be returning the largest common denominator of a and b. </p> <p> <code>def gcd(a,b): return b and gcd(b, a % b) or a</code></p> <p>Thank you !</p>
-1
2016-10-07T15:31:54Z
39,921,032
<p>The function continuously returns <code>gcd(b, a % b)</code> while <code>b</code> has a truthy value, i.e not equal to zero in this case. </p> <p>When <code>b</code> reaches <code>0</code> (after consecutively being assigned to the result of <code>a % b</code>), <code>b and gcd(b, a % b)</code> will be <code>False</code> and the value of <code>a</code> will be returned.</p>
0
2016-10-07T15:37:10Z
[ "python", "python-2.7", "function", "python-3.x" ]
referencing class members from child class
39,921,165
<p>Edit: sorry for the confusion about parent/child. I am new to OOP so confusing my terms. </p> <p>I would like to understand the appropriate strategy to reference class attributes which will be provided by an inherited (child class). </p> <p>I have a case where I have a common base class which will be used, and multiple parent classes which the child class can inherit from. Each child class will have the same set of methods but different implementations. The problem I have is that I need the child class to reference class attributes of the parent. The code below seems to work fine but my IDE (pycharm) complains of an unresolved attribute reference, so I am wondering if this is an anti-pattern. </p> <p>Module <strong>parent1.py</strong>:</p> <pre><code>class Parent(object): def __init__(self): pass def do_something(self): result = self.instance_id </code></pre> <p>Module <strong>parent2.py</strong>: </p> <pre><code>class Parent(object): def __init__(self): pass def do_something(self): result = self.instance_id+1 </code></pre> <p>Module <strong>child.py</strong>:</p> <pre><code>if CONSTANT: from parent1 import Parent else: from parent2 import Parent class Child(Parent): def __init__(self, instance_id): self.instance_id = instance_id Parent.__init__(self) </code></pre> <p>In this case the pycharm IDE flags the reference to self.instance_id in Parent1 and Parent2 as an 'Unresolved attribute reference' even though the code works. I thought about moving this into each parent class, but nothing about instance_id needs to change in the Parent class, so it feels redundant to define it once for each Parent. So my question is as follows: 1. Is there anything wrong with this code organization? 2. If there is nothing wrong with it, how can i fix the IDE to resolve this reference?</p>
2
2016-10-07T15:44:43Z
39,922,510
<p>Use a <code>BaseParent</code> class that defines <code>instance_id</code>, and have both <code>Parent</code> implementations inherit from it. This will shut up your IDE. As a side benefit, <code>Child</code> can extend either <code>Parent</code>, but will always be an instance of <code>BaseParent</code>.</p> <p>That aside, this is not very <em>kosher</em> object-oriented design. Changing the class hierarchy during program execution falls under <em>metaprogramming</em>, a very powerful tool that should be rarely used.</p> <p>Metaprogramming, like multiple inheritance, is sometimes the perfect solution for a problem -- but it comes at a cost. Both introduce a layer of complexity that's hard to understand, easy to miss while walking the codebase and difficult to maintain afterwards.</p> <p>This is especially true when the reader is not the implementer, or even for the same person after some time. I would revise the decision, in most cases this kind of approach is not necessary.</p>
1
2016-10-07T17:00:50Z
[ "python", "class", "python-3.x" ]
Django: Using get_form_kwarg to pass url pramater into form __init__ for ModelChoiceField selection filiter
39,921,273
<p>I am building a FAQ app.</p> <p>Model flow Topic -> Section -> Article.</p> <p>Article has a FK to Section which has a FK to Topic.</p> <p>In my create article from I want to take in the Topic_Pk so when the user selects a Section the choice selection is limited to just the Sections attached under the Topic.</p> <p>I am using get_from_kwarg to pass the Topic_Pk from the url to <code>__init__</code> in the form. I keep getting a <code>TypeError __init__() got an unexpected keyword argument 'topic_pk'</code>. I do not want to pop the data or set topic_pk=None in the <code>__init__</code> parameters as this would invalidate the whole point.</p> <p>What is it I am missing to allow me to use this variable?</p> <p>Url:</p> <pre><code>url(r'^ironfaq/(?P&lt;topic_pk&gt;\d+)/article/create$', ArticleCreateView.as_view()), </code></pre> <p>View:</p> <pre><code>class ArticleCreateView(CreateView): model = Article form_class = CreateArticleForm template_name = "faq/form_create.html" success_url = "/ironfaq" def get_form_kwargs(self): kwargs = super(ArticleCreateView,self).get_form_kwargs() kwargs.update(self.kwargs) return kwargs </code></pre> <p>Form:</p> <pre><code>class CreateArticleForm(forms.ModelForm): section = forms.ModelChoiceField(queryset=Section.objects.none()) def __init__(self, *args, **kwargs): super(CreateArticleForm, self).__init__(*args, **kwargs) self.fields['section'].queryset = Section.objects.filter(topic_pk=self.kwargs['topic_pk']) class Meta: model = Article widgets = { 'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}), } fields = ('title','section','answer') </code></pre> <p>Model:</p> <pre><code>class Article(Audit): title = models.CharField(max_length=255) sort = models.SmallIntegerField() slug = models.SlugField() section = models.ForeignKey(Section,on_delete=models.CASCADE) answer = models.TextField() vote_up = models.IntegerField() vote_down = models.IntegerField() view_count = models.IntegerField(default=0) class Meta: verbose_name_plural = "articles" def __str__(self): return self.title def total_votes(self): return self.vote_up + self.vote_down def percent_yes(self): return (float(self.vote_up) / self.total_votes()) * 100 def get_absolute_url(self): return ('faq-article-detail',(), {'topic__slug': self.section.topic.slug, 'section__slug': self.section.slug, 'slug': self.slug}) </code></pre>
1
2016-10-07T15:50:44Z
39,921,451
<p>For your current <code>__init__</code> signature, you <strong>must</strong> pop <code>topic_pk</code> from kwargs before you call <code>super()</code>, otherwise you'll get the <code>TypeError</code>. </p> <p>In your question, you say that popping the value would 'invalidate the whole point', but I think you're mistaken. You can still use the <code>topic_pk</code> value after calling <code>super()</code>.</p> <pre><code>class CreateArticleForm(forms.ModelForm): section = forms.ModelChoiceField(queryset=Section.objects.none()) def __init__(self, *args, **kwargs): topic_pk = kwargs.pop('topic_pk') super(CreateArticleForm, self).__init__(*args, **kwargs) self.fields['section'].queryset = Section.objects.filter(topic_pk=topic_pk) </code></pre> <p>Another approach would be to use <code>topic_pk</code> as a named argument. Note that this changes the signature of the <code>__init__</code> method, so it might break other code (for example if you had <code>CreateArticleForm(request.POST)</code> somewhere else).</p> <pre><code> def __init__(self, topic_pk=None, *args, **kwargs): super(CreateArticleForm, self).__init__(*args, **kwargs) self.fields['section'].queryset = Section.objects.filter(topic_pk=topic_pk) </code></pre>
3
2016-10-07T16:00:03Z
[ "python", "django" ]
Access XML element by name
39,921,344
<p><a href="http://i.stack.imgur.com/Yp0yd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Yp0yd.png" alt="enter image description here"></a></p> <p>Im using <code>xml.etree.ElementTree</code> to parse my XML data. I'm trying to get the text value of <code>&lt;Name&gt;</code></p> <p>This is my code.</p> <pre><code>for Content in Zone[0]: print(Content.find('Name').text) </code></pre> <p>It is returning as NoneObject</p> <p>However, I am able to access the Element using</p> <pre><code>for Content in Zone[0]: print(Content[12].text) </code></pre> <p>I think I might have found the problem as when I print the tags out, it doesn't display <code>Name</code> and instead it displays <code>{http://schemas.datacontract.org/2004/07/}Name</code>. What is the extra data infront of the tag name?</p>
-1
2016-10-07T15:54:46Z
39,927,491
<p>Your XML is likely has default namespace -namespace declared with no prefix-. Notice that descendant elements without prefix inherits default namespace implicitly. You can handle default namespace the way you would <a href="http://stackoverflow.com/questions/14853243/parsing-xml-with-namespace-in-python-via-elementtree">handle prefixed namespaces</a>; just map a prefix to the namespace URI, and use that prefix along with element name to reference element in namespace :</p> <pre><code>namespaces = {'d': 'http://schemas.datacontract.org/2004/07/'} for Content in Zone[0]: print(Content.find('d:Name', namespaces).text) </code></pre>
0
2016-10-08T00:35:15Z
[ "python", "xml" ]
Parsing XML response with repeated tags
39,921,353
<p>This is my XML response - </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Dataset name="aggregations/g/ds083.2/2/TP" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xml.opendap.org/ns/DAP2" xsi:schemaLocation="http://xml.opendap.org/ns/DAP2 http://xml.opendap.org/dap/dap2.xsd" &gt; &lt;Attribute name="NC_GLOBAL" type="Container"&gt; &lt;Attribute name="Originating_or_generating_Center" type="String"&gt; &lt;value&gt;US National Weather Service, National Centres for Environmental Prediction (NCEP)&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Originating_or_generating_Subcenter" type="String"&gt; &lt;value&gt;0&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="GRIB_table_version" type="String"&gt; &lt;value&gt;2,1&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Type_of_generating_process" type="String"&gt; &lt;value&gt;Forecast&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Analysis_or_forecast_generating_process_identifier_defined_by_originating_centre" type="String"&gt; &lt;value&gt;Analysis from GDAS (Global Data Assimilation System)&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="file_format" type="String"&gt; &lt;value&gt;GRIB-2&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Conventions" type="String"&gt; &lt;value&gt;CF-1.6&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="history" type="String"&gt; &lt;value&gt;Read using CDM IOSP GribCollection v3&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="featureType" type="String"&gt; &lt;value&gt;GRID&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="_CoordSysBuilder" type="String"&gt; &lt;value&gt;ucar.nc2.dataset.conv.CF1Convention&lt;/value&gt; &lt;/Attribute&gt; &lt;/Attribute&gt; &lt;Grid name="Temperature_isobaric"&gt; &lt;Attribute name="long_name" type="String"&gt; &lt;value&gt;Temperature @ Isobaric surface&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="units" type="String"&gt; &lt;value&gt;K&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="abbreviation" type="String"&gt; &lt;value&gt;TMP&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="missing_value" type="Float32"&gt; &lt;value&gt;NaN&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="grid_mapping" type="String"&gt; &lt;value&gt;LatLon_Projection&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="coordinates" type="String"&gt; &lt;value&gt;reftime3 time3 isobaric3 lat lon &lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Grib_Variable_Id" type="String"&gt; &lt;value&gt;VAR_7-0--1-0_L100&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Grib2_Parameter" type="Int32"&gt; &lt;value&gt;0&lt;/value&gt; &lt;value&gt;0&lt;/value&gt; &lt;value&gt;0&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Grib2_Parameter_Discipline" type="String"&gt; &lt;value&gt;Meteorological products&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Grib2_Parameter_Category" type="String"&gt; &lt;value&gt;Temperature&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Grib2_Parameter_Name" type="String"&gt; &lt;value&gt;Temperature&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Grib2_Level_Type" type="String"&gt; &lt;value&gt;Isobaric surface&lt;/value&gt; &lt;/Attribute&gt; &lt;Attribute name="Grib2_Generating_Process_Type" type="String"&gt; &lt;value&gt;Forecast&lt;/value&gt; &lt;/Attribute&gt; &lt;Array name="Temperature_isobaric"&gt; &lt;Float32/&gt; &lt;dimension name="time3" size="12911"/&gt; &lt;dimension name="isobaric3" size="31"/&gt; &lt;dimension name="lat" size="181"/&gt; &lt;dimension name="lon" size="360"/&gt; &lt;/Array&gt; &lt;Map name="time3"&gt; &lt;Float64/&gt; &lt;dimension name="time3" size="12911"/&gt; &lt;/Map&gt; &lt;Map name="isobaric3"&gt; &lt;Float32/&gt; &lt;dimension name="isobaric3" size="31"/&gt; &lt;/Map&gt; &lt;Map name="lat"&gt; &lt;Float32/&gt; &lt;dimension name="lat" size="181"/&gt; &lt;/Map&gt; &lt;Map name="lon"&gt; &lt;Float32/&gt; &lt;dimension name="lon" size="360"/&gt; &lt;/Map&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>I want to be able to get <em>ALL</em> the names of "Map" attribute i.e. time,isobaric,lat,lon. Currently with the below code it <em>only</em> prints out the first one. I tried iterating but it only prints the time variable n times. </p> <pre><code> import requests from xml.etree import ElementTree response = requests.get("http://rda.ucar.edu/thredds/dodsC/aggregations/g/ds083.2/2/TP.ddx?Temperature_isobaric") tree = ElementTree.fromstring(response.content) grid = tree.find("{http://xml.opendap.org/ns/DAP2}Grid") map = grid.find("{http://xml.opendap.org/ns/DAP2}Map") for child in map: print(child.get('name')) </code></pre>
0
2016-10-07T15:55:07Z
39,921,690
<p>Two small changes:</p> <pre><code>map = grid.findall("{http://xml.opendap.org/ns/DAP2}Map") for child in map: print(child.get('name')) </code></pre> <p><code>findall</code> gets all matches, and when you are looping over <code>child in map</code> you want to be sure that you are returning values relating to <code>child</code>.</p>
2
2016-10-07T16:12:40Z
[ "python", "xml", "xml-parsing", "httprequest", "python-3.5" ]
How to remove the border of a Tkinter OptionMenu Widget
39,921,360
<p>I have been looking through multiple websites, which only give me a half satisfactory answer, how would I colour each part of of a Tkinter OptionMenu Widget?</p> <p>Code Snippet:</p> <pre><code>from tkinter import * root = Tk() text = StringVar() fr = Frame (root,bg="yellow") fr.grid() menu = OptionMenu (fr, text, "hi", "there") menu.grid (pady=50, padx=50) # Pretty colouring goes here # Or ugly yellow, I don't mind menu ["menu"] ["bg"] = "yellow" menu ["bg"] = "yellow" menu ["activebackground"] = "green" root.mainloop() </code></pre> <p>Or should I just give up and settle for grey?</p>
-1
2016-10-07T15:55:16Z
39,941,732
<p>I don't understand your problem.</p> <p>menu["menu"] is a tkinter.Menu object, so you can set others options.</p> <p>Possible colors options are :</p> <ul> <li>activebackground -> that you want </li> <li>activeforeground -> that you want</li> <li>background</li> <li>bg</li> <li>disabledforeground</li> <li>fg</li> <li>foreground </li> <li>selectcolor</li> </ul>
0
2016-10-09T08:53:23Z
[ "python", "python-3.x", "tkinter", "colors", "optionmenu" ]
How to remove the border of a Tkinter OptionMenu Widget
39,921,360
<p>I have been looking through multiple websites, which only give me a half satisfactory answer, how would I colour each part of of a Tkinter OptionMenu Widget?</p> <p>Code Snippet:</p> <pre><code>from tkinter import * root = Tk() text = StringVar() fr = Frame (root,bg="yellow") fr.grid() menu = OptionMenu (fr, text, "hi", "there") menu.grid (pady=50, padx=50) # Pretty colouring goes here # Or ugly yellow, I don't mind menu ["menu"] ["bg"] = "yellow" menu ["bg"] = "yellow" menu ["activebackground"] = "green" root.mainloop() </code></pre> <p>Or should I just give up and settle for grey?</p>
-1
2016-10-07T15:55:16Z
39,953,629
<p>All that I had to do was set the <code>highlightthickness</code> option to <code>0</code></p> <p><code>menu["highlightthickness"]=0</code></p> <p>This get's rid of the ugly border around the drop down menu.</p>
0
2016-10-10T07:55:17Z
[ "python", "python-3.x", "tkinter", "colors", "optionmenu" ]
I keep getting 'invalid character in identifier' when opening a file in python
39,921,432
<p>So I'm trying to open a file with the following code: </p> <pre><code>open(‘datapickle’, ‘rb’) as f: names, F, approximate = pickle.load(f) </code></pre> <p>However, I constantly get: <a href="http://i.stack.imgur.com/qPhR9.png" rel="nofollow"><img src="http://i.stack.imgur.com/qPhR9.png" alt="enter image description here"></a></p> <p>what can I do to fix this? Please help :( </p>
1
2016-10-07T15:59:15Z
39,921,475
<p>Two problems:</p> <ol> <li><p>Those tick characters <code>‘</code> are not valid. Use single <code>'</code> or double <code>"</code> quotes.</p></li> <li><p>The correct syntax is <code>with open(...) as f</code>. You're missing the <code>with</code> statement.</p></li> </ol> <p>The editor you're using should be highlighting your text in different colors to help you with this. If you don't have an editor that can do this, try downloading <a href="https://www.sublimetext.com/" rel="nofollow">Sublime Text</a> or <a href="https://atom.io/" rel="nofollow">Atom</a>.</p>
4
2016-10-07T16:01:50Z
[ "python", "pickle" ]
Reading hdf5 file quickly with cython and h5py
39,921,433
<p>I'm trying to speed up a python3 function that takes some data, which is an array of indexes and saves them if they meet a certain criterion. I have tried to speed it up by using "cython -a script.py", but the bottle neck seems to be the h5py I/O slicing datasets.</p> <p>I'm relatively new to cython, so I was wondering whether there is anyway to speed this up or am I just limited by the h5py I/O here?</p> <p>Here is the function I'm trying to improve:</p> <pre><code>import numpy as np import h5py cimport numpy as np cimport cython from libc.math cimport sqrt DTYPE64 = np.int64 ctypedef np.int64_t DTYPE64_t DTYPE32 = np.int32 ctypedef np.int32_t DTYPE32_t @cython.boundscheck(False) @cython.wraparound(False) def tag_subhalo_branch(np.ndarray[DTYPE64_t] halos_z0_treeindxs, np.ndarray[DTYPE64_t] tree_pindx, np.ndarray[DTYPE32_t] tree_psnapnum, np.ndarray[DTYPE64_t] tree_psnapid, np.ndarray[DTYPE64_t] tree_hsnapid, hf, int size): cdef int i cdef double radial, progen_x, progen_y, progen_z cdef double host_x, host_y, host_z, host_rvir cdef DTYPE64_t progen_indx, progen_haloid, host_id cdef DTYPE32_t progen_snap cdef int j = 0 cdef int size_array = size cdef np.ndarray[DTYPE64_t] backsplash_ids = np.zeros(size_array, dtype=DTYPE64) for i in range(0, size_array): progen_indx = tree_pindx[halos_z0_treeindxs[i]] if progen_indx != -1: progen_snap = tree_psnapnum[progen_indx] progen_haloid = tree_psnapid[progen_indx] while progen_indx != -1 and progen_snap != -1: # ** This is slow ** grp = hf['Snapshots/snap_' + str('%03d' % progen_snap) + '/'] host_id = grp['HaloCatalog'][(progen_haloid - 1), 2] # ** if host_id != -1: # ** This is slow ** progen_x = grp['HaloCatalog'][(progen_haloid - 1), 6] host_x = grp['HaloCatalog'][(host_id - 1), 6] progen_y = grp['HaloCatalog'][(progen_haloid - 1), 7] host_y = grp['HaloCatalog'][(host_id - 1), 7] progen_z = grp['HaloCatalog'][(progen_haloid - 1), 8] host_z = grp['HaloCatalog'][(host_id - 1), 8] # ** radial = 0 radial += (progen_x - host_x)**2 radial += (progen_y - host_y)**2 radial += (progen_z - host_z)**2 radial = sqrt(radial) host_rvir = grp['HaloCatalog'][(host_id - 1), 24] if radial &lt;= host_rvir: backsplash_ids[j] = tree_hsnapid[ halos_z0_treeindxs[i]] j += 1 break # Find next progenitor information progen_indx = tree_pindx[progen_indx] progen_snap = tree_psnapnum[progen_indx] progen_haloid = tree_psnapid[progen_indx] return backsplash_ids </code></pre>
0
2016-10-07T15:59:17Z
39,923,322
<p>As described here: <a href="http://api.h5py.org/" rel="nofollow">http://api.h5py.org/</a>, <code>h5py</code> uses <code>cython</code> code to interface with the <code>HDF5</code> <code>c</code> code. So your own <code>cython</code> code might be able to access that directly. But I suspect that will require a lot more study.</p> <p>Your code is using the Python interface to <code>h5py</code>, and <code>cythonizing</code> isn't going to touch that.</p> <p><code>cython</code> code is best used for low level actions, especially iterative things that can't be expressed as array operations. Study and experiment with the <code>numpy</code> examples first. You are diving into <code>cython</code> at the deep end of the pool.</p> <p>Have you tried to improve that code just with Python and numpy? Just at glance I'm seeing a lot of redundant <code>h5py</code> calls.</p> <p>====================</p> <p>Your <code>radial</code> calculation accesses the <code>h5py</code> indexing 6 times when it could get by with 2. Maybe you wrote it that way in hopes that <code>cython</code> would preform the following calculation faster than numpy?</p> <pre><code>data = grp['HaloCatalog'] progen = data[progen_haloid-1, 6:9] host = data[host_id-1, 6:9] radial = np.sqrt((progren-host)**2).sum(axis=1)) </code></pre> <p>Why not load all <code>data[progen_haloid-1,:]</code> and <code>data[host_id-1,:]</code>? Even all of <code>data</code>? I'd have to review when <code>h5py</code> switches from working directly with the arrays on the file and when they become <code>numpy</code> arrays. In any case, math on arrays in memory will be a lot faster than file reads.</p>
0
2016-10-07T18:00:24Z
[ "python", "cython", "h5py" ]
Django 1.7 and PSQL: on_delete=models.SET_NULL not work
39,921,445
<p>My models.py:</p> <pre><code>class MyFile(models.Model): file = models.FileField(upload_to="myfiles", max_length=500, storage=OverwriteStorage()) slug = models.SlugField(max_length=500, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, blank=True, null=True,) date_created = models.DateTimeField(auto_now_add = True, blank=True, null=True) date_expired = models.DateTimeField(default=default_time, blank=True, null=True) expires = models.BooleanField(default=True) def __str__(self): return self.file.name @models.permalink def get_absolute_url(self): return ('myfile:myfile-new', ) def save(self, *args, **kwargs): self.slug = self.file.name super(MyFile, self).save(*args, **kwargs) def delete(self, *args, **kwargs): self.file.delete(False) super(MyFile, self).delete(*args, **kwargs) class Meta: managed = True @receiver(pre_delete, sender=MyFile) def remove_file(**kwargs): instance = kwargs.get('instance') instance.file.delete(save=False) class Operation(models.Model): id = models.AutoField(primary_key = True) user = models.ForeignKey(User, blank=True, null=True) myfile = models.ForeignKey(MyFile, blank=True, null=True) def get_data(self): return json.loads(self.data) class Meta: managed = True class UserProfile(models.Model): user = models.OneToOneField(User) subscribe = models.BooleanField(default=True) def __unicode__(self): return u'Profile of user: %s' % (self.user.username) class Meta: managed = True def create_user_profile(sender, instance, created, **kwargs): from django.conf import settings subscribe = False if created: profile, created = UserProfile.objects.get_or_create(user=instance, subscribe=subscribe) post_save.connect(create_user_profile, sender=User) </code></pre> <p>But, if User deleted, all related myfiles still deleted.</p> <p>Any idea? Thanks</p> <p><strong>UPDATE</strong></p> <p>Database is postgres9.3.5, and I used \d+ to check the information of tables before and after migration, <strong>NO difference</strong>. wired.</p> <pre><code># \d+ ui.myproject_myfile; Table "ui.myproject_myfile" Column | Type | Modifiers | Storage | Stats target | Description --------------+--------------------------+------------------------------------------------------------------+----------+--------------+------------- id | integer | not null default nextval('ui.myproject_myfile_id_seq'::regclass) | plain | | file | character varying(500) | not null | extended | | slug | character varying(500) | not null | extended | | user_id | integer | | plain | | date_created | timestamp with time zone | | plain | | date_expired | timestamp with time zone | | plain | | expires | boolean | not null | plain | | Indexes: "myproject_myfile_pkey" PRIMARY KEY, btree (id) "myproject_myfile_2dbcba41" btree (slug) "myproject_myfile_e8701ad4" btree (user_id) Foreign-key constraints: "myproject_myfile_user_id_a422765c7101118_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES ui.auth_user(id) DEFERRABLE INITIALLY DEFERRED Referenced by: TABLE "ui.myproject_operation" CONSTRAINT "myproject_ope_myfile_id_3f071e8e8361943b_fk_myproject_myfile_id" FOREIGN KEY (myfile_id) REFERENCES ui.myproject_myfile(id) DEFERRABLE INITIALLY DEFERRED Has OIDs: no </code></pre> <p><strong>UPDATE</strong></p> <pre><code>#ALTER TABLE ui.myproject_myfile ADD CONSTRAINT user_id_fk FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE SET NULL; </code></pre> <p><strong>Then, I found the following added to the descriptions of my table. But still not work. If user deleted, all myfiles deleted, too.</strong> "user_id_fk" FOREIGN KEY (user_id) REFERENCES ui.auth_user(id) ON DELETE SET NULL</p> <p><strong>UPDATE</strong></p> <p>I am thinking about whether to delete this post. Problem solved after VM rebooted. NO idea why. But thank all of you.</p>
0
2016-10-07T15:59:46Z
39,922,893
<p>The default behavior of <code>on_delete</code> results in all related objects being deleted; in this case, the related object is MyFile.</p> <p>If you're trying to preserve the MyFile object, maybe consider adding a default via <code>on_delete=SET_DEFAULT</code> or using a callable passed to <code>on_default=SET(callable)</code></p>
0
2016-10-07T17:28:42Z
[ "python", "django", "django-models" ]
Python Threading: Making the thread function return from an external signal
39,921,570
<p>Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread. </p> <h1>test27.py</h1> <pre><code>import threading import time lock = threading.Lock() def Read(x,y): flag = 1 while True: lock.acquire() try: z = x+y; w = x-y print z*w time.sleep(1) if flag == 0: print "ABORTING" return finally: print " SINGLE run of thread executed" lock.release() </code></pre> <h1>test28.py</h1> <pre><code>import time, threading from test27 import Read print "Hello Welcome" a = 2; b = 5 t = threading.Thread(target = Read, name = 'Example Thread', args = (a,b)) t.start() time.sleep(5) t.flag = 0 # This is not updating the flag variable in Read FUNCTION t.join() # Because of the above command I am unable to wait until the thread finishes. It is blocking. print "PROGRAM ENDED" </code></pre>
0
2016-10-07T16:06:36Z
39,921,795
<p>Regular variables should not be tracked in threads. This is done to prevent race condition. You must use thread-safe constructs to communicate between threads. For a simple flag use <code>threading.Event</code>. Also you cannot access local variable <code>flag</code> via thread object. It is local, and is only visible from scope. You must either use a global variable, as in my example below or create an Object before calling your thread and use a member variable.</p> <pre><code>from threading import Event flag = Event() def Read(x,y): global flag flag.clear() ... if flag.is_set(): return </code></pre> <p>main thread:</p> <pre><code>sleep(5) flag.set() </code></pre> <p>P.S.: I just noticed that you attempted to use lock() in the thread, but failed to use it in the main thread. For a simple flag go with Event. For a lock() you need to lock both parts and mitigate a risk of a deadlock. </p>
0
2016-10-07T16:18:31Z
[ "python", "multithreading", "time" ]
Python Threading: Making the thread function return from an external signal
39,921,570
<p>Could anyone please point out whats wrong with this code. I am trying to return the thread through a variable flag, which I want to control in my main thread. </p> <h1>test27.py</h1> <pre><code>import threading import time lock = threading.Lock() def Read(x,y): flag = 1 while True: lock.acquire() try: z = x+y; w = x-y print z*w time.sleep(1) if flag == 0: print "ABORTING" return finally: print " SINGLE run of thread executed" lock.release() </code></pre> <h1>test28.py</h1> <pre><code>import time, threading from test27 import Read print "Hello Welcome" a = 2; b = 5 t = threading.Thread(target = Read, name = 'Example Thread', args = (a,b)) t.start() time.sleep(5) t.flag = 0 # This is not updating the flag variable in Read FUNCTION t.join() # Because of the above command I am unable to wait until the thread finishes. It is blocking. print "PROGRAM ENDED" </code></pre>
0
2016-10-07T16:06:36Z
39,926,065
<p>The <code>Thread</code> class can be instantiated with the <code>target</code> argument. Then you just give it a function which should be raun in a new thread. It is a convenient way to start a simple thread, but for more control it is usualy easier to have a class inherited from <code>Thread</code>, which has additional member variables, like the <code>flag</code> for aborting.</p> <p>For example:</p> <pre><code>import time import threading class MyThread(threading.Thread): def __init__(self, x, y): super().__init__() # or in Python 2: # super(MyThread, self).__init__() self.x = x self.y = y self._stop_requested = False def run(self): while not self._stop_requested: z = self.x + self.y w = self.x - self.y print (z * w) time.sleep(1) def stop(self, timeout=None): self._stop_requested = True self.join(timeout) </code></pre> <p>Then, to start the thread, call <code>start()</code> and then to stop it call <code>stop()</code>:</p> <pre><code>&gt;&gt;&gt; def run_thread_for_5_seconds(): ... t = MyThread(3, 4) ... t.start() ... time.sleep(5) ... t.stop() ... &gt;&gt;&gt; run_thread_for_5_seconds() -7 -7 -7 -7 -7 &gt;&gt;&gt; </code></pre>
0
2016-10-07T21:28:51Z
[ "python", "multithreading", "time" ]
Tensorflow: How to make a custom activation function with only python?
39,921,607
<p>So in Tensorflow it is possible to make your own activation function. But it is quite complicated, you have to write it in C++ and recompile the whole of tensorflow <a href="https://www.quora.com/Is-it-possible-to-add-new-activation-functions-to-TensorFlow-Theano-Torch-How" rel="nofollow">[1]</a> <a href="https://www.tensorflow.org/versions/r0.11/how_tos/adding_an_op/index.html" rel="nofollow">[2]</a>.</p> <p>Is there a simpler way?</p>
3
2016-10-07T16:08:19Z
39,921,608
<p><strong>Yes There is!</strong></p> <p><strong>Credit:</strong> It was hard to find the information and get it working but here is an example copying from the principles and code found <a href="https://github.com/tensorflow/tensorflow/issues/1095" rel="nofollow">here</a> and <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow">here</a>.</p> <p><strong>Requirements:</strong> Before we start, there are two requirement for this to be able to succeed. First you need to be able to write your activation as a function on numpy arrays. Second you have to be able to write the derivative of that function either as a function in Tensorflow (easier) or in the worst case scenario as a function on numpy arrays. </p> <p><strong>Writing Activation function:</strong></p> <p>So let's take for example this function which we would want to use an activation function:</p> <pre><code>def spiky(x): r = x % 1 if r &lt;= 0.5: return r else: return 0 </code></pre> <p>Which look as follows: <a href="http://i.stack.imgur.com/gTUBr.png" rel="nofollow"><img src="http://i.stack.imgur.com/gTUBr.png" alt="Spiky Activation"></a></p> <p>The first step is making it into a numpy function, this is easy:</p> <pre><code>import numpy as np np_spiky = np.vectorize(spiky) </code></pre> <p>Now we should write its derivative.</p> <p><strong>Gradient of Activation:</strong> In our case it is easy, it is 1 if x mod 1 &lt; 0.5 and 0 otherwise. So:</p> <pre><code>def d_spiky(x): r = x % 1 if r &lt;= 0.5: return 1 else: return 0 np_d_spiky = np.vectorize(d_spiky) </code></pre> <p>Now for the hard part of making a TensorFlow function out of it.</p> <p><strong>Making a numpy fct to a tensorflow fct:</strong> We will start by making np_d_spiky into a tensorflow function. There is a function in tensorflow <code>tf.py_func(func, inp, Tout, stateful=stateful, name=name)</code> <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/script_ops.html" rel="nofollow">[doc]</a> which transforms any numpy function to a tensorflow function, so we can use it:</p> <pre><code>import tensorflow as tf from tensorflow.python.framework import ops np_d_spiky_32 = lambda x: np_d_spiky(x).astype(np.float32) def tf_d_spiky(x,name=None): with ops.op_scope([x], name, "d_spiky") as name: y = tf.py_func(np_d_spiky_32, [x], [tf.float32], name=name, stateful=False) return y[0] </code></pre> <p><code>tf.py_func</code> acts on lists of tensors (and returns a list of tensors), that is why we have <code>[x]</code> (and return <code>y[0]</code>). The <code>stateful</code> option is to tell tensorflow whether the function always gives the same output for the same input (stateful = False) in which case tensorflow can simply the tensorflow graph, this is our case and will probably be the case in most situations. One thing to be careful of at this point is that numpy used <code>float64</code> but tensorflow uses <code>float32</code> so you need to convert your function to use <code>float32</code> before you can convert it to a tensorflow function otherwise tensorflow will complain. This is why we need to make <code>np_d_spiky_32</code> first. </p> <p><strong>What about the Gradients?</strong> The problem with only doing the above is that even though we now have <code>tf_d_spiky</code> which is the tensorflow version of <code>np_d_spiky</code>, we couldn't use it as an activation function if we wanted to because tensorflow doesn't know how to calculate the gradients of that function. </p> <p><strong>Hack to get Gradients:</strong> As explained in the sources mentioned above, there is a hack to define gradients of a function using <code>tf.RegisterGradient</code> <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html#RegisterGradient" rel="nofollow">[doc]</a> and <code>tf.Graph.gradient_override_map</code> <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/framework.html" rel="nofollow">[doc]</a>. Copying the code from <a href="https://gist.github.com/harpone/3453185b41d8d985356cbe5e57d67342" rel="nofollow">harpone</a> we can modify the <code>tf.py_func</code> function to make it define the gradient at the same time:</p> <pre><code>def py_func(func, inp, Tout, stateful=True, name=None, grad=None): # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) # see _MySquareGrad for grad example g = tf.get_default_graph() with g.gradient_override_map({"PyFunc": rnd_name}): return tf.py_func(func, inp, Tout, stateful=stateful, name=name) </code></pre> <p>Now we are almost done, the only thing is that the grad function we need to pass to the above py_func function needs to take a special form. It needs to take in an operation, and the previous gradients before the operation and propagate the gradients backward after the operation.</p> <p><strong>Gradient Function:</strong> So for our spiky activation function that is how we would do it:</p> <pre><code>def spikygrad(op, grad): x = op.inputs[0] n_gr = tf_d_spiky(x) return grad * n_gr </code></pre> <p>The activation function has only one input, that is why <code>x = op.inputs[0]</code>. If the operation had many inputs, we would need to return a tuple, one gradient for each input. For example if the operation was <code>a-b</code>the gradient with respect to <code>a</code> is <code>+1</code> and with respect to <code>b</code> is <code>-1</code> so we would have <code>return +1*grad,-1*grad</code>. Notice that we need to return tensorflow functions of the input, that is why need <code>tf_d_spiky</code>, <code>np_d_spiky</code> would not have worked because it cannot act on tensorflow tensors. Alternatively we could have written the derivative using tensorflow functions:</p> <pre><code>def spikygrad2(op, grad): x = op.inputs[0] r = tf.mod(x,1) n_gr = tf.to_float(tf.less_equal(r, 0.5)) return grad * n_gr </code></pre> <p><strong>Combining it all together:</strong> Now that we have all the pieces, we can combine them all together:</p> <pre><code>np_spiky_32 = lambda x: np_spiky(x).astype(np.float32) def tf_spiky(x, name=None): with ops.op_scope([x], name, "spiky") as name: y = py_func(np_spiky_32, [x], [tf.float32], name=name, grad=spikygrad) # &lt;-- here's the call to the gradient return y[0] </code></pre> <p>And now we are done. And we can test it.</p> <p><strong>Test:</strong></p> <pre><code>with tf.Session() as sess: x = tf.constant([0.2,0.7,1.2,1.7]) y = tf_spiky(x) tf.initialize_all_variables().run() print(x.eval(), y.eval(), tf.gradients(y, [x])[0].eval()) </code></pre> <blockquote> <p>[ 0.2 0.69999999 1.20000005 1.70000005] [ 0.2 0. 0.20000005 0.] [ 1. 0. 1. 0.]</p> </blockquote> <p><strong>Success!</strong></p>
4
2016-10-07T16:08:19Z
[ "python", "tensorflow", "custom-build", "activation-function" ]
autoit.pixel_search returning color is not found
39,921,610
<p>I'm trying to grab the coordinates for a specific pixel value on the screen, but I can't seem to get any results. The error I get is "autoit.autoit.AutoItError: color is not found".</p> <p>To verify my code I have the mouse move the the pixel that has the colour I want. This is not necessary, it was just part of a test. I have two monitors and my fear was that the pixel search couldn't distinguish what monitor I wanted. So to test autoit knew where to look I did a basic "move mouse". Sure enough it moved to my image on monitor one, so I know it has the right monitor.</p> <p>Second I tested if the "autoit.pixel_get_color" could grab the value I wanted, it does (65281).Thought I might have to use the decimal instead of the HEX provided from the Windows Info application.</p> <p>I tested with the code below, this is the code using SciTE - light (.au3 file) and it works fine.</p> <pre><code>$coord = PixelSearch(0, 0, 1434, 899, 0x00FF02) If Not @error Then MsgBox(0, "X and Y are:", $coord[0] &amp; "," &amp; $coord[1]) EndIf </code></pre> <p>I tested grabbing the pixel with pyautogui and ultimately I can do it, but it is not as "clean" as autoit, so I'm trying to avoid it if possible. Autoit has that nice Window info screen that shows me the color, so it is really easy to just plug numbers into my script.</p> <p>Here is the code I have written currently in Python.</p> <pre><code>import autoit import pyautogui pyautogui.confirm('Press OK to start running script') autoit.mouse_move(374,608,10) # move mouse to where the color I want is located. pixelcolor = autoit.pixel_get_color(374,608) #get color of pixel pixelsearch = autoit.pixel_search(0,0,1434,899,0x00FF02) # search entire screen for color pixelsearch = autoit.pixel_search(0,0,1434,899,65281) # Tried using the value from the get_color, still same error. </code></pre> <p>Any Ideas?</p>
0
2016-10-07T16:08:20Z
39,940,047
<p>So I figured out how to resolve my problem. I don't know why it works or what caused the problem, but for now here is the solution</p> <p>The correct formula for PixelSearch is PixelSearch(left, top, right, bottom). </p> <p>After playing around with the numbers it appears pyautoit is using (right, top, left, bottom). If I plug in my numbers with that formula it works perfectly, EXCEPT on my third monitor. </p> <p>My third monitor seems to work with (left, top, right, bottom). I am wondering if it has something to do with negative numbers (-1680, 0, -3, 1050), not 100% sure.</p> <p>I tested this on my work computer (two monitors), home computer, (three monitors), and my laptop. In all scenarios the (right, top, left, bottom) worked, except home computer on the third monitor.</p> <p>Hope this helps someone else out in the future.</p>
0
2016-10-09T04:34:03Z
[ "python", "autoit" ]
Checking the upper triangle matrix elements in python
39,921,627
<p>I have an upper triangle matrix, with many empty elements, however, I want to check which indices have empty elements but I want to check only those on upper, cause it's normal that the lower ones will be empty, so I don't want to check those. So I want to check the elements shown in the picture if they are empty or not, covering all the cases no matter what the size of n is:<a href="http://i.stack.imgur.com/D1WpY.png" rel="nofollow"><img src="http://i.stack.imgur.com/D1WpY.png" alt="enter image description here"></a></p> <p>Here is my trial, but it's not covering everything and it's also making repetition, what I'm doing wrong?</p> <pre><code>for i in range(len(m)): for j in range(len(m)): words_length = len(words) if (m[i][j] == '' and i == j) or (m[i][j] == '' and i== j-3): print ("["), print (i+1), print (","), print (j+1), print ("]"), print(":"), print("-") for s in range(0,words_length-1): if ((m[i][j] == '' and i== s and j == i+1 ) or (m[i][j] == '' and i== 0 and j== words_length-1)): print ("["), print (i+1), print (","), print (j+1), print ("]"), print(":"), print("-") for r in range(0,words_length-3): if (m[i][j] == '' and i==r and j== i+2 ): print ("chart"), print ("["), print (i+1), print (","), print (j+1), print ("]"), print(":"), print("-") </code></pre>
0
2016-10-07T16:09:32Z
39,921,811
<p>I think i got it, by simply adding when <code>j&gt; i</code></p>
0
2016-10-07T16:19:59Z
[ "python", "matrix" ]
Adding an integer and string to a list with new lines
39,921,654
<p>I have some code that generates a integer and a str and I can get them to append into a list but I would like them on a seperate line for each int and str. My code is as follows:</p> <pre><code>responses = [] responses.append(respTime) responses.append(category_repeated) responses = [0.11700010299682617 correct 0.1000001431 correct 0.0779998302 correct] </code></pre> <p>I would like this so it can be opened into libreOffice calc into rows with two columns:</p> <pre><code>0.117000 correct 0.100000 correct </code></pre> <p>Thanks in advance for any advice. </p>
0
2016-10-07T16:11:03Z
39,923,778
<p>It is easier to process if you have a list of tuples:</p> <pre><code>responses = [] responses.append((respTime, category_repeated)) # &lt;--- slight difference responses == [(0.11700010299682617, 'correct'), (0.1000001431, 'correct')] # responses[0] == (0.11700010299682617, 'correct') </code></pre> <p>Here is an example for writing a .csv file from the docs:</p> <pre><code>import csv with open('eggs.csv', 'wb') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) </code></pre>
2
2016-10-07T18:32:14Z
[ "python", "string", "list", "int", "rows" ]
Probabilistically Running Based On Hour
39,921,674
<p>I have a function that I want to run with increasing probability each hour until noon then decreasing probability until midnight. I can imagine a normal distribution centered on noon would do it (so the probability of running the function is 100% at noon but very low at midnight), however I cannot convert that into python code.</p> <p>For example, if the code is executed at 1am it has a very low probability of running. But if the code is executed at noon, it has a 100% probability of running.</p> <p>This is a completely crude, unpythonic, manual attempt at what I want:</p> <pre><code>currentHour = 12 if currentHour == 1: print('probability = 0') elif currentHour == 2: print('probability = 0') elif currentHour == 3: print('probability = .1') elif currentHour == 4: print('probability = .2') elif currentHour == 5: print('probability = .3') elif currentHour == 6: print('probability = .4') elif currentHour == 7: print('probability = .5') elif currentHour == 8: print('probability = .6') elif currentHour == 9: print('probability = .7') elif currentHour == 10: print('probability = .8') elif currentHour == 11: print('probability = .9') elif currentHour == 12: print('probability = 1') elif currentHour == 13: print('probability = .9') elif currentHour == 13: print('probability = .8') elif currentHour == 14: print('probability = .7') elif currentHour == 15: print('probability = .6') elif currentHour == 16: print('probability = .5') elif currentHour == 17: print('probability = .4') elif currentHour == 18: print('probability = .3') elif currentHour == 19: print('probability = .2') elif currentHour == 20: print('probability = .1') elif currentHour == 21: print('probability = 0') elif currentHour == 22: print('probability = 0') elif currentHour == 23: print('probability = 0') elif currentHour == 24: print('probability = 0') </code></pre>
0
2016-10-07T16:12:03Z
39,922,728
<p>Pure magic. I figured it out. No, just joking. When you asked that question, it immediately reminded me of sinus waves, they go up and then down again - just like your thing you're trying to do.</p> <p>According to <a href="http://jwilson.coe.uga.edu/emt668/EMT668.Folders.../sine/assmt1.html" rel="nofollow">this</a> page:</p> <blockquote> <p>The graphs of functions defined by y = sin x are called sine waves or sinusoidal waves. [...] This graph repeats every 6.28 units or 2 pi radians. It ranges from -1 to 1.</p> </blockquote> <p>So I came up with this:</p> <pre><code>sin((hour/24)*pi) </code></pre> <p>You can integrate this in python like this:</p> <pre><code>import math import time hour = int(time.strftime("%H")) probability = math.sin(hour/24.0*math.pi) print(probability) </code></pre> <p>Why? Because <code>sin(0*pi)</code> is 0. And <code>sin(0.5*pi)</code> is <code>1</code>. You want that at 12 hours the probability is the highest, so <code>1</code>. This value occurs on <code>sin(0.5*pi)</code>. On 24 hours, the value will be <code>sin(1*pi)</code>, which is <code>0</code> again.</p> <p>Then I converted that value ranging from <code>0</code> to <code>1</code>, to <code>0</code> and <code>24</code>, by dividing the current hour by <code>24</code>.</p> <p><a href="http://i.stack.imgur.com/Vgdvp.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Vgdvp.jpg" alt="Half sine"></a></p>
1
2016-10-07T17:16:49Z
[ "python" ]
Probabilistically Running Based On Hour
39,921,674
<p>I have a function that I want to run with increasing probability each hour until noon then decreasing probability until midnight. I can imagine a normal distribution centered on noon would do it (so the probability of running the function is 100% at noon but very low at midnight), however I cannot convert that into python code.</p> <p>For example, if the code is executed at 1am it has a very low probability of running. But if the code is executed at noon, it has a 100% probability of running.</p> <p>This is a completely crude, unpythonic, manual attempt at what I want:</p> <pre><code>currentHour = 12 if currentHour == 1: print('probability = 0') elif currentHour == 2: print('probability = 0') elif currentHour == 3: print('probability = .1') elif currentHour == 4: print('probability = .2') elif currentHour == 5: print('probability = .3') elif currentHour == 6: print('probability = .4') elif currentHour == 7: print('probability = .5') elif currentHour == 8: print('probability = .6') elif currentHour == 9: print('probability = .7') elif currentHour == 10: print('probability = .8') elif currentHour == 11: print('probability = .9') elif currentHour == 12: print('probability = 1') elif currentHour == 13: print('probability = .9') elif currentHour == 13: print('probability = .8') elif currentHour == 14: print('probability = .7') elif currentHour == 15: print('probability = .6') elif currentHour == 16: print('probability = .5') elif currentHour == 17: print('probability = .4') elif currentHour == 18: print('probability = .3') elif currentHour == 19: print('probability = .2') elif currentHour == 20: print('probability = .1') elif currentHour == 21: print('probability = 0') elif currentHour == 22: print('probability = 0') elif currentHour == 23: print('probability = 0') elif currentHour == 24: print('probability = 0') </code></pre>
0
2016-10-07T16:12:03Z
39,923,113
<p>Lots of options. Just make a function that returns a value between 0 and 1 based on the hour. Then, make a random float between 0 and 1. If the float is less than the probability, run the program.</p> <pre><code>import numpy as np def prob_sawtooth(hour): return 1. - abs((hour - 12.) / 12.) def prob_sin(hour): return np.sin(hour / 24. * np.pi) def prob_gaussian(hour, stdev=6.): gauss = lambda x, m, s: np.exp(-(x-m)**2 / (2*s**2)) / np.sqrt(2*np.pi*s**2) return gauss(hour, 12., stdev) / gauss(12., 12., stdev) test = np.random.rand() #14:00 if test &lt;= prob_gaussian(14.): # run program pass </code></pre>
1
2016-10-07T17:44:59Z
[ "python" ]
Python cx_Oracle error
39,921,696
<p>I try to run a python scrapy crawler with crontab on Ubuntu, but i got this error message:</p> <pre><code>Traceback (most recent call last): File "/usr/bin/scrapy", line 9, in &lt;module&gt; load_entry_point('Scrapy==1.0.3', 'console_scripts', 'scrapy')() File "/usr/lib/python2.7/dist-packages/scrapy/cmdline.py", line 142, in execu$ cmd.crawler_process = CrawlerProcess(settings) File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 209, in __ini$ super(CrawlerProcess, self).__init__(settings) File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 115, in __ini$ self.spider_loader = _get_spider_loader(settings) File "/usr/lib/python2.7/dist-packages/scrapy/crawler.py", line 296, in _get_$ return loader_cls.from_settings(settings.frozencopy()) File "/usr/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 30, in f$ return cls(settings) File "/usr/lib/python2.7/dist-packages/scrapy/spiderloader.py", line 21, in _$ for module in walk_modules(name): File "/usr/lib/python2.7/dist-packages/scrapy/utils/misc.py", line 71, in wal$ submod = import_module(fullpath) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/home/kebodev/scrapy/qgtest2/qgtest2/spiders/jsonspider.py", line 5, in &lt;module&gt; import cx_Oracle ImportError: libclntsh.so.11.1: cannot open shared object file: No such file or directory </code></pre> <p>I edit my ~/.bashrc with root user and added this lines:</p> <pre><code>export ORACLE_HOME=/u01/app/oracle/product/11.2.0/xe export ORACLE_SID=XE export NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh` export ORACLE_BASE=/u01/app/oracle export LD_LIBRARY_PATH=$ORACLE_HOME/lib:$LD_LIBRARY_PATH export PATH=$ORACLE_HOME/bin:$PATH </code></pre> <p>My libclntsh.so.11.1 is located here: <code>/u01/app/oracle/product/11.2.0/xe/lib</code></p> <p>If I try to run my python scrapy crawler from terminal, it's running, and it's also works if I try to import cx_Oracle in python shell, but with crontab it's not ok..</p> <p>This is how my cron job line looks like: </p> <pre><code>* * * * * root /etc/listarunner.sh &gt;&gt; /home/kebodev/scrapy/qgtest2/etcronlog1.log 2&gt;&amp;1 </code></pre> <p>And this is my <code>listarunner.sh</code> file:</p> <pre><code>#!/bin/bash cd /home/kebodev/scrapy/qgtest2 PATH=$PATH:/usr/local/bin export PATH scrapy crawl jsontst </code></pre> <p>Can anybody help me?</p> <p>Thank you! </p>
0
2016-10-07T16:13:06Z
39,934,020
<p>I have a few options you can try:</p> <p>1) Set the environment variables in listarunner.sh instead of ~/.bashrc</p> <p>2) Use a file in /etc/ld.so.conf.d to make the setting of LD_LIBRARY_PATH unnecessary</p> <p>3) Rebuild cx_Oracle, first setting the environment variable FORCE_RPATH to any value before building.</p> <p>Hopefully one of those will help you out!</p>
1
2016-10-08T15:16:30Z
[ "python", "ubuntu", "scrapy", "crontab", "cx-oracle" ]
Caeser Cipher Cracking Python
39,921,743
<p>I am running this using Python 2.7.12</p> <pre><code>charset="ABCDEFGHIJKLMNOPQRSTUVWXYZ" # The list of characters to be encrypted numchars=len(charset) # number of characters that are in the list for encryption def caesar_crack(crackme,i,newkey): print '[*] CRACKING - key: %d; ciphertext: %s' % (i,crackme) crackme=crackme.upper() plaintext='' #initialise plaintext as an empty string while i &lt;= 26: for ch in crackme: #'for' will check each character in plaintext against charset if ch in charset: pos=charset.find(ch) #finds the position of the current character pos=pos-newkey else: new='' # do nothing with characters not in charet if pos&gt;=len(charset): #if the pos of the character is more or equal to the charset e.g -22 it will add 26 to get the correct letter positioning/value pos=pos+26 else: new=charset[pos] plaintext=plaintext+new print '[*] plaintext: ' + plaintext if i &lt;= 27: newkey=newkey+1 i=i+1 return plaintext def main(): # test cases newkey=0 i=0 crackme = 'PBATENGHYNGVBAFLBHUNIRPENPXRQGURPBQRNAQGURFUVSGJNFGUVEGRRA' # call functions with text cases caesar_crack(crackme,i,newkey) # boilerplate if __name__ == '__main__': main() </code></pre> <p>This is what I have thus far, I am currently looking to get this to loop multiple times, prefferably 26 (1 for each number/letter of the alphabet).</p> <p>I feel as though what I have should work just fine but I'm almost certain that what I have should work but upon running it will only run once eg <code>newkey = 0</code> and <code>i = 0</code> but will increment to the next value <code>newkey = 1</code> and <code>i = 1</code> but will not then rerun.</p> <p>Can anyone spot the fatal flaw that I'm missing? Or any tips as to how to make it run more efficiently, all would be appreciated.</p>
0
2016-10-07T16:15:47Z
39,922,170
<p>just move the indentation of </p> <pre><code>return plaintext </code></pre> <p>one step to left</p> <p>that will resolve the looping issue and it will go through all 26 numbers</p> <p>didnt check the remaining of the program if it is good </p>
0
2016-10-07T16:40:37Z
[ "python", "python-2.7", "caesar-cipher" ]
How to calculate user input in python
39,921,791
<p>I am supposed to write a program in Python that asks for grades one at a time. When the user enters “done” , calculate the following: grade average.</p> <p>This is what I have so far:</p> <pre><code>def main(): user_input = input("Enter grade: ") number = user_input while True: user_input = input("Enter grade: ") if user_input == "done": break avg(number) def avg(a): average = sum(a)/len(a) print(average) if __name__ == "__main__": main() </code></pre> <p>Whenever I enter "done," the program gives me this error.</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>I have tried changing the user_input variable to :</p> <blockquote> <p>user_input = int(input("Enter grade: "))</p> </blockquote> <p>But, another error: TypeError: </p> <blockquote> <p>'int' object is not iterable user input</p> </blockquote> <p>I am extremely new to programming. Can anyone help me work this out? I have been searching online for the past two hours and have not found anything that did not just produce another error.</p>
-2
2016-10-07T16:18:09Z
39,921,903
<p>I am noticing some things which may solve the issue for you.</p> <ol> <li>You're feeding <code>number</code> to the <code>avg</code> function when really you want to give it a list of numbers.</li> <li>I think you should do something like this: make a list called numbers and append each user input to that list. Then use the avg function on the numbers list.</li> </ol>
1
2016-10-07T16:25:09Z
[ "python", "input" ]
How to calculate user input in python
39,921,791
<p>I am supposed to write a program in Python that asks for grades one at a time. When the user enters “done” , calculate the following: grade average.</p> <p>This is what I have so far:</p> <pre><code>def main(): user_input = input("Enter grade: ") number = user_input while True: user_input = input("Enter grade: ") if user_input == "done": break avg(number) def avg(a): average = sum(a)/len(a) print(average) if __name__ == "__main__": main() </code></pre> <p>Whenever I enter "done," the program gives me this error.</p> <blockquote> <p>TypeError: 'int' object is not iterable</p> </blockquote> <p>I have tried changing the user_input variable to :</p> <blockquote> <p>user_input = int(input("Enter grade: "))</p> </blockquote> <p>But, another error: TypeError: </p> <blockquote> <p>'int' object is not iterable user input</p> </blockquote> <p>I am extremely new to programming. Can anyone help me work this out? I have been searching online for the past two hours and have not found anything that did not just produce another error.</p>
-2
2016-10-07T16:18:09Z
39,922,850
<p>There are a few flaws in your logic.</p> <ul> <li>Each time you ask for user input in <code>main()</code>, you override the value of <code>user_input</code>. What you should be doing, is gathering each numbers in a <code>list()</code>.</li> <li>What the errors Python raised are telling you, is that the builtin function <code>sum()</code>, takes a list of numbers, not a single number, which your passing in.</li> <li>the <code>input()</code> function returns a string, so you need to convert the input to a integer.</li> </ul> <p>I would rewrite your program as the following:</p> <pre><code>def main(): # create a list to store each grade # that the user inputs. grades = [] # while forever while True: # get input from the user. # I am not converting the input to a integer # here, because were expecting the user to # enter a string when done. i = input("Enter grade: ") # if the user enters 'done' break the loop. if i == 'done':break # add the grade the user entered to our grades list. # converting it to an integer. grades.append(int(i)) # print the return value # of the avg function. print("Grade average:", avg(grades)) def avg(grades): # return the average of # the grades. # note that I'm using the builtin round() # function here. That is because # the average is sometimes a # long decimal. If this does not matter # to you, you can remove it. return round(sum(grades)/len(grades), 2) # call the function main() main() </code></pre>
0
2016-10-07T17:25:42Z
[ "python", "input" ]
Django Python, Form show the csrf token
39,921,797
<p>I'm trying to make a variable form in django but it seems not working properly, I hope you can help me because i show me the token instead of form values.</p> <p><a href="http://i.stack.imgur.com/ARP7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/ARP7l.png" alt="enter image description here"></a></p> <p><strong>Help me please!</strong></p> <p>url.</p> <pre><code>url(r'^test', views.test), </code></pre> <p>views.</p> <pre><code>def test(request): if request.method == "POST": for key, value in request.POST.items(): response = '%s %s' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') </code></pre> <p>datos2.</p> <pre><code>&lt;form action="/test" method="post"&gt; {% csrf_token %} &lt;input type="text" name="eee"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;p&gt;ADD VALUE&lt;/p&gt; &lt;button onclick="myFunction()"&gt;ADD&lt;/button&gt; &lt;script&gt; function myFunction() { var x = document.createElement("INPUT"); x.setAttribute("type", "text"); x.setAttribute("value", "0"); x.setAttribute("name", "eee"); document.body.appendChild(x); } &lt;/script&gt; </code></pre> <p><a href="http://i.stack.imgur.com/WyzCp.png" rel="nofollow"><img src="http://i.stack.imgur.com/WyzCp.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/67MhH.png" rel="nofollow"><img src="http://i.stack.imgur.com/67MhH.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/CBABH.png" rel="nofollow"><img src="http://i.stack.imgur.com/CBABH.png" alt="enter image description here"></a></p> <p>Help me please!</p>
0
2016-10-07T16:18:40Z
39,922,180
<p>In order to obtain values from form you should retrieve them from your request object and return in form of context as a part of your rendered template. Here what your code accomplish currently: </p> <p>Check method of the request</p> <pre><code>if request.method == "POST": </code></pre> <p>Assign to variable response values from POST dictionary, but next value in dictionary overwrites previous one, so as a result, result is last item from POST dictionary, which is csrf token value </p> <pre><code>for key, value in request.POST.items(): response = '%s %s' % (key, value) </code></pre> <p>Here you return whatever is in your response variable as a http response. You are not rendering template at this step. You just return content of your variable as a response.</p> <pre><code>return HttpResponse(response) </code></pre> <p>And, consequently, execution flow will never reach this statement:</p> <pre><code>return render(request, 'datos2.html') </code></pre> <p>This is it. </p> <p>I'm not sure i understand you question properly, but if you use post method it means you want to receive values from form. You can do it like this:</p> <pre><code>if 'name_of_your_html_input_field' in request.POST: result=request.POST.get('name_of_your_html_input_field') return render(request, "template_name.html", {'data':result}) </code></pre> <p>And in your template you should: Put <code>{{data}}</code> somewhere.</p>
0
2016-10-07T16:41:20Z
[ "python", "django", "forms", "token" ]
Django Python, Form show the csrf token
39,921,797
<p>I'm trying to make a variable form in django but it seems not working properly, I hope you can help me because i show me the token instead of form values.</p> <p><a href="http://i.stack.imgur.com/ARP7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/ARP7l.png" alt="enter image description here"></a></p> <p><strong>Help me please!</strong></p> <p>url.</p> <pre><code>url(r'^test', views.test), </code></pre> <p>views.</p> <pre><code>def test(request): if request.method == "POST": for key, value in request.POST.items(): response = '%s %s' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') </code></pre> <p>datos2.</p> <pre><code>&lt;form action="/test" method="post"&gt; {% csrf_token %} &lt;input type="text" name="eee"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;p&gt;ADD VALUE&lt;/p&gt; &lt;button onclick="myFunction()"&gt;ADD&lt;/button&gt; &lt;script&gt; function myFunction() { var x = document.createElement("INPUT"); x.setAttribute("type", "text"); x.setAttribute("value", "0"); x.setAttribute("name", "eee"); document.body.appendChild(x); } &lt;/script&gt; </code></pre> <p><a href="http://i.stack.imgur.com/WyzCp.png" rel="nofollow"><img src="http://i.stack.imgur.com/WyzCp.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/67MhH.png" rel="nofollow"><img src="http://i.stack.imgur.com/67MhH.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/CBABH.png" rel="nofollow"><img src="http://i.stack.imgur.com/CBABH.png" alt="enter image description here"></a></p> <p>Help me please!</p>
0
2016-10-07T16:18:40Z
39,922,199
<p>The <code>csrfmiddlewaretoken</code> <em>is</em> a form value. Each time you set <code>response</code> in your loop, it overwrites the previous value. In your case, <code>csrfmiddlewaretoken</code> is the final item in <code>request.POST.items()</code>, so this is the only result you see.</p> <pre><code> for key, value in request.POST.items(): response = '%s %s' % (key, value) </code></pre> <p>Instead, you could build up a string, and return it at the end. Then you'll see all the values in <code>request.POST</code>.</p> <pre><code> response = '' for key, value in request.POST.items(): response += '%s %s&lt;br&gt;' % (key, value) return HttpResponse(response) </code></pre> <p>Note, this will still show the csrf token, because you are showing the values of all the form fields, and the csrf token is a hidden form field. If you don't want to display the middleware token, you could check the key value and exclude it.</p> <pre><code> response = '' for key, value in request.POST.items(): if key != 'csrfmiddlwaretoken' response += '%s %s\n' % (key, value) return HttpResponse(response) </code></pre>
0
2016-10-07T16:42:21Z
[ "python", "django", "forms", "token" ]
Django Python, Form show the csrf token
39,921,797
<p>I'm trying to make a variable form in django but it seems not working properly, I hope you can help me because i show me the token instead of form values.</p> <p><a href="http://i.stack.imgur.com/ARP7l.png" rel="nofollow"><img src="http://i.stack.imgur.com/ARP7l.png" alt="enter image description here"></a></p> <p><strong>Help me please!</strong></p> <p>url.</p> <pre><code>url(r'^test', views.test), </code></pre> <p>views.</p> <pre><code>def test(request): if request.method == "POST": for key, value in request.POST.items(): response = '%s %s' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') </code></pre> <p>datos2.</p> <pre><code>&lt;form action="/test" method="post"&gt; {% csrf_token %} &lt;input type="text" name="eee"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;p&gt;ADD VALUE&lt;/p&gt; &lt;button onclick="myFunction()"&gt;ADD&lt;/button&gt; &lt;script&gt; function myFunction() { var x = document.createElement("INPUT"); x.setAttribute("type", "text"); x.setAttribute("value", "0"); x.setAttribute("name", "eee"); document.body.appendChild(x); } &lt;/script&gt; </code></pre> <p><a href="http://i.stack.imgur.com/WyzCp.png" rel="nofollow"><img src="http://i.stack.imgur.com/WyzCp.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/67MhH.png" rel="nofollow"><img src="http://i.stack.imgur.com/67MhH.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/CBABH.png" rel="nofollow"><img src="http://i.stack.imgur.com/CBABH.png" alt="enter image description here"></a></p> <p>Help me please!</p>
0
2016-10-07T16:18:40Z
39,925,712
<p>But it still showing the token :(</p> <pre><code>def test(request): if request.method == "POST": response = '' for key, value in request.POST.items(): response += '%s %s\n' % (key, value) return HttpResponse(response) return render(request, 'datos2.html') </code></pre> <p><a href="http://i.stack.imgur.com/V6RtY.png" rel="nofollow"><img src="http://i.stack.imgur.com/V6RtY.png" alt="enter image description here"></a></p>
0
2016-10-07T20:58:30Z
[ "python", "django", "forms", "token" ]
How do I turn a string of numbers into a list on Python?
39,921,819
<p>I'm trying to figure out how many numbers in a text file are larger than 0.1. The text file has 1001 last names and numbers in the following format:</p> <pre><code>Doe 5 Anderson 0.3 Smith 6 </code></pre> <p>I figured out how to separate the numbers but i'm having trouble converting my string of numbers into a list so that I can then compare them to 0.1</p> <p>Here is what I have so far:</p> <pre><code> infile = open('last.txt') lines = infile.readlines() for line in lines: items = line.split() nums = (items[1]) </code></pre> <p>also, once I have my list, how do I go about comparing it to 0.1?</p>
1
2016-10-07T16:20:26Z
39,921,878
<p>Supposing <code>lines</code> is a list of strings, and each of them consists of exactly one number and nothing more.</p> <pre><code>result = sum(1 if float(x) &gt; 0.1 else 0 for x in lines) </code></pre> <p>Another very similar way to do the same:</p> <pre><code>result = sum(float(x) &gt; 0.1 for x in lines) </code></pre>
4
2016-10-07T16:23:35Z
[ "python" ]
How do I turn a string of numbers into a list on Python?
39,921,819
<p>I'm trying to figure out how many numbers in a text file are larger than 0.1. The text file has 1001 last names and numbers in the following format:</p> <pre><code>Doe 5 Anderson 0.3 Smith 6 </code></pre> <p>I figured out how to separate the numbers but i'm having trouble converting my string of numbers into a list so that I can then compare them to 0.1</p> <p>Here is what I have so far:</p> <pre><code> infile = open('last.txt') lines = infile.readlines() for line in lines: items = line.split() nums = (items[1]) </code></pre> <p>also, once I have my list, how do I go about comparing it to 0.1?</p>
1
2016-10-07T16:20:26Z
39,922,283
<p>From your description, and code snippet, you seem to have a file that has a space separated name an number like so:</p> <pre><code>Name1 0.5 Name2 7 Name3 11 </code></pre> <p>In order to get a sum of how many number are greater than 0.1, you can do the following:</p> <pre><code>result = sum(float(line.split()[1]) &gt; 0.1 for line in lines) </code></pre>
0
2016-10-07T16:47:21Z
[ "python" ]
How do I turn a string of numbers into a list on Python?
39,921,819
<p>I'm trying to figure out how many numbers in a text file are larger than 0.1. The text file has 1001 last names and numbers in the following format:</p> <pre><code>Doe 5 Anderson 0.3 Smith 6 </code></pre> <p>I figured out how to separate the numbers but i'm having trouble converting my string of numbers into a list so that I can then compare them to 0.1</p> <p>Here is what I have so far:</p> <pre><code> infile = open('last.txt') lines = infile.readlines() for line in lines: items = line.split() nums = (items[1]) </code></pre> <p>also, once I have my list, how do I go about comparing it to 0.1?</p>
1
2016-10-07T16:20:26Z
39,958,072
<p>The other answers tell you how to count the occurrences which are greater than 0.1, but you may want to have the numbers in a list so that they can be used for other purposes. To do that, you need a small modification to your code:</p> <pre><code>with open('last.txt', 'r') as infile: lines = infile.readlines() nums = [] for line in lines: items = line.split() nums.append(float(items[1])) </code></pre> <p>This gives you a list <code>nums</code> of all of the numbers from your file. Note that I have also used the Python context manager (invoked with <code>with</code>) to open the file which ensures that it is closed properly once you are no longer using it. </p> <p>Now you can still count the occurrences of values larger than 0.1 in <code>nums</code>:</p> <pre><code>sum(1 if x &gt; 0.1 else 0 for x in nums) </code></pre>
0
2016-10-10T12:14:22Z
[ "python" ]
Managing multiple lists with multiple tuples
39,921,863
<p>I have approximately 2000 lines of data in the following format:</p> <pre><code>. . [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'), (13, 16, 'LOC', 'New York')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Craig Rivera'), (7, 12, 'DOB', 'October 10 , 1954'), (5, 7, 'LOC', 'Manhattan')] [(0, 1, 'Blank', ''), (0, 4, 'NAME', 'Margery Pitt Durant'), (14, 16, 'LOC', 'Flint'), (6, 11, 'DOB', 'May 24 , 1887'), (16, 18, 'LOC', 'Michigan')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Austin Watson'), (10, 13, 'LOC', 'Ann Arbor'), (13, 15, 'LOC', 'Michigan'), (4, 9, 'DOB', 'January 13 , 1992')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Gary Spatz'), (5, 8, 'LOC', 'New York'), (16, 19, 'LOC', 'New York'), (19, 21, 'LOC', 'Miami'), (21, 23, 'LOC', 'Florida'), (8, 13, 'DOB', 'April 1 , 1951')] . . . </code></pre> <p>They are basically many lists each of them containing details of people like name, dob, loc etc. inside respective tuples.</p> <p>I want to extract name of all the people and their corresponding dob in the following format:</p> <pre><code>('Ayiesha Woods', 'DateOfBirth', 'July 2 , 1979') ('Craig Rivera', 'DateOfBirth', 'October 10 , 1954') </code></pre> <p>and so on..</p> <p>This is my attempt:</p> <pre><code>temp = "DateOFBirth" results = [] for n1 in text: for n2 in text: if n1 is not n2: if text[1][2] == 'NAME' and text[2][2] == 'DOB': rel = text[1][3], temp, text[2][3] print(rel) results.append(rel) </code></pre> <p>This will only output if the name tuple is at position 1 and date tuple is at position 2 in the list which is not always the case.</p> <p>What do I do if I want to output the result irrespective of the position of the name tuple or date tuple in the list.</p> <p>EDIT:</p> <p>I have a list containing tuples like:</p> <pre><code>text = [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Vance Trimble'), (5, 7, 'LOC', 'Harrison'), (7, 9, 'LOC', 'Arkansas'), (9, 14, 'DOB', 'July 6 , 1913')] </code></pre> <p>I am looking to extract data in the following format:</p> <pre><code>('Vance Trimble', 'DateOFBirth', 'July 6 , 1913') </code></pre> <p>My code:</p> <pre><code>temp = "DateOFBirth" if text[1][2] == 'NAME' and text[4][2] == 'DOB': rel = text[1][3], temp, text[4][3] print(rel) </code></pre> <p>Ho do i do this without having to hardcode like:</p> <pre><code>text[1][2] == 'NAME' and text[4][2] == 'DOB' </code></pre> <p>so that it searches the list by itself for 'NAME' and 'DOB' and gets the output.</p>
1
2016-10-07T16:22:45Z
39,922,218
<p>Break down the problem into simple steps:</p> <ol> <li>Loop through the list of records. </li> <li>Each record consists of a list of tuples in somewhat arbitrary order.</li> <li>Look through each tuple in the record (loop) looking for NAME and DOB.</li> <li>When found add the desired data from the tuple to result.</li> </ol> <p>Viola!</p> <pre><code>results = [] for rec in records: result = ["", "DateOfBirth", ""] for item in rec: if "NAME" in item: result[0] = item[3] elif "DOB" in item: result[2] = item[3] results.append(tuple(result)) print(results) </code></pre>
2
2016-10-07T16:43:33Z
[ "python", "list", "python-3.x" ]
Managing multiple lists with multiple tuples
39,921,863
<p>I have approximately 2000 lines of data in the following format:</p> <pre><code>. . [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'), (13, 16, 'LOC', 'New York')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Craig Rivera'), (7, 12, 'DOB', 'October 10 , 1954'), (5, 7, 'LOC', 'Manhattan')] [(0, 1, 'Blank', ''), (0, 4, 'NAME', 'Margery Pitt Durant'), (14, 16, 'LOC', 'Flint'), (6, 11, 'DOB', 'May 24 , 1887'), (16, 18, 'LOC', 'Michigan')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Austin Watson'), (10, 13, 'LOC', 'Ann Arbor'), (13, 15, 'LOC', 'Michigan'), (4, 9, 'DOB', 'January 13 , 1992')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Gary Spatz'), (5, 8, 'LOC', 'New York'), (16, 19, 'LOC', 'New York'), (19, 21, 'LOC', 'Miami'), (21, 23, 'LOC', 'Florida'), (8, 13, 'DOB', 'April 1 , 1951')] . . . </code></pre> <p>They are basically many lists each of them containing details of people like name, dob, loc etc. inside respective tuples.</p> <p>I want to extract name of all the people and their corresponding dob in the following format:</p> <pre><code>('Ayiesha Woods', 'DateOfBirth', 'July 2 , 1979') ('Craig Rivera', 'DateOfBirth', 'October 10 , 1954') </code></pre> <p>and so on..</p> <p>This is my attempt:</p> <pre><code>temp = "DateOFBirth" results = [] for n1 in text: for n2 in text: if n1 is not n2: if text[1][2] == 'NAME' and text[2][2] == 'DOB': rel = text[1][3], temp, text[2][3] print(rel) results.append(rel) </code></pre> <p>This will only output if the name tuple is at position 1 and date tuple is at position 2 in the list which is not always the case.</p> <p>What do I do if I want to output the result irrespective of the position of the name tuple or date tuple in the list.</p> <p>EDIT:</p> <p>I have a list containing tuples like:</p> <pre><code>text = [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Vance Trimble'), (5, 7, 'LOC', 'Harrison'), (7, 9, 'LOC', 'Arkansas'), (9, 14, 'DOB', 'July 6 , 1913')] </code></pre> <p>I am looking to extract data in the following format:</p> <pre><code>('Vance Trimble', 'DateOFBirth', 'July 6 , 1913') </code></pre> <p>My code:</p> <pre><code>temp = "DateOFBirth" if text[1][2] == 'NAME' and text[4][2] == 'DOB': rel = text[1][3], temp, text[4][3] print(rel) </code></pre> <p>Ho do i do this without having to hardcode like:</p> <pre><code>text[1][2] == 'NAME' and text[4][2] == 'DOB' </code></pre> <p>so that it searches the list by itself for 'NAME' and 'DOB' and gets the output.</p>
1
2016-10-07T16:22:45Z
39,922,303
<p>I would recommend writing a helper function which retrieves the information from your data. I am also assuming that you are working with a list of lists of tuples.</p> <pre><code> test_list = [[(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'), (13, 16, 'LOC', 'New York')], [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Craig Rivera'), (7, 12, 'DOB', 'October 10 , 1954'), (5, 7, 'LOC', 'Manhattan')], [(0, 1, 'Blank', ''), (0, 4, 'NAME', 'Margery Pitt Durant'), (14, 16, 'LOC', 'Flint'), (6, 11, 'DOB', 'May 24 , 1887'), (16, 18, 'LOC', 'Michigan')], [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Austin Watson'), (10, 13, 'LOC', 'Ann Arbor'), (13, 15, 'LOC', 'Michigan'), (4, 9, 'DOB', 'January 13 , 1992')], [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Gary Spatz'), (5, 8, 'LOC', 'New York'), (16, 19, 'LOC', 'New York'), (19, 21, 'LOC', 'Miami'), (21, 23, 'LOC', 'Florida'), (8, 13, 'DOB', 'April 1 , 1951')]] #Helper function def get_person_info(lst): person_name = list(filter(lambda x: 'NAME' in x, lst))[0][3:] person_dob = list(filter(lambda x: 'DOB' in x, lst))[0][2:4] return person_name + person_dob #Use it with map list(map(get_person_info, test_list)) </code></pre> <p>Output:</p> <pre><code>[('Ayiesha Woods', 'DOB', 'July 2 , 1979'), ('Craig Rivera', 'DOB', 'October 10 , 1954'), ('Margery Pitt Durant', 'DOB', 'May 24 , 1887'), ('Austin Watson', 'DOB', 'January 13 , 1992'), ('Gary Spatz', 'DOB', 'April 1 , 1951')] </code></pre> <p>Testing the helper function with <code>text</code>:</p> <pre><code>text = [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Vance Trimble'), (5, 7, 'LOC', 'Harrison'), (7, 9, 'LOC', 'Arkansas'), (9, 14, 'DOB', 'July 6 , 1913')] get_person_info(text) ## ('Vance Trimble', 'DOB', 'July 6 , 1913') </code></pre> <p>You can easily replace 'DOB' with 'DateOFBirth'.</p>
1
2016-10-07T16:48:31Z
[ "python", "list", "python-3.x" ]
Managing multiple lists with multiple tuples
39,921,863
<p>I have approximately 2000 lines of data in the following format:</p> <pre><code>. . [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Ayiesha Woods'), (5, 10, 'DOB', 'July 2 , 1979'), (10, 13, 'LOC', 'Long Island'), (13, 16, 'LOC', 'New York')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Craig Rivera'), (7, 12, 'DOB', 'October 10 , 1954'), (5, 7, 'LOC', 'Manhattan')] [(0, 1, 'Blank', ''), (0, 4, 'NAME', 'Margery Pitt Durant'), (14, 16, 'LOC', 'Flint'), (6, 11, 'DOB', 'May 24 , 1887'), (16, 18, 'LOC', 'Michigan')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Austin Watson'), (10, 13, 'LOC', 'Ann Arbor'), (13, 15, 'LOC', 'Michigan'), (4, 9, 'DOB', 'January 13 , 1992')] [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Gary Spatz'), (5, 8, 'LOC', 'New York'), (16, 19, 'LOC', 'New York'), (19, 21, 'LOC', 'Miami'), (21, 23, 'LOC', 'Florida'), (8, 13, 'DOB', 'April 1 , 1951')] . . . </code></pre> <p>They are basically many lists each of them containing details of people like name, dob, loc etc. inside respective tuples.</p> <p>I want to extract name of all the people and their corresponding dob in the following format:</p> <pre><code>('Ayiesha Woods', 'DateOfBirth', 'July 2 , 1979') ('Craig Rivera', 'DateOfBirth', 'October 10 , 1954') </code></pre> <p>and so on..</p> <p>This is my attempt:</p> <pre><code>temp = "DateOFBirth" results = [] for n1 in text: for n2 in text: if n1 is not n2: if text[1][2] == 'NAME' and text[2][2] == 'DOB': rel = text[1][3], temp, text[2][3] print(rel) results.append(rel) </code></pre> <p>This will only output if the name tuple is at position 1 and date tuple is at position 2 in the list which is not always the case.</p> <p>What do I do if I want to output the result irrespective of the position of the name tuple or date tuple in the list.</p> <p>EDIT:</p> <p>I have a list containing tuples like:</p> <pre><code>text = [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Vance Trimble'), (5, 7, 'LOC', 'Harrison'), (7, 9, 'LOC', 'Arkansas'), (9, 14, 'DOB', 'July 6 , 1913')] </code></pre> <p>I am looking to extract data in the following format:</p> <pre><code>('Vance Trimble', 'DateOFBirth', 'July 6 , 1913') </code></pre> <p>My code:</p> <pre><code>temp = "DateOFBirth" if text[1][2] == 'NAME' and text[4][2] == 'DOB': rel = text[1][3], temp, text[4][3] print(rel) </code></pre> <p>Ho do i do this without having to hardcode like:</p> <pre><code>text[1][2] == 'NAME' and text[4][2] == 'DOB' </code></pre> <p>so that it searches the list by itself for 'NAME' and 'DOB' and gets the output.</p>
1
2016-10-07T16:22:45Z
39,922,606
<p>You can do this:</p> <pre><code>temp = "DateOFBirth" text = [(0, 1, 'Blank', ''), (0, 3, 'NAME', 'Vance Trimble'), (5, 7, 'LOC', 'Harrison'), (7, 9, 'LOC', 'Arkansas'), (9, 14, 'DOB', 'July 6 , 1913')] rel = [] for i in text: if 'NAME' in i: rel.append(i[i.index('NAME')+1]) rel.append(temp) elif 'DOB' in i: rel.append(i[i.index('DOB')+1]) print rel # result: # ['Vance Trimble', 'DateOFBirth', 'July 6 , 1913'] </code></pre> <p>In this way the results are independent of the location of the items 'NAME' and 'DOB' in the tuples, but only if e.g. the actual name always follows the 'tag' <code>'NAME'</code>, as it is here: <code>(0, 3, 'NAME', 'Vance Trimble')</code>, where the actual name follows the <code>NAME</code>.</p>
1
2016-10-07T17:07:43Z
[ "python", "list", "python-3.x" ]
Collapse / expand text in Text widget
39,921,864
<p>I have a Text widget with ALOT of information being printed to it. Id like to have sections of it minimizable so I can hide information until I need it. </p> <pre><code>from tkinter import * main = Tk() list1 = ['blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n" 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n", 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n",'blah', 'blah', 'blah', 'blah', 'blah', 'blah' , "\n"] list2 = ['blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n" 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n", 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n",'blah', 'blah', 'blah', 'blah', 'blah', 'blah' , "\n"] list3 = ['blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n" 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n", 'blah', 'blah', 'blah', 'blah', 'blah', 'blah', "\n",'blah', 'blah', 'blah', 'blah', 'blah', 'blah' , "\n"] textwin = Text(main, height=20, width=150) textwin.grid(rowspan=5, columnspan=5) textwin.config(state='normal') textwin.insert('end', "+--------------------------------------------------------------------------------- \n") textwin.insert('end', list1) textwin.insert('end', "+--------------------------------------------------------------------------------- \n") textwin.insert('end', list2) textwin.insert('end', "+--------------------------------------------------------------------------------- \n") textwin.insert('end', list3) main.mainloop() </code></pre> <p>I tried placing a button in the Text widget but it shrinks the Text widget to the size of the button and nothing else is displayed. I looked into linking text so I could make the "+" run a function that would delete/hide the section of text but I only found hyperlink instructions. </p> <p>If this is not doable in the Text widget i'm open to other ideas. Maybe i'll have to move everything to a tree view widget. </p>
2
2016-10-07T16:22:56Z
39,922,936
<p>You can configure a text tag to hide a range of characters. You can then hide or show a range of characters by applying or removing this tag. If you want to insert a button into the text, you will need to use the <code>window_create</code> method of the text widget.</p> <p>You'll have to write the code to apply or remove the tag. For example, you could tag the start of a block with "block_start" or "heading" or something like that, then add a double-click binding on that tag to find all of the code between it and the next heading, and then either add or remove the "hidden" tag. Or, you could embed a button widget that does the same thing.</p> <p><strong>To configure the tag:</strong></p> <pre><code>textwin.tag_configure("hidden", elide=True) </code></pre> <p><strong>To hide a block of text</strong>, where <code>start</code> and <code>end</code> represent the range of characters to hide:</p> <pre><code>textwin.tag_add("hidden", start, end) </code></pre> <p><strong>To show a block of text</strong>, where <code>start</code> and <code>end</code> represent the range of characters to show:</p> <pre><code>textwin.tag_remove("hidden", start, end) </code></pre> <h2>Example</h2> <p>The following code is a contrived example that lets you double-click a header to hide or show the text under the header:</p> <pre><code>import tkinter as tk from tkinter import font class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent, borderwidth=1, relief="sunken") self.text = tk.Text(self, borderwidth=0, highlightthickness=0, wrap="word") self.vsb = tk.Scrollbar(self, command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.text.pack(side="left", fill="both", expand=True) self.text.tag_configure("hidden", elide=True) self.text.tag_configure("header", background="black", foreground="white", spacing1=10, spacing3=10) self.text.tag_bind("header", "&lt;Double-1&gt;", self._toggle_visibility) for i in range(3): self.text.insert("end", "Header %s\n" % i, "header") self.text.insert("end", "blah blah blah blah\nblah blah blah\n\n") def _toggle_visibility(self, event): block_start, block_end = self._get_block("insert") # is any of the text tagged with "hidden"? If so, show it next_hidden = self.text.tag_nextrange("hidden", block_start, block_end) if next_hidden: self.text.tag_remove("hidden", block_start, block_end) else: self.text.tag_add("hidden", block_start, block_end) def _get_block(self, index): '''return indicies after header, to next header or EOF''' start = self.text.index("%s lineend+1c" % index) next_header = self.text.tag_nextrange("header", start) if next_header: end = next_header[0] else: end = self.text.index("end-1c") return (start, end) if __name__ == "__main__": root = tk.Tk() Example(root).pack(fill="both", expand=True) root.mainloop() </code></pre>
3
2016-10-07T17:32:08Z
[ "python", "python-3.x", "tkinter" ]
Using .asof and MultiIndex in Pandas
39,922,050
<p>I've seen this question asked a few times but with no answer. The short version:</p> <p>I have a pandas <code>DataFrame</code> with a two-level <code>MultiIndex</code> index; both levels are integers. How can I use <code>.asof()</code> on this <code>DataFrame</code>?</p> <p>Long version:</p> <p>I have a <code>DataFrame</code> with some time series data:</p> <pre><code>&gt;&gt;&gt; df A 2016-01-01 00:00:00 1.560878 2016-01-01 01:00:00 -1.029380 ... ... 2016-01-30 20:00:00 0.429422 2016-01-30 21:00:00 -0.182349 2016-01-30 22:00:00 -0.939461 2016-01-30 23:00:00 0.009930 2016-01-31 00:00:00 -0.854283 [721 rows x 1 columns] </code></pre> <p>I'm then constructing a weekly model of that data:</p> <pre><code>&gt;&gt;&gt; df['weekday'] = df.index.weekday &gt;&gt;&gt; df['hour_of_day'] = df.index.hour &gt;&gt;&gt; weekly_model = df.groupby(['weekday', 'hour_of_day']).mean() &gt;&gt;&gt; weekly_model A weekday hour_of_day 0 0 0.260597 1 0.333094 ... ... 20 0.388932 21 -0.082020 22 -0.346888 23 1.525928 [168 rows x 1 columns] </code></pre> <p>That's what gives me a <code>DataFrame</code> with the index described above.</p> <p>I'm now trying to extrapolate that model into an annual time series:</p> <pre><code>&gt;&gt;&gt; dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H') &gt;&gt;&gt; annual_series = weekly weekly weekly_model &gt;&gt;&gt; annual_series = weekly_model.A.asof((dates.weekday, dates.hour)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/core/series.py", line 2657, in asof locs = self.index.asof_locs(where, notnull(values)) File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/indexes/base.py", line 1553, in asof_locs locs = self.values[mask].searchsorted(where.values, side='right') ValueError: operands could not be broadcast together with shapes (8760,) (2,) &gt;&gt;&gt; dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H') &gt;&gt;&gt; annual_series = weekly_model.A.asof((dates.weekday, dates.hour)) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/core/series.py", line 2657, in asof locs = self.index.asof_locs(where, notnull(values)) File "/home/tkcook/azimuth-web/lib/python3.5/site-packages/pandas/indexes/base.py", line 1553, in asof_locs locs = self.values[mask].searchsorted(where.values, side='right') ValueError: operands could not be broadcast together with shapes (8760,) (2,) </code></pre> <p>What does this error mean, and what's the best way of doing this?</p> <p>The best I've come up with so far is this:</p> <pre><code>&gt;&gt;&gt; annual_series = weekly_model.A.loc[list(zip(dates.weekday, dates.hour))] </code></pre> <p>It works, but it means turning the <code>zip</code> iterator into a list first, which is not exactly memory-friendly. Is there a way of avoiding this?</p>
1
2016-10-07T16:34:07Z
39,923,806
<p>I read your post multiple times and I think I finally get what you are trying to achieve.</p> <p>try this:</p> <pre><code>df['weekday'] = df.index.weekday df['hour_of_day'] = df.index.hour weekly_model = df.groupby(['weekday', 'hour_of_day']).mean() dates = pd.date_range('2015/1/1', '2015/12/31 23:59', freq='H') </code></pre> <p>then use merge like this:</p> <pre><code>annual_series = pd.merge(df.reset_index(), weekly_model.reset_index(), on=['weekday', 'hour_of_day']).set_index('date') </code></pre> <p>now you can use asof since you have dates as index</p> <pre><code>annual_series.asof(dates) </code></pre> <p>is that what you were looking for?</p>
1
2016-10-07T18:34:06Z
[ "python", "pandas" ]
Delete entire node using lxml
39,922,132
<p>I have a an xml document like the following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;company&lt;/groupId&gt; &lt;artifactId&gt;art-id&lt;/artifactId&gt; &lt;version&gt;RELEASE&lt;/version&gt; &lt;/parent&gt; &lt;properties&gt; &lt;tomcat.username&gt;admin&lt;/tomcat.username&gt; &lt;tomcat.password&gt;admin&lt;/tomcat.password&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;asdf&lt;/groupId&gt; &lt;artifactId&gt;asdf&lt;/artifactId&gt; &lt;version&gt;[3.8,)&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;asdf&lt;/groupId&gt; &lt;artifactId&gt;asdf&lt;/artifactId&gt; &lt;version&gt;[4.1,)&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>how can I delete the entire node "dependencies"?</p> <p>I have looked at other questions and answers on stackoverflow and what is different about is the namespace aspect of this xml, and the other questions ask to delete a subelement like "dependency" while I want to delete the whole node "dependencies." Is there an easy way using lxml to delete the entire node?</p> <p>The following gives a 'NoneType' object has no attribute 'remove' error:</p> <pre><code>from lxml import etree as ET tree = ET.parse('pom.xml') namespace = '{http://maven.apache.org/POM/4.0.0}' root = ET.Element(namespace+'project') root.find(namespace+'dependencies').remove() </code></pre>
1
2016-10-07T16:38:55Z
39,922,424
<p>First, grab the root node. Since it is <code>&lt;project ... &gt;</code> (vs <code>&lt;project .../&gt;</code>) the "parent" element of <code>dependencies</code> is <code>project</code>. Example from the documentation:</p> <blockquote> <p>import xml.etree.ElementTree as ET<br> tree = ET.parse('country_data.xml')<br> root = tree.getroot() </p> </blockquote> <p>Once you have the root, check <code>root.tag()</code>, it should be "project".</p> <p>Then do <code>root.remove(root.find('dependencies'))</code>, where <code>root</code> is the <code>project</code> node.</p> <p>If it were <code>&lt;project .../&gt;</code> then it would be invalid XML since there must be a root element. I can see exactly where you are coming from, though.</p>
1
2016-10-07T16:56:02Z
[ "python", "xml", "lxml" ]
Delete entire node using lxml
39,922,132
<p>I have a an xml document like the following:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;company&lt;/groupId&gt; &lt;artifactId&gt;art-id&lt;/artifactId&gt; &lt;version&gt;RELEASE&lt;/version&gt; &lt;/parent&gt; &lt;properties&gt; &lt;tomcat.username&gt;admin&lt;/tomcat.username&gt; &lt;tomcat.password&gt;admin&lt;/tomcat.password&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;asdf&lt;/groupId&gt; &lt;artifactId&gt;asdf&lt;/artifactId&gt; &lt;version&gt;[3.8,)&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;asdf&lt;/groupId&gt; &lt;artifactId&gt;asdf&lt;/artifactId&gt; &lt;version&gt;[4.1,)&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>how can I delete the entire node "dependencies"?</p> <p>I have looked at other questions and answers on stackoverflow and what is different about is the namespace aspect of this xml, and the other questions ask to delete a subelement like "dependency" while I want to delete the whole node "dependencies." Is there an easy way using lxml to delete the entire node?</p> <p>The following gives a 'NoneType' object has no attribute 'remove' error:</p> <pre><code>from lxml import etree as ET tree = ET.parse('pom.xml') namespace = '{http://maven.apache.org/POM/4.0.0}' root = ET.Element(namespace+'project') root.find(namespace+'dependencies').remove() </code></pre>
1
2016-10-07T16:38:55Z
39,924,138
<p>You can create a dict mapping for your namespace(s), find the <em>node</em> then call <em>root.remove</em> passing the node, you don't call <em>.remove</em> on the node:</p> <pre><code>x = """&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;company&lt;/groupId&gt; &lt;artifactId&gt;art-id&lt;/artifactId&gt; &lt;version&gt;RELEASE&lt;/version&gt; &lt;/parent&gt; &lt;properties&gt; &lt;tomcat.username&gt;admin&lt;/tomcat.username&gt; &lt;tomcat.password&gt;admin&lt;/tomcat.password&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;asdf&lt;/groupId&gt; &lt;artifactId&gt;asdf&lt;/artifactId&gt; &lt;version&gt;[3.8,)&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;asdf&lt;/groupId&gt; &lt;artifactId&gt;asdf&lt;/artifactId&gt; &lt;version&gt;[4.1,)&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/project&gt;""" import lxml.etree as et from StringIO import StringIO tree = et.parse(StringIO(x)) root =tree.getroot() nsmap = {"mav":"http://maven.apache.org/POM/4.0.0"} root.remove(root.find("mav:dependencies", namespaces=nsmap)) print(et.tostring(tree)) </code></pre> <p>Which would give you:</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;groupId&gt;company&lt;/groupId&gt; &lt;artifactId&gt;art-id&lt;/artifactId&gt; &lt;version&gt;RELEASE&lt;/version&gt; &lt;/parent&gt; &lt;properties&gt; &lt;tomcat.username&gt;admin&lt;/tomcat.username&gt; &lt;tomcat.password&gt;admin&lt;/tomcat.password&gt; &lt;/properties&gt; &lt;/project&gt; </code></pre>
1
2016-10-07T18:58:04Z
[ "python", "xml", "lxml" ]
Python selenium click element while displayed
39,922,247
<p>I'm scraping a dynamic page that requires the user to click a "Load More Results" button several times in order to get all data. Is there a better way to approach the task of clicking on an element while displayed? </p> <pre><code>def clickon(xpath): try: element = driver.find_element_by_xpath(xpath) except: print "RETRYING CLICKON() for %s" % (xpath) time.sleep(1) clickon(xpath) else: element.click() time.sleep(3) def click_element_while_displayed(xpath): element = driver.find_element_by_xpath(xpath) try: while element.is_displayed(): clickon(xpath) except: pass </code></pre>
1
2016-10-07T16:45:29Z
39,922,345
<p>I suspect you are asking this question because the current solution is slow. This is mostly because you have these hardcoded <code>time.sleep()</code> delays which wait for more than they usually should. To tackle this problem I'd start using <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">Explicit Waits</a> - initialize an endless loop and break it once selenium stopped waiting for the button to be clickable:</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException wait = WebDriverWait(driver, 10) while True: try: element = wait.until(EC.element_to_be_clickable((By.XPATH, xpath))) element.click() except TimeoutException: break # cannot click the button anymore # TODO: wait for the results of the click action </code></pre> <p>Now the last <code>TODO</code> part is also important - here I suggest you wait for a specific condition that would indicate that click resulted into something on a page - for instance, more results were loaded. For example, you can use a custom Expected Condition similar to <a href="http://stackoverflow.com/a/30177865/771848">this one</a>.</p>
3
2016-10-07T16:51:13Z
[ "python", "selenium", "selenium-webdriver" ]
Python segmentation fault on Thread switch
39,922,369
<p>I'm developing an application that should check if the computer is able to ping google.com. To do that I use python subprocess module and issue a call as shown in the code below:</p> <pre><code>response = subprocess.call("ping -c 1 google.com -q", shell=True) </code></pre> <p>However, after running for some time, the program exits with a segmentation fault.</p> <p>I Have the following code:</p> <p><strong>daemon.py</strong></p> <pre><code>def dataset_save(smartphone, mote): print("DATA LOGGER:\tStarting Now") with open('dataset.csv', 'a+') as dataset: dataset.write(str(datetime.datetime.today()) + ',' + \ str(datetime.datetime.today().weekday()) + ',' + \ str(smartphone.connected) + ',' + \ str(mote.A0_pw) + ',' + \ str(mote.B00_pw) + ',' + \ str(mote.B01_pw) + ',' + \ str(mote.B10_pw) + ',' + \ str(mote.B11_pw) + ',' + \ str(presence.get_value()) + ',' + \ str(temperature.get_value()) + ',' + \ str(luminosity.get_value()) + '\n') print("DATA LOGGER: \tData successfully logged @ %s!" %str(datetime.datetime.today())) return def run(): check_internet() while True: dataset_save(smartphone, gateway) check_presence() </code></pre> <p><strong>check_internet.py</strong></p> <pre><code>def check_internet(): response = subprocess.call("ping -c 1 google.com -q", shell=True) print(response) if response == 0: print ("CONNECTIVITY: \tConnected to internet") threading.Timer(1, check_internet).start() return else: print("CONNECTIVITY: \tUnable to connect to internet") threading.Timer(1, check_internet).start() return </code></pre> <p>Running this on GDB I get the following trace upon the segmentation fault:</p> <pre><code>--- google.com ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 146.626/146.626/146.626/0.000 ms 0 CONNECTIVITY: Connected to internet [New Thread 0xb55ffb40 (LWP 4064)] Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0xb65ffb40 (LWP 4043)] PING google.com (216.58.222.110) 56(84) bytes of data. __deallocate_stack (pd=0xb65ffb40) at allocatestack.c:760 760 allocatestack.c: No such file or directory. (gdb) --- google.com ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 146.504/146.504/146.504/0.000 ms (gdb) bt #0 __deallocate_stack (pd=0xb65ffb40) at allocatestack.c:760 #1 0xb7fc3eab in start_thread (arg=0xb65ffb40) at pthread_create.c:427 #2 0xb7e8164e in clone () at ../sysdeps/unix/sysv/linux/i386/clone.S:129 (gdb) </code></pre> <p>Is there any reason why I should not use threding.Timer like I'm using? It seems to me that the successive creation of threads is responsible for this segmentation fault.</p> <p>Thanks.</p>
2
2016-10-07T16:52:23Z
39,922,946
<p>You're rearming the timer from within the timer itself, which may not be too good (recursive call with threads, argh). You don't really need <code>Timer</code> if you're not too demanding about ping delay accuracy: you could start a thread that loops and pings google periodically like this:</p> <pre><code>import threading,subprocess,time def check_internet(): while True: time.sleep(1) response = subprocess.call("ping -n 1 google.com".split()) print(response) if response == 0: print("CONNECTIVITY: \tConnected to internet") else: print("CONNECTIVITY: \tUnable to connect to internet") t=threading.Thread(target=check_internet) t.start() print("Started") t.join() </code></pre> <p>you only create 1 thread, which creates 1 ping process every 1+ seconds (it's not a regulated timer, but it should be enough).</p> <p>EDIT: version without <code>ping</code> output:</p> <pre><code>import threading,subprocess,time def check_internet(): while True: time.sleep(1) p = subprocess.Popen("ping -n 1 google.com".split(),stdout=subprocess.PIPE,stderr=subprocess.STDOUT) out,err = p.communicate() response = p.wait() if response == 0: print("CONNECTIVITY: \tConnected to internet") else: print("CONNECTIVITY: \tUnable to connect to internet") t=threading.Thread(target=check_internet) t.start() print("Started") t.join() </code></pre>
0
2016-10-07T17:33:03Z
[ "python", "multithreading", "segmentation-fault" ]
TraCI value doesn't tally with output
39,922,382
<p>When I do <code>traci.edge.getWaitingTime(str(-108542273))</code> at the last step of the simulation, I get a value of <code>0</code> from it. </p> <p>But when I went to verify on the edge-based state dump generated and found out that the value was <code>15</code>. Why does the traci value not reflect that? Do they not mean the same thing?</p> <pre><code>&lt;meandata xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://sumo.dlr.de/xsd/meandata_file.xsd"&gt; &lt;interval begin="0.00" end="602.00" id="edgebased"&gt; &lt;edge id="-108542273" sampledSeconds="288.08" traveltime="6.77" density="8.67" occupancy="4.33" waitingTime="15.00" speed="8.15" departed="0" arrived="0" entered="39" left="39" laneChangedFrom="0" laneChangedTo="0"/&gt; ... more edge entries &lt;/interval&gt; &lt;/meandata&gt; </code></pre> <p>I extracted the value on the very <strong>last step</strong> of the simulation, so I believe the 2 should reflect the same thing?</p> <p>Here's my whole python code</p> <pre><code>import os, sys import subprocess if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'tools') sys.path.append(tools) else: sys.exit("please declare environment variable 'SUMO_HOME'") def runTraCI(): trip_outputFile = "trip.output.xml" vehroute_outputFile = "vehroute.output.xml" PORT = 8817 sumoBinary = "sumo" sumoProcess = subprocess.Popen([sumoBinary, "-c", "data/tracitest.sumocfg", "--no-warnings", "true", "--remote-port", str(PORT), "--tripinfo-output", trip_outputFile, "--vehroute-output", vehroute_outputFile], stdout=sys.stdout, stderr=sys.stderr) import traci import traci.constants as tc traci.init(PORT) step = 0 edgeList = traci.edge.getIDList() #a list of edges of the network waitingTimeDict = {key: None for key in edgeList} # create an empty waitingTime dict while step &lt;= 600: if (step % 300) == 0: # read reading every 300s for key, value in waitingTimeDict.iteritems(): waitingTimeDict[key] = traci.edge.getWaitingTime(str(-108542273)) traci.simulationStep() step += 1 print waitingTimeDict #when I print this, every value is 0. In another word, edgeID("-108542273") waitingTime was return as 0 to me. traci.close() sys.exit() runTraCI() </code></pre>
0
2016-10-07T16:53:08Z
39,966,732
<p>The meandata output is aggregated over time, so it shows the sum of the waiting times in the interval. The TraCI call however only returns the waiting time on the given edge in the last simulation step (no aggregation over time).</p>
0
2016-10-10T21:04:23Z
[ "python", "sumo" ]
Missing levels in python contour plot
39,922,504
<p>I am trying to plot contours with specified levels of a simulated velocity field, my values are in the range of [75,150], and I specified my levels to be <code>levels=[75,95,115,135,150]</code>,but it's only giving me the 95,115,135 lines. I checked my 2d array and I do have points with values of 75 and 150 lying on straight lines, but the plot is just not showing them. I am wondering why would that be the case. Thanks a lot!! Here is my code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse #some parameters...does not matter i=60*np.pi/180 #inclination r=100 #radius vc=150 vr=0 x=np.arange(-100,100,1) y=np.arange(-100,100,1) xx,yy=np.meshgrid(x,y) #simulate velocity fields....does not matter either def projv((x, y),v_c, v_r, inc): projvy = v_c*x*np.cos(inc)/np.sqrt(x**2+y**2) + v_r*y*np.cos(inc)/np.sqrt(x**2+y**2) projvx = v_c*y/np.sqrt(x**2+y**2) + v_r*x/np.sqrt(x**2+y**2) v = np.sqrt(projvx**2 + projvy**2) return v.ravel() #here is my 2d array vel = projv((xx,yy),vc, vr, i).reshape(200,200) #levels I specified levels=[75,95,115,135,150] cs=plt.contour(x,y,vel,levels) plt.clabel(cs,inline=1,fontsize=9) plt.show() </code></pre> <p>Then I got this:<a href="http://i.stack.imgur.com/1exAh.png" rel="nofollow"><img src="http://i.stack.imgur.com/1exAh.png" alt="This is not showing the 75 and 150 contour levels that I specified. Why?"></a></p>
3
2016-10-07T17:00:17Z
39,922,697
<p>You are missing the 75 and 150 contours because those values are never crossed in the array. The value 150 exists, and the value 75(.000000000000014) exist, but those are the min and max values. Contours describe a line/surface <strong>boundary</strong>.</p> <pre><code>#levels modified levels=[76,95,115,135,149] cs=plt.contour(x,y,vel,levels) plt.clabel(cs,inline=1,fontsize=9) </code></pre> <p><a href="http://i.stack.imgur.com/APVfF.png" rel="nofollow"><img src="http://i.stack.imgur.com/APVfF.png" alt="with modified levels"></a></p>
0
2016-10-07T17:14:38Z
[ "python", "matplotlib", "contour" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to clarify for me so that I understand.</p> <p>Here is what the assignment said about the program I have to write:</p> <p><strong>Required:</strong> Write an OO Python Program showing how your sub-classes inherit from the super-class(es) You can have one class (preferred but not a must) or two or more super classes.</p> <p>What I have to do is write a oo python program showing sub-classing inherited by a class or two or more superclasses. The program has to be about shapes. As an example of what I mean by that is:</p> <p>Shape: Square</p> <p>Attributes:</p> <ul> <li>length </li> <li>width</li> </ul> <p>Methods:</p> <ul> <li>area</li> <li>perimeter</li> </ul> <p>I have more shapes of course but from that I find the common attributes and methods from all the shapes and make superclasses and sup-classes.</p> <p>My super classes are like: 2dShapes, circles and 3dShapes. My sub-classes are like length and width. My methods are area and perimeter. Note I am rambling at this point. The code snippet below does not show this instead I was thinking about making a superclass for attributes and methods and than sub-classes for the shapes? maybe?</p> <p>Question: is this a good class structure? Is there a better way to structure the classes here? Here is an example of what I'm thinking about how to do this.</p> <pre><code>class Shapes(attributes): def __init__(self): attributes.__init__(self) # not sure how to go on to make the attributes like height and length, radius ect. Maybe like this??? def height(self): raise NotImplementedError # again this program is not supose to actually do anything. The program is just for us to understand inheritance with classes and super classes. class 2dShapes(Shapes): class Square(self): def height(self): # ??? </code></pre> <p>So at this point I am so confused about where to start. Also I am super new to python so be gentle to me :p</p>
1
2016-10-07T17:03:57Z
39,922,895
<p>One of the big ideas of using inheritance is to be able to re-use code.. If you have a large body of functions that are the same for several classes, having one parent class that holds those functions allows you to only write them once, and to modify them all at the same time. for example, if you want to implement classes for the shapes: Square, Rectangle, and Parallelogram, you could create a parent class: Quadrangle that contains things like a generic area or perimeter functions:</p> <pre class="lang-python prettyprint-override"><code>class quadrangle(object): def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width def perimeter(self): return 2*self.length + 2*self.width class square(quadrangle): def __init__(self, length): super(square, self).__init__(length, length) #creates a quadrangle with equal lenght and width class rectangle(quadrangle): #renamed for convienience sake but otherwise the same pass class parallelogram(quadrangle): def __init__(self, length, width, angle): #angle in radians self.angle = angle super(parallelogram, self).__init__(length, width) def perimeter(self): #override parent's perimiter #do some math return 5 </code></pre>
1
2016-10-07T17:28:53Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to clarify for me so that I understand.</p> <p>Here is what the assignment said about the program I have to write:</p> <p><strong>Required:</strong> Write an OO Python Program showing how your sub-classes inherit from the super-class(es) You can have one class (preferred but not a must) or two or more super classes.</p> <p>What I have to do is write a oo python program showing sub-classing inherited by a class or two or more superclasses. The program has to be about shapes. As an example of what I mean by that is:</p> <p>Shape: Square</p> <p>Attributes:</p> <ul> <li>length </li> <li>width</li> </ul> <p>Methods:</p> <ul> <li>area</li> <li>perimeter</li> </ul> <p>I have more shapes of course but from that I find the common attributes and methods from all the shapes and make superclasses and sup-classes.</p> <p>My super classes are like: 2dShapes, circles and 3dShapes. My sub-classes are like length and width. My methods are area and perimeter. Note I am rambling at this point. The code snippet below does not show this instead I was thinking about making a superclass for attributes and methods and than sub-classes for the shapes? maybe?</p> <p>Question: is this a good class structure? Is there a better way to structure the classes here? Here is an example of what I'm thinking about how to do this.</p> <pre><code>class Shapes(attributes): def __init__(self): attributes.__init__(self) # not sure how to go on to make the attributes like height and length, radius ect. Maybe like this??? def height(self): raise NotImplementedError # again this program is not supose to actually do anything. The program is just for us to understand inheritance with classes and super classes. class 2dShapes(Shapes): class Square(self): def height(self): # ??? </code></pre> <p>So at this point I am so confused about where to start. Also I am super new to python so be gentle to me :p</p>
1
2016-10-07T17:03:57Z
39,922,947
<p>Let's start with the Shapes class. In the __init__ , you have to set the attributes. First you need 2 parameters other than self. You can use the same names as the attributes or pick different names.</p> <pre><code>class Shapes(attributes): def __init__(self, length, width): self.length = length self.width = width </code></pre> <p>If you want to inherit from Shapes class, other than putting it in () in 2dShapes class definition, you have to call the __init__ of the Shapes class and pass a reference and other parameters to it, like this:</p> <pre><code>class 2dShapes(Shapes): def __init__(self, length, width): Shapes.__init__(self, length, width) </code></pre> <p>If you want to use a method of Shapes in 2dShapes, you have to call it just like how we did for the __init__, lets say there is a method called area() in Shapes. In the 2dShapes, you can access it by Shapes.area(self). Here is an example:</p> <pre><code>class Shapes(attributes): def __init__(self, length, width): self.length = length self.width = width def area(self): return self.length * self.width class 2dShapes(Shapes): def __init__(self, length, width): Shapes.__init__(self, length, width) def area(self): return Shapes.area(self) </code></pre>
1
2016-10-07T17:33:04Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to clarify for me so that I understand.</p> <p>Here is what the assignment said about the program I have to write:</p> <p><strong>Required:</strong> Write an OO Python Program showing how your sub-classes inherit from the super-class(es) You can have one class (preferred but not a must) or two or more super classes.</p> <p>What I have to do is write a oo python program showing sub-classing inherited by a class or two or more superclasses. The program has to be about shapes. As an example of what I mean by that is:</p> <p>Shape: Square</p> <p>Attributes:</p> <ul> <li>length </li> <li>width</li> </ul> <p>Methods:</p> <ul> <li>area</li> <li>perimeter</li> </ul> <p>I have more shapes of course but from that I find the common attributes and methods from all the shapes and make superclasses and sup-classes.</p> <p>My super classes are like: 2dShapes, circles and 3dShapes. My sub-classes are like length and width. My methods are area and perimeter. Note I am rambling at this point. The code snippet below does not show this instead I was thinking about making a superclass for attributes and methods and than sub-classes for the shapes? maybe?</p> <p>Question: is this a good class structure? Is there a better way to structure the classes here? Here is an example of what I'm thinking about how to do this.</p> <pre><code>class Shapes(attributes): def __init__(self): attributes.__init__(self) # not sure how to go on to make the attributes like height and length, radius ect. Maybe like this??? def height(self): raise NotImplementedError # again this program is not supose to actually do anything. The program is just for us to understand inheritance with classes and super classes. class 2dShapes(Shapes): class Square(self): def height(self): # ??? </code></pre> <p>So at this point I am so confused about where to start. Also I am super new to python so be gentle to me :p</p>
1
2016-10-07T17:03:57Z
39,923,122
<p>I do not want to give answers that are too specific, because homework, but here is an example which I think might orient you in the right direction.</p> <p>In Object Oriented Programming, there is the concept of polymorphism: when instances of many different subclasses are related by some common superclass. You often see it explained as "a B is an A", like in "a Pear is a Fruit", "a Cat is an Animal", "a Triangle is a Shape". Subclasses all share a common set of methods and members present in the superclass, but their implementation of these methods can vary.</p> <p>Here is an example (sorry, C style, not a Python person) with animals. The method hearNoise() accepts an animal, but will also work correctly if a subtype is passed to it:</p> <pre><code>abstract class Animal { abstract String makeNoise(); } class Cat extends Animal { String makeNoise() { return "Meow!"; } } class Dog extends Animal { String makeNoise() { return "Woof!"; } } void hearNoise(Animal a) { println(a.makeNoise()); } int main() { hearNoise(new Cat()); //returns "Meow!" hearNoise(new Dog()); //returns "Woof!" } </code></pre> <p>The same principles can be applied to geometric shapes. They all have common methods and members : their perimeter, their area, their color, etc. When you have a shape, you can expect with 100% certitude you will be able to call a method to calculate a perimeter. However, the implementation, the way that specific shape subclass handles perimeter calculation, is what differs from shape to shape.</p>
2
2016-10-07T17:45:43Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to clarify for me so that I understand.</p> <p>Here is what the assignment said about the program I have to write:</p> <p><strong>Required:</strong> Write an OO Python Program showing how your sub-classes inherit from the super-class(es) You can have one class (preferred but not a must) or two or more super classes.</p> <p>What I have to do is write a oo python program showing sub-classing inherited by a class or two or more superclasses. The program has to be about shapes. As an example of what I mean by that is:</p> <p>Shape: Square</p> <p>Attributes:</p> <ul> <li>length </li> <li>width</li> </ul> <p>Methods:</p> <ul> <li>area</li> <li>perimeter</li> </ul> <p>I have more shapes of course but from that I find the common attributes and methods from all the shapes and make superclasses and sup-classes.</p> <p>My super classes are like: 2dShapes, circles and 3dShapes. My sub-classes are like length and width. My methods are area and perimeter. Note I am rambling at this point. The code snippet below does not show this instead I was thinking about making a superclass for attributes and methods and than sub-classes for the shapes? maybe?</p> <p>Question: is this a good class structure? Is there a better way to structure the classes here? Here is an example of what I'm thinking about how to do this.</p> <pre><code>class Shapes(attributes): def __init__(self): attributes.__init__(self) # not sure how to go on to make the attributes like height and length, radius ect. Maybe like this??? def height(self): raise NotImplementedError # again this program is not supose to actually do anything. The program is just for us to understand inheritance with classes and super classes. class 2dShapes(Shapes): class Square(self): def height(self): # ??? </code></pre> <p>So at this point I am so confused about where to start. Also I am super new to python so be gentle to me :p</p>
1
2016-10-07T17:03:57Z
39,923,323
<p>Be careful not to confuse "attributes" with "methods". There is an @property syntax which wraps attribute access within a method call, but you should ignore that for now.</p> <pre><code>class Shapes(attributes): def __init__(self): </code></pre> <p>For this part, just absorb the arguments here. e.g:</p> <pre><code>def __init__(self, *args, **kwargs): pass </code></pre> <p>Reason being, that you are only using Shapes to pass them to a subclass. <code>*args</code> absorbs lists of named arguments, while <code>**kwargs</code> absorbs dictionaries. So this <code>init()</code> will accept <code>my_shapes_instance = Shapes(length, width, height)</code> because it has <code>*args</code>, and it would accept <code>Shapes(length, width, height, {'cost': '10'})</code> because it has <code>**kwargs</code> as well. </p> <p>If it were <code>__init__(length, width, height)</code> and you passed <code>(length, width, height, color)</code> then it would not work. But if you use <code>*args</code> then it will accept anything. Will it <em>use</em> all of these arguments? Only if you define that it does.</p> <p>You can ignore **kwargs for now since you are not initializing these objects with dictionaries.</p> <pre><code>attributes.__init__(self) # not sure how to go on to make the attributes like height and length, radius ect. Maybe like this??? def height(self): raise NotImplementedError # again this program is not supose to actually do anything. The program is just for us to understand inheritance with classes and super classes. </code></pre> <p>What you have done above is define a method "height", not an <em>attribute</em> "height". What you want is more like this:</p> <pre><code>def __init__(self, height): self.height = height </code></pre> <p>Even better is this, but do it in the Square subclass:</p> <pre><code>class Square(Shapes): def __init__(self, height, *args, **kwargs): super(Square, self).__init__(height, *args, **kwargs) self.height = height </code></pre> <p>Now you can subclass Square with Rectangle, adding in new args as you go. Just follow a similar <strong>init</strong> pattern as above. Rectangle will not need you to add a height method, since it is already available from the parent.</p>
1
2016-10-07T18:00:25Z
[ "python", "python-3.x", "oop", "inheritance" ]
OOP : Trying to design a good class structure
39,922,553
<p>Follow up code snippet review question I posted: <a href="http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances">http://codereview.stackexchange.com/questions/143576/oop-designing-class-inheritances</a></p> <p>This is homework so off the bat I am not asking to do it for me but to clarify for me so that I understand.</p> <p>Here is what the assignment said about the program I have to write:</p> <p><strong>Required:</strong> Write an OO Python Program showing how your sub-classes inherit from the super-class(es) You can have one class (preferred but not a must) or two or more super classes.</p> <p>What I have to do is write a oo python program showing sub-classing inherited by a class or two or more superclasses. The program has to be about shapes. As an example of what I mean by that is:</p> <p>Shape: Square</p> <p>Attributes:</p> <ul> <li>length </li> <li>width</li> </ul> <p>Methods:</p> <ul> <li>area</li> <li>perimeter</li> </ul> <p>I have more shapes of course but from that I find the common attributes and methods from all the shapes and make superclasses and sup-classes.</p> <p>My super classes are like: 2dShapes, circles and 3dShapes. My sub-classes are like length and width. My methods are area and perimeter. Note I am rambling at this point. The code snippet below does not show this instead I was thinking about making a superclass for attributes and methods and than sub-classes for the shapes? maybe?</p> <p>Question: is this a good class structure? Is there a better way to structure the classes here? Here is an example of what I'm thinking about how to do this.</p> <pre><code>class Shapes(attributes): def __init__(self): attributes.__init__(self) # not sure how to go on to make the attributes like height and length, radius ect. Maybe like this??? def height(self): raise NotImplementedError # again this program is not supose to actually do anything. The program is just for us to understand inheritance with classes and super classes. class 2dShapes(Shapes): class Square(self): def height(self): # ??? </code></pre> <p>So at this point I am so confused about where to start. Also I am super new to python so be gentle to me :p</p>
1
2016-10-07T17:03:57Z
39,923,382
<pre><code>class Vehicle(object): #class variable shared between all instances of objects. number_of_vehicles = 0 def __init__(self,length,width,color,wheels): self.length = length self.width = width self.color = color self.wheels = wheels Vehicle.number_of_vehicles += 1 #increasing class varaible count def get_length(self): print("I am %d meters long!"%self.length) def get_wdith(self): print("I am %d meters wide!"%self.width) def get_color(self): print("My color is %s!"%self.color) def get_wheels(self): print("I have %d number of wheels"%self.wheels) #calling my methods so I don't need to call each of their own def get_stats(self): self.get_length() self.get_wheels() self.get_wdith() self.get_color() def honk(self): print("beep beep") class Car(Vehicle): def vroom(self): print("Cars go vroom vroom") class Cooper(Car): def drift(self): print("Mini Coopers can drift well") class Airplanes(Vehicle): def fly(self): print("weeeeee I'm flying") class Tank(Vehicle): #custom init because tanks have guns!~ #taking the gun size and tossing the rest of the arguments to the parent. #if the parent doesn't find a __init__ it will keep going up until one is found or unelss we call it. #Here we made a new __init__ so it doesn't go looking for one, but we call super() which is calling for the #parent's __init__ def __init__(self,gun_size,*args): self.gun_size = gun_size super(Tank,self).__init__(*args) def fire(self): print("pew pew pew") #I have my custom get_stats but still calls parent's one so I don't repeat code. def get_stats(self): print("my gun is this big: %d " %self.gun_size) super(Tank,self).get_stats() a = Cooper(150,150,"blue",4) a.drift() a.vroom() a.honk() a.get_stats() print(a.number_of_vehicles) b = Airplanes(200,150,"white",2) b.fly() print(b.number_of_vehicles) c = Tank(500,500,250,"Green",18) c.fire() print(c.number_of_vehicles) c.get_stats() </code></pre> <p>Outputs:</p> <pre><code>Mini Coopers can drift well Cars go vroom vroom beep beep I am 150 meters long! I have 4 number of wheels I am 150 meters wide! My color is blue! 1 #vehicle count weeeeee I'm flying # start of plan section 2 #vehicle count pew pew pew #start of tank section 3 #vehicle count my gun is this big: 500 I am 500 meters long! I have 18 number of wheels I am 250 meters wide! My color is Green! </code></pre> <p>So the point of this post was to show you relationship of inheritance. </p> <p>We have a base class called <code>Vehicle</code> which is a sub class of <code>object</code>. Don't worry about <code>object</code> if you want you can read up on it. </p> <p>Vehicle class has some attibutes that all vehicles would have, length, width, color, wheels. It also have a class variable called <code>number_of_vehicles</code> which keeps track of how many object instances Vehicle has, basically how many Vehicles we "made". We also have some class methods, that access and uses the attributes we defined in <code>__init__</code>. You can do math on them and what not but for now we are just using them as print statements to show they work. We have a special class method that calls other methods in the same class. So <code>get_stats</code> calls the other <code>get_x</code> methods in the instance. This allows me to call those 4 methods with just "one" method call from my object, see <code>a.get_stats()</code>. We can still call the other methods on it's own like <code>get_color</code>. </p> <p>We have a sub class called Car which is a vehicle, so we inherit it. Only cars can go vroom, but all cars can go vroom so we have a vroom method only at the car level. The trick is to think what does this class have that is unique to only instances of this class, and if not, can I put it in the parent's class. All vehicles have wheels and so on, but not all vehicles can go vroom (for this example only). </p> <p>We have a sub class of Car, the cooper (mini cooper), which only it can drift (once again for this example only in real life the drift method would go in vehicle cause all vehicles can draft but bare with me). So this cooper is the only car that can drift so it's down here instead of in the Car class.</p> <p>Tank's sub class is interesting. Here we have the basic of a vehicle but we have something new, a gun! So our vehicle class can't handle a gun, so we have to make a new <code>__init__</code> method. We assign the object variable <code>gun_size</code> and then pass the rest of the tank's attribute to Vehicle's <code>__init__</code> since the rest of the attributes are the same as Vehicle. We call <code>super(Tank,self).__init__(*args)</code> which is basically saying, I am a tank, this is me, please handle the rest of my attribute, parent of mine. Since tanks have a special attribute of a gun, we have to modify our <code>get_stats</code> method, to deal with the <code>gun_size</code> attribute, but the rest of the stats on the tank are the same as vehicle, so we just call our parents to handle the rest after we deal with our gun. </p> <p>Now I know this is a very silly example, but I do hope you find some useful information in here. There are other majors points I haven't touched upon but this is a starting point. So back to your original question. Think abstract, the highest level would be a shape, then Rectangles are a type of shape so they would inherit it. Squares are special rectangles, so they would inherit rectangles and so on. </p> <p>If you have questions don't hesitate to ask. </p>
1
2016-10-07T18:04:28Z
[ "python", "python-3.x", "oop", "inheritance" ]
Python - creating directories after button click
39,922,632
<p>I'm a bit new to Python so forgive the ignorance.</p> <p>I am currently toying with a little app to create directories based on user input. I have made a bash script that does this perfectly but would like put a GUI on it.</p> <p>So far i have got this function that works:</p> <pre><code>def on_TextEntry_activate(self, widget): ParentFolder = widget.get_text() os.chdir("/home/user/folder/") if not os.path.exists(ParentFolder): os.makdirs(ParentFolder), 0755) os.chdir(ParentFolder) os.makedirs("FolderA", 0755) os.makedirs("FolderB", 0755) os.makedirs("FolderC", 0755) print "Your new folders have been created" </code></pre> <p>So, like i said, this particular function works. What i would like to happen is to have a "create" button that runs this function instead of the text entry box doing it. As i would eventually like to add other text entry box for other things but that's more than likely going to be another post though!!</p> <p>So if you could then that would be great .. please be gentle with me! :D</p> <p>Thanks in advance.</p>
-1
2016-10-07T17:09:06Z
39,922,755
<p>For user interfaces in python, use TKInter to create that button you want. run -pip install TkInter as TK </p> <p>which version of python are you on?</p>
-1
2016-10-07T17:18:38Z
[ "python", "linux", "glade" ]
Python - creating directories after button click
39,922,632
<p>I'm a bit new to Python so forgive the ignorance.</p> <p>I am currently toying with a little app to create directories based on user input. I have made a bash script that does this perfectly but would like put a GUI on it.</p> <p>So far i have got this function that works:</p> <pre><code>def on_TextEntry_activate(self, widget): ParentFolder = widget.get_text() os.chdir("/home/user/folder/") if not os.path.exists(ParentFolder): os.makdirs(ParentFolder), 0755) os.chdir(ParentFolder) os.makedirs("FolderA", 0755) os.makedirs("FolderB", 0755) os.makedirs("FolderC", 0755) print "Your new folders have been created" </code></pre> <p>So, like i said, this particular function works. What i would like to happen is to have a "create" button that runs this function instead of the text entry box doing it. As i would eventually like to add other text entry box for other things but that's more than likely going to be another post though!!</p> <p>So if you could then that would be great .. please be gentle with me! :D</p> <p>Thanks in advance.</p>
-1
2016-10-07T17:09:06Z
39,979,617
<p>Don't worry chaps, i've got the answer to my question now! (see below):</p> <pre><code>def on_createbutton_clicked(self, widget): ParentFolder = self.ui.ParentFolder.get_text() os.chdir("/home/user/folder/") if not os.path.exists(ParentFolder): os.makdirs(ParentFolder), 0755) os.chdir(ParentFolder) os.makedirs("FolderA", 0755) os.makedirs("FolderB", 0755) os.makedirs("FolderC", 0755) print "Your new folders have been created" </code></pre> <p>Just one line is all it takes! &lt;&lt; my new mantra </p>
0
2016-10-11T14:28:28Z
[ "python", "linux", "glade" ]
Apply style map when writing a DataFrame to html with pandas
39,922,633
<p>I want to output a pandas DataFrame to .html and also apply a style. The documentation* gives this example which displays negative values as red.</p> <pre><code>import pandas as pd import numpy as np np.random.seed(24) df = pd.DataFrame({'A': np.linspace(1, 10, 10)}) df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1) df.iloc[0, 2] = np.nan def color_negative_red(val): """ Takes a scalar and returns a string with the css property `'color: red'` for negative strings, black otherwise. """ color = 'red' if val &lt; 0 else 'black' return 'color: %s' % color s = df.style.applymap(color_negative_red) s </code></pre> <p>Can I output the formatted df using the "to_html" method? From that documentation** I see that there is a "formatters" option but I can't figure out how to apply it in this case.</p> <p>Here is how I'm writing the unformatted df:</p> <pre><code>df.to_html(r'c:\temp\html.html') </code></pre> <p>*<a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/style.html</a></p> <p>**<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html</a></p>
1
2016-10-07T17:09:14Z
39,925,277
<p>I don't know if it is the best (or idiomatic) way to do that, but it should work:</p> <pre><code>with open('html.html', 'w') as html: html.write(s.render()) </code></pre>
2
2016-10-07T20:25:55Z
[ "python", "pandas" ]
tox tests, use setup.py extra_require as tox deps source
39,922,650
<p>I want to use setup.py as the authority on packages to install for testing, done with extra_requires like so:</p> <pre><code>setup( # ... extras_require={ 'test': ['pytest', ], }, ) </code></pre> <p>Tox only appears to be capable of <a href="https://testrun.org/tox/latest/example/basic.html#depending-on-requirements-txt" rel="nofollow">installing from a requirements.txt</a> file which just implies a step of snapshotting requirements before testing (which I'm ignorant how to do automatically) or by <a href="https://testrun.org/tox/latest/config.html#confval-deps=MULTI-LINE-LIST" rel="nofollow">duplicating the test dependencies</a> into the tox file, which is all I want to avoid. <a href="http://lists.idyll.org/pipermail/testing-in-python/2015-March/006285.html" rel="nofollow">One mailing list post</a> suggested that tox.ini should be the authority on test dependencies, but I don't wish to straightjacket tox into the project that completely.</p>
0
2016-10-07T17:10:30Z
39,922,651
<p>I've come up with a nasty hack that seems to work</p> <pre><code># tox.ini ... [testenv] ... install_command = pip install {opts} {packages} {env:PWD}[test] </code></pre> <p>The defualt <code>install_command</code> is <code>pip install {opts} {packages}</code>, unfortunately <code>{packages}</code> is a required argument. Additionally tox doesn't expose the project directory as a magic variable; but it does expose the <code>env</code> of the shell that ran it.</p> <p>This works by assuming you ran <code>tox</code> from the same directory as your <code>setup.py</code> and <code>tox.ini</code>, and assuming your shell exposes <code>PWD</code> as your current path. Tox appears to use something like <code>shlex</code> to split your <code>install_command</code> into a shell-safe set of arguments, so we cant do things like <code>{packages}[test]</code>. Ultimately this hack will name your package twice, but I think that's okay since <code>{env:PWD}[test]</code> names your package plus the <code>extra_require</code> block you want.</p> <p>I don't know a better way, the <a href="https://github.com/pypa/sampleproject/" rel="nofollow">PYPA SampleProject</a> seems content with specifying your test dependencies in both setup.py and tox.ini.</p>
0
2016-10-07T17:10:30Z
[ "python", "testing", "setup.py", "tox" ]
Python : How to make a quiz and check if the answer is correct?
39,922,668
<p>I'm taking a computer science course and I recently took a test and there was a question whose answer I did not know and I want to know how to do it.</p> <p>The Question/problem was Ask the user 7 questions. Then check how many were correct and then give a percentage. I am familiar with input and operators and variables but I do not understand how to check if the answer the user inputed was correct and how to calculate how many were correct and how many were incorrect</p>
-4
2016-10-07T17:12:13Z
39,922,818
<p>How about something like this (pseudo-code)?</p> <pre><code>qa = [ ('Q1', 'A1'), ('Q2', 'A2'), ] num_correct = 0 for q,a in qa: user_answer = raw_input(q) if user_answer == a: num_correct += 1 print 'Total questions:', len(qa) print 'Total correct:', num_correct </code></pre> <p>You should be able to find out the rest.</p>
1
2016-10-07T17:23:48Z
[ "python", "input" ]
Python : How to make a quiz and check if the answer is correct?
39,922,668
<p>I'm taking a computer science course and I recently took a test and there was a question whose answer I did not know and I want to know how to do it.</p> <p>The Question/problem was Ask the user 7 questions. Then check how many were correct and then give a percentage. I am familiar with input and operators and variables but I do not understand how to check if the answer the user inputed was correct and how to calculate how many were correct and how many were incorrect</p>
-4
2016-10-07T17:12:13Z
39,937,040
<p>Ive Done It, Code of What I Did Below:</p> <p>q1=int(input("What Is 5+1 ")) if q1==6: print ("Correct") corr1=int(1) else: print ("Wrong, The Answer Is: 6") corr1=int(0)</p> <p>q2=int(input("What Is 6+9 ")) if q2==15: print ("Correct") corr2=int(1) else: print ("Wrong, The Answer Is: 115") corr2=int(0)</p> <p>q3=int(input("What Is 54+4 ")) if q3==58: print ("Correct") corr3=int(1) else: print ("Wrong, The Answer Is: 58") corr3=int(0)</p> <p>q4=int(input("What Is 43+9 ")) if q4==52: print ("Correct") corr4=int(1) else: print ("Wrong, The Answer Is: 52") corr4=int(0)</p> <p>q5=int(input("What Is 67+9 ")) if q5==76: print ("Correct") corr5=int(1) else: print ("Wrong, The Answer Is: 76") corr5=int(0)</p> <p>q6=int(input("What Is 64+14 ")) if q6==78: print ("Correct") corr6=int(1) else: print ("Wrong, The Answer Is: 78") corr6=int(0)</p> <p>q7=int(input("What Is 44+3 ")) if q7==47: print ("Correct") corr7=int(1) else: print ("Wrong, The Answer Is: 47") corr7=int(0)</p> <p>correct=corr1+corr2+corr3+corr4+corr5+corr6+corr7 print("You Scored %s/7" %(correct))</p> <p>per=int(correct/7*100)</p> <p>if per>=50: print("Congratulations You Passed With A %s Percent" % (per)) else: print("Oh No You Did Not Pass The Test And Scored A %s Percent, Try Harder Next Time!" %(per)) </p>
0
2016-10-08T20:27:40Z
[ "python", "input" ]
python changes values of list
39,922,701
<p>I am fairly new to Python so please be patient, this is probably simple. I am trying to build an adjacency list representation of a graph. In this particular representation I decided to use list of lists where the first value of each sublist represents the tail node and all other values represent head nodes. For example, the graph with edges <code>1-&gt;2, 2-&gt;3, 3-&gt;1, 1-&gt;3</code> will be represented as <code>[[1,2,3],[2,3],[3,1]]</code>.</p> <p>Running the following code on this edge list, gives a problem I do not understand.</p> <p>The edge list (<code>Example.txt</code>):</p> <pre><code>1 2 2 3 3 1 3 4 5 4 6 4 8 6 6 7 7 8 </code></pre> <p>The Code:</p> <pre><code>def adjacency_list(graph): graph_copy = graph[:] g_tmp = [] nodes = [] for arc in graph_copy: choice_flag_1 = arc[0] not in nodes choice_flag_2 = arc[1] not in nodes if choice_flag_1: g_tmp.append(arc) nodes.append(arc[0]) else: idx = [item[0] for item in g_tmp].index(arc[0]) g_tmp[idx].append(arc[1]) if choice_flag_2: g_tmp.append([arc[1]]) nodes.append(arc[1]) return g_tmp # Read input from file g = [] with open('Example.txt') as f: for line in f: line_split = line.split() new_line = [] for element in line_split: new_line.append(int(element)) g.append(new_line) print('File Read. There are: %i items.' % len(g)) graph = adjacency_list(g) </code></pre> <p>During runtime, when the code processes arc <code>6 7</code> (second to last line in file), the following lines (found in the <code>else</code> statement) append <code>7</code> <strong>not only</strong> to <code>g_tmp</code> <strong>but also</strong> to <code>graph_copy</code> and <code>graph</code>.</p> <pre><code>idx = [item[0] for item in g_tmp].index(arc[0]) g_tmp[idx].append(arc[1]) </code></pre> <p>What is happening?</p> <p>Thank you!</p> <p>J</p> <p>P.S. I'm running Python 3.5</p> <p>P.P.S. I also tried replacing <code>graph_copy = graph[:]</code> with <code>graph_copy = list(graph)</code>. Same behavior.</p>
1
2016-10-07T17:14:53Z
39,925,753
<p>The problem is in the lines</p> <pre><code> if choice_flag_1: g_tmp.append(arc) </code></pre> <p>When you append arc, you are appending a shallow copy of the inner list. Replace with a new list like so</p> <pre><code> if choice_flag_1: g_tmp.append([arc[0],arc[1]]) </code></pre>
1
2016-10-07T21:01:37Z
[ "python", "list", "graph" ]
Is random.sample truly random?
39,922,724
<p>I have a list with <code>155k</code> files. When I <code>random.sample(list, 100)</code>, while the results are not the same from the previous sample, they look similar. </p> <p>Is there a better alternative to <code>random.sample</code> that returns a new list of random 100 files? </p> <pre><code>folders = get_all_folders('/data/gazette-txt-files') # get all files from all folders def get_all_files(): files = [] for folder in folders: files.append(glob.glob("/data/gazette-txt-files/" + folder + "/*.txt")) # convert 2D list into 1D formatted_list = [] for file in files: for f in file: formatted_list.append(f) # 200 random text files return random.sample(formatted_list, 200) </code></pre>
-2
2016-10-07T17:16:14Z
39,922,890
<p>You may need to seed the generator. See <a href="https://docs.python.org/2/library/random.html#random.seed" rel="nofollow">here</a> in the Documentation.</p> <p>Just call <code>random.seed()</code> before you get the samples.</p>
-1
2016-10-07T17:28:26Z
[ "python", "python-3.x", "random" ]
Is random.sample truly random?
39,922,724
<p>I have a list with <code>155k</code> files. When I <code>random.sample(list, 100)</code>, while the results are not the same from the previous sample, they look similar. </p> <p>Is there a better alternative to <code>random.sample</code> that returns a new list of random 100 files? </p> <pre><code>folders = get_all_folders('/data/gazette-txt-files') # get all files from all folders def get_all_files(): files = [] for folder in folders: files.append(glob.glob("/data/gazette-txt-files/" + folder + "/*.txt")) # convert 2D list into 1D formatted_list = [] for file in files: for f in file: formatted_list.append(f) # 200 random text files return random.sample(formatted_list, 200) </code></pre>
-2
2016-10-07T17:16:14Z
39,923,025
<p>For purposes like randomly selecting elements from a list, using <code>random.sample</code> suffices, true randomness isn't provided and I'm unaware if this is even theoretically possible. </p> <p><code>random</code> (by default) uses a <a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator" rel="nofollow">Pseudo Random Number Generator</a> (PRNG) called Mersenne Twister (MT) which, although suitable for applications such as simulations (and minor things like picking from a list of paths), shouldn't be used in areas where security is a concern due to the fact that <a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator#Potential_problems_with_deterministic_generators" rel="nofollow">it is deterministic</a>.</p> <p>This is why Python <code>3.6</code> also introduces <code>secrets.py</code> with <a href="https://www.python.org/dev/peps/pep-0506/" rel="nofollow">PEP 506</a>, which uses <code>SystemRandom</code> (<code>urandom</code>) by default and is capable of producing <a href="https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator" rel="nofollow">cryptographically secure pseudo random numbers</a>. </p> <p>Of course, bottom line is, that even if you use a PRNG or CPRNG to generate your numbers they're still going to be pseudo random.</p>
2
2016-10-07T17:38:52Z
[ "python", "python-3.x", "random" ]
Encountering an Error in Robot Framework after tests run
39,922,763
<p>I am new to using Robot Framework, and have run into a problem while running tests on a Jenkins server. The tests are passing, and after the tests run I get the following message:</p> <blockquote> <p>Output: /opt/bitnami/apps/jenkins/jenkins_home/jobs/Robot Test/workspace/robot/Results/output.xml</p> <p>[ ERROR ] Reading XML source '/opt/bitnami/apps/jenkins/jenkins_home/jobs/Robot Test/workspace/robot/Results/output.xml' failed: ImportError: >No module named expat; use SimpleXMLTreeBuilder instead</p> </blockquote> <p>I get this message regardless of what tests I run. I am not explicitly calling expat or any other xml module. </p> <p>I am running Python 2.7.9 and Robot Framework 3.0. </p> <p>If I run "pybot -o NONE" to cancel the logging the error goes away, but I do want the logging and do not know how to stop the error. </p> <p>Thanks for any help you can offer.</p>
-1
2016-10-07T17:19:17Z
39,962,145
<p>In case it helps anyone who finds this, it appears that my issue was that some of the modules I installed using pip were not installed using "sudo". This led a few of them to install the module, but with errors. When I uninstalled them, and then reinstalled them with sudo, this error has not reappeared. </p>
0
2016-10-10T15:56:11Z
[ "python", "python-2.7", "selenium", "jenkins", "robotframework" ]
Python - Determine Tic-Tac-Toe Winner
39,922,967
<p>I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)</p> <p>I have written the following function to do so:</p> <blockquote> <p>This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bit of hardcoding.</p> </blockquote> <pre><code>def iswinner(board, decorator): win = True for row in range(len(board)): for col in range(len(board)): if board[row][col] == decorator: win = True else: win = False break </code></pre> <p>Where "board" is a 2D array of size n^2 and "decorator" is the "X" or "O" value</p> <p>What I hope to accomplish is that the function loops through the 2D array's rows. Then loops through the values in each row. If that element matches the "decorator" then it continues and checks the next but if it doesn't, then it breaks from the first loop and goes to the next row. It does this until it finds n elements in the same row. Then it would give a bool value of True otherwise False.</p> <p>The code doesn't seem to do that and even when I checked with the following "board" it gave me an output of "True"</p> <blockquote> <pre><code>check_list = [['O', 'X', 'X'], ['O', 'X', 'O'], ['O', 'X', 'X']] </code></pre> </blockquote> <p>Thank you so much!</p> <p>Best, Seyed</p>
0
2016-10-07T17:34:57Z
39,923,094
<p>You can just make a set of each row, and check its length. If it contains only one element, then the game has been won.</p> <pre><code>def returnWinner(board): for row in board: if len(set(row)) == 1: return row[0] return -1 </code></pre> <p>This will return "O" if there is a full line of "O", "X" if there is a line of "X", and -1 otherwise.</p> <p>Below is the code of a full Tic-Tac-Toe checker, it should not be hard to understand, but do not hesitate to ask:</p> <pre><code>import numpy as np def checkRows(board): for row in board: if len(set(row)) == 1: return row[0] return 0 def checkDiagonals(board): if len(set([board[i][i] for i in range(len(board))])) == 1: return board[0][0] if len(set([board[i][len(board)-i-1] for i in range(len(board))])) == 1: return board[0][len(board)-1] return 0 def checkWin(board): #transposition to check rows, then columns for newBoard in [board, np.transpose(board)]: result = checkRows(newBoard) if result: return result return checkDiagonals(board) a = [['X', 'A', 'X'], ['A', 'X', 'A'], ['A', 'X', 'A']] print(checkWin(a)) </code></pre> <p>Note that this works regardless of the symbols you choose to put in your tic-tac-toe ("O" &amp; "X" is as fine as "bloop" &amp; "!"), and for any size of grid, as long as it is a square.</p>
2
2016-10-07T17:43:52Z
[ "python", "arrays", "loops", "boolean", "break" ]
Python - Determine Tic-Tac-Toe Winner
39,922,967
<p>I am trying to write a code that determines the winner of a tic-tac-toe game. (This is for a college assignment)</p> <p>I have written the following function to do so:</p> <blockquote> <p>This code only checks for horizontal lines, I haven't added the rest. I feel that this is something that needs a bit of hardcoding.</p> </blockquote> <pre><code>def iswinner(board, decorator): win = True for row in range(len(board)): for col in range(len(board)): if board[row][col] == decorator: win = True else: win = False break </code></pre> <p>Where "board" is a 2D array of size n^2 and "decorator" is the "X" or "O" value</p> <p>What I hope to accomplish is that the function loops through the 2D array's rows. Then loops through the values in each row. If that element matches the "decorator" then it continues and checks the next but if it doesn't, then it breaks from the first loop and goes to the next row. It does this until it finds n elements in the same row. Then it would give a bool value of True otherwise False.</p> <p>The code doesn't seem to do that and even when I checked with the following "board" it gave me an output of "True"</p> <blockquote> <pre><code>check_list = [['O', 'X', 'X'], ['O', 'X', 'O'], ['O', 'X', 'X']] </code></pre> </blockquote> <p>Thank you so much!</p> <p>Best, Seyed</p>
0
2016-10-07T17:34:57Z
39,923,218
<p>One way to do this would be to create a set (a generator function would be even better) of all the possible index combinations to check for the win. Then loop through those index combinations and check if they all contain the same value, if so, then it's a win.</p> <pre><code>def win_indexes(n): # Rows for r in range(n): yield [(r, c) for c in range(n)] # Columns for c in range(n): yield [(r, c) for r in range(n)] # Diagonal top left to bottom right yield [(i, i) for i in range(n)] # Diagonal top right to bottom left yield [(i, n - 1 - i) for i in range(n) def is_winner(board, decorator): n = len(board) for indexes in win_indexes(n): if all(board[r][c] == decorator for r, c in indexes): return True return False </code></pre>
1
2016-10-07T17:52:29Z
[ "python", "arrays", "loops", "boolean", "break" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 Bob 65 Oranges 10/7/2016 Tony 1 Grapes 10/7/2016 Bob 1 Grapes 10/7/2016 Tom 87 Grapes 10/7/2016 Bob 22 Grapes 10/7/2016 Bob 12 Grapes 10/7/2016 Tony 15 </code></pre> <p>I want to aggregate this by name and then by fruit to get a total number of fruit per name.</p> <pre><code>Bob,Apples,16 ( for example ) </code></pre> <p>I tried grouping by Name and Fruit but how do I get the total number of fruit.</p>
4
2016-10-07T17:36:25Z
39,923,012
<p>use the sum() method</p> <pre><code>df.groupby(['Name','Fruit']).sum() Out[31]: Number Fruit Name Apples Bob 16 Mike 9 Steve 10 Grapes Bob 35 Tom 87 Tony 15 Oranges Bob 67 Mike 57 Tom 15 Tony 1 </code></pre>
3
2016-10-07T17:37:45Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 Bob 65 Oranges 10/7/2016 Tony 1 Grapes 10/7/2016 Bob 1 Grapes 10/7/2016 Tom 87 Grapes 10/7/2016 Bob 22 Grapes 10/7/2016 Bob 12 Grapes 10/7/2016 Tony 15 </code></pre> <p>I want to aggregate this by name and then by fruit to get a total number of fruit per name.</p> <pre><code>Bob,Apples,16 ( for example ) </code></pre> <p>I tried grouping by Name and Fruit but how do I get the total number of fruit.</p>
4
2016-10-07T17:36:25Z
39,923,111
<p>You can use <code>groupby</code> and <code>sum</code>:</p> <pre><code>df.groupby(['Name', 'Fruit']).sum() Number Name Fruit Bob Apples 16 Grapes 35 Oranges 67 Mike Apples 9 Oranges 57 Steve Apples 10 Tom Grapes 87 Oranges 15 Tony Grapes 15 Oranges 1 </code></pre>
1
2016-10-07T17:44:57Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 Bob 65 Oranges 10/7/2016 Tony 1 Grapes 10/7/2016 Bob 1 Grapes 10/7/2016 Tom 87 Grapes 10/7/2016 Bob 22 Grapes 10/7/2016 Bob 12 Grapes 10/7/2016 Tony 15 </code></pre> <p>I want to aggregate this by name and then by fruit to get a total number of fruit per name.</p> <pre><code>Bob,Apples,16 ( for example ) </code></pre> <p>I tried grouping by Name and Fruit but how do I get the total number of fruit.</p>
4
2016-10-07T17:36:25Z
39,923,815
<p>Both the other answers accomplish what you want. </p> <p>You can use the <code>pivot</code> functionality to arrange the data in a nice table</p> <pre><code>df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0) Name Bob Mike Steve Tom Tony Fruit Apples 16.0 9.0 10.0 0.0 0.0 Grapes 35.0 0.0 0.0 87.0 15.0 Oranges 67.0 57.0 0.0 15.0 1.0 </code></pre>
1
2016-10-07T18:35:14Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Pandas group-by and sum
39,922,986
<p>I am using this data frame:</p> <pre><code>Fruit Date Name Number Apples 10/6/2016 Bob 7 Apples 10/6/2016 Bob 8 Apples 10/6/2016 Mike 9 Apples 10/7/2016 Steve 10 Apples 10/7/2016 Bob 1 Oranges 10/7/2016 Bob 2 Oranges 10/6/2016 Tom 15 Oranges 10/6/2016 Mike 57 Oranges 10/6/2016 Bob 65 Oranges 10/7/2016 Tony 1 Grapes 10/7/2016 Bob 1 Grapes 10/7/2016 Tom 87 Grapes 10/7/2016 Bob 22 Grapes 10/7/2016 Bob 12 Grapes 10/7/2016 Tony 15 </code></pre> <p>I want to aggregate this by name and then by fruit to get a total number of fruit per name.</p> <pre><code>Bob,Apples,16 ( for example ) </code></pre> <p>I tried grouping by Name and Fruit but how do I get the total number of fruit.</p>
4
2016-10-07T17:36:25Z
39,931,909
<p>Also you can use agg function,</p> <pre><code>df.groupby(['Name', 'Fruit'])['Number'].agg('sum') </code></pre>
0
2016-10-08T11:40:26Z
[ "python", "pandas", "dataframe", "group-by", "aggregate" ]
Obtain difference between two lists of objects in Python using hash
39,923,021
<p>My objective is to get the difference between two lists containing objects.</p> <p>I have implemented a class named Branch and overwritten its <code>__eq__</code> and <code>__ne__</code> methods as follows:</p> <pre><code>class Branch(object): def __str__(self): return self.name def __eq__(self, other): if isinstance(other, Branch): return (self.valueFrom == other.valueFrom) \ and (self.valueTo == other.valueTo) \ and (self.inService == other.inService) return NotImplemented def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return result return not result def __init__(self, name, valueFrom, valueTo, inService=True): self.name = name self.valueFrom = valueFrom self.valueTo = valueTo self.inService = inService </code></pre> <p>My first attempt was to use the method <code>difference</code> from the <code>set</code> type. However it appears this is not possible as it uses the hash of the object and not the <code>__eq__</code>method as I would like to.</p> <p>Following code shows the problem:</p> <pre><code>b1 = Branch("branch1", 1, 2) b1b = Branch("equal to branch1", 1, 2) b2 = Branch("branch2", 2, 3) b3 = Branch("branch3", 3, 1) b3_off = Branch("branch3 not in service", 3, 1, False) l1 =[b1,b2,b3] l2 =[b1b,b2,b3_off] difference = set(l1).difference(l2) for branch in difference: print branch </code></pre> <p>Output is:</p> <pre><code>&gt;&gt;&gt; branch1 branch3 </code></pre> <p>However I wish to get as output only branch3 as <code>b1</code> and <code>b1b</code> should be treated as equal.</p> <p>Is it possible to use sets to resolve this? Or should I approach the problem from a different perspective?</p>
2
2016-10-07T17:38:25Z
39,923,304
<p>You would need to implement <em>hash</em>, what you choose to is up to you but the following would work:</p> <pre><code>def __hash__(self): return hash((self.valueFrom , self.valueTo , self.inService)) </code></pre> <p>All you need to implement is hash and eq:</p> <pre><code>class Branch(object): def __init__(self, name, valueFrom, valueTo, inService=True): self.name = name self.valueFrom = valueFrom self.valueTo = valueTo self.inService = inService def __eq__(self, other): if isinstance(other, Branch): return (self.valueFrom,self.valueTo,self.inService )\ ==(other.valueFrom, other.valueTo, other.inService) return NotImplemented def __str__(self): return self.name def __hash__(self): return hash((self.valueFrom, self.valueTo,self.inService)) </code></pre>
4
2016-10-07T17:58:41Z
[ "python", "list", "object", "set", "difference" ]
Pygame: Adding a background
39,923,023
<p>I'm making a project for my senior year. Its a game where i can move a user. I would like to add a background that goes behind all the pictures i've blitted. I've searched everywhere but i can't seem to find the solution. Could anybody help?</p> <pre><code>import pygame import os class Player(object): def __init__(self): self.image = pygame.image.load("player1.png") self.image2 = pygame.transform.flip(self.image, True, False) self.coffee=pygame.image.load("coffee.png") self.computer=pygame.image.load("computer.png") self.flipped = False self.x = 0 self.y = 0 def handle_keys(self): """ Movement keys """ key = pygame.key.get_pressed() dist = 5 if key[pygame.K_DOWN]: self.y += dist elif key[pygame.K_UP]: self.y -= dist if key[pygame.K_RIGHT]: self.x += dist self.flipped = False elif key[pygame.K_LEFT]: self.x -= dist self.flipped = True def draw(self, surface): if self.flipped: image = self.image2 else: image = self.image surface.blit(image, (self.x, self.y)) surface.blit(self.coffee, (700,500)) surface.blit(self.computer,(0,500)) pygame.init() screen = pygame.display.set_mode((810, 610)) #creates the screen player = Player() clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() # quit the screen running = False player.handle_keys() # movement keys screen.fill((255,255,255)) # fill the screen with white player.draw(screen) # draw the player to the screen pygame.display.update() # update the screen clock.tick(60) # Limits Frames Per Second to 60 or less </code></pre>
0
2016-10-07T17:38:33Z
39,923,273
<p>A background image is no different from any other image. Just .blit it first.</p>
1
2016-10-07T17:55:50Z
[ "python", "python-2.7" ]
How to sum up each element in array list?
39,923,028
<p>Having a bit of writing out the code. </p> <p>For example, if I have an array of: </p> <pre><code>a = ([0, 0, 1, 2], [0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 3], [0, 1, 1, 3]) </code></pre> <p>if I want to add first element of each item, </p> <p>as in to return a list of 0 + 0 + 0 + 1 + 0, 0 + 1 + 0, 0 + 0 ... </p> <p>I wrote the code: </p> <pre><code>def test(lst): sum = 0 test_lst = [] i = 0 while i in range(0, 4): for j in range(0, len(lst)): sum += lst[j][i] test_lst.append(sum) i += 1 return test_lst </code></pre> <p>I get index size error. How can I go about this?</p>
-2
2016-10-07T17:39:12Z
39,923,137
<pre><code>sum(zip(*a)[0]) </code></pre> <p><code>zip</code> is a function that takes any number of n-length sequences and returns n tuples (among other things). The first of these tuples has the elements that came first in the tuples passed to <code>zip</code>. <code>sum</code> adds them together.</p> <p>EDIT:</p> <p>In Python 3, the above doesn't work. Use:</p> <pre><code>sum(next(zip(*a))) </code></pre> <p>instead. For all such sums,</p> <pre><code>map(sum, zip(*a)) </code></pre>
6
2016-10-07T17:46:48Z
[ "python", "arrays", "list" ]
How to sum up each element in array list?
39,923,028
<p>Having a bit of writing out the code. </p> <p>For example, if I have an array of: </p> <pre><code>a = ([0, 0, 1, 2], [0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 3], [0, 1, 1, 3]) </code></pre> <p>if I want to add first element of each item, </p> <p>as in to return a list of 0 + 0 + 0 + 1 + 0, 0 + 1 + 0, 0 + 0 ... </p> <p>I wrote the code: </p> <pre><code>def test(lst): sum = 0 test_lst = [] i = 0 while i in range(0, 4): for j in range(0, len(lst)): sum += lst[j][i] test_lst.append(sum) i += 1 return test_lst </code></pre> <p>I get index size error. How can I go about this?</p>
-2
2016-10-07T17:39:12Z
39,923,149
<pre><code>a = ([0, 0, 1, 2], [0, 1, 1, 0], [0, 0, 1, 0], [1, 0, 1, 3], [0, 1, 1, 3]) </code></pre> <p>Try using list comprehensions:</p> <pre><code>sum([item[0] for item in a]) </code></pre> <p>The line above takes the first element of each list in the tuple, then puts it into a temporary list. We then call sum on that temporary list, which yields the answer. </p>
0
2016-10-07T17:47:28Z
[ "python", "arrays", "list" ]
Speed up numpy summation between big arrays
39,923,085
<p>I have a code running operations on <code>numpy</code> arrays. While linear algebra operations seem fast, I now am finding a bottleneck in a different issue: the summation of two distinct arrays. In the example below <code>WE3</code> and <code>T1</code> are two <code>1000X1000X1000</code> arrays. First I calculate <code>WE3</code> using a numpy operation, then I sum those arrays.</p> <pre><code>import numpy as np import scipy as sp import time N = 100 n = 1000 X = np.random.uniform(size = (N,n)) wE = np.mean(X,0) wE3 = np.einsum('i,j,k-&gt;ijk', wE, wE, wE) #22 secs T1 = np.random.uniform(size = (n,n,n)) a = wE3 + T1 #115 secs </code></pre> <p>The calculation of <code>wE3</code> takes like 22 seconds, while the addition between <code>WE3</code> and <code>T1</code> takes 115 seconds.</p> <p>Is there any known reason why the summation of those arrays is such slower than the calculation of WE3? They should have more or less the same complexity..</p> <p>Is there a way to speed up that code? </p>
0
2016-10-07T17:42:54Z
39,923,433
<p>That <code>np.einsum('i,j,k-&gt;ijk', wE, wE, wE)</code> part isn't doing any sum-reduction and is essentially just broadcasted elementwise multiplication. So, we can replace that with something like this -</p> <pre><code>wE[:,None,None] * wE[:,None] * wE </code></pre> <p>Runtime test -</p> <pre><code>In [9]: # Setup inputs at 1/5th of original dataset sizes ...: N = 20 ...: n = 200 ...: X = np.random.uniform(size = (N,n)) ...: wE = np.mean(X,0) ...: In [10]: %timeit np.einsum('i,j,k-&gt;ijk', wE, wE, wE) 10 loops, best of 3: 45.7 ms per loop In [11]: %timeit wE[:,None,None] * wE[:,None] * wE 10 loops, best of 3: 26.1 ms per loop </code></pre> <hr> <p>Next up, we have <code>wE3 + T1</code>, where <code>T1 = np.random.uniform(size = (n,n,n))</code> doesn't look like could be helped in a big way as we have to create <code>T1</code> anyway and then it's just element-wise addition. It seems we can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.add.html" rel="nofollow"><code>np.add</code></a> that lets us write back the results to one of the arrays : <code>wE3</code> or <code>T1</code>. Let's say we choose <code>T1</code>, if that's okay to be modified. I guess this would bring slight memory efficiency as we won't be adding another variable into workspace.</p> <p>Thus, we could do -</p> <pre><code>np.add(wE3,T1,out=T1) </code></pre> <p>Runtime test -</p> <pre><code>In [58]: def func1(wE3): ...: T1 = np.random.uniform(size = (n,n,n)) ...: return wE3 + T1 ...: ...: def func2(wE3): ...: T1 = np.random.uniform(size = (n,n,n)) ...: np.add(wE3,T1,out=T1) ...: return T1 ...: In [59]: # Setup inputs at 1/4th of original dataset sizes ...: N = 25 ...: n = 250 ...: X = np.random.uniform(size = (N,n)) ...: wE = np.mean(X,0) ...: wE3 = np.einsum('i,j,k-&gt;ijk', wE, wE, wE) ...: In [60]: %timeit func1(wE3) 1 loops, best of 3: 390 ms per loop In [61]: %timeit func2(wE3) 1 loops, best of 3: 363 ms per loop </code></pre> <p>Using <a href="http://stackoverflow.com/questions/39923085/speed-up-numpy-summation-between-big-arrays#comment67131799_39923433"><code>@Aaron's suggestion</code></a>, we can use a loop and assuming that writing back the results into <code>wE3</code> is okay, we could do -</p> <pre><code>wE3 = wE[:,None,None] * wE[:,None] * wE for x in wE3: np.add(x, np.random.uniform(size = (n,n)), out=x) </code></pre> <p><strong>Final results</strong></p> <p>Thus, putting back all the suggested improvements, finally the runtime test results were -</p> <pre><code>In [97]: def func1(wE): ...: wE3 = np.einsum('i,j,k-&gt;ijk', wE, wE, wE) ...: T1 = np.random.uniform(size = (n,n,n)) ...: return wE3 + T1 ...: ...: def func2(wE): ...: wE3 = wE[:,None,None] * wE[:,None] * wE ...: for x in wE3: ...: np.add(x, np.random.uniform(size = (n,n)), out=x) ...: return wE3 ...: In [98]: # Setup inputs at 1/3rd of original dataset sizes ...: N = 33 ...: n = 330 ...: X = np.random.uniform(size = (N,n)) ...: wE = np.mean(X,0) ...: In [99]: %timeit func1(wE) 1 loops, best of 3: 1.09 s per loop In [100]: %timeit func2(wE) 1 loops, best of 3: 879 ms per loop </code></pre>
1
2016-10-07T18:08:45Z
[ "python", "arrays", "numpy" ]
Speed up numpy summation between big arrays
39,923,085
<p>I have a code running operations on <code>numpy</code> arrays. While linear algebra operations seem fast, I now am finding a bottleneck in a different issue: the summation of two distinct arrays. In the example below <code>WE3</code> and <code>T1</code> are two <code>1000X1000X1000</code> arrays. First I calculate <code>WE3</code> using a numpy operation, then I sum those arrays.</p> <pre><code>import numpy as np import scipy as sp import time N = 100 n = 1000 X = np.random.uniform(size = (N,n)) wE = np.mean(X,0) wE3 = np.einsum('i,j,k-&gt;ijk', wE, wE, wE) #22 secs T1 = np.random.uniform(size = (n,n,n)) a = wE3 + T1 #115 secs </code></pre> <p>The calculation of <code>wE3</code> takes like 22 seconds, while the addition between <code>WE3</code> and <code>T1</code> takes 115 seconds.</p> <p>Is there any known reason why the summation of those arrays is such slower than the calculation of WE3? They should have more or less the same complexity..</p> <p>Is there a way to speed up that code? </p>
0
2016-10-07T17:42:54Z
39,923,660
<blockquote> <p>Is there any known reason why the summation of those arrays is such slower than the calculation of WE3?</p> </blockquote> <p>The arrays <code>wE3</code>, <code>T1</code> and <code>a</code> each require 8 gigabytes of memory. You are probably running out of physical memory, and <a href="http://serverfault.com/questions/48486/what-is-swap-memory">swap memory</a> access is killing your performance.</p> <blockquote> <p>Is there a way to speed up that code? </p> </blockquote> <p>Get more physical memory (i.e. RAM).</p> <p>If that is not possible, take a look at what you are going to do with these arrays, and see if you can work in batches such that the total memory required when processing a batch remains within the limits of your physical memory.</p>
1
2016-10-07T18:24:19Z
[ "python", "arrays", "numpy" ]
Speed up numpy summation between big arrays
39,923,085
<p>I have a code running operations on <code>numpy</code> arrays. While linear algebra operations seem fast, I now am finding a bottleneck in a different issue: the summation of two distinct arrays. In the example below <code>WE3</code> and <code>T1</code> are two <code>1000X1000X1000</code> arrays. First I calculate <code>WE3</code> using a numpy operation, then I sum those arrays.</p> <pre><code>import numpy as np import scipy as sp import time N = 100 n = 1000 X = np.random.uniform(size = (N,n)) wE = np.mean(X,0) wE3 = np.einsum('i,j,k-&gt;ijk', wE, wE, wE) #22 secs T1 = np.random.uniform(size = (n,n,n)) a = wE3 + T1 #115 secs </code></pre> <p>The calculation of <code>wE3</code> takes like 22 seconds, while the addition between <code>WE3</code> and <code>T1</code> takes 115 seconds.</p> <p>Is there any known reason why the summation of those arrays is such slower than the calculation of WE3? They should have more or less the same complexity..</p> <p>Is there a way to speed up that code? </p>
0
2016-10-07T17:42:54Z
39,927,739
<p>You should really use Numba's Jit (just in time compiler) for this. It is a purely numpy pipeline, which is perfect for Numba.</p> <p>All you have to do is throw that above code into a function, and put an @jit decorater on top. It gets speedups close to Cython. </p> <p>However, as others have pointed out, it appears you're trying to work with data too large for your local machine, and numba would not solve your problems</p>
0
2016-10-08T01:19:10Z
[ "python", "arrays", "numpy" ]
Python3, nested dict comparison (recursive?)
39,923,152
<p>I'm writing a program to take a .csv file and create 'metrics' for ticket closure data. Each ticket has one or more time entries; the goal is to grab the 'delta' (ie - time difference) for <code>open</code> -> <code>close</code> and <code>time_start</code> -> <code>time_end</code> on a PER TICKET basis; these are not real variables, they're just for the purpose of this question.</p> <p>So, say we have ticket 12345 that has 3 time entries like so:</p> <p><code>ticket: 12345 open: 2016-09-26 00:00:00.000 close: 2016-09-27 00:01:00.000 time_start: 2016-09-26 00:01:00.000 time_end: 2016-09-26 00:02:00.000 ticket: 12345 open: 2016-09-26 00:00:00.000 close: 2016-09-27 00:01:00.000 time_start: 2016-09-26 00:01:00.000 time_end: 2016-09-26 00:02:00.000 ticket: 12345 open: 2016-09-26 00:00:00.000 close: 2016-09-27 00:01:00.000 time_start: 2016-09-26 00:01:00.000 time_end: 2016-09-27 00:02:00.000</code></p> <p>I'd like to have the program display ONE entry for this, adding up the 'deltas', like so:</p> <p><code>ticket: 12345 Delta open/close ($total time from open to close): Delta start/end: ($total time of ALL ticket time entries added up)</code></p> <p>Here's what I have so far; </p> <p>.csv example: </p> <pre><code>Ticket #,Ticket Type,Opened,Closed,Time Entry Day,Start,End 737385,Software,2016-09-06 12:48:31.680,2016-09-06 15:41:52.933,2016-09-06 00:00:00.000,1900-01-01 15:02:00.417,1900-01-01 15:41:00.417 737318,Hardware,2016-09-06 12:20:28.403,2016-09-06 14:35:58.223,2016-09-06 00:00:00.000,1900-01-01 14:04:00.883,1900-01-01 14:35:00.883 737296,Printing/Scan/Fax,2016-09-06 11:37:10.387,2016-09-06 13:33:07.577,2016-09-06 00:00:00.000,1900-01-01 13:29:00.240,1900-01-01 13:33:00.240 737273,Software,2016-09-06 10:54:40.177,2016-09-06 13:28:24.140,2016-09-06 00:00:00.000,1900-01-01 13:17:00.860,1900-01-01 13:28:00.860 737261,Software,2016-09-06 10:33:09.070,2016-09-06 13:19:41.573,2016-09-06 00:00:00.000,1900-01-01 13:05:00.113,1900-01-01 13:15:00.113 737238,Software,2016-09-06 09:52:57.090,2016-09-06 14:42:16.287,2016-09-06 00:00:00.000,1900-01-01 12:01:00.350,1900-01-01 12:04:00.350 737238,Software,2016-09-06 09:52:57.090,2016-09-06 14:42:16.287,2016-09-06 00:00:00.000,1900-01-01 14:36:00.913,1900-01-01 14:42:00.913 737220,Password,2016-09-06 09:28:16.060,2016-09-06 11:41:16.750,2016-09-06 00:00:00.000,1900-01-01 11:30:00.303,1900-01-01 11:36:00.303 737197,Hardware,2016-09-06 08:50:23.197,2016-09-06 14:02:18.817,2016-09-06 00:00:00.000,1900-01-01 13:48:00.530,1900-01-01 14:02:00.530 736964,Internal,2016-09-06 01:02:27.453,2016-09-06 05:46:00.160,2016-09-06 00:00:00.000,1900-01-01 06:38:00.917,1900-01-01 06:45:00.917 </code></pre> <p>class Time_Entry.py:</p> <pre><code>#! /usr/bin/python from datetime import * class Time_Entry: def __init__(self, ticket_no, time_entry_day, opened, closed, start, end): self.ticket_no = ticket_no self.time_entry_day = time_entry_day self.opened = opened self.closed = closed self.start = datetime.strptime(start, '%Y-%m-%d %H:%M:%S.%f') self.end = datetime.strptime(end, '%Y-%m-%d %H:%M:%S.%f') self.total_open_close_delta = 0 self.total_start_end_delta = 0 def open_close_delta(self, topen, tclose): open_time = datetime.strptime(topen, '%Y-%m-%d %H:%M:%S.%f') if tclose != '\\N': close_time = datetime.strptime(tclose, '%Y-%m-%d %H:%M:%S.%f') self.total_open_close_delta = close_time - open_time def start_end_delta(self, tstart, tend): start_time = datetime.strptime(tstart, '%Y-%m-%d %H:%M:%S.%f') end_time = datetime.strptime(tend, '%Y-%m-%d %H:%M:%S.%f') start_end_delta = (end_time - start_time).seconds self.total_start_end_delta += start_end_delta return (self.total_start_end_delta) def add_start_end_delta(self, delta): self.total_start_end_delta += delta def display(self): print('Ticket #: %7.7s Start: %-15s End: %-15s Delta: %-10s' % (self.ticket_no, self.start.time(), self.end.time(), self.total_start_end_delta)) </code></pre> <p>Which is called by metrics.py:</p> <pre><code>#! /usr/bin/python import csv import pprint from Time_Entry import * file = '/home/jmd9qs/userdrive/metrics.csv' # setup CSV, load up a list of dicts reader = csv.DictReader(open(file)) dict_list = [] for line in reader: dict_list.append(line) def load_tickets(ticket_list): for i, key in enumerate(ticket_list): ticket_no = key['Ticket #'] time_entry_day = key['Time Entry Day'] opened = key['Opened'] closed = key['Closed'] start = key['Start'] end = key['End'] time_entry = Time_Entry(ticket_no, time_entry_day, opened, closed, start, end) time_entry.open_close_delta(opened, closed) time_entry.start_end_delta(start, end) for h, key2 in enumerate(ticket_list): ticket_no2 = key2['Ticket #'] time_entry_day2 = key2['Time Entry Day'] opened2 = key2['Opened'] closed2 = key2['Closed'] start2 = key2['Start'] end2 = key2['End'] time_entry2 = Time_Entry(ticket_no2, time_entry_day2, opened2, closed2, start2, end2) if time_entry.ticket_no == time_entry2.ticket_no and i != h: # add delta and remove second time_entry from dict (no counting twice) time_entry2_delta = time_entry2.start_end_delta(start2, end2) time_entry.add_start_end_delta(time_entry2_delta) del dict_list[h] time_entry.display() load_tickets(dict_list) </code></pre> <p>This seems to work OK so far; however, I get multiple lines of output per ticket instead of one with the 'deltas' added. FYI the way the program displays output is different from my example, which is intentional. See example below:</p> <pre><code>Ticket #: 738388 Start: 15:24:00.313000 End: 15:35:00.313000 Delta: 2400 Ticket #: 738388 Start: 16:30:00.593000 End: 16:40:00.593000 Delta: 1260 Ticket #: 738381 Start: 15:40:00.763000 End: 16:04:00.767000 Delta: 1440 Ticket #: 738357 Start: 13:50:00.717000 End: 14:10:00.717000 Delta: 1200 Ticket #: 738231 Start: 11:16:00.677000 End: 11:21:00.677000 Delta: 720 Ticket #: 738203 Start: 16:15:00.710000 End: 16:31:00.710000 Delta: 2160 Ticket #: 738203 Start: 09:57:00.060000 End: 10:02:00.060000 Delta: 1560 Ticket #: 738203 Start: 12:26:00.597000 End: 12:31:00.597000 Delta: 900 Ticket #: 738135 Start: 13:25:00.880000 End: 13:50:00.880000 Delta: 2040 Ticket #: 738124 Start: 07:56:00.117000 End: 08:31:00.117000 Delta: 2100 Ticket #: 738121 Start: 07:47:00.903000 End: 07:52:00.903000 Delta: 300 Ticket #: 738115 Start: 07:15:00.443000 End: 07:20:00.443000 Delta: 300 Ticket #: 737926 Start: 06:40:00.813000 End: 06:47:00.813000 Delta: 420 Ticket #: 737684 Start: 18:50:00.060000 End: 20:10:00.060000 Delta: 13380 Ticket #: 737684 Start: 13:00:00.560000 End: 13:08:00.560000 Delta: 8880 Ticket #: 737684 Start: 08:45:00 End: 10:00:00 Delta: 9480 </code></pre> <p>Note that there are a few tickets with more than one entry, which is what I don't want.</p> <p>Any notes on style, convention, etc. are also welcome as I'm trying to be more 'Pythonic'</p>
0
2016-10-07T17:47:33Z
39,925,585
<p>The problem here is that with a nested loop like the one you implemented you double-examine the same ticket. Let me explain it better:</p> <pre><code>ticket_list = [111111, 111111, 666666, 777777] # lets simplify considering the ids only # I'm trying to keep the same variable names for i, key1 in enumerate(ticket_list): # outer loop cnt = 1 for h, key2 in enumerate(ticket_list): # inner loop if key1 == key2 and i != h: print('&gt;&gt; match on i:', i, '- h:', h) cnt += 1 print('Found', key1, cnt, 'times') </code></pre> <p>See how it double counts the <code>111111</code></p> <pre><code>&gt;&gt; match on i: 0 - h: 1 Found 111111 2 times &gt;&gt; match on i: 1 - h: 0 Found 111111 2 times Found 666666 1 times Found 777777 1 times </code></pre> <p>That's because you will match the <code>111111</code> both when the inner loop examines the first position and the outer the second (<code>i: 0, h: 1</code>), and again when the outer is on the second position and the inner is on the first (<code>i: 1, h: 0</code>).</p> <hr> <h2>A proposed solution</h2> <p>A better solution for your problem is to group the entries of the same ticket together and then sum your deltas. <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>groupby</code></a> is ideal for your task. Here I took the liberty to rewrite some code:</p> <p>Here I modified the constructor in order to accept the dictionary itself. It makes passing the parameters later less messy. I also removed the methods to add the deltas, later we'll see why. </p> <pre><code>import csv import itertools from datetime import * class Time_Entry(object): def __init__(self, entry): self.ticket_no = entry['Ticket #'] self.time_entry_day = entry['Time Entry Day'] self.opened = datetime.strptime(entry['Opened'], '%Y-%m-%d %H:%M:%S.%f') self.closed = datetime.strptime(entry['Closed'], '%Y-%m-%d %H:%M:%S.%f') self.start = datetime.strptime(entry['Start'], '%Y-%m-%d %H:%M:%S.%f') self.end = datetime.strptime(entry['End'], '%Y-%m-%d %H:%M:%S.%f') self.total_open_close_delta = (self.closed - self.opened).seconds self.total_start_end_delta = (self.end - self.start).seconds def display(self): print('Ticket #: %7.7s Start: %-15s End: %-15s Delta: %-10s' % (self.ticket_no, self.start.time(), self.end.time(), self.total_start_end_delta)) </code></pre> <p>Here we load the data using <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a>, the final output will be a the list of <code>Time_Entry</code> objects:</p> <pre><code>with open('metrics.csv') as ticket_list: time_entry_list = [Time_Entry(line) for line in csv.DictReader(ticket_list)] print(time_entry_list) # [&lt;Time_Entry object at 0x101142f60&gt;, &lt;Time_Entry object at 0x10114d048&gt;, &lt;Time_Entry object at 0x1011fddd8&gt;, ... ] </code></pre> <p>In the nested-loop version instead you kept rebuilding the <code>Time_Entry</code> inside the inner loop, which means for 100 entries you end up initializing 10000 temporary variables! Creating a list "outside" instead allows us to initialize each <code>Time_Entry</code> only once.</p> <p>Here comes the magic: we can use the <code>groupby</code> in order to collect all the objects with the same <code>ticket_no</code> in the same list:</p> <pre><code>sorted(time_entry_list, key=lambda x: x.ticket_no) ticket_grps = itertools.groupby(time_entry_list, key=lambda x: x.ticket_no) tickets = [(id, [t for t in tickets]) for id, tickets in ticket_grps] </code></pre> <p>The final result in <code>ticket</code> is a list tuples with the ticket id in the first position, and the list of associated <code>Time_Entry</code> in the last:</p> <pre><code>print(tickets) # [('737385', [&lt;Time_Entry object at 0x101142f60&gt;]), # ('737318', [&lt;Time_Entry object at 0x10114d048&gt;]), # ('737238', [&lt;Time_Entry object at 0x1011fdd68&gt;, &lt;Time_Entry object at 0x1011fde80&gt;]), # ...] </code></pre> <p>So finally we can iterate over all the tickets, and using again a list comprehension we can build a list containing only the deltas so we can sum them together. You can see why we removed the old method to update the deltas, since now we simply store their value for the single entry and then sum them externally.</p> <p>Here is your result:</p> <pre><code>for ticket in tickets: print('ticket:', ticket[0]) # extract list of deltas and then sum print('Delta open / close:', sum([entry.total_open_close_delta for entry in ticket[1]])) print('Delta start / end:', sum([entry.total_start_end_delta for entry in ticket[1]])) print('(found {} occurrences)'.format(len(ticket[1]))) print() </code></pre> <p>Output:</p> <pre><code>ticket: 736964 Delta open / close: 17012 Delta start / end: 420 (found 1 occurrences) ticket: 737197 Delta open / close: 18715 Delta start / end: 840 (found 1 occurrences) ticket: 737220 Delta open / close: 7980 Delta start / end: 360 (found 1 occurrences) ticket: 737238 Delta open / close: 34718 Delta start / end: 540 (found 2 occurrences) ticket: 737261 Delta open / close: 9992 Delta start / end: 600 (found 1 occurrences) ticket: 737273 Delta open / close: 9223 Delta start / end: 660 (found 1 occurrences) ticket: 737296 Delta open / close: 6957 Delta start / end: 240 (found 1 occurrences) ticket: 737318 Delta open / close: 8129 Delta start / end: 1860 (found 1 occurrences) ticket: 737385 Delta open / close: 10401 Delta start / end: 2340 (found 1 occurrences) </code></pre> <p>At the end of the story: list comprehensions can be super-useful, they allows you to do a lot of stuff with a super-compact syntax. Also the python standard library contains a lot of ready-to-use tools that can really come to your aid, so get familiar!</p>
2
2016-10-07T20:48:44Z
[ "python", "list", "csv", "dictionary", "recursion" ]