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
RTSP: cannot get session identifier
39,192,256
<p>I am trying to control an ip cam using a python script (I can see the stream with VLC or mplayer).</p> <p>After received OPTIONS and DESCRIBE informations, every SETUP I try give me an error:</p> <pre><code>SETUP rtsp://192.168.0.41:554/xxxxxx RTSP/1.0 CSeq: 3 Transport: RTP/AVP/UDP;unicast;client_port=3056-3057 RTSP/1.0 400 Bad Request Allow: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER, SET_PARAMETER,USER_CMD_SET </code></pre> <p>so I never receive the session identification.</p> <p>Maybe the problem is in the Transport line, but I think it's because I do not know what to put in place of the xxxxxxx (I tried and googled a lot but with non results)</p> <p>Here are the output of OPTIONS and DESCRIBE:</p> <pre><code> OPTIONS rtsp://192.168.0.41:554 RTSP/1.0 CSeq: 1 RTSP/1.0 200 OK CSeq: 1 Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE, GET_PARAMETER, SET_PARAMETER,USER_CMD_SET --------------------------------- DESCRIBE rtsp://192.168.0.41:554/onvif2 RTSP/1.0 CSeq: 2 RTSP/1.0 200 OK CSeq: 2 Content-Type: application/sdp Content-Length: 360 v=0 o=- 1421069297525233 1 IN IP4 192.168.0.41 s=H.264 Video, RtspServer_0.0.0.2 t=0 0 a=tool:RtspServer_0.0.0.2 a=type:broadcast a=control:* a=range:npt=0- m=video 0 RTP/AVP 96 c=IN IP4 0.0.0.0 b=AS:500 a=rtpmap:96 H264/90000 a=fmtp:96 packetization-mode=1;profile-level-id=42001F;sprop-parameter-sets=Z0IAH5WoFAFuQA==,aM48gA== a=control:track1 </code></pre> <p>What that * stands for?</p> <p>And what is "track1"? </p> <p>(note: if I check for onvif1, that is the other streaming sent by the cam, the result is the same, but with track2, that means that the server answer should be appropriate)</p>
0
2016-08-28T14:22:03Z
39,230,867
<p>Finally I discovered the problem: missing <strong>\r\n</strong> in the last python code line!</p> <p>wrong:</p> <pre><code>Transport: RTP/AVP/UDP;unicast;client_port=52318-52319 </code></pre> <p>correct:</p> <pre><code>Transport: RTP/AVP/UDP;unicast;client_port=52318-52319\r\n </code></pre> <p>Now it works.</p>
0
2016-08-30T14:55:59Z
[ "python", "streaming", "rtsp", "onvif" ]
Django Multi-site with shared database
39,192,404
<p>I am about to develop multiple sites for different real estate companies. All share the same html, sections, etc. The difference is in the content, specially the properties... But some of those properties can be shared among the rest of the companies.</p> <p>I am thinking in sharing the same database and differentiate content using the url. In this way I can use only one project instead of one for each company.</p> <p>Does anyone have recommendations for this kind of projects?</p> <p>Thanks,</p>
0
2016-08-28T14:38:37Z
39,196,364
<p>I have done that.<br> Was it a good idea? Yes, in my case it was. I had to reuse the same content and when we changed the content, it had to be changed on all pages. On a simple site, a triple deploy and changing the content in three different projects is kind of overkill. But whereas it works fine in a simple front-end page (that hardly even requires Django), I do not recommend it for "real" web apps. </p> <p>What will break? Think about the things that your pages will share and see if it's a problem. </p> <p>1) I'm guessing that if you'll want to have user login capability on the page (besides the admin login), then that's a problem, if I can use the same user for different companies that have no apparent connection whatsoever. You could be in for a lot of trouble if the companies find out that user private details aren't as private as they thought. And the same goes for the users who really don't have a clue how they ended up with a user account on a page they've never visited. </p> <p>2) URLs. You can't have different ones for each company without some extra hacking. If one of the companies wants to have <code>/about/</code> and the other one <code>/company/</code> page, you're gonna start hacking a bad solution that will blow up in your face when the companies ask for the next page.</p> <p>3) Anything else you might want to have on your page that is connected to hardcoded data or database values. I.e. social authentication etc.</p> <p>What can you do about it? </p> <p>If I was hellbound on solving the first one, here's what I would do:<br> - Override the user model and add info about the registering page<br> - Create custom managers for user model for each page<br> - Write a middleware that only lets you use the page-specific manager for the current request<br> All in all, I wouldn't do it in a million years. Way too hacky, way too vulnerable. Just create separate databases. </p> <p>For solving the second one, you can create a multi-host middleware that checks from which domain the request comes from and returns the correct URL config. Sth similar to <a href="https://djangosnippets.org/snippets/1509/" rel="nofollow">this</a> . It's not really hard to rewrite and modify to your needs.</p> <p>It's impossible to decide for you, but I've given you something to think about before going one way or the other. Good luck!</p>
0
2016-08-28T22:27:53Z
[ "python", "django" ]
Which is faster a dictionary retrieve or a list indexing?
39,192,442
<p>I'm trying to decide which data structure best fits my needs.</p> <p>Technical details apart, I may translate the needs of my program to use dictionaries or to use lists, and since performance will be an issue I was wondering what may be a faster solution. I ended up concluding that retrieving/indexing will be the critical operation.</p> <p>So what's more efficient in terms of memory usage and speed?</p>
0
2016-08-28T14:44:45Z
39,192,475
<p>Well, retrieving from a dict has the same complexity as retrieving from a list:</p> <pre><code>_dict[1] _list[1] </code></pre> <p>but..., with dicts, u can use:</p> <pre><code>_dict.get(1, 'something else') </code></pre> <p>It just returns 'something else' if there is no key <code>1</code>. Using lists, you cannot do that. You just want to get item indexed by number <code>1</code>. If you will ask for item outside your list, so index will be higher than your list length, then your program will raise <code>IndexError</code> which must be handled. Next problem will be that you will have to know size of that list, so you need to check it first.</p>
0
2016-08-28T14:48:13Z
[ "python", "list", "dictionary", "profiling" ]
Which is faster a dictionary retrieve or a list indexing?
39,192,442
<p>I'm trying to decide which data structure best fits my needs.</p> <p>Technical details apart, I may translate the needs of my program to use dictionaries or to use lists, and since performance will be an issue I was wondering what may be a faster solution. I ended up concluding that retrieving/indexing will be the critical operation.</p> <p>So what's more efficient in terms of memory usage and speed?</p>
0
2016-08-28T14:44:45Z
39,192,562
<p><a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">https://wiki.python.org/moin/TimeComplexity</a> provides all the info you're looking for</p>
0
2016-08-28T14:57:37Z
[ "python", "list", "dictionary", "profiling" ]
Which is faster a dictionary retrieve or a list indexing?
39,192,442
<p>I'm trying to decide which data structure best fits my needs.</p> <p>Technical details apart, I may translate the needs of my program to use dictionaries or to use lists, and since performance will be an issue I was wondering what may be a faster solution. I ended up concluding that retrieving/indexing will be the critical operation.</p> <p>So what's more efficient in terms of memory usage and speed?</p>
0
2016-08-28T14:44:45Z
39,192,976
<p>If you don't need to search, use a list. It's faster, and uses less RAM than a dict. For small collections (&lt;100 items) the speed differences are minimal, but for large collections the dict will be around 20% slower. And it will certainly use more RAM.</p> <p>Here's some <code>timeit</code> code that compares the access speed of list vs dict. It also shows the RAM consumed by the collection objects themselves (but not that of the data objects they hold).</p> <pre><code>#!/usr/bin/env python3 ''' Compare list vs dict access speed See http://stackoverflow.com/q/39192442/4014959 Written by PM 2Ring 2016.08.29 ''' from sys import getsizeof from timeit import Timer commands = {'dict' : 'for i in r:d[i]', 'list' : 'for i in r:a[i]'} def time_test(loops, reps): timings = [] setup = 'from __main__ import r, a, d' for name, cmd in commands.items(): result = Timer(cmd, setup).repeat(reps, loops) result.sort() timings.append((result, name)) timings.sort() for result, name in timings: print(name, result) #Find the ratio of slowest / fastest tlo, thi = [timings[i][0][0] for i in (0, -1)] print('ratio: {0:f}\n'.format(thi / tlo)) num = 2000 r = range(num) a = list(r) d = {i:i for i in r} fmt = 'Sizes: num={}, list={}, dict={}' print(fmt.format(num, getsizeof(a), getsizeof(d))) loops, reps = 2000, 3 time_test(loops, reps) </code></pre> <p><strong>output</strong></p> <pre><code>Sizes: num=2000, list=9056, dict=49200 list [1.2624831110006198, 1.3356713940011105, 1.406396518003021] dict [1.506095960001403, 1.525646976999269, 1.5623748449979757] ratio: 1.192963 </code></pre> <p>The speed difference is actually higher than it appears in those results, since the time taken to retrieve the integers from the <code>r</code> range object is roughly the same as the time taken to do the list &amp; dict accesses. You can measure that by adding an entry like this to the <code>commands</code> dictionary:</p> <pre><code>'none': 'for i in r:i' </code></pre>
1
2016-08-28T15:42:50Z
[ "python", "list", "dictionary", "profiling" ]
I have a nested list, but i want to add a nested list inside the nested list
39,192,477
<p>I have a list like:</p> <pre><code>[[21, 32, 32], [23, 34, 32], [32, 34, 57]] </code></pre> <p>I would like to convert each number to its own list like</p> <pre><code>[[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]] </code></pre> <p>How would i do that?</p> <p>Thanks!</p>
2
2016-08-28T14:48:24Z
39,192,518
<p>Use a <em>list comprehension</em>:</p> <pre><code>&gt;&gt;&gt; lst = [[21, 32, 32], [23, 34, 32], [32, 34, 57]] &gt;&gt;&gt; new_lst = [[[i] for i in sub_lst] for sub_lst in lst] &gt;&gt;&gt; new_lst [[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]] </code></pre> <hr> <p>You can also use <code>numpy</code> by simply adding an extra axis using <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow"><code>np.newaxis</code></a> while <em>slicing</em> your array:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; l = np.array([[21, 32, 32], [23, 34, 32], [32, 34, 57]]) &gt;&gt;&gt; l[:, :, np.newaxis] # or l[:, :, None] array([[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]]) </code></pre>
1
2016-08-28T14:52:43Z
[ "python", "python-3.x" ]
I have a nested list, but i want to add a nested list inside the nested list
39,192,477
<p>I have a list like:</p> <pre><code>[[21, 32, 32], [23, 34, 32], [32, 34, 57]] </code></pre> <p>I would like to convert each number to its own list like</p> <pre><code>[[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]] </code></pre> <p>How would i do that?</p> <p>Thanks!</p>
2
2016-08-28T14:48:24Z
39,192,545
<p>Here is a method using <code>numpy.reshape()</code>:</p> <pre><code>import numpy as np arr = np.array([[21, 32, 32], [23, 34, 32], [32, 34, 57]]) arr.reshape(3,3,1) # array([[[21], # [32], # [32]], # [[23], # [34], # [32]], # [[32], # [34], # [57]]]) </code></pre>
1
2016-08-28T14:55:39Z
[ "python", "python-3.x" ]
I have a nested list, but i want to add a nested list inside the nested list
39,192,477
<p>I have a list like:</p> <pre><code>[[21, 32, 32], [23, 34, 32], [32, 34, 57]] </code></pre> <p>I would like to convert each number to its own list like</p> <pre><code>[[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]] </code></pre> <p>How would i do that?</p> <p>Thanks!</p>
2
2016-08-28T14:48:24Z
39,195,015
<p>Method using list comprehension:</p> <pre><code>a = [[21, 32, 32], [23, 34, 32], [32, 34, 57]] print [[[element] for element in each] for each in a] </code></pre> <p>Output:</p> <pre><code>[[[21], [32], [32]], [[23], [34], [32]], [[32], [34], [57]]] </code></pre>
0
2016-08-28T19:30:43Z
[ "python", "python-3.x" ]
pytest-bdd reuse same method for different steps
39,192,481
<p>I want to use same method for @given, @when and @then of same step. e.g. </p> <pre><code>Scenario: Launch an application Given username and password entered And login button pressed Then the app launches Scenario: Launch application again Given user logged out And username and password entered When login button pressed Then the app launches </code></pre> <p>If I do this in the implementation of step:</p> <pre><code>@when('login button pressed') @given('login button pressed') def loginButtonPressed(): print 'button pressed' </code></pre> <p>It seems, pytest_bdd cannot handle this. I get the error: </p> <blockquote> <p>fixture 'login button pressed' not found Is there a way I can maybe alias the steps?</p> </blockquote>
2
2016-08-28T14:48:40Z
39,582,866
<p>In pytest-BDD it does not currently support the ability to use two different step types/definitions on one function definition. How ever there are "work arounds"</p> <p><strong>Option 1: Turn off Gherkin strict mode</strong> </p> <pre><code>@pytest.fixture def pytestbdd_strict_gherkin(): return False </code></pre> <p>This will allow you to use steps in any order:</p> <pre><code>@when('login button pressed') def loginButtonPressed(): print 'button pressed' </code></pre> <p>In gherkin</p> <pre><code>Scenario: Use given anywhere Given username and password entered when login button pressed then I am logged in when login button pressed </code></pre> <p><em>pros:</em> don't have to create given/when/then versions...</p> <p><em>cons:</em> can make less readable... goes against true step procedure. </p> <p>see for more info <a href="http://pytest-bdd.readthedocs.io/en/latest/#relax-strict-gherkin-language-validation" rel="nofollow">Relax strict gherkin</a></p> <p><strong>Option 2: Call previously defined function in new step definition</strong></p> <pre><code>@given('login button pressed') def loginButtonPressed(): # do stuff... # do more stuff... print 'button pressed' @when('login button pressed') def when_loginButtonPressed(): loginButtonPressed() @then('login button pressed') def then_loginButtonPressed(): loginButtonPressed() </code></pre> <p><em>pros:</em> Doesn't duplicate function body code, keep given->when->then pattern. Still maintainable (change code 1 place) </p> <p><em>cons:</em> Still have to create new function definitions for given, when, then versions... </p>
0
2016-09-19T22:10:04Z
[ "python", "bdd", "py.test" ]
pandas dataframe fillna() not working?
39,192,614
<p>I have a data set in which I am performing a principal components analysis (PCA). I get a <code>ValueError</code> message when I try to transform the data. Below is some of the code:</p> <pre><code>import pandas as pd import numpy as np import matplotlib as mpl from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA as sklearnPCA data = pd.read_csv('test.csv',header=0) X = data.ix[:,0:1000].values # values of 1000 predictor variables Y = data.ix[:,1000].values # values of binary outcome variable sklearn_pca = sklearnPCA(n_components=2) X_std = StandardScaler().fit_transform(X) </code></pre> <p>It is here that I get the following error message:</p> <pre class="lang-none prettyprint-override"><code>ValueError: Input contains NaN, infinity or a value too large for dtype('float64'). </code></pre> <p>So I then checked whether the original data set had any NaN values:</p> <pre><code>print(data.isnull().values.any()) # prints True data.fillna(0) # replace NaN values with 0 print(data.isnull().values.any()) # prints True </code></pre> <p>I don't understand why <code>data.isnull().values.any()</code> is still printing <code>True</code> even after I replaced the NaN values with 0.</p>
0
2016-08-28T15:02:46Z
39,192,648
<p>You have to replace data by the returned object from <code>fillna</code></p> <p>Small reproducer:</p> <pre><code>import pandas as pd data = pd.DataFrame(data=[0,float('nan'),2,3]) print(data.isnull().values.any()) # prints True data = data.fillna(0) # replace NaN values with 0 print(data.isnull().values.any()) # prints False now :) </code></pre>
0
2016-08-28T15:07:00Z
[ "python", "pandas", "dataframe", "missing-data" ]
I want to print integer variables string separated by some string in Python3
39,192,628
<p>I am trying to print 3 integer variables separated by some string. But it is giving me an error </p> <blockquote> <p>TypeError: unsupported operand type(s) for +: 'int' and 'str'.</p> </blockquote> <p>My attempt: </p> <pre><code>def unpack_values(grades): first, *middle, last = grades avg = sum(middle)/len(middle) print(str(first)+"-------"+str(avg)+" ---- "+str(last)) unpack_values(['10', '20', '30', '40', '50']) </code></pre>
-2
2016-08-28T15:04:13Z
39,192,658
<p>The error occurs when trying to calculate <code>sum(middle)</code>, because <code>middle</code> is a list of strings. You need to convert it to integers first.</p> <pre><code>In [1]: def unpack_values(grades): ...: first, *middle, last = [int(g) for g in grades] ...: avg = sum(middle) / len(middle) ...: print('{} ------ {} ------ {}'.format(first, avg, last)) ...: In [2]: unpack_values(['10', '20', '30', '40', '50']) 10 ------ 30.0 ------ 50 </code></pre>
5
2016-08-28T15:08:18Z
[ "python", "python-3.x" ]
Finding the minimum of a function on a closed interval with Python
39,192,643
<p>Updated: How do I find the minimum of a function on a closed interval [0,3.5] in Python? So far I found the max and min but am unsure how to filter out the minimum from here. </p> <pre><code>import sympy as sp x = sp.symbols('x') f = (x**3 / 3) - (2 * x**2) + (3 * x) + 1 fprime = f.diff(x) all_solutions = [(xx, f.subs(x, xx)) for xx in sp.solve(fprime, x)] print (all_solutions) </code></pre>
1
2016-08-28T15:05:51Z
39,192,723
<p>Here's a possible solution using sympy:</p> <pre><code>import sympy as sp x = sp.Symbol('x', real=True) f = (x**3 / 3) - (2 * x**2) - 3 * x + 1 #f = 3 * x**4 - 4 * x**3 - 12 * x**2 + 3 fprime = f.diff(x) all_solutions = [(xx, f.subs(x, xx)) for xx in sp.solve(fprime, x)] interval = [0, 3.5] interval_solutions = filter( lambda x: x[0] &gt;= interval[0] and x[0] &lt;= interval[1], all_solutions) print(all_solutions) print(interval_solutions) </code></pre> <p><code>all_solutions</code> is giving you all points where the first derivative is zero, <code>interval_solutions</code> is constraining those solutions to a closed interval. This should give you some good clues to find minimums and maximums :-)</p>
1
2016-08-28T15:14:22Z
[ "python", "numpy", "sympy" ]
Finding the minimum of a function on a closed interval with Python
39,192,643
<p>Updated: How do I find the minimum of a function on a closed interval [0,3.5] in Python? So far I found the max and min but am unsure how to filter out the minimum from here. </p> <pre><code>import sympy as sp x = sp.symbols('x') f = (x**3 / 3) - (2 * x**2) + (3 * x) + 1 fprime = f.diff(x) all_solutions = [(xx, f.subs(x, xx)) for xx in sp.solve(fprime, x)] print (all_solutions) </code></pre>
1
2016-08-28T15:05:51Z
39,193,838
<p><a href="http://i.stack.imgur.com/88Dzj.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/88Dzj.jpg" alt="Interactive Python session"></a></p> <p>The f.subs commands show two ways of displaying the value of the given function at x=3.5, the first as a rational approximation, the second as the exact fraction.</p> <p><a href="http://i.stack.imgur.com/xrVic.png" rel="nofollow"><img src="http://i.stack.imgur.com/xrVic.png" alt="Graph produced by plot command"></a></p>
0
2016-08-28T17:13:03Z
[ "python", "numpy", "sympy" ]
Finding the minimum of a function on a closed interval with Python
39,192,643
<p>Updated: How do I find the minimum of a function on a closed interval [0,3.5] in Python? So far I found the max and min but am unsure how to filter out the minimum from here. </p> <pre><code>import sympy as sp x = sp.symbols('x') f = (x**3 / 3) - (2 * x**2) + (3 * x) + 1 fprime = f.diff(x) all_solutions = [(xx, f.subs(x, xx)) for xx in sp.solve(fprime, x)] print (all_solutions) </code></pre>
1
2016-08-28T15:05:51Z
39,235,550
<p>Perhaps something like this</p> <pre><code>from sympy import solveset, symbols, Interval, Min x = symbols('x') lower_bound = 0 upper_bound = 3.5 function = (x**3/3) - (2*x**2) - 3*x + 1 zeros = solveset(function, x, domain=Interval(lower_bound, upper_bound)) assert zeros.is_FiniteSet # If there are infinite solutions the next line will hang. ans = Min(function.subs(x, lower_bound), function.subs(x, upper_bound), *[function.subs(x, i) for i in zeros]) </code></pre>
1
2016-08-30T19:22:50Z
[ "python", "numpy", "sympy" ]
Feature extraction
39,192,660
<p>Suppose I have been given data sets with headers : id, query, product_title, product_description, brand, color, relevance.</p> <p>Only id and relevance is in numeric format while all others consists of words and numbers. Relevance is the relevancy or ranking of a product with respect to a given query. For eg - query = "abc" and product_title = "product_x" --> relevance = "2.3"</p> <p>In training sets, all these fields are filled but in test set, relevance is not given and I have to find out by using some machine learning algorithms. I am having problem in determining which features should I use in such a problem ? for example, I should use TF-IDF here. What other features can I obtain from such data sets ? </p> <p>Moreover, if you can refer to me any book/ resources specifically for 'feature extraction' topic that will be great. I always feel troubled in this phase. Thanks in advance. </p>
-2
2016-08-28T15:08:26Z
39,197,840
<p>I think there is no book that will give the answers you need, as feature extraction is the phase that relates directly to the problem being solved and the existing data,the only tip you will find is to create features that describe the data you have. In the past i worked in a problem similar to yours and some features i used were:</p> <ul> <li>Number of query words in product title.</li> <li>Number of query words in product description.</li> <li>n-igram counts</li> <li>tf-idf</li> <li>Cosine similarity</li> </ul> <p>All this after some preprocessing like taking all text to upper(or lower) case, stemming, standard dictionary normalization.</p> <p>Again, this depends on the problmen and the data and you will not find the direct answer, its like posting a question: "i need to develop a product selling system, how do i do it? Is there any book?" . You will find books on programming and software engineering, but you will not find a book on developing your specific system,you'll have to use general knowledge and creativity to craft your solution.</p>
1
2016-08-29T02:45:19Z
[ "python", "machine-learning" ]
Running shell script from python
39,192,749
<p>I have written a small python programme which writes a C-shell script, and then calls the script with subprocess. However, python fails to execute the script. I tested this in the terminal and discovered that the script will also not run from the terminal (i.e. not a python issue). Further testing revealed I could write an identical script in a text editor (vi) and then successfully execute it from the terminal (i.e. I don't think the contents of the script are at fault). Eventually I found that if I tried to run the output from python directly in the terminal with <code>./myscript.com</code> it would <em>not</em> run. However, if I open with vi, make <em>NO</em> changes, save and then run from the terminal using <code>./myscript.com</code> (i.e. the exact same command) it will execute. The script is included below, in case it is of use, however, most of the contents are very specific to the particular programme I am trying to run. I have no idea how to debug this further, or why the effect of opening, saving and closing in vi is sufficient to allow the script to be executed. (I have checked the permissions for example and these are unchanged after the vi step.) Any suggestions on how to proceed which be much appreciated.</p> <pre><code>#!/bin/csh # bin2pipe -in /full/path/to/this/script/recon.spc -bad 0.0 -noswap \ -xN 1714 \ -xT 1714 \ -xFT Freq \ -xMODE Real \ -xSW 4184.570312 \ -xCAR 10.929523 \ -xOBS 800.130005 \ -xLAB 1H \ -yN 2048 \ -yT 2048 \ -yFT Freq \ -yMODE Real \ -ySW 1700.680054 \ -yCAR 125.728023 \ -yOBS 81.075996 \ -yLAB 1H \ -ndim 2 \ |nmrPipe -fn TP -auto \ |nmrPipe -fn REV \ |nmrPipe -fn TP -auto \ -out recon.spc.pipe.ft2 -ov -verb </code></pre>
0
2016-08-28T15:17:13Z
39,214,180
<p>In case this is useful I used <code>xxd</code> (as suggested in the comments above, <a href="http://linuxcommand.org/man_pages/xxd1.html" rel="nofollow">http://linuxcommand.org/man_pages/xxd1.html</a>) to convert both script files, one created in python and one written manually, to hex</p> <pre><code>xxd script.txt output.txt </code></pre> <p>I then compared the output for the two files with <code>diff</code> and could see an additional character <code>0a</code> in hex at the end of the file. This corresponds to a newline. As detailed here <a href="http://stackoverflow.com/questions/729692/why-should-text-files-end-with-a-newline">Why should text files end with a newline?</a> and here <a href="http://stackoverflow.com/questions/1050640/vim-disable-automatic-newline-at-end-of-file">VIM Disable Automatic Newline At End Of File</a>, <code>vi</code> adds a newline character at the end of the file if there isn't one. This was enabling the script to run. Without the newline character at the end (which I hadn't included in the python script), the script wouldn't run.</p>
0
2016-08-29T19:56:58Z
[ "python", "shell", "unix", "vi", "csh" ]
Make Bleach to allow code tags
39,192,753
<p>I'm trying to use <a href="https://github.com/mozilla/bleach" rel="nofollow">bleach</a> to escape HTML tags. It works just fine, unless I'm trying to insert a code snipped as a content of a page. The snippet is inserted like this:</p> <pre><code>&lt;pre&gt; &lt;code&gt; Code sample &lt;/code&gt; &lt;/pre&gt; </code></pre> <p>The code sample may contain html tags. How can I make bleach not to escape tags if they are inside <code>&lt;pre&gt;&lt;code&gt;</code>? I know I can whitelist some tags, but it seems that there is not way to whitelist all tags if they are inside the code block and blacklist then in other cases. The outer html markup is produced from Markdown.</p> <p>Moreover, bleach escapes all &lt; and > signs, but if they occur in the code snippet, it looks like this:</p> <pre><code>for (auto a = 0; i &amp;lt; 10; ++i) </code></pre> <p>If bleach is not capable of this, could you advice another escaper, that can do what I need?</p>
2
2016-08-28T15:17:27Z
39,193,438
<p>You want to whitelist children tags of &lt; pre > and &lt; code >. From what I can infer from reading on the documentation, you have to define one by one the tags you want to whitelist or use a callable that every time a tag gets encountered the callable will be invoked.</p> <p>Check on the documentation the section named: <a href="https://bleach.readthedocs.io/en/latest/clean.html#callable-filters" rel="nofollow">Callable Filters</a></p> <p>A possible solution for your problem is to pass a function on the clean bleach.clean that will check whether the tag encountered by then clean method is a child of the code html tag. You will have to parse the HTML there, you can use HTML parser for that along with <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#treebuilder-objects" rel="nofollow">TreeBuilder</a> of <code>xml.eTree</code> package</p> <p>Here is an <a href="http://stackoverflow.com/questions/13334044/get-the-html-under-a-tag-using-htmlparser-python">example</a> on a different answer.</p>
0
2016-08-28T16:31:46Z
[ "python", "markdown", "bleach" ]
Create list from multiple lists
39,192,759
<p>I saved the results of a loop in a varibale. Now I have multiple (>500) separate lists. Which was okay for the beginning, but now I would like to work again with those lists. Do someone has an idea how I can create one list out of those multiple lists?</p> <p>The code I have so far:</p> <pre><code>for f in file: #do some stuff my_results =[] if score &gt;= 0: my_result.append(str(score)) print my_result </code></pre> <p>So the results in my_result look like:</p> <pre><code>['3'] ['8'] ['6'] ... </code></pre> <p>But I want them to be like:</p> <pre><code>[['3'], ['8'], ['6'],...] </code></pre> <p>I tried it this way:</p> <pre><code>one_list = [] for item in my_result: one_list.append(item) </code></pre> <p>But unfortunately it didn't work! So is there a way how I can combine all those lists to simply one list? </p> <p>Thanks fo your help! :)</p>
0
2016-08-28T15:17:47Z
39,192,828
<p>You are creating <code>my_result</code> at every iteration, as you've put the initialization part inside the loop. Put it outside the loop, so that it become initialized only once.</p> <pre><code>my_results =[] for f in file: #do some stuff if score &gt;= 0: my_results.append(str(score)) print my_result </code></pre>
1
2016-08-28T15:23:43Z
[ "python", "python-2.7" ]
Create list from multiple lists
39,192,759
<p>I saved the results of a loop in a varibale. Now I have multiple (>500) separate lists. Which was okay for the beginning, but now I would like to work again with those lists. Do someone has an idea how I can create one list out of those multiple lists?</p> <p>The code I have so far:</p> <pre><code>for f in file: #do some stuff my_results =[] if score &gt;= 0: my_result.append(str(score)) print my_result </code></pre> <p>So the results in my_result look like:</p> <pre><code>['3'] ['8'] ['6'] ... </code></pre> <p>But I want them to be like:</p> <pre><code>[['3'], ['8'], ['6'],...] </code></pre> <p>I tried it this way:</p> <pre><code>one_list = [] for item in my_result: one_list.append(item) </code></pre> <p>But unfortunately it didn't work! So is there a way how I can combine all those lists to simply one list? </p> <p>Thanks fo your help! :)</p>
0
2016-08-28T15:17:47Z
39,192,830
<p>You are on the right track, but you seem confused about for loops. This should do what you want:</p> <pre><code>my_result = [] for f in file: #do some stuff here if score &gt;= 0: my_result.append(str(score)) print my_result </code></pre> <p>The problem with your current code is that you keep setting <code>my_result</code> to an empty list <code>[]</code> for every item in file, thereby deleting all previous entries.</p> <p>By the way, there is a typo throughout your code snippet as well as the other answer; <code>my_result</code> and <code>my_results</code> are two different lists so your code will not work because you want to assign to one list but actually assign to a completely different one.</p>
1
2016-08-28T15:23:54Z
[ "python", "python-2.7" ]
Create list from multiple lists
39,192,759
<p>I saved the results of a loop in a varibale. Now I have multiple (>500) separate lists. Which was okay for the beginning, but now I would like to work again with those lists. Do someone has an idea how I can create one list out of those multiple lists?</p> <p>The code I have so far:</p> <pre><code>for f in file: #do some stuff my_results =[] if score &gt;= 0: my_result.append(str(score)) print my_result </code></pre> <p>So the results in my_result look like:</p> <pre><code>['3'] ['8'] ['6'] ... </code></pre> <p>But I want them to be like:</p> <pre><code>[['3'], ['8'], ['6'],...] </code></pre> <p>I tried it this way:</p> <pre><code>one_list = [] for item in my_result: one_list.append(item) </code></pre> <p>But unfortunately it didn't work! So is there a way how I can combine all those lists to simply one list? </p> <p>Thanks fo your help! :)</p>
0
2016-08-28T15:17:47Z
39,193,311
<p>You can use list comprehension, that would be fast, if you are not doing some stuff inside the for loop.</p> <pre><code>my_result = [str(score) for score in file if score &gt;= 0] </code></pre>
1
2016-08-28T16:18:10Z
[ "python", "python-2.7" ]
Python split a list into n groups in all possible combinations of group length and elements within group
39,192,777
<p>I want to split a list into n groups in all possible combinations (allowing for variable group length). </p> <p>Say, I have the following list:</p> <pre><code>lst=[1,2,3,4] </code></pre> <p>If I specify n=2, the list could be divided either into groups of 1 element-3 elements or 2 elements-2 elements. Within those two ways of splitting the list, there are unique combinations of which elements go in each list. </p> <p>With n=2, these would be:</p> <pre><code>(1),(2,3,4) (2),(1,3,4) (3),(1,2,4) (4),(1,2,3) (1,2),(3,4) (1,3),(2,4) (1,4),(2,3) </code></pre> <p>With n=1 these would be:</p> <pre><code>(1,2,3,4) </code></pre> <p>And with n=3 these would be:</p> <pre><code>(1),(2),(3,4) (1),(3),(2,4) (1),(4),(2,3) (2),(3),(1,4) (2),(4),(1,3) (3),(4),(1,2) </code></pre> <p>I am not interested in groups of length 0, and order within a group does not matter.</p> <p>I found two similar questions, but they don't answer my question exactly.</p> <p><a href="http://stackoverflow.com/questions/5360220/how-to-split-a-list-into-pairs-in-all-possible-ways">This</a> question splits a list into all combinations where each group is of length n (I found the answer by @tokland) to be particularly useful). However, I am not looking for all groups to be of the same length. </p> <p>And then the first step of <a href="http://stackoverflow.com/questions/9088321/show-all-possible-groupings-of-a-list-given-only-the-amount-of-sublists-length">this</a> question gets unique combinations of split locations to split a list into n groups. However, list order is preserved here and unique combinations of elements within these groups is not determined.</p> <p>I am looking for a combination of these two questions - a list is split into n groups in all possible combinations of group length as well as combinations of elements within a group.</p>
2
2016-08-28T15:19:35Z
39,193,050
<p>Try to use:</p> <pre><code>from itertool import combinations, permutations </code></pre>
0
2016-08-28T15:50:02Z
[ "python" ]
Python split a list into n groups in all possible combinations of group length and elements within group
39,192,777
<p>I want to split a list into n groups in all possible combinations (allowing for variable group length). </p> <p>Say, I have the following list:</p> <pre><code>lst=[1,2,3,4] </code></pre> <p>If I specify n=2, the list could be divided either into groups of 1 element-3 elements or 2 elements-2 elements. Within those two ways of splitting the list, there are unique combinations of which elements go in each list. </p> <p>With n=2, these would be:</p> <pre><code>(1),(2,3,4) (2),(1,3,4) (3),(1,2,4) (4),(1,2,3) (1,2),(3,4) (1,3),(2,4) (1,4),(2,3) </code></pre> <p>With n=1 these would be:</p> <pre><code>(1,2,3,4) </code></pre> <p>And with n=3 these would be:</p> <pre><code>(1),(2),(3,4) (1),(3),(2,4) (1),(4),(2,3) (2),(3),(1,4) (2),(4),(1,3) (3),(4),(1,2) </code></pre> <p>I am not interested in groups of length 0, and order within a group does not matter.</p> <p>I found two similar questions, but they don't answer my question exactly.</p> <p><a href="http://stackoverflow.com/questions/5360220/how-to-split-a-list-into-pairs-in-all-possible-ways">This</a> question splits a list into all combinations where each group is of length n (I found the answer by @tokland) to be particularly useful). However, I am not looking for all groups to be of the same length. </p> <p>And then the first step of <a href="http://stackoverflow.com/questions/9088321/show-all-possible-groupings-of-a-list-given-only-the-amount-of-sublists-length">this</a> question gets unique combinations of split locations to split a list into n groups. However, list order is preserved here and unique combinations of elements within these groups is not determined.</p> <p>I am looking for a combination of these two questions - a list is split into n groups in all possible combinations of group length as well as combinations of elements within a group.</p>
2
2016-08-28T15:19:35Z
39,197,711
<p>Following the helpful links from @friendly_dog, I'm attempting to answer my own question by tweaking the functions used in <a href="http://stackoverflow.com/questions/19368375/set-partitions-in-python/30134039#30134039">this</a> post. I have a rough solution that works, although I fear it is not particularly efficient and could use some improvement. I end up generating many more sets of partitions than I need, and then filter out for the ones that differ only by sort order.</p> <p>First, I take these 3 functions from <a href="http://stackoverflow.com/questions/19368375/set-partitions-in-python/30134039#30134039">Set partitions in Python</a>:</p> <pre><code>import itertools from copy import deepcopy def slice_by_lengths(lengths, the_list): for length in lengths: new = [] for i in range(length): new.append(the_list.pop(0)) yield new def partition(number): return {(x,) + y for x in range(1, number) for y in partition(number-x)} | {(number,)} def subgrups(my_list): partitions = partition(len(my_list)) permed = [] for each_partition in partitions: permed.append(set(itertools.permutations(each_partition, len(each_partition)))) for each_tuple in itertools.chain(*permed): yield list(slice_by_lengths(each_tuple, deepcopy(my_list))) </code></pre> <p>I then write a function that wraps the <code>subgrups</code> function and applies it to each permutation of my original list. I loop through these subgroup permutations and if they are equal in length to the desired number of partitions, I sort them in a way that allows me to identify duplicates. I'm not sure if there is a better approach to this.</p> <pre><code>def return_partition(my_list,num_groups): filtered=[] for perm in itertools.permutations(my_list,len(my_list)): for sub_group_perm in subgrups(list(perm)): if len(sub_group_perm)==num_groups: #sort within each partition sort1=[sorted(i) for i in sub_group_perm] #sort by first element of each partition sort2=sorted(sort1, key=lambda t:t[0]) #sort by the number of elements in each partition sort3=sorted(sort2, key=lambda t:len(t)) #if this new sorted set of partitions has not been added, add it if sort3 not in filtered: filtered.append(sort3) return filtered </code></pre> <p>Running it on my original example list, I see that it produces the desired output, tested on two partitions and three partitions.</p> <pre><code>&gt;&gt;&gt; for i in return_partition([1,2,3,4],2): ... print i ... [[1], [2, 3, 4]] [[4], [1, 2, 3]] [[1, 2], [3, 4]] [[3], [1, 2, 4]] [[1, 3], [2, 4]] [[2], [1, 3, 4]] [[1, 4], [2, 3]] &gt;&gt;&gt; &gt;&gt;&gt; for i in return_partition([1,2,3,4],3): ... print i ... [[1], [4], [2, 3]] [[3], [4], [1, 2]] [[1], [2], [3, 4]] [[1], [3], [2, 4]] [[2], [4], [1, 3]] [[2], [3], [1, 4]] &gt;&gt;&gt; </code></pre>
0
2016-08-29T02:21:47Z
[ "python" ]
Python split a list into n groups in all possible combinations of group length and elements within group
39,192,777
<p>I want to split a list into n groups in all possible combinations (allowing for variable group length). </p> <p>Say, I have the following list:</p> <pre><code>lst=[1,2,3,4] </code></pre> <p>If I specify n=2, the list could be divided either into groups of 1 element-3 elements or 2 elements-2 elements. Within those two ways of splitting the list, there are unique combinations of which elements go in each list. </p> <p>With n=2, these would be:</p> <pre><code>(1),(2,3,4) (2),(1,3,4) (3),(1,2,4) (4),(1,2,3) (1,2),(3,4) (1,3),(2,4) (1,4),(2,3) </code></pre> <p>With n=1 these would be:</p> <pre><code>(1,2,3,4) </code></pre> <p>And with n=3 these would be:</p> <pre><code>(1),(2),(3,4) (1),(3),(2,4) (1),(4),(2,3) (2),(3),(1,4) (2),(4),(1,3) (3),(4),(1,2) </code></pre> <p>I am not interested in groups of length 0, and order within a group does not matter.</p> <p>I found two similar questions, but they don't answer my question exactly.</p> <p><a href="http://stackoverflow.com/questions/5360220/how-to-split-a-list-into-pairs-in-all-possible-ways">This</a> question splits a list into all combinations where each group is of length n (I found the answer by @tokland) to be particularly useful). However, I am not looking for all groups to be of the same length. </p> <p>And then the first step of <a href="http://stackoverflow.com/questions/9088321/show-all-possible-groupings-of-a-list-given-only-the-amount-of-sublists-length">this</a> question gets unique combinations of split locations to split a list into n groups. However, list order is preserved here and unique combinations of elements within these groups is not determined.</p> <p>I am looking for a combination of these two questions - a list is split into n groups in all possible combinations of group length as well as combinations of elements within a group.</p>
2
2016-08-28T15:19:35Z
39,199,937
<p>We can use the basic recursive algorithm from <a href="http://stackoverflow.com/a/30134039">this answer</a> and modify it to produce partitions of a particular length without having to generate and filter out unwanted partitions. </p> <pre><code>def sorted_k_partitions(seq, k): """Returns a list of all unique k-partitions of `seq`. Each partition is a list of parts, and each part is a tuple. The parts in each individual partition will be sorted in shortlex order (i.e., by length first, then lexicographically). The overall list of partitions will then be sorted by the length of their first part, the length of their second part, ..., the length of their last part, and then lexicographically. """ n = len(seq) groups = [] # a list of lists, currently empty def generate_partitions(i): if i &gt;= n: yield list(map(tuple, groups)) else: if n - i &gt; k - len(groups): for group in groups: group.append(seq[i]) yield from generate_partitions(i + 1) group.pop() if len(groups) &lt; k: groups.append([seq[i]]) yield from generate_partitions(i + 1) groups.pop() result = generate_partitions(0) # Sort the parts in each partition in shortlex order result = [sorted(ps, key = lambda p: (len(p), p)) for ps in result] # Sort partitions by the length of each part, then lexicographically. result = sorted(result, key = lambda ps: (*map(len, ps), ps)) return result </code></pre> <p>There's quite a lot going on here, so let me explain. </p> <p>First, we start with a procedural, bottom-up (teminology?) implementation of the same <a href="http://stackoverflow.com/a/30134039">aforementioned recursive algorithm</a>:</p> <pre><code>def partitions(seq): """-&gt; a list of all unique partitions of `seq` in no particular order. Each partition is a list of parts, and each part is a tuple. """ n = len(seq) groups = [] # a list of lists, currently empty def generate_partitions(i): if i &gt;= n: yield list(map(tuple, groups)) else: for group in groups group.append(seq[i]) yield from generate_partitions(i + 1) group.pop() groups.append([seq[i]]) yield from generate_partitions(i + 1) groups.pop() if n &gt; 0: return list(generate_partitions(0)) else: return [[()]] </code></pre> <p>The main algorithm is in the nested <code>generate_partitions</code> function. Basically, it walks through the sequence, and for each item, it: 1) puts the item into each of current groups (a.k.a parts) in the working set and recurses; 2) puts the item in its own, new group. </p> <p>When we reach the end of the sequence (<code>i == n</code>), we yield a (deep) copy of the working set that we've been building up.</p> <p>Now, to get partitions of a particular length, we <em>could</em> simply filter or group the results for the ones we're looking for and be done with it, but this approach performs a lot of unnecessary work (i.e. recursive calls) if we just wanted partitions of some length <code>k</code>. </p> <p>Note that in the function above, the length of a partition (i.e. the # of groups) is increased whenever:</p> <pre><code> # this adds a new group (or part) to the partition groups.append([seq[i]]) yield from generate_partitions(i + 1) groups.pop() </code></pre> <p>...is executed. Thus, we limit the size of a partition by simply putting a guard on that block, like so:</p> <pre><code>def partitions(seq, k): ... def generate_partitions(i): ... # only add a new group if the total number would not exceed k if len(groups) &lt; k: groups.append([seq[i]]) yield from generate_partitions(i + 1) groups.pop() </code></pre> <p>Adding the new parameter and just that line to the <code>partitions</code> function will now cause it to only generate partitions of length <em>up to</em> <code>k</code>. This is almost what we want. The problem is that the <code>for</code> loop still sometimes generates partitions of length <em>less than</em> <code>k</code>. </p> <p>In order to prune those recursive branches, we need to only execute the <code>for</code> loop when we can be sure that we have enough remaining elements in our sequence to expand the working set to a total of <code>k</code> groups. The number of remaining elements--or elements that haven't yet been placed into a group--is <code>n - i</code> (or <code>len(seq) - i</code>). And <code>k - len(groups)</code> is the number of new groups that we need to add to produce a valid k-partition. If <code>n - i &lt;= k - len(groups)</code>, then we <em>cannot</em> waste an item by adding it one of the current groups--we <em>must</em> create a new group. </p> <p>So we simply add another guard, this time to the other recursive branch:</p> <pre><code> def generate_partitions(i): ... # only add to current groups if the number of remaining items # exceeds the number of required new groups. if n - i &gt; k - len(groups): for group in groups: group.append(seq[i]) yield from generate_partitions(i + 1) group.pop() # only add a new group if the total number would not exceed k if len(groups) &lt; k: groups.append([seq[i]]) yield from generate_partitions(i + 1) groups.pop() </code></pre> <p>And with that, you have a working k-partition generator. You could probably collapse some of the recursive calls even further (for example, if there are 3 remaining items and we need 3 more groups, then you already know that you must split each item into their own group), but I wanted to show the function as a slight modification of the basic algorithm which generates all partitions. </p> <p>The only thing left to do is sort the results. Unfortunately, rather than figuring out how to directly generate the partitions in the desired order (an exercise for a smarter dog), I cheated and just sorted post-generation. </p> <pre><code>def sorted_k_partitions(seq, k): ... result = generate_partitions(0) # Sort the parts in each partition in shortlex order result = [sorted(ps, key = lambda p: (len(p), p)) for ps in result] # Sort partitions by the length of each part, then lexicographically. result = sorted(result, key = lambda ps: (*map(len, ps), ps)) return result </code></pre> <p>Somewhat self-explanatory, except for the key functions. The first one: </p> <pre><code>key = lambda p: (len(p), p) </code></pre> <p>says to sort a sequence by length, then by the sequence itself (which, in Python, are ordered lexicographically by default). The <code>p</code> stands for "part". This is used to sort the parts/groups within a partition. This key means that, for example, <code>(4,)</code> precedes <code>(1, 2, 3)</code>, so that <code>[(1, 2, 3), (4,)]</code> is sorted as <code>[(4,), (1, 2, 3)]</code>.</p> <pre><code>key = lambda ps: (*map(len, ps), ps) # or for Python versions &lt;3.5: lambda ps: tuple(map(len, ps)) + (ps,) </code></pre> <p>The <code>ps</code> here stands for "parts", plural. This one says to sort a sequence by the lengths of each of its elements (which must be sequence themselves), then (lexicographically) by the sequence itself. This is used to sort the partitions with respect to each other, so that, for example, <code>[(4,), (1, 2, 3)]</code> precedes <code>[(1, 2), (3, 4)]</code>. </p> <p>The following:</p> <pre><code>seq = [1, 2, 3, 4] for k in 1, 2, 3, 4: for groups in sorted_k_partitions(seq, k): print(k, groups) </code></pre> <p>produces:</p> <pre><code>1 [(1, 2, 3, 4)] 2 [(1,), (2, 3, 4)] 2 [(2,), (1, 3, 4)] 2 [(3,), (1, 2, 4)] 2 [(4,), (1, 2, 3)] 2 [(1, 2), (3, 4)] 2 [(1, 3), (2, 4)] 2 [(1, 4), (2, 3)] 3 [(1,), (2,), (3, 4)] 3 [(1,), (3,), (2, 4)] 3 [(1,), (4,), (2, 3)] 3 [(2,), (3,), (1, 4)] 3 [(2,), (4,), (1, 3)] 3 [(3,), (4,), (1, 2)] 4 [(1,), (2,), (3,), (4,)] </code></pre>
2
2016-08-29T06:38:09Z
[ "python" ]
What does self[] mean in a method?
39,192,798
<p>When reading a python program, I once find a function uses <code>self</code> in the following way. </p> <pre><code>class Auto(object): _biases_str = "biases{0}" def _b(self, n, suffix=""): name_b_out = self._biases_str.format(i + 1) + "_out" return `self[self._biases_str.format(n) + suffix]` </code></pre> <p>The line of <code>name_b_out = self._biases_str.format(i + 1) + "_out"</code> looks usual to me, i.e., we always <code>self.</code> to define something. But I am not very clear about the usage of <code>self[self._biases_str.format(n) + suffix]</code>. In specifc, what does <code>self[]</code> mean here, or what does it do?</p>
0
2016-08-28T15:20:45Z
39,192,852
<p>It doesn't mean anything other than what <code>variable[something]</code> would mean. In Python <code>variable[something]</code> in an expression will just call <code>variable.__getitem__(something)</code>, and <code>self</code> is the name conventionally used for the current object, or the receiver, in Python, so <code>self[self._biases_str.format(n) + suffix]</code> would mean pretty much the same as <code>self.__getitem__(self._biases_str.format(n) + suffix)</code></p> <p>I guess there is a method <code>__getitem__</code> defined for that class as well.</p>
5
2016-08-28T15:25:58Z
[ "python", "python-2.7", "python-3.x" ]
does python function work if multiple user call it at same instant
39,192,846
<p>I am using django framework. I have built one web application using python and django. I am not using any classes or oops concept in my application. I am just using python's function. for e.g. </p> <pre><code>def addnum(request): a=request.GET.get('a') b=request.GET.get('b') res=a+b return HttpResponse(json.dumps(res), content_type="application/json") </code></pre> <p>Now this kind of functions i am calling from client side using ajax and getting back my result</p> <p>My question is .. if multiple users are accessing the application at same instant.. so this 'addnum' function will get call at same instant ... Then how will it work. will it get break for some of user and incorrect output ? will it decrease performance and increase response time? will it work parallely and everything will work fine?</p> <p>Please help me to get out of this problem/confusion!</p>
1
2016-08-28T15:25:11Z
39,194,389
<p>It does not depend upon how you are writing your code it depends upon the server that how it handles multiple requests. I think that a free server on <a href="http://pythonanywhere.com" rel="nofollow">pythonanywhere</a> would be able to handle about 1K concurrent user requests. A server and user is connected using unique identification of ports which allows multiple connections on the server with different users. In simple language we can say that for every user requests server create instances that processes these requests.</p>
0
2016-08-28T18:17:15Z
[ "javascript", "python", "django", "python-2.7", "django-views" ]
does python function work if multiple user call it at same instant
39,192,846
<p>I am using django framework. I have built one web application using python and django. I am not using any classes or oops concept in my application. I am just using python's function. for e.g. </p> <pre><code>def addnum(request): a=request.GET.get('a') b=request.GET.get('b') res=a+b return HttpResponse(json.dumps(res), content_type="application/json") </code></pre> <p>Now this kind of functions i am calling from client side using ajax and getting back my result</p> <p>My question is .. if multiple users are accessing the application at same instant.. so this 'addnum' function will get call at same instant ... Then how will it work. will it get break for some of user and incorrect output ? will it decrease performance and increase response time? will it work parallely and everything will work fine?</p> <p>Please help me to get out of this problem/confusion!</p>
1
2016-08-28T15:25:11Z
39,233,232
<p>When multiple users access it "at the same time", it's actually not at the same time. Let's say you are using uWSGI to serve your webapp, which means that your webapp has a bunch of workers that handle requests.</p> <p>Let's take the simplest case where you just have a single worker. In this case, everything is just sequential. uWSGI automatically queues up all the requests for you in the order that they came in, and feeds it to your webapp one by one. Hopefully this is clear that it wouldn't cause any race conditions with respect to incorrect output. </p> <p>However, if you are say getting 10 requests a second, that means that that one worker needs to process each request in &lt;10ms. If it can't do that then requests will start to pile up.</p> <p>Also, let's say you do get 10 requests "instantaneously". Then one request may return in 10ms, the second one in 20ms, the third one in 30ms etc. (This is actually not accurate because there is also network round trip time but let's ignore that for now)</p> <p>Now let's say you setup multiple workers (separate processes) to help process those requests faster. But since they are separate processes, they don't share memory. So there really isn't any race conditions in this case. (note this changes if you do stuff like write to/read from a file etc)</p> <p>Here, you could have multiple workers processing requests in parallel. But it's still just uWSGI maintaining a queue of requests that it feeds to workers whenever that worker finishes processing requests and frees up.</p>
0
2016-08-30T17:02:23Z
[ "javascript", "python", "django", "python-2.7", "django-views" ]
Why is translated Sudoku solver slower than original?
39,192,878
<p>I transcribed my Java Sudoku solver into python. Everything works, however solving takes up to 2mins, while the identical puzzle takes only a few seconds in Java. Also the iterations needed amount to the exact same number. Am I missing something?</p> <pre><code>import numpy as np def solve_recursive(puzzle, pos): if(pos == 81): print puzzle return True if(puzzle[pos] != 0): if (not solve_recursive(puzzle, pos+1)): return False else: return True row = np.copy(puzzle[pos//9*9:pos//9*9+9]) col = np.copy(puzzle[pos%9::9]) short = (pos%9)//3*3 + pos//27*27 square = np.concatenate((puzzle[short:short+3],puzzle[short+9:short+12],puzzle[short+18:short+21])) for i in range(1,10): puzzle[pos] = i if(i not in row and i not in col and i not in square and solve_recursive(puzzle, pos+1)): return True puzzle[pos] = 0 return False puzzle = np.array([[0,0,0,0,0,0,0,8,3], [0,2,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,4,0], [0,0,0,6,1,0,2,0,0], [8,0,0,0,0,0,9,0,0], [0,0,4,0,0,0,0,0,0], [0,6,0,3,0,0,5,0,0], [1,0,0,0,0,0,0,7,0], [0,0,0,0,0,8,0,0,0]]) solve_recursive(puzzle.ravel(), 0) </code></pre> <p>EDIT:</p> <p>As suggested by @hpaulj I reworked my code to work with numpy´s 2D arrays:</p> <pre><code>import numpy as np def solve_recursive(puzzle, pos): if pos == (0,9): print puzzle raise Exception("Solution") if(puzzle[pos] != 0): if(pos[0] == 8): solve_recursive(puzzle, (0,pos[1]+1)) return elif pos[0] &lt; 8: solve_recursive(puzzle, (pos[0]+1, pos[1])) return for i in range(1,10): if(i not in puzzle[pos[0]] and i not in puzzle[:,pos[1]] and i not in puzzle[pos[0]//3*3:pos[0]//3*3+3,pos[1]//3*3:pos[1]//3*3+3]): puzzle[pos] = i if(pos[0] == 8): solve_recursive(puzzle, (0,pos[1]+1)) elif pos[0] &lt; 8: solve_recursive(puzzle, (pos[0]+1, pos[1])) puzzle[pos] = 0 puzzle = np.array([[0,0,0,0,0,0,0,8,3], [0,2,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,4,0], [0,0,0,6,1,0,2,0,0], [8,0,0,0,0,0,9,0,0], [0,0,4,0,0,0,0,0,0], [0,6,0,3,0,0,5,0,0], [1,0,0,0,0,0,0,7,0], [0,0,0,0,0,8,0,0,0]]) solve_recursive(puzzle, (0,0)) </code></pre> <p>Ignoring the fact that throwing an exception at the bottom of the recursive calls is rather inelegant, this is just inconsiderably faster than my original solution. Would using dictionaries like the linked Norvig solver be a reasonable alternative? </p>
-1
2016-08-28T15:29:37Z
39,195,131
<p>I modified your function to print the <code>pos</code> and to maintain a running count of the times it's been called. And I stop it early.</p> <p>Stopping at <code>pos==46</code> results in 1190 calls, with just a slight visible delay. But for 47 the count is 416621, with a minute or more run. </p> <p>Assuming it's doing some sort of recursive search, the problem had a quantum jump in difficulty between 46 and 47. </p> <p>Yes, Python as an interpreted language will run slower than Java. Possible solutions include figuring out why there's this kind of jump in recursion calls. Or improving the speed of each call.</p> <p>You set up 9x9 numpy array, but then immediately ravel it. The function itself then treats the board as a list of 81 values. That means selecting rows and columns and submatrices is much more complicated than if the array were still 2d. In effect the array is just a list.</p> <p>I can imagine 2 ways of speeding up the calls. One is to recode it to use a list board. For small arrays and iterative actions lists have less overhead than arrays, so often are faster. An alternative is to code it to really take advantage of the 2d nature of the array. <code>numpy</code> solutions are good only if they let <code>numpy</code> use compiled code to perform most actions. Iteration over an array is slow.</p> <p>==================</p> <p>Changing your function so that it works with a flat list instead of the raveled array, runs much faster. For a max pos of 47, it runs in 15sec, versus 1m 15s for your original (same board and iteration count).</p> <p>I'm cleaning up a 2d numpy array version, but not making it any faster.</p> <p>A pure list version is also a good candidate for running faster on <code>pypy</code>.</p> <p>A portion of the code that works with a 2d array</p> <pre><code> r,c = np.unravel_index(pos, (9,9)) if(puzzle[r,c] != 0): return solve_numpy(puzzle, pos+1) row = puzzle[r,:].copy() col = puzzle[:,c].copy() r1, c1 = 3*(r//3), 3*(c//3) square = puzzle[r1:r1+3, c1:c1+3].flatten() for i in range(1,10): puzzle[r,c] = i if(i not in row and i not in col and i not in square): if solve_numpy(puzzle, pos+1): return True puzzle[r,c] = 0 </code></pre> <p>Indexing is clearer, but there isn't a speed improvement. Other than simpler indexing, it doesn't make much use of whole array operations.</p> <p>The <code>list</code> version doesn't look that much different from the original, but is much faster:</p> <pre><code> row = puzzle[pos//9*9:pos//9*9+9] col = puzzle[pos%9::9] short = (pos%9)//3*3 + pos//27*27 square = puzzle[short:short+3] + \ puzzle[short+9:short+12] + \ puzzle[short+18:short+21] </code></pre> <p><a href="http://norvig.com/sudoku.html" rel="nofollow">http://norvig.com/sudoku.html</a> Discusses sudoku solution methods, with pythoN - by an AI expert.</p> <p>With this <code>Norvig</code> solver, your grid solution takes 0.01 sec. Information is stored primarily in dictionaries. Your case is an easy one, than can be solved with his 2 basic assignment strategies. Without searching the solution is very fast.</p>
2
2016-08-28T19:44:35Z
[ "java", "python", "numpy", "sudoku" ]
Django Product Total
39,193,002
<p>I'm trying to learn in Django. I'm trying to prepare the inventory application. But I do not calculate the input and output products. </p> <p>I prepare models &amp; views.</p> <p><strong>Models:</strong></p> <pre><code>class Kategori(models.Model): adi = models.CharField(max_length=10, verbose_name="Kategori") def __str__(self): return self.adi class Birim(models.Model): birim = models.CharField(max_length=2, verbose_name="Birim") def __str__(self): return self.birim class Urunler(models.Model): adi = models.CharField(max_length=50, verbose_name="Ürün Adı") kod = models.PositiveSmallIntegerField(verbose_name="Ürün Kodu", blank=True, null=True) etkenMadde = models.CharField(max_length=100, verbose_name="İçerik Etken Madde", blank=True, null=True) tarih = models.DateField(default=datetime.now(), editable=False) birim = models.ForeignKey(Birim, verbose_name="Birim") kategori = models.ForeignKey(Kategori, verbose_name="Kategori") aciklama = models.CharField(max_length=50, verbose_name="Açıklama", blank=True, null=True) def __str__(self): return self.adi class StokCikis(models.Model): urun = models.ForeignKey(Urunler, related_name="scikis_urun", verbose_name="Ürün") tarih = models.DateTimeField(default=datetime.now()) miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0) teslimAlan = models.CharField(max_length=20, verbose_name="Teslim Alan") tesimEden = models.CharField(max_length=20, verbose_name="Teslim Eden") def __str__(self): return self.urun.adi class StokGiris(models.Model): urun = models.ForeignKey(Urunler, related_name="sgiris_urun", verbose_name="Ürün") tedarikci = models.CharField(max_length=100, verbose_name="Tedarikçi", blank=True, null=True) irsaliyeNo = models.PositiveSmallIntegerField(verbose_name="İrsaliye No", blank=True, null=True) tarih = models.DateField(default=datetime.now().strftime("%d.%m.%Y")) miktar = models.PositiveSmallIntegerField(verbose_name="Miktar", default=0) aciklama = models.CharField(max_length=100, verbose_name="Açıklama", blank=True, null=True) def __str__(self): return self.urun.adi </code></pre> <p><strong>Views.py</strong></p> <pre><code>def kategori(request): kategori = Kategori.objects.all() return render_to_response('stok_kategoriler.html', locals()) def kategoriEkle(request): kategoriId = request.GET.get('id') if kategoriId: ktgr = Kategori.objects.get(pk=kategoriId) form = KategoriForm(instance=ktgr) else: form = KategoriForm if request.method == 'POST': if kategoriId: form = KategoriForm(request.POST, instance=ktgr) else: form = KategoriForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/stok/kategoriler') button = "Ekle" baslik = "Kategoriler" return render(request, 'stok_kategori_ekle.html', locals()) def kategoriSil(request): kategoriId = request.GET.get('id') kategori = Kategori.objects.get(pk=kategoriId) kategori.delete() return HttpResponseRedirect('/stok/kategoriler') def stokBirimler(request): birimler = Birim.objects.all() return render_to_response('stok_birimler.html',locals()) def stokBirimEkle(request): birimId = request.GET.get('id') if birimId: stok_birim = Birim.objects.get(pk=birimId) form = BirimForm(instance=stok_birim) else: form = BirimForm() if request.method == 'POST': if birimId: form = BirimForm(request.POST, instance=stok_birim) else: form = BirimForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/stok/birimler/') baslik = "Stok Birimleri" return render(request, 'stok_birim_ekle.html', locals()) def stokBirimSil(request): birimId = request.GET.get('id') birim = Birim.objects.get(pk=birimId) birim.delete() return HttpResponseRedirect('/stok/birimler/') def stokUrunler(request): urunler = Urunler.objects.all() return render_to_response('stok_urunler.html', locals()) def urunEkle(request): urunId = request.GET.get('id') if urunId: stok_urun = Urunler.objects.get(pk=urunId) form = UrunForm(instance=stok_urun) else: form = UrunForm() if request.method == 'POST': if urunId: form = UrunForm(request.POST, instance=stok_urun) else: form = UrunForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/stok/urunler/') baslik = "Stok Ürünleri" return render(request, 'stok_urun_ekle.html', locals()) def urunSil(request): urunId = request.GET.get('id') urun = Urunler.objects.get(pk=urunId) urun.delete() return HttpResponseRedirect('/stok/urunler/') </code></pre> <p>Located in the model StokGiris.miktari and Stok.Cikis.miktari fields need calculation. <strong>Total = StokGiris.miktari - StokCikis.miktari</strong> and I want to list the records.</p>
0
2016-08-28T15:45:09Z
39,196,158
<p>If I understand your question correctly, you want to aggregate the values of <code>miktar</code> of both models and subtract them from each other. You can do it with Django built-in aggregation:</p> <pre><code>from django.db.models import Sum total = StokGiris.objects.all().aggregate(Sum('miktar')) - StokCikis.objects.all().aggregate(Sum('miktar')) </code></pre> <p>As for listing the records... Not really sure what you mean again, but some ways to "list the records":</p> <pre><code># Just a list of DB items list_of_stokgiris = list(StokGiris.objects.all()) # Serialized list of dictionaries with the DB values list_of_stokcikis = StokCikis.objects.values() # You can add an argument to specify which fields you want to be serialized # Serialized list of tuples with DB values # I.e. [('Filipp',), ('Artjom',), ('Marat',)] list_of_urunler = Urunler.objects.values_list('adi') # Same here for the argument. Multiple args are also supported. </code></pre>
0
2016-08-28T21:56:01Z
[ "python", "django" ]
Python html div class
39,193,005
<p>I'm trying to write a simple program which saves the values of a table in a matrix (later I want to send the matrix to a database).</p> <p>Here is my code:</p> <pre><code>pfad = "https://business.facebook.com/ads/manager/account/ads/?act=516059741896803&amp;pid=p2&amp;report_spec=6056690557117&amp;business_id=401807279988717" html = urlopen(pfad) r=requests.get(pfad) soup = BeautifulSoup(html.read(),'html.parser') mydivs = soup.findAll("div", { "class" : "ellipsis_1ha3" }) # no output: for div in mydivs: if (div["class"]=="ellipsis_1ha3"): print div # output: [] print(mydivs) </code></pre> <p>I want the values inside of the <code>div</code>s with class <code>ellipsis _1ha3</code>, but I don't know why it doesn't work. Can anyone help me?</p> <p>Here is an example html which is like the original</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; .ellipsis_1ha3 { width: 100px; border: 1px solid black; } .a { width: 100px; border: 1px solid black; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;div style="display: inline-flex;"&gt; &lt;div class="a"&gt;Purchase&lt;/div&gt; &lt;div class="a"&gt;Clicks&lt;/div&gt; &lt;/div&gt; &lt;/br&gt; &lt;div style="display: inline-flex;"&gt; &lt;div class="ellipsis_1ha3"&gt;20&lt;/div&gt; &lt;div class="ellipsis_1ha3"&gt;30&lt;/div&gt; &lt;/div&gt; &lt;/br&gt; &lt;div style="display: inline-flex;"&gt; &lt;div class="ellipsis_1ha3"&gt;10&lt;/div&gt; &lt;div class="ellipsis_1ha3"&gt;50&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>SECOND EXAMPLE</p> <pre><code>pfad = "http://www.bundesliga.de/de/liga/tabelle/" html = urlopen(pfad) soup = BeautifulSoup(html.read(),'html.parser') mydivs = soup.findAll('div', { 'class' : 'wwe-cursor-pointer' }) for div in mydivs: if ("wwe-cursor-pointer" in div["class"]): print div </code></pre>
-1
2016-08-28T15:45:27Z
39,194,180
<p>Try using <code>lxml</code> and xpath expressions to pull out the relevant information. Beautifulsoup is built on lxml, I believe. Assuming you loaded the document into a string called <code>html_string</code>.</p> <pre><code>from lxml import html h = html.fromstring(html_string) h.xpath('//div[@class="ellipsis_1ha3"]/node()') #output: ['20', '30', '10', '50'] </code></pre>
0
2016-08-28T17:51:32Z
[ "python", "html", "beautifulsoup" ]
Location of static files when creating a Django exe using pyinstaller
39,193,073
<p>I have a Django project with the following structure: root videos static templates</p> <p>and the STATIC_URL setting in settings.py is STATIC_URL = '/static/'</p> <p>I managed to use pyinstaller to create a windows executable from manage.py. I can start the Django server but I can't figure out where to put the static files.</p> <p>When I first started the server it could not find the templates as well, it searched for them in : 'root\django\contrib\admin\templates\videos\' I copied the templates to this folder and it worked. But I can't figure out where to put the static files. I tried putting them in 'root\django\contrib\admin\static' to recreate the original structure. But it seems it doesn't search for them there... </p> <p>Anyone knows where the static files should go? Or how to define the place where a bundled pyinstaller exe will look for them ?</p>
0
2016-08-28T15:53:09Z
39,193,157
<p>First make sure that <code>django.contrib.staticfiles</code> is included in your <code>INSTALLED_APPS</code> in <code>settings.py</code>. Then have to insert in your <code>settings.py</code> for example this one:</p> <pre><code>STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] </code></pre> <p>I hope definition of <code>BASE_DIR</code> you have in the top of <code>settings.py</code>. <code>BASE_DIR</code> points to a folder, where your <code>manage.py</code> file exists. So if you would have static files in the same dir, then you leave above setting as it is. If not, let's say in the same dir, next to <code>manage.py</code> you will have folder named <code>app</code>, then your settings should look like:</p> <pre><code>STATICFILES_DIRS = [ os.path.join(BASE_DIR, "app/static"), ] </code></pre> <p>And you can even run:</p> <pre><code>python manage.py collectstatic </code></pre> <p>To get admin static files into your static directory.</p> <p>Hope that helps.</p>
0
2016-08-28T16:01:42Z
[ "python", "django", "pyinstaller" ]
Moving python package without messing internal imports
39,193,092
<p>I wrote a python package that includes many modules. The modules import each other within the package. Now after it is complete I wish to move my package inside a different package as a subdirectory. But I can't do it because now all the imports get errors because they can't find the modules on their new path.</p> <p>For example -</p> <p>In module <code>my_package.a</code> I have:</p> <pre><code>x = 5 </code></pre> <p>In module <code>my_package.b</code>:</p> <pre><code>from my_package.a import x print x </code></pre> <p>Before I did: <code>from my_package import b</code>, and now I wish to do <code>from tools.my_package import b</code>, and get the same result.</p> <p>What is the right way to change a package logic path without having to add the new path to <code>sys.path</code>?</p>
1
2016-08-28T15:55:46Z
39,193,824
<p>I would use relative imports internally:</p> <pre><code>from .a import x </code></pre> <p>If your module is self-contained, you can relocate it without issues if it uses relative imports.</p>
1
2016-08-28T17:12:04Z
[ "python", "import", "packages" ]
pandas: dataframe from dict with comma separated values
39,193,110
<p>I'm trying to create a DataFrame from a nested dictionary, where the values are in comma separated strings.</p> <p>Each value is nested in a dict, such as:</p> <pre><code>dict = {"1":{ "event":"A, B, C"}, "2":{ "event":"D, B, A, C"}, "3":{ "event":"D, B, C"} } </code></pre> <p>My desired output is:</p> <pre><code> A B C D 0 A B C NaN 1 A B C D 2 NaN B C D </code></pre> <p>All I have so far is converting the dict to dataframe and splitting the items in each list. But I'm not sure this is getting me any closer to my objective.</p> <pre><code>df = pd.DataFrame(dict) Out[439]: 1 2 3 event A, B, C D, B, A, C D, B, C In [441]: df.loc['event'].str.split(',').apply(pd.Series) Out[441]: 0 1 2 3 1 A B C NaN 2 D B A C 3 D B C NaN </code></pre> <p>Any help is appreciated. Thanks</p>
1
2016-08-28T15:56:58Z
39,193,319
<p>From what you have(modified the split a little to strip the extra spaces) <code>df1</code>, you can probably just <code>stack</code> the result and use <code>pd.crosstab()</code> on the index and value column:</p> <pre><code>df1 = df.loc['event'].str.split('\s*,\s*').apply(pd.Series) df2 = df1.stack().rename('value').reset_index() pd.crosstab(df2.level_0, df2.value) # value A B C D # level_0 # 1 1 1 1 0 # 2 1 1 1 1 # 3 0 1 1 1 </code></pre> <p>This is not exactly as you asked for, but I imagine you may prefer this to your desired output.</p> <p>To get exactly what you are looking for, you can add an extra column which is equal to the value column above and then unstack the index that contains the values:</p> <pre><code>df2 = df1.stack().rename('value').reset_index() df2['value2'] = df2.value df2.set_index(['level_0', 'value']).drop('level_1', axis = 1).unstack(level = 1) # value2 # value A B C D # level_0 # 1 A B C None # 2 A B C D # 3 None B C D </code></pre>
1
2016-08-28T16:19:05Z
[ "python", "pandas", "dataframe" ]
pandas: dataframe from dict with comma separated values
39,193,110
<p>I'm trying to create a DataFrame from a nested dictionary, where the values are in comma separated strings.</p> <p>Each value is nested in a dict, such as:</p> <pre><code>dict = {"1":{ "event":"A, B, C"}, "2":{ "event":"D, B, A, C"}, "3":{ "event":"D, B, C"} } </code></pre> <p>My desired output is:</p> <pre><code> A B C D 0 A B C NaN 1 A B C D 2 NaN B C D </code></pre> <p>All I have so far is converting the dict to dataframe and splitting the items in each list. But I'm not sure this is getting me any closer to my objective.</p> <pre><code>df = pd.DataFrame(dict) Out[439]: 1 2 3 event A, B, C D, B, A, C D, B, C In [441]: df.loc['event'].str.split(',').apply(pd.Series) Out[441]: 0 1 2 3 1 A B C NaN 2 D B A C 3 D B C NaN </code></pre> <p>Any help is appreciated. Thanks</p>
1
2016-08-28T15:56:58Z
39,193,945
<p>You can use a couple of comprehensions to massage the nested dict into a better format for creation of a DataFrame that flags if an entry for the column exists or not:</p> <pre><code>the_dict = {"1":{ "event":"A, B, C"}, "2":{ "event":"D, B, A, C"}, "3":{ "event":"D, B, C"} } df = pd.DataFrame([[{z:1 for z in y.split(', ')} for y in x.values()][0] for x in the_dict.values()]) &gt;&gt;&gt; df A B C D 0 1.0 1 1 NaN 1 1.0 1 1 1.0 2 NaN 1 1 1.0 </code></pre> <p>Once you've made the DataFrame you can simply loop through the columns and convert the values that flagged the existence of the letter into a letter using the <code>where</code> method(below this does where NaN leave as NaN, otherwise it inserts the letter for the column):</p> <pre><code>for col in df.columns: df_mask = df[col].isnull() df[col]=df[col].where(df_mask,col) &gt;&gt;&gt; df A B C D 0 A B C NaN 1 A B C D 2 NaN B C D </code></pre> <p>Based on @merlin's suggestion you can go straight to the answer within the comprehension:</p> <pre><code>df = pd.DataFrame([[{z:z for z in y.split(', ')} for y in x.values()][0] for x in the_dict.values()]) &gt;&gt;&gt; df A B C D 0 A B C NaN 1 A B C D 2 NaN B C D </code></pre>
2
2016-08-28T17:26:22Z
[ "python", "pandas", "dataframe" ]
how to find match first word in string with regex in python
39,193,133
<p>I want to match the word <code>'St' or 'St.' or 'st' or 'st.'</code> BUT only in first word of a string. For example ' St. Mary Church Church St.' - should find ONLY first St. </p> <ul> <li>'st. Mary Church Church St.' - should find ONLY 'st.' </li> <li>'st Mary Church Church St.' - should find ONLY 'st'</li> </ul> <p>I want to eventually replace the first occurence with 'Saint'.</p> <p>I have literally spent hours trying to find a regex that will match this problem so i have tried myself first and i now for some of you it will be easy!</p>
0
2016-08-28T15:58:59Z
39,193,245
<p>You don't need to use a regex for this, just use the <code>split()</code> method on your string to split it by whitespace. This will return a list of every word in your string:</p> <pre><code>matches = ["St", "St.", "st", "st."] name = "St. Mary Church Church St." words = name.split() #split the string into words into a list if words [0] in matches: words[0] = "Saint" #replace the first word in the list (St.) with Saint new_name = "".join([word + " " for word in words]).strip() #create the new name from the words, separated by spaces and remove the last whitespace print(new_name) #Output: "Saint Mary Church Church St." </code></pre>
1
2016-08-28T16:11:05Z
[ "python", "regex" ]
how to find match first word in string with regex in python
39,193,133
<p>I want to match the word <code>'St' or 'St.' or 'st' or 'st.'</code> BUT only in first word of a string. For example ' St. Mary Church Church St.' - should find ONLY first St. </p> <ul> <li>'st. Mary Church Church St.' - should find ONLY 'st.' </li> <li>'st Mary Church Church St.' - should find ONLY 'st'</li> </ul> <p>I want to eventually replace the first occurence with 'Saint'.</p> <p>I have literally spent hours trying to find a regex that will match this problem so i have tried myself first and i now for some of you it will be easy!</p>
0
2016-08-28T15:58:59Z
39,193,251
<pre><code>import re string = "Some text" replace = {'St': 'Saint', 'St.': 'Saint', 'st': 'Saint', 'st.': 'Saint'} replace = dict((re.escape(k), v) for k, v in replace.iteritems()) pattern = re.compile("|".join(replace.keys())) for text in string.split(): text = pattern.sub(lambda m: replace[re.escape(m.group(0))], text) </code></pre> <p>This should work I guess, please check. <a href="http://stackoverflow.com/questions/6116978/python-replace-multiple-strings">Source</a></p>
-1
2016-08-28T16:11:27Z
[ "python", "regex" ]
how to find match first word in string with regex in python
39,193,133
<p>I want to match the word <code>'St' or 'St.' or 'st' or 'st.'</code> BUT only in first word of a string. For example ' St. Mary Church Church St.' - should find ONLY first St. </p> <ul> <li>'st. Mary Church Church St.' - should find ONLY 'st.' </li> <li>'st Mary Church Church St.' - should find ONLY 'st'</li> </ul> <p>I want to eventually replace the first occurence with 'Saint'.</p> <p>I have literally spent hours trying to find a regex that will match this problem so i have tried myself first and i now for some of you it will be easy!</p>
0
2016-08-28T15:58:59Z
39,193,348
<p>Regex <code>sub</code> allows you to define the number of occurence to replace in a string. </p> <p>i.e. : </p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "St. Mary Church Church St." &gt;&gt;&gt; new_s = re.sub(r'^(St.|st.|St|st)\s', r'Saint ', s, 1) # the last argument defines the number of occurrences to be replaced. In this case, it will replace the first occurrence only. &gt;&gt;&gt; new_s 'Saint Mary Church Church St.' &gt;&gt;&gt; </code></pre> <p>Hope it hepls. </p>
1
2016-08-28T16:21:59Z
[ "python", "regex" ]
how to find match first word in string with regex in python
39,193,133
<p>I want to match the word <code>'St' or 'St.' or 'st' or 'st.'</code> BUT only in first word of a string. For example ' St. Mary Church Church St.' - should find ONLY first St. </p> <ul> <li>'st. Mary Church Church St.' - should find ONLY 'st.' </li> <li>'st Mary Church Church St.' - should find ONLY 'st'</li> </ul> <p>I want to eventually replace the first occurence with 'Saint'.</p> <p>I have literally spent hours trying to find a regex that will match this problem so i have tried myself first and i now for some of you it will be easy!</p>
0
2016-08-28T15:58:59Z
39,193,434
<p>Try using the regex <code>'^\S+'</code> to match the first non-space character in your string.</p> <pre><code>import re s = 'st Mary Church Church St.' m = re.match(r'^\S+', s) m.group() # 'st' s = 'st. Mary Church Church St.' m = re.match(r'^\S+', s) m.group() # 'st.' </code></pre>
-1
2016-08-28T16:31:26Z
[ "python", "regex" ]
Splitting strings in python using import re
39,193,180
<p>Why does this work:</p> <pre><code>string = 'N{P}[ST]{P}' &gt;&gt;&gt; import re &gt;&gt;&gt; re.split(r"[\[\]]", string) &gt;&gt;&gt; ['N{P}', 'ST', '{P}'] </code></pre> <p>But this don't?</p> <pre><code>&gt;&gt;&gt; re.split(r"{\{\}}", string) </code></pre>
0
2016-08-28T16:03:52Z
39,193,221
<p>You have to do this:</p> <pre><code>re.split(r"[{}]", string) </code></pre> <p><code>r"{\{\}}"</code> is a special re syntax to repeat groups (ex: <code>(ab){1,3}</code> matches <code>ab</code>, <code>abab</code> or <code>ababab</code>) but not the character range (note that you don't have to escape the curly braces in a character range). (I admit I don't know what your strange regex is supposed to do specially in the re.split context, but not what you want :))</p>
1
2016-08-28T16:08:14Z
[ "python", "regex" ]
Splitting strings in python using import re
39,193,180
<p>Why does this work:</p> <pre><code>string = 'N{P}[ST]{P}' &gt;&gt;&gt; import re &gt;&gt;&gt; re.split(r"[\[\]]", string) &gt;&gt;&gt; ['N{P}', 'ST', '{P}'] </code></pre> <p>But this don't?</p> <pre><code>&gt;&gt;&gt; re.split(r"{\{\}}", string) </code></pre>
0
2016-08-28T16:03:52Z
39,193,257
<p><code>{</code> and <code>}</code> are meta-characters in regular expressions and should be escaped or put into a character class<br> <code>{\{\}}</code> - means just escaped curly braces within unescaped </p>
0
2016-08-28T16:12:02Z
[ "python", "regex" ]
scrapy LxmlLinkExtractor to crawl relative urls
39,193,198
<p>I want to crawl all the relative urls under tag in <a href="http://news.qq.com/" rel="nofollow">http://news.qq.com/</a></p> <p>the code of mine is that:</p> <pre><code>import scrapy from scrapy.selector import Selector from homework.items import HomeworkItem from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor class News1Spider(scrapy.Spider): name = "News1" allowed_domains = ["http://news.qq.com/"] start_urls = ( 'http://news.qq.com/', ) rules = ( Rule(LxmlLinkExtractor(restrict_xpaths='//div[@class="Q- tpList"]/div/a/@href'),callback='parse'), ) def parse(self, response): sel = Selector(response) #lis = sel.xpath('//div[@class="Q-tpList"]') #item = TutorialItem() #for li in lis: title = sel.xpath('//div[@id=C-Main-Article-QQ]/div[1]/text()').extract() content =sel.xpath('//div[@id=Cnt-Main-Article-QQ]/p/text()').extract() print title </code></pre> <p>when running cmd scrapy crawl News1</p> <p>I cant get the title in command window ,Could you please tell me how to revise it and why? thanks</p>
1
2016-08-28T16:05:35Z
39,193,247
<p>You're subclassing <code>Spider</code>, but since you have <code>start_urls</code>, I think you meant to use <code>CrawlSpider</code>. In this case, you need to revise your structure, since <code>parse</code> is actually used internally by <code>CrawlSpider</code> to find new links to crawl:</p> <pre><code>rules = ( Rule(LxmlLinkExtractor(restrict_xpaths='//div[@class="Q- tpList"]/div/a/@href'), callback='parse_page'), ) def parse_page(self, response): ... </code></pre> <p>You should fix this class name and remove the spaces as well:</p> <pre><code>//div[@class="Q- tpList"]/div/a/@href ^^^ </code></pre> <p>Finally, I think you're using an old version of Scrapy. I suggest you upgrade now before writing more code using the old API, since it'll be harder to switch later.</p>
0
2016-08-28T16:11:10Z
[ "python", "scrapy", "web-crawler" ]
scrapy LxmlLinkExtractor to crawl relative urls
39,193,198
<p>I want to crawl all the relative urls under tag in <a href="http://news.qq.com/" rel="nofollow">http://news.qq.com/</a></p> <p>the code of mine is that:</p> <pre><code>import scrapy from scrapy.selector import Selector from homework.items import HomeworkItem from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.lxmlhtml import LxmlLinkExtractor class News1Spider(scrapy.Spider): name = "News1" allowed_domains = ["http://news.qq.com/"] start_urls = ( 'http://news.qq.com/', ) rules = ( Rule(LxmlLinkExtractor(restrict_xpaths='//div[@class="Q- tpList"]/div/a/@href'),callback='parse'), ) def parse(self, response): sel = Selector(response) #lis = sel.xpath('//div[@class="Q-tpList"]') #item = TutorialItem() #for li in lis: title = sel.xpath('//div[@id=C-Main-Article-QQ]/div[1]/text()').extract() content =sel.xpath('//div[@id=Cnt-Main-Article-QQ]/p/text()').extract() print title </code></pre> <p>when running cmd scrapy crawl News1</p> <p>I cant get the title in command window ,Could you please tell me how to revise it and why? thanks</p>
1
2016-08-28T16:05:35Z
39,203,066
<p>First thing you are either using an outdate scrapy version or having bad imports since right now scrapy has only 1 type of link extractors - LinkExtractor (which is renamed LxmlExtractor)</p> <p>I've tested this and it works perfectly fine:</p> <pre><code>$ scrapy shell 'http://news.qq.com/' from scrapy.linkextractors import LinkExtractor LinkExtractor(restrict_xpaths=['//div[@class="Q-tpList"]/div/a']).extract_links(response) # got 43 results </code></pre> <p>Note no spaces in xpath <code>@class</code> check and it points to <code>a</code> node rather than <code>@href</code> attribute because LinkExtractor extract nodes not parameters.</p>
0
2016-08-29T09:40:54Z
[ "python", "scrapy", "web-crawler" ]
Get first letter with maximum occurence of a string
39,193,241
<p>I would like to get the first letter with the maximum occurence of a string.</p> <p>For instance:</p> <pre><code> "google" -&gt; g "azerty" -&gt; a "bbbaaa" -&gt; b </code></pre> <p>I already have a working code, using <a href="https://docs.python.org/3/library/collections.html#collections.Counter">OrdererDict()</a> to avoid automatic keys rearangement:</p> <pre><code>from collections import OrderedDict sentence = "google" d = OrderedDict() for letter in sentence: if letter not in d.keys(): d[letter] = sentence.count(letter) print(max(d, key=d.get)) # g </code></pre> <p>but I'm looking for a possible one-liner or more elegant solution (if it's possible).</p> <p><strong>Note:</strong> I already tried to use <a href="https://docs.python.org/3/library/collections.html#collections.Counter">Counter()</a> but it doesn't work, since dict in python don't remember the order that keys were inserted. </p> <p>e.g</p> <pre><code>from collections import Counter sentence = "bbbaaa" c = Counter(sentence) print(c.most_common()[0][0]) # have 50% chances of printing 'a' rather than 'b'. </code></pre> <p>Bonus question: Can someone explains why OrderedDict() are not the default dictionary behavior in python?</p>
6
2016-08-28T16:10:42Z
39,193,335
<p>The documentation for <code>collections.OrderedDict</code> actually has <a href="https://docs.python.org/3/library/collections.html#ordereddict-examples-and-recipes">a recipe for an <code>OrderedCounter</code></a>:</p> <pre><code>In [5]: from collections import Counter, OrderedDict In [6]: class OrderedCounter(Counter, OrderedDict): ...: pass ...: In [7]: OrderedCounter("google").most_common()[0][0] Out[7]: 'g' </code></pre>
6
2016-08-28T16:20:46Z
[ "python", "string", "python-3.x", "dictionary" ]
Get first letter with maximum occurence of a string
39,193,241
<p>I would like to get the first letter with the maximum occurence of a string.</p> <p>For instance:</p> <pre><code> "google" -&gt; g "azerty" -&gt; a "bbbaaa" -&gt; b </code></pre> <p>I already have a working code, using <a href="https://docs.python.org/3/library/collections.html#collections.Counter">OrdererDict()</a> to avoid automatic keys rearangement:</p> <pre><code>from collections import OrderedDict sentence = "google" d = OrderedDict() for letter in sentence: if letter not in d.keys(): d[letter] = sentence.count(letter) print(max(d, key=d.get)) # g </code></pre> <p>but I'm looking for a possible one-liner or more elegant solution (if it's possible).</p> <p><strong>Note:</strong> I already tried to use <a href="https://docs.python.org/3/library/collections.html#collections.Counter">Counter()</a> but it doesn't work, since dict in python don't remember the order that keys were inserted. </p> <p>e.g</p> <pre><code>from collections import Counter sentence = "bbbaaa" c = Counter(sentence) print(c.most_common()[0][0]) # have 50% chances of printing 'a' rather than 'b'. </code></pre> <p>Bonus question: Can someone explains why OrderedDict() are not the default dictionary behavior in python?</p>
6
2016-08-28T16:10:42Z
39,193,379
<p>Probably not very fast, but one-liner!</p> <pre><code>&gt;&gt;&gt; s = "aaabbbbc" &gt;&gt;&gt; sorted(s, key=lambda c: (-s.count(c), s.index(c)))[0] 'b' </code></pre> <p><strong>Edit</strong></p> <p>Even shorter, thanks to @Ohad Eytan's comment:</p> <pre><code>&gt;&gt;&gt; min(s, key=lambda c: (-s.count(c), s.index(c))) 'b' </code></pre> <p><strong>Benchmark</strong></p> <p>Feeling bored tonight, so I benchmarked (using <code>timeit</code>) test @Joohwan's <code>most_common_char()</code> solution (mostcc), @Blender's <code>OrderedCounter</code> solution (odict) and my own one liner solution (onelin, using the <code>min</code> variant). The fastest solution was consistently mostcc: up to ~10x faster than onelin for long strings containing few different characters, and up to ~4x faster than odict for very short strings. For short strings or strings with little repeated chars, onelin beats odict (otherwise, it's the reverse). Here are the details (Length=length of the string, #chars=number of different unicode chars to randomly pick from for each char, mostcc=time to execute 10,000 times mostcc, odict=how much longer odict was compared to mostcc, onelin=how much longer oneline was compared to mostcc).</p> <pre><code>Length #chars mostcc odict onelin 10 10: 0.08s 3.76x 1.61x 10 100: 0.10s 3.57x 1.27x 10 1000: 0.12s 3.12x 1.34x 100 10: 0.43s 1.96x 3.29x 100 100: 0.59s 2.16x 2.18x 100 1000: 0.80s 1.92x 1.72x 1000 10: 3.48s 1.56x 9.79x 1000 100: 3.44s 1.72x 6.43x 1000 1000: 6.55s 1.68x 3.30x </code></pre>
5
2016-08-28T16:25:35Z
[ "python", "string", "python-3.x", "dictionary" ]
Get first letter with maximum occurence of a string
39,193,241
<p>I would like to get the first letter with the maximum occurence of a string.</p> <p>For instance:</p> <pre><code> "google" -&gt; g "azerty" -&gt; a "bbbaaa" -&gt; b </code></pre> <p>I already have a working code, using <a href="https://docs.python.org/3/library/collections.html#collections.Counter">OrdererDict()</a> to avoid automatic keys rearangement:</p> <pre><code>from collections import OrderedDict sentence = "google" d = OrderedDict() for letter in sentence: if letter not in d.keys(): d[letter] = sentence.count(letter) print(max(d, key=d.get)) # g </code></pre> <p>but I'm looking for a possible one-liner or more elegant solution (if it's possible).</p> <p><strong>Note:</strong> I already tried to use <a href="https://docs.python.org/3/library/collections.html#collections.Counter">Counter()</a> but it doesn't work, since dict in python don't remember the order that keys were inserted. </p> <p>e.g</p> <pre><code>from collections import Counter sentence = "bbbaaa" c = Counter(sentence) print(c.most_common()[0][0]) # have 50% chances of printing 'a' rather than 'b'. </code></pre> <p>Bonus question: Can someone explains why OrderedDict() are not the default dictionary behavior in python?</p>
6
2016-08-28T16:10:42Z
39,193,424
<p>You can use <code>Counter()</code> together with <code>next()</code> to find the first letter that meets the condition:</p> <pre><code>&gt;&gt;&gt; s = "google" &gt;&gt;&gt; c = Counter(s) &gt;&gt;&gt; next(x for x in s if c[x] == c.most_common(1)[0][1]) 'g' </code></pre>
2
2016-08-28T16:30:41Z
[ "python", "string", "python-3.x", "dictionary" ]
Get first letter with maximum occurence of a string
39,193,241
<p>I would like to get the first letter with the maximum occurence of a string.</p> <p>For instance:</p> <pre><code> "google" -&gt; g "azerty" -&gt; a "bbbaaa" -&gt; b </code></pre> <p>I already have a working code, using <a href="https://docs.python.org/3/library/collections.html#collections.Counter">OrdererDict()</a> to avoid automatic keys rearangement:</p> <pre><code>from collections import OrderedDict sentence = "google" d = OrderedDict() for letter in sentence: if letter not in d.keys(): d[letter] = sentence.count(letter) print(max(d, key=d.get)) # g </code></pre> <p>but I'm looking for a possible one-liner or more elegant solution (if it's possible).</p> <p><strong>Note:</strong> I already tried to use <a href="https://docs.python.org/3/library/collections.html#collections.Counter">Counter()</a> but it doesn't work, since dict in python don't remember the order that keys were inserted. </p> <p>e.g</p> <pre><code>from collections import Counter sentence = "bbbaaa" c = Counter(sentence) print(c.most_common()[0][0]) # have 50% chances of printing 'a' rather than 'b'. </code></pre> <p>Bonus question: Can someone explains why OrderedDict() are not the default dictionary behavior in python?</p>
6
2016-08-28T16:10:42Z
39,193,439
<p>You can also fix the issue you describe at the end of your question about using Counter by having the resulting list sorted by various attributes: firstly count, secondly lexicographical order like this:</p> <pre><code>from collections import Counter sentence = "google" c = Counter(sentence) print(sorted(c.most_common(), key = lambda x: (-x[1], sentence.index(x[0])))) </code></pre> <p>Output:</p> <pre><code>=&gt; [('g', 2), ('o', 2), ('l', 1), ('e', 1)] </code></pre> <p>Just for fun:</p> <p><em>Golfed Version</em>:</p> <pre><code># If your sentence is s: print(sorted(collections.Counter(s).most_common(),key=lambda x:(-x[1],s.index(x[0])))) </code></pre>
1
2016-08-28T16:31:49Z
[ "python", "string", "python-3.x", "dictionary" ]
Get first letter with maximum occurence of a string
39,193,241
<p>I would like to get the first letter with the maximum occurence of a string.</p> <p>For instance:</p> <pre><code> "google" -&gt; g "azerty" -&gt; a "bbbaaa" -&gt; b </code></pre> <p>I already have a working code, using <a href="https://docs.python.org/3/library/collections.html#collections.Counter">OrdererDict()</a> to avoid automatic keys rearangement:</p> <pre><code>from collections import OrderedDict sentence = "google" d = OrderedDict() for letter in sentence: if letter not in d.keys(): d[letter] = sentence.count(letter) print(max(d, key=d.get)) # g </code></pre> <p>but I'm looking for a possible one-liner or more elegant solution (if it's possible).</p> <p><strong>Note:</strong> I already tried to use <a href="https://docs.python.org/3/library/collections.html#collections.Counter">Counter()</a> but it doesn't work, since dict in python don't remember the order that keys were inserted. </p> <p>e.g</p> <pre><code>from collections import Counter sentence = "bbbaaa" c = Counter(sentence) print(c.most_common()[0][0]) # have 50% chances of printing 'a' rather than 'b'. </code></pre> <p>Bonus question: Can someone explains why OrderedDict() are not the default dictionary behavior in python?</p>
6
2016-08-28T16:10:42Z
39,193,896
<p>I am aware that you want a one-liner, but what if you had to repeat this task many times or handle really long sentences? I don't know the exact use case here but it could be worth your time considering the space and time complexity of the algorithm.</p> <p>In your solution, for example, you are iterating through the sentence many times more than necessary with <code>sentence.count()</code>, which takes <code>O(n * number of unique characters)</code>. After that you iterate through the ordereddict once more to find the max (another <code>O(number of unique characters)</code> operation).</p> <p>In the accepted solution, we end up having to define a new class (which breaks your 1 liner requirement btw) and instantiate new objects with alot of boilerplate code and functionalities you probably won't need every time you want to execute your task.</p> <p>If you don't mind having a few more lines of code (again, I know this is not what the question is asking), we can build a reusable function which only has to iterate through the string <strong>once</strong> and use constant and minimal space:</p> <pre><code>from collections import defaultdict def most_common_char(sentence): if not sentence: return '' max_count = 1 max_char = sentence[-1] char_counts = defaultdict(int) char_counts[max_char] = 1 for i in xrange(len(sentence) - 2, -1, -1): char = sentence[i] char_counts[char] += 1 if char_counts[char] &gt;= max_count: max_count = char_counts[char] max_char = char return max_char </code></pre> <p>We keep track of the character with the max count <strong>as</strong> we go through the string and spit it out at the end of the iteration. Note that we iterate <em>backwards</em> since you want the letter that comes first (i.e. last updated wins).</p>
3
2016-08-28T17:19:59Z
[ "python", "string", "python-3.x", "dictionary" ]
Log in to ASP website using Python's Requests module
39,193,278
<p>Im trying to webscrap some information from my school page, but im having hard time to get past login. I know there are similar threeds, i have spend whole day reading, but cannot make it work. </p> <p>This is program im using (User name and password were changed):</p> <pre><code>import requests payload = {'ctl00$cphmain$Loginname': 'name', 'ctl00$cphmain$TextBoxHeslo': 'password'} page = requests.post('http://gymnaziumbma.no-ip.org:81/login.aspx', payload) open_page = requests.get("http://gymnaziumbma.no-ip.org:81/prehled.aspx?s=44&amp;c=prub") #Check content if page.text == open_page.text: print("Same page") else: print(open_page.text) print("Different page!") </code></pre> <p>Can you tell me, what im doing wrong? Am i missing some parameter? Is requests good metod for this? I was trying robobrowser and BeautifulSoup, but doesnt work either. I bet im missing something really trivial.</p> <p>Im using Python 3.5 </p>
0
2016-08-28T16:14:41Z
39,204,230
<p>First off, you are not using a <a href="http://docs.python-requests.org/en/master/user/advanced/#session-objects" rel="nofollow">Session</a> so even if your first post successfully logs you on the second knows nothing about it. Second, you are missing data that needs to be posted, <em>__VIEWSTATEGENERATOR</em> and <em>__VIEWSTATE</em> which you can parse from the source using <em>BeautifulSoup</em>:</p> <pre><code>from bs4 import BeautifulSoup data = {'ctl00$cphmain$Loginname': 'name', 'ctl00$cphmain$TextBoxHeslo': 'password'} # A Session object will persist the login cookies. with requests.Session() as s: page = s.get('http://gymnaziumbma.no-ip.org:81/login.aspx').content soup = BeautifulSoup(page) data["___VIEWSTATE"] = soup.select_one("#__VIEWSTATE")["value"] data["__VIEWSTATEGENERATOR"] = soup.select_one("#__VIEWSTATEGENERATOR")["value"] s.post('http://gymnaziumbma.no-ip.org:81/login.aspx', data=data) open_page = s.get("http://gymnaziumbma.no-ip.org:81/prehled.aspx?s=44&amp;c=prub") #Check content if page.text == open_page.text: print("Same page") else: print(open_page.text) print("Different page!") </code></pre> <p>You can see all the form data that gets posted in Chrome dev tools.</p> <p><a href="http://i.stack.imgur.com/yxgky.png" rel="nofollow"><img src="http://i.stack.imgur.com/yxgky.png" alt="enter image description here"></a></p> <p>What is posted above should be enough to get logged in, if not any value you need can be parsed from the login table using BeautifulSoup.</p>
0
2016-08-29T10:39:21Z
[ "python", "asp.net", "login", "web-scraping", "python-requests" ]
How to get top of keys from dict by values?
39,193,279
<p>I have dictionary:</p> <pre><code>{ "key1" : 1, "key2" : 2, ...., "key100" : 100 } </code></pre> <p>I want to get list top5 keys by sort values from this dictionary:</p> <pre><code>[ "key100", "key99",.. "key95" ] </code></pre> <p>How to do it ?</p>
0
2016-08-28T16:14:41Z
39,193,322
<p>Just sort keys using lambda function to return value as key, reversed, and take the 5 first values:</p> <pre><code>d={ "key1" : 1, "key2" : 2, "key3" : 3, "key200" : 200 , "key100" : 100 , "key400" : 400} print(sorted(d.keys(),reverse=True,key=lambda x : d[x] )[:5]) </code></pre> <p>output:</p> <pre><code>['key400', 'key200', 'key100', 'key3', 'key2'] </code></pre>
4
2016-08-28T16:19:16Z
[ "python" ]
How to get top of keys from dict by values?
39,193,279
<p>I have dictionary:</p> <pre><code>{ "key1" : 1, "key2" : 2, ...., "key100" : 100 } </code></pre> <p>I want to get list top5 keys by sort values from this dictionary:</p> <pre><code>[ "key100", "key99",.. "key95" ] </code></pre> <p>How to do it ?</p>
0
2016-08-28T16:14:41Z
39,193,400
<pre><code>d = { "key1" : 1, "key2" : 2, ...., "key100" : 100 } a = sorted(d.values()) a.reverse() req_list = [] for i in a[:5]: req_list.append(d.keys()[d.values().index(i)]) print req_list </code></pre> <p>This would give you the list with greatest 5 values. Is this what you wanted?</p>
0
2016-08-28T16:27:47Z
[ "python" ]
How to get top of keys from dict by values?
39,193,279
<p>I have dictionary:</p> <pre><code>{ "key1" : 1, "key2" : 2, ...., "key100" : 100 } </code></pre> <p>I want to get list top5 keys by sort values from this dictionary:</p> <pre><code>[ "key100", "key99",.. "key95" ] </code></pre> <p>How to do it ?</p>
0
2016-08-28T16:14:41Z
39,193,657
<pre><code>Python 2.7.10 (default, Oct 23 2015, 19:19:21) &gt;&gt;&gt; d = {"key1": 1, "key2": 2, "key3": 3, "key98": 98 , "key99": 99 , "key100": 100} &gt;&gt;&gt; sorted(d, reverse=True, key=d.get)[:3] ['key100', 'key99', 'key98'] </code></pre>
0
2016-08-28T16:53:24Z
[ "python" ]
How To Open A Custom File Extension as .txt Using Python
39,193,307
<p>I'm making a code that will create a new form of file extension (in this case .aobj, which will be used to help me make games easier). I tried using the code below (this is using Python)</p> <pre><code>print "Starting..." info = [] part1 = open('temporary.aobj', 'r') part2 = part1.readlines() for line in part2: info.append(line) print info </code></pre> <p>Instead of this printing out what's actually in the file when i used notepad, it shows this:</p> <pre><code>Starting... [[...], [...], [...]] </code></pre> <p>I'm guessing this is because it doesn't recognize the file format, but how can i fix this? </p>
0
2016-08-28T16:17:49Z
39,193,387
<p>You are printing info, which is an object somewhat similar to nested list. </p> <pre><code>a = [[1,2],[3,4]] print (a) </code></pre> <p>This prints<br> [[1, 2], [3, 4]]</p> <pre><code>for i in a: print(i) </code></pre> <p>This prints <br> [1, 2] [3, 4]</p> <pre><code>for i in a: for j in i: print(j,end=' ') print() </code></pre> <p>This prints<br> 1 2<br> 3 4 </p> <p>Which is what you seem to want. So, instead of printing the info object as is, do something like this-</p> <pre><code>for line in info: for word in line: print(word,end=' ') print() </code></pre> <p>PS: My codes are for Python3. There shouldn't be many differences for Python2.</p>
0
2016-08-28T16:26:36Z
[ "python", "file" ]
How To Open A Custom File Extension as .txt Using Python
39,193,307
<p>I'm making a code that will create a new form of file extension (in this case .aobj, which will be used to help me make games easier). I tried using the code below (this is using Python)</p> <pre><code>print "Starting..." info = [] part1 = open('temporary.aobj', 'r') part2 = part1.readlines() for line in part2: info.append(line) print info </code></pre> <p>Instead of this printing out what's actually in the file when i used notepad, it shows this:</p> <pre><code>Starting... [[...], [...], [...]] </code></pre> <p>I'm guessing this is because it doesn't recognize the file format, but how can i fix this? </p>
0
2016-08-28T16:17:49Z
39,194,417
<p>I was experimenting and found out that it would allow you to read the format properly as long as you wrote the info using python's write() function. As so:</p> <pre><code>file = open('temporary.aobj', 'r+') file.write('foo') info = file.readlines() lines = [] for line in info: lines.append(line) print lines </code></pre> <p>This will print out the info that is inside of it, it's slightly slower because you are required to write all the info using python.</p>
0
2016-08-28T18:21:33Z
[ "python", "file" ]
How to extract content between a prefix and a suffix?
39,193,338
<p>I want to extract text from {inside} the curly brackets. The differences between those texts are the prefixes, such as <code>\section{</code> or <code>\subsection{</code> to categorize everything accordingly. And every end needs to be set by the next closed curly bracket <code>}</code>.</p> <pre><code>file = "This is a string of an \section{example file} used for \subsection{Latex} documents." # These are some Latex commands to be considered: heading_1 = "\\\\section{" heading_2 = "\\\\subsection{" # This is my attempt. for letter in file: print("The current letter: " + letter + "\n") </code></pre> <p>I want to process a Latex file by using Python to convert it for my database.</p>
0
2016-08-28T16:20:51Z
39,193,922
<p>I think you want to use the regular expression module. </p> <pre><code>import re s = "This is a string of an \section{example file} used for \subsection{Latex} documents." pattern = re.compile(r'\\(?:sub)?section\{(.*?)\}') re.findall(pattern, s) #output: ['example file', 'Latex'] </code></pre>
0
2016-08-28T17:23:46Z
[ "python", "latex" ]
How to extract content between a prefix and a suffix?
39,193,338
<p>I want to extract text from {inside} the curly brackets. The differences between those texts are the prefixes, such as <code>\section{</code> or <code>\subsection{</code> to categorize everything accordingly. And every end needs to be set by the next closed curly bracket <code>}</code>.</p> <pre><code>file = "This is a string of an \section{example file} used for \subsection{Latex} documents." # These are some Latex commands to be considered: heading_1 = "\\\\section{" heading_2 = "\\\\subsection{" # This is my attempt. for letter in file: print("The current letter: " + letter + "\n") </code></pre> <p>I want to process a Latex file by using Python to convert it for my database.</p>
0
2016-08-28T16:20:51Z
39,194,739
<p>If you just want the pairs <code>(section-level, title)</code> for all the file you can use a simple regex:</p> <pre><code>import re codewords = [ 'section', 'subsection', # add other here if you want to ] regex = re.compile(r'\\({})\{{([^}}]+)\}}'.format('|'.join(re.escape(word) for word in codewords))) </code></pre> <p>Sample usage:</p> <pre><code>In [15]: text = ''' ...: \section{First section} ...: ...: \subsection{Subsection one} ...: ...: Some text ...: ...: \subsection{Subsection two} ...: ...: Other text ...: ...: \subsection{Subsection three} ...: ...: Some other text ...: ...: ...: Also some more text \texttt{other stuff} ...: ...: \section{Second section} ...: ...: \section{Third section} ...: ...: \subsection{Last subsection} ...: ''' In [16]: regex.findall(text) Out[16]: [('section', 'First section'), ('subsection', 'Subsection one'), ('subsection', 'Subsection two'), ('subsection', 'Subsection three'), ('section', 'Second section'), ('section', 'Third section'), ('subsection', 'Last subsection')] </code></pre> <p>By changing the value of the <code>codewords</code> list you'll be able to match more kind of commands.</p> <p>To apply this to a file simply <code>read()</code> it first:</p> <pre><code>with open('myfile.tex') as f: regex.findall(f.read()) </code></pre> <p>If you have the guarantee that all those commands are on the same line then you can be more memory efficient and do:</p> <p>with open('myfile.tex') as f: results = [] for line in f: results.extends(regex.findall(line))</p> <p>Or if you want to be a bit more fancy:</p> <pre><code>from itertools import chain with open('myfile.tex') as f: results = chain.from_iterable(map(regex.findall, f)) </code></pre> <p>Note however that if you have something like:</p> <pre><code>\section{A very long title} </code></pre> <p>This will fail, why the solution using <code>read()</code> will get that section too.</p> <hr> <p>In any case you have to be aware that the slightest change in format will break these kind of solutions. As such for a safer alternative you'll have to look for a proper LaTeX parser.</p> <hr> <p>If you want to group together the subsections "contained" in a given section you can do so after obtaining the result with the above solution. You have to use something like <code>itertools.groupby</code>.</p> <p>from itertools import groupby, count, chain</p> <pre><code>results = regex.findall(text) def make_key(counter): def key(match): nonlocal counter val = next(counter) if match[0] == 'section': val = next(counter) counter = chain([val], counter) return val return key organized_result = {} for key, group in groupby(results, key=make_key(count())): _, section_name = next(group) organized_result[section_name] = section = [] for _, subsection_name in group: section.append(subsection_name) </code></pre> <p>And the final result will be:</p> <pre><code>In [12]: organized_result Out[12]: {'First section': ['Subsection one', 'Subsection two', 'Subsection three'], 'Second section': [], 'Third section': ['Last subsection']} </code></pre> <p>Which matches the structure of the text at the beginning of the post.</p> <p>If you want to make this extensible using the <code>codewords</code> list things will get quite a bit more complex. </p>
0
2016-08-28T18:56:57Z
[ "python", "latex" ]
Assistance with Python regex
39,193,354
<p>I have the following strings.</p> <p>Example:</p> <ul> <li>12 CG GRB</li> <li>6GRC 11.2 MK</li> <li>2 GR 1.75LRG</li> </ul> <p>And I would like to break them to the following group</p> <ul> <li>[12,CG] [GRB]</li> <li>[6,GRC] [11.2,MK]</li> <li>[2,GR] [1.75,LRG]</li> </ul> <p>I'm using this regex - (\d+.?\d*).*?([A-Z]+) but with it, I'm unable to capture the first example correctly. Instead of [12,CG] [GRB], i get [12,CG].</p> <p>Any help will be much appreciated.</p> <pre><code>import re p = re.compile(ur'(\d+\.?\d*).*?([A-Z]+)') test_str = u"12 CG GRB" re.findall(p, test_str) </code></pre>
0
2016-08-28T16:22:31Z
39,193,452
<p>You may replace the <code>.*?</code> with a <code>\s*</code> to match zero or more whitespasces, and make the first capture group optional:</p> <pre><code>(\d*\.?\d+)?\s*([A-Z]+) ^^^^ </code></pre> <p>See the <a href="https://regex101.com/r/tK3tL1/1" rel="nofollow">regex demo</a>.</p> <p>Note I also modified the number matching subpattern to <code>\d*\.?\d+</code> to also mathc numbers like <code>.56</code>. You may keep your own pattern for that.</p> <p><em>Pattern details</em>:</p> <ul> <li><code>(\d*\.?\d+)?</code> - Optional group 1 capturing <ul> <li><code>\d*</code> - zero or more digits</li> <li><code>\.?</code> - an optional dot</li> <li><code>\d+</code> - 1 or more digits</li> </ul></li> <li><code>\s*</code> - zero or more whitespaces</li> <li><code>([A-Z]+)</code> - Group 2 capturing one or more uppercase ASCII letters.</li> </ul> <p>To get the capture group contents as a list of tuples, use a <code>re.findall</code> (<a href="http://ideone.com/NVwFPN" rel="nofollow">demo</a>):</p> <pre><code>import re p = re.compile(r'(\d*\.?\d+)?\s*([A-Z]+)') s = "12 CG GRB\n6GRC 11.2 MK\n2 GR 1.75LRG" print(p.findall(s)) </code></pre>
0
2016-08-28T16:32:47Z
[ "python", "regex" ]
Assistance with Python regex
39,193,354
<p>I have the following strings.</p> <p>Example:</p> <ul> <li>12 CG GRB</li> <li>6GRC 11.2 MK</li> <li>2 GR 1.75LRG</li> </ul> <p>And I would like to break them to the following group</p> <ul> <li>[12,CG] [GRB]</li> <li>[6,GRC] [11.2,MK]</li> <li>[2,GR] [1.75,LRG]</li> </ul> <p>I'm using this regex - (\d+.?\d*).*?([A-Z]+) but with it, I'm unable to capture the first example correctly. Instead of [12,CG] [GRB], i get [12,CG].</p> <p>Any help will be much appreciated.</p> <pre><code>import re p = re.compile(ur'(\d+\.?\d*).*?([A-Z]+)') test_str = u"12 CG GRB" re.findall(p, test_str) </code></pre>
0
2016-08-28T16:22:31Z
39,208,915
<pre><code>s = "12 CG GRB\n6GRC 11.2 MK\n2 GR 1.75LRG" re.split(r"(?&lt;!\d)\s", s) </code></pre> <p>The output is:</p> <pre><code>['12 CG', 'GRB', '6GRC', '11.2 MK', '2 GR', '1.75LRG'] </code></pre>
0
2016-08-29T14:39:15Z
[ "python", "regex" ]
Py_InitModule copies the name but not the function pointer?
39,193,366
<p>When I register callbacks using <code>Py_InitModule</code>, and if I later change the function pointer in the structure to point to a new function, the new function is called. But if I change the name, the new name is not recognized.</p> <pre><code>#include &lt;Python.h&gt; PyObject* foo1(PyObject *self, PyObject *args) { printf("foo1\n"); Py_RETURN_NONE; } PyObject* foo2(PyObject *self, PyObject *args) { printf("foo2\n"); Py_RETURN_NONE; } int main() { PyMethodDef methods[] = { { "foo", foo1, METH_VARARGS, "foo" }, { 0, 0, 0, 0 } }; Py_Initialize(); Py_InitModule("foo", methods); PyRun_SimpleString("import foo\n"); PyRun_SimpleString("foo.foo()\n"); methods[0].ml_meth = foo2; PyRun_SimpleString("foo.foo()\n"); methods[0].ml_name = "foo2"; PyRun_SimpleString("foo.foo()\n"); PyRun_SimpleString("foo.foo2()\n"); return 0; } </code></pre> <p>This gives the following output:</p> <pre>foo1 foo2 foo2 Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'foo2'</pre> <p>This seems a very inconsistent behavior. I first encountered it when I used a stack variable for <code>PyMethodDef methods</code>, which crashed the program once the variable went out of scope and I still tried to call the C++ callback from python. So I tested that changing the pointer indeed changes which function is called even though I haven't re-registered it with another <code>Py_InitModule</code> call. But at the same time, changing the name does not have this behavior.</p> <p>So far I'm pretty certain that <code>PyMethodDef</code> needs to live for as long as python code tries to call the methods (i.e. can't be stack/local variable), but only the function pointers themselves are used.</p> <p>Is this an intentional behavior, or some oversight? The documentation doesn't mention anything about PyMethodDef lifetime that I could find.</p>
1
2016-08-28T16:23:44Z
39,193,891
<p>The inconsistency you see arises from the difference between a function's code, which is the property of the function itself, and the name by which it is invoked from a module, which is the property of the module (key in its dict). While a function's name is also stored in the function object, it is only used for <code>repr</code> and is not a fundamental property of the function.</p> <p>This is quite intentional, as it allows using the same function object in different places under different names - or even without name, if the function is stored in a container. This would not be possible if one could "rename" it just by changing a property of the function.</p> <p>One can demonstrate this same difference using regular Python functions, like this:</p> <pre><code>&gt;&gt;&gt; def add(a, b): return a + b ... &gt;&gt;&gt; def sub(a, b): return a - b ... &gt;&gt;&gt; add &lt;function add at 0x7f9383127938&gt; # the function has a name &gt;&gt;&gt; add.__name__ = 'foo' &gt;&gt;&gt; add # the name is changed, but... &lt;function foo at 0x7f9383127938&gt; &gt;&gt;&gt; foo # the change doesn't affect the module Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'foo' is not defined &gt;&gt;&gt; add.__code__ = sub.__code__ # we can change the code, though &gt;&gt;&gt; add(2, 2) 0 </code></pre> <p>As for your question in the comment: the method fields are not copied because <code>Py_InitModule</code> and related functions are designed to be called with statically allocated structures, creating copies of which would be a waste of space. Not copying them explains why changing the actual C callback in <code>ml_meth</code> changes the Python callable.</p>
2
2016-08-28T17:19:07Z
[ "python", "c++", "python-embedding" ]
Merge counter.items() dictionaries into one dictionary
39,193,519
<p>How do I get the output of this code into one dictionary with total number of key:value pairs?</p> <pre><code>import re from collections import Counter splitfirst = open('output.txt', 'r') input = splitfirst.read() output = re.split('\n', input) for line in output: counter = Counter(line) ab = counter.items() #gives list of tuples will be converted to dict abdict = dict(ab) print abdict </code></pre> <p>Here is a sample of what I get:</p> <pre><code>{' ': 393, '-': 5, ',': 1, '.': 1} {' ': 382, '-': 4, ',': 5, '/': 1, '.': 5, '|': 1, '_': 1, '~': 1} {' ': 394, '-': 1, ',': 2, '.': 3} {'!': 1, ' ': 386, 'c': 1, '-': 1, ',': 3, '.': 3, 'v': 1, '=': 1, '\\': 1, '_': 1, '~': 1} {'!': 3, ' ': 379, 'c': 1, 'e': 1, 'g': 1, ')': 1, 'j': 1, '-': 3, ',': 2, '.': 1, 't': 1, 'z': 2, ']': 1, '\\': 1, '_': 2} </code></pre> <p>I have 400 of such dictionaries, and Ideally I have to merge them together, but if I understand correctly Counter does not give them all, rather gives them all one after another.</p> <p>Any help would be appreciated. </p>
1
2016-08-28T16:40:18Z
39,193,551
<p>The <code>+</code> operator merges counters:</p> <pre><code>&gt;&gt;&gt; Counter('hello') + Counter('world') Counter({'l': 3, 'o': 2, 'e': 1, 'r': 1, 'h': 1, 'd': 1, 'w': 1}) </code></pre> <p>so you can use <code>sum</code> to combine a collection of them:</p> <pre><code>from collections import Counter with open('output.txt', 'r') as f: lines = list(f) counters = [Counter(line) for line in lines] combined = sum(counters, Counter()) </code></pre> <p>(You also don’t need to use regular expressions to split files into lines; they’re already iterables of lines.)</p>
1
2016-08-28T16:43:43Z
[ "python", "python-2.7", "dictionary", "merge", "counter" ]
Merge counter.items() dictionaries into one dictionary
39,193,519
<p>How do I get the output of this code into one dictionary with total number of key:value pairs?</p> <pre><code>import re from collections import Counter splitfirst = open('output.txt', 'r') input = splitfirst.read() output = re.split('\n', input) for line in output: counter = Counter(line) ab = counter.items() #gives list of tuples will be converted to dict abdict = dict(ab) print abdict </code></pre> <p>Here is a sample of what I get:</p> <pre><code>{' ': 393, '-': 5, ',': 1, '.': 1} {' ': 382, '-': 4, ',': 5, '/': 1, '.': 5, '|': 1, '_': 1, '~': 1} {' ': 394, '-': 1, ',': 2, '.': 3} {'!': 1, ' ': 386, 'c': 1, '-': 1, ',': 3, '.': 3, 'v': 1, '=': 1, '\\': 1, '_': 1, '~': 1} {'!': 3, ' ': 379, 'c': 1, 'e': 1, 'g': 1, ')': 1, 'j': 1, '-': 3, ',': 2, '.': 1, 't': 1, 'z': 2, ']': 1, '\\': 1, '_': 2} </code></pre> <p>I have 400 of such dictionaries, and Ideally I have to merge them together, but if I understand correctly Counter does not give them all, rather gives them all one after another.</p> <p>Any help would be appreciated. </p>
1
2016-08-28T16:40:18Z
39,193,680
<p>Here's a <a href="http://stackoverflow.com/help/mcve">mcve</a> of your problem:</p> <pre><code>import re from collections import Counter data = """this is the first line this is the second one this is the last one """ output = Counter() for line in re.split('\n', data): output += Counter(line) print output </code></pre> <p>Applying the method in your example you'd get this:</p> <pre><code>import re from collections import Counter with open('output.txt', 'r') as f: data = f.read() output = Counter() for line in re.split('\n', data): output += Counter(line) print output </code></pre>
0
2016-08-28T16:57:21Z
[ "python", "python-2.7", "dictionary", "merge", "counter" ]
How to create a dynamic SQL query
39,193,527
<p>I have a large sqlite table of 33k records (movies) . I want to give the user the ability to search in that table via filters . Each movie record has 10 fields : Actors, Directors, Runtime, Genre, Rating and few more . The only filters available for the user to use are people (Include Actors and Directors), Genre, Rating and Runtime . </p> <p>The problem is that the user can use two filters or more, hence we don't really know which filter will be used . Filters values are passed via an HTTP req to the server which process it and create an SQL query based on filters to execute on the db .</p> <p>What I can't understand is how can I create an SQL query if I don't know which filters will be used ? Because only used filters will be sent to the server .</p> <p>Basically I want to find a way to create an SQL query based on sent filters by each users . </p>
0
2016-08-28T16:40:55Z
39,193,642
<p>If you're given a list of filters, you can just apply <code>Query.filter_by()</code> or <code>Query.filter()</code> over and over:</p> <pre><code>filters = [ ('rating', 3), ('runtime', 90), ('genre', 'documentary') ] query = session.query(Movie) for column, value in filters: # Make sure `column` and `value` are legal values! query = query.filter_by(**{column: value}) </code></pre> <p>Since the query is evaluated only at the end, you're essentially doing:</p> <pre><code>query = query.filter_by(...).filter_by(...) ... </code></pre> <p>In the last line, <code>filter_by(**{column: value})</code> is notation for <code>filter_by(value_of_column_variable=value)</code>.</p>
2
2016-08-28T16:52:10Z
[ "python", "sql", "sqlalchemy", "flask-sqlalchemy" ]
Make image to use it like character in pygame
39,193,549
<p>I'm beginner with using pygame but i saw a website that provide a tutorial and he used character in the program </p> <p>here it is <a href="http://i.stack.imgur.com/lKN08.png" rel="nofollow"><img src="http://i.stack.imgur.com/lKN08.png" alt="enter image description here"></a> </p> <p>so my question is can i make a character like this or not and if yes is there is any websites that can me make something like this </p>
-7
2016-08-28T16:43:27Z
39,196,738
<p>Your question is vague: Do you want to MAKE a character or make an image BEHAVE like a character?</p> <p><strong>If you wanted to make a character</strong><br> If you wanted to make a character, I suggest going to <a href="http://pixelartor.com/" rel="nofollow">PixelArtor</a> and choosing the file size you want. I recommend 64 by 64 or 128 by 128, because if you choose 32 by 32 or below, it might be too small. If you are on a Unix system, there might already be an installation package for <a href="http://gimp.org" rel="nofollow">GIMP</a> on there, so go to downloads page and read the instructions on how you install it. If there isn't you can download it on the downloads page. (I'm running Windows, so I wouldn't know for sure)</p> <p>You can then display the image on your PyGame screen like so:</p> <pre><code>import pygame from pygame.locals import * display = pygame.display.set_mode((1024,1024)) # window size is determined here pygame.init() character = pygame.image.load("your/path/to/character.png") display.blit(character,(0,0)) # These are the X and Y coordinates pygame.display.update() </code></pre> <p>But of course, that creates a still image that will not move no matter what keys you press.</p> <p><strong>If you want a loaded image to behave like a character</strong></p> <pre><code>import pygame from pygame.locals import * display = pygame.display.set_mode((1024,1024)) # window size is determined here pygame.init() character = pygame.image.load("your/path/to/character.png") background = pygame.image.load("your/path/to/background.png") characterx = 0 charactery = 0 while True: display.blit(background,(0,0)) display.blit(character,(characterx,charactery)) for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_a: characterx -= 2 if event.key == K_d: characterx += 2 if event.key == K_w: charactery -= 2 if event.key == K_s: charactery += 2 if event.type == QUIT: pygame.quit() exit() pygame.display.update() </code></pre> <p>Okay, so in this code, the objects in play are: characterx and charactery store the X and Y positions of the loaded image character. These change when keys are pressed, changing where the character is displayed, simulating movement. The event loop is the line that starts <code>for event in pygame.event.get():</code> This loop handles events like mouse movement, clicking, keyboard detection, and quitting. The background is so that the extra trails left by the character don't show up. Try removing the line <code>display.blit(background,(0,0))</code> and you will see that the character "trail" is left behind.</p>
0
2016-08-28T23:31:43Z
[ "python", "python-2.7", "pygame" ]
Object Persistence in SqlAlchemy - Adding Self to a database
39,193,592
<p>I have an object which I am trying to add persistence to using sqlalchemy to allow for a local lookup of the object if I've already created an instance of it before. Within the init statement for the object, I have the following code:</p> <pre><code>persistent = session.query(exists().where(myobject.myfield==self.myfield)).scalar() if not persistent: self.create_object_from_scratch() session.add(myfield, self) session.commit() else: self.utilize_object_in_database() </code></pre> <p>As per the above, the object can determine if it is already in the database by whether the primary key myfield is in the database. If it is not, I would like to create the object and then add it into the session and commit. The database structure that I've set up is just two columns... a primary key (string) and a BLOB which is supposed to represent my 'object' for retrieval. </p> <p>However, with this approach I get an UnmappedInstanceError : "Class '<strong>builtin</strong>.str' is not mapped. </p> <p>My question is, given what I am trying to accomplish here (persistence of a python object) am I approaching this correctly/efficiently? Is it possible to add 'self' into a database as a BLOB using sqlalchemy?</p>
0
2016-08-28T16:47:55Z
39,194,703
<p>Take a look at signature of <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.add" rel="nofollow"><code>session.add</code></a> method:</p> <pre><code>add(instance, _warn=True) </code></pre> <p>As you can see, you need to pass instance of class that you want to store. There is no need to specify primary key because you already did it when you <a href="http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping" rel="nofollow">declared a mapping</a> for this class. So the right way store this object is:</p> <pre><code>session.add(self) </code></pre> <p>The error message that you got means that you tried to add to session an instance of <code>str</code> and there is no mapping to any table in database declared for this datatype.</p>
1
2016-08-28T18:52:40Z
[ "python", "sqlalchemy" ]
GAE Python: How to use NDB KeyProperty models for many-to-one relationship?
39,193,684
<p>There are posts on how to <a href="http://stackoverflow.com/questions/14192331/how-to-set-an-ndb-keyproperty">set</a>, <a href="http://stackoverflow.com/questions/19868410/how-do-i-use-ndb-keyproperty-properly-in-this-situation">get</a>, <a href="http://stackoverflow.com/questions/14072491/app-engine-structured-property-vs-reference-property-for-one-to-many-relationsh">KeyProperty/StructuredProperty</a>, but nothing tells me how to use NDB for modeling many-to-one.</p> <p>I have two Models:</p> <pre><code>class Department(ndb.Model): department_id = ndb.IntegerProperty() name = ndb.StringProperty() class Student(ndb.Model): student_id = ndb.IntegerProperty() name = ndb.StringProperty() dept = ndb.KeyProperty(Kind=Department) </code></pre> <p>How is the many-to-one is ensured, i.e whenever there is an insert into student record, it has to validate department key w.r.t to department datastore? </p> <p>How do you insert student record to ensure many-to-one relationship?</p> <p>Option 1:</p> <pre><code># Insert student record without checking for valid dept id. GAE automatically validates student = Student(student_id=...., dept=ndb.Key(Department, input_dept_id)) </code></pre> <p>Option 2:</p> <pre><code># check for valid dept id and then insert student record dept_key = ndb.Key(Department, input_dept_id) if(dept_key.get()): student = Student(student_id=...., dept=dept_key) </code></pre> <p>I tried option 1 with an dept_id not in department entities and it was able to insert that student entity. I'm fairly new to GAE.</p>
1
2016-08-28T16:57:31Z
39,210,503
<p>According to the documentation (<a href="https://cloud.google.com/appengine/docs/python/datastore/entities" rel="nofollow">https://cloud.google.com/appengine/docs/python/datastore/entities</a>), "The Datastore API does not distinguish between creating a new entity and updating an existing one". That is, the put() method will either create a non-existing entity or update an existing one.</p> <p>So, Option 2 seems the way to go. (Option 1 indeed does not provide any validation)</p>
1
2016-08-29T16:01:57Z
[ "python", "google-app-engine" ]
I can't able to install gunicorn whitenoise in heroku
39,193,716
<p>I'm trying to deploy my <code>python-django website on heroku</code> .I used the command </p> <pre><code>(firstproject) $ pip install dj-database-url gunicorn whitenoise </code></pre> <p>I got an error like this</p> <pre><code>Requirement already satisfied (use --upgrade to upgrade): dj-database-url in /home/aparna/firstproject/lib/python3.4/site-packages Requirement already satisfied (use --upgrade to upgrade): gunicorn in /home/aparna/firstproject/lib/python3.4/site-packages Downloading/unpacking whitenose Could not find any downloads that satisfy the requirement whitenose Cleaning up... No distributions at all found for whitenose Storing debug log for failure in /home/aparna/.pip/pip.log </code></pre> <p>How can I solve this error to deploy my website on heroku?</p>
0
2016-08-28T17:01:37Z
39,194,127
<p>The error message is saying that you typed <code>whitenose</code> rather than <code>whitenoise</code>.</p>
0
2016-08-28T17:45:35Z
[ "python", "django", "heroku" ]
Python create indented string from a list
39,193,735
<p>I have a list of table of contents that I'd like to create into an indented string</p> <pre><code>list = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] </code></pre> <p>And the desired result is this:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>I've tried this:</p> <pre><code>toc = '' for tocitem in list: if re.match('(\d+)\.', tocitem): toc += tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc += '\t\t' + tocitem + '\n' </code></pre> <p>But the tabs are not recognized, that is I get this</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>What am I doing wrong?</p>
2
2016-08-28T17:03:17Z
39,193,785
<p>Reverse the order of <code>if re.match(...)</code> statements. All of your items pass the first test so the code never enters elif block.</p>
1
2016-08-28T17:08:52Z
[ "python" ]
Python create indented string from a list
39,193,735
<p>I have a list of table of contents that I'd like to create into an indented string</p> <pre><code>list = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] </code></pre> <p>And the desired result is this:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>I've tried this:</p> <pre><code>toc = '' for tocitem in list: if re.match('(\d+)\.', tocitem): toc += tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc += '\t\t' + tocitem + '\n' </code></pre> <p>But the tabs are not recognized, that is I get this</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>What am I doing wrong?</p>
2
2016-08-28T17:03:17Z
39,193,798
<p>Try this:</p> <pre><code>toc = '' for tocitem in list: if re.match('(\d+)\.(\d+)\.', tocitem): toc += '\t\t' + tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc +=tocitem + '\n' </code></pre>
1
2016-08-28T17:09:50Z
[ "python" ]
Python create indented string from a list
39,193,735
<p>I have a list of table of contents that I'd like to create into an indented string</p> <pre><code>list = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] </code></pre> <p>And the desired result is this:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>I've tried this:</p> <pre><code>toc = '' for tocitem in list: if re.match('(\d+)\.', tocitem): toc += tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc += '\t\t' + tocitem + '\n' </code></pre> <p>But the tabs are not recognized, that is I get this</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>What am I doing wrong?</p>
2
2016-08-28T17:03:17Z
39,193,805
<p>First, I use <code>lst</code> instead of <code>list</code>, because <code>list</code> is a function...</p> <p>Next, for this to work you need to match first the longest<br> series of numbers, then work down to the shortest one.</p> <pre><code>toc = '' for tocitem in lst: if re.match('(\d+)\.(\d+)\.(\d+)', tocitem): toc += '\t\t' + tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc += tocitem + '\n' </code></pre> <p>And there's the output:</p> <pre><code> 1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>Now, this was regarding your question.<br> However, I would do this without <code>if</code>s, more systematically<br> as follows:</p> <pre><code>toc = '' for tocitem in lst: s = re.match(r'\S+', tocitem).group(0) digits = [x for x in s.split('.') if x.strip() != ''] toc += (len(digits) - 1) * 4 * ' ' + tocitem + '\n' </code></pre> <p>The regex simply finds the first section up until the space,<br> then splits on dot and take all the items which are not blank.<br></p>
1
2016-08-28T17:10:13Z
[ "python" ]
Python create indented string from a list
39,193,735
<p>I have a list of table of contents that I'd like to create into an indented string</p> <pre><code>list = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] </code></pre> <p>And the desired result is this:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>I've tried this:</p> <pre><code>toc = '' for tocitem in list: if re.match('(\d+)\.', tocitem): toc += tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc += '\t\t' + tocitem + '\n' </code></pre> <p>But the tabs are not recognized, that is I get this</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>What am I doing wrong?</p>
2
2016-08-28T17:03:17Z
39,193,871
<p>The first if-condition matches also the other cases. So you have to switch the order, or make a more general approach:</p> <pre><code>toc = '' for tocitem in list: number = tocitem.split()[0] toc += '\t' * number.strip('.').count('.') + tocitem + '\n' </code></pre>
1
2016-08-28T17:17:12Z
[ "python" ]
Python create indented string from a list
39,193,735
<p>I have a list of table of contents that I'd like to create into an indented string</p> <pre><code>list = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] </code></pre> <p>And the desired result is this:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>I've tried this:</p> <pre><code>toc = '' for tocitem in list: if re.match('(\d+)\.', tocitem): toc += tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc += '\t\t' + tocitem + '\n' </code></pre> <p>But the tabs are not recognized, that is I get this</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>What am I doing wrong?</p>
2
2016-08-28T17:03:17Z
39,193,946
<p>Really interesting question! here's a possible solution which assumes your data isn't sorted.</p> <p><strong>python 2.x</strong>:</p> <pre><code>import re import random # Unordered data!!! lst = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] random.seed(1) random.shuffle(lst) # Creating TOC data = {v[:v.rindex(" ")]: v for v in lst} keys = sorted(data.keys(), key=lambda x: map( int, filter(lambda x: x, x.split('.')))) toc = '' for k in keys: number = data[k].split()[0] toc += '\t' * number.strip('.').count('.') + k + '\n' print toc </code></pre>
1
2016-08-28T17:26:23Z
[ "python" ]
Python create indented string from a list
39,193,735
<p>I have a list of table of contents that I'd like to create into an indented string</p> <pre><code>list = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] </code></pre> <p>And the desired result is this:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>I've tried this:</p> <pre><code>toc = '' for tocitem in list: if re.match('(\d+)\.', tocitem): toc += tocitem + '\n' elif re.match('(\d+)\.(\d+)', tocitem): toc += '\t' + tocitem + '\n' else: toc += '\t\t' + tocitem + '\n' </code></pre> <p>But the tabs are not recognized, that is I get this</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>What am I doing wrong?</p>
2
2016-08-28T17:03:17Z
39,194,002
<p>Given the sorted list with section titles:</p> <pre><code>li = ['1. Section', '1.1 Subsection', '1.1.1 Subsubsection', '1.1.2 Subsubsection', '2. Section', '2.1 Subsection', '2.1.1 Subsubsection', '2.1.2 Subsubsection', '2.2 Subsection', '2.2.1 Subsubsection'] </code></pre> <p>You can do:</p> <pre><code>print '\n'.join(['\t'*(len(re.findall(r"(\d+)", s))-1)+s for s in li]) </code></pre> <p>Prints:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre> <p>Given a random order list that you want to sort first:</p> <pre><code>li=['2.1.2 Subsubsection', '2.1.1 Subsubsection', '1.1.1 Subsubsection', '1. Section', '2. Section', '1.1 Subsection', '2.2 Subsection', '2.2.1 Subsubsection', '2.1 Subsection', '1.1.2 Subsubsection'] </code></pre> <p>You can sort and indent in one loop without a regex:</p> <pre><code>for n, s in sorted([(ni, si) for ni, _, si in [x.partition(' ') for x in li]]): print '\t'*(len([e for e in n.split('.') if e])-1)+n, s </code></pre> <p>Prints:</p> <pre><code>1. Section 1.1 Subsection 1.1.1 Subsubsection 1.1.2 Subsubsection 2. Section 2.1 Subsection 2.1.1 Subsubsection 2.1.2 Subsubsection 2.2 Subsection 2.2.1 Subsubsection </code></pre>
1
2016-08-28T17:31:54Z
[ "python" ]
Derivative of summations
39,193,771
<p>I am using sympy from time to time, but am not very good at it. At the moment I am stuck with defining a list of indexed variables, i.e. n1 to nmax and performing a summation on it. Then I want to be able to take the derivative:</p> <p>So far I tried the following:</p> <pre><code>numSpecies = 10 n = IndexedBase('n') i = symbols("i",cls=Idx) nges = summation(n[i],[i,1,numSpecies]) </code></pre> <p>However, if i try to take the derivative with respect to one variable, this fails:</p> <pre><code>diff(nges,n[5]) </code></pre> <p>I also tried to avoid working with <a href="http://docs.sympy.org/latest/modules/tensor/indexed.html" rel="nofollow"><code>IndexedBase</code></a>.</p> <pre><code>numSpecies = 10 n = symbols('n0:%d'%numSpecies) k = symbols('k',integer=True) ntot = summation(n[k],[k,0,numSpecies]) </code></pre> <p>However, here already the summation fails because mixing python tuples and the sympy summation.</p> <p>How I can perform indexedbase derivatives or some kind of workaround?</p>
8
2016-08-28T17:06:58Z
39,193,990
<p>I don't know why the <code>IndexedBase</code> approach does not work (I would be interested to know also). You can, however, do the following:</p> <pre><code>import sympy as sp numSpecies = 10 n = sp.symbols('n0:%d'%numSpecies) # note that n equals the tuple (n0, n1, ..., n9) ntot = sum(n) # sum elements of n using the standard # Python function for summing tuple elements #ntot = sp.Add(*n) # same result using Sympy function sp.diff(ntot, n[5]) </code></pre>
1
2016-08-28T17:30:46Z
[ "python", "sympy", "derivative" ]
Derivative of summations
39,193,771
<p>I am using sympy from time to time, but am not very good at it. At the moment I am stuck with defining a list of indexed variables, i.e. n1 to nmax and performing a summation on it. Then I want to be able to take the derivative:</p> <p>So far I tried the following:</p> <pre><code>numSpecies = 10 n = IndexedBase('n') i = symbols("i",cls=Idx) nges = summation(n[i],[i,1,numSpecies]) </code></pre> <p>However, if i try to take the derivative with respect to one variable, this fails:</p> <pre><code>diff(nges,n[5]) </code></pre> <p>I also tried to avoid working with <a href="http://docs.sympy.org/latest/modules/tensor/indexed.html" rel="nofollow"><code>IndexedBase</code></a>.</p> <pre><code>numSpecies = 10 n = symbols('n0:%d'%numSpecies) k = symbols('k',integer=True) ntot = summation(n[k],[k,0,numSpecies]) </code></pre> <p>However, here already the summation fails because mixing python tuples and the sympy summation.</p> <p>How I can perform indexedbase derivatives or some kind of workaround?</p>
8
2016-08-28T17:06:58Z
39,194,000
<p>I'm not clear about what you want to do. However, perhaps this will help. Edited in response to two comments received.</p> <pre><code>from sympy import * nspecies = 10 [var('n%s'%_) for _ in range(nspecies)] expr = sympify('+'.join(['n%s'%_ for _ in range(nspecies)])) expr print ( diff(expr,n1) ) expr = sympify('n0**n1+n1**n2') expr print ( diff(expr,n1) ) </code></pre> <p>Only the first expression responds to the original question. This is the output.</p> <pre><code>1 n0**n1*log(n0) + n1**n2*n2/n1 </code></pre>
1
2016-08-28T17:31:39Z
[ "python", "sympy", "derivative" ]
Derivative of summations
39,193,771
<p>I am using sympy from time to time, but am not very good at it. At the moment I am stuck with defining a list of indexed variables, i.e. n1 to nmax and performing a summation on it. Then I want to be able to take the derivative:</p> <p>So far I tried the following:</p> <pre><code>numSpecies = 10 n = IndexedBase('n') i = symbols("i",cls=Idx) nges = summation(n[i],[i,1,numSpecies]) </code></pre> <p>However, if i try to take the derivative with respect to one variable, this fails:</p> <pre><code>diff(nges,n[5]) </code></pre> <p>I also tried to avoid working with <a href="http://docs.sympy.org/latest/modules/tensor/indexed.html" rel="nofollow"><code>IndexedBase</code></a>.</p> <pre><code>numSpecies = 10 n = symbols('n0:%d'%numSpecies) k = symbols('k',integer=True) ntot = summation(n[k],[k,0,numSpecies]) </code></pre> <p>However, here already the summation fails because mixing python tuples and the sympy summation.</p> <p>How I can perform indexedbase derivatives or some kind of workaround?</p>
8
2016-08-28T17:06:58Z
39,202,749
<p>With SymPy's development version, your example works.</p> <p>To install SymPy's development version, just pull it down with <code>git</code>:</p> <pre><code>git clone git://github.com/sympy/sympy.git cd sympy </code></pre> <p>Then run python from that path or set the <code>PYTHONPATH</code> to include that directory before Python's default installation.</p> <p>Your example on the development version:</p> <pre><code>In [3]: numSpecies = 10 In [4]: n = IndexedBase('n') In [5]: i = symbols("i",cls=Idx) In [6]: nges = summation(n[i],[i,1,numSpecies]) In [7]: nges Out[7]: n[10] + n[1] + n[2] + n[3] + n[4] + n[5] + n[6] + n[7] + n[8] + n[9] In [8]: diff(nges,n[5]) Out[8]: 1 </code></pre> <p>You could also use the contracted form of summation:</p> <pre><code>In [9]: nges_uneval = Sum(n[i], [i,1,numSpecies]) In [10]: nges_uneval Out[10]: 10 ___ ╲ ╲ n[i] ╱ ╱ ‾‾‾ i = 1 In [11]: diff(nges_uneval, n[5]) Out[11]: 10 ___ ╲ ╲ δ ╱ 5,i ╱ ‾‾‾ i = 1 In [12]: diff(nges_uneval, n[5]).doit() Out[12]: 1 </code></pre> <p>Also notice that in the next SymPy version you will be able to derive symbols with symbolic indices:</p> <pre><code>In [13]: j = symbols("j") In [13]: diff(n[i], n[j]) Out[13]: δ j,i </code></pre> <p>Where you get the <a href="https://en.wikipedia.org/wiki/Kronecker_delta" rel="nofollow">Kronecker delta</a>.</p> <p>If you don't feel like installing the SymPy development version, just wait for the next full version (probably coming out this autumn), it will support derivatives of <code>IndexedBase</code>.</p>
4
2016-08-29T09:26:25Z
[ "python", "sympy", "derivative" ]
Tkinter .icursor(*arg) strange behaviour
39,193,794
<p>I'd like to create an Entry with Tkinter where the user can type its telephone number and the text dynamically changes in order that once finished it becomes like <code>+34 1234567890</code>.</p> <p>In my code the function <code>.icursor(n)</code>, used to set the cursor position, at first does not work properly, but then, surpassed the prefix, it does.</p> <p>This is my code snippet (It belongs to a much larger one).</p> <pre><code>from Tkinter import * def TelephoneCheck(self,Vari): Plain = Vari.get() Plain = list(Plain) Plain_flat = [] for element in Plain: try: check = int(element) Plain_flat.append(element) except: pass if len(Plain_flat) &gt; 2: Plain_flat.insert(2,' ') Plain = ''.join(Plain_flat) Plain = '+'+Plain self.istn.set(Plain) self.InsertTelephoneNumber.icursor(len(Plain)) def CreateInsertTelephoneNumber(self,X,Y,color='white'): self.istn = StringVar() self.istn.trace('w', lambda name, index, mode, istn=self.istn: self.TelephoneCheck(istn)) self.InsertTelephoneNumber = Entry(Body,textvariable=self.istn) self.InsertTelephoneNumber.config(bg=color) self.InsertTelephoneNumber.place(height=20,width=230,y=Y+27,x=X+245) def LabelBody(self,X,Y): TelephoneText = Label(Body,text='Telephone Number *') TelephoneText.place(y=Y+4,x=X+243) self.CreateInsertTelephoneNumber(X,Y) </code></pre> <p>As you see, theoretically, the position should be setted at the end of the string everytime the user adds a number. I can not understand why it works like a charm only after the prefix and not when the first number is typed (It results as <code>+(Cursor here)3</code> instead of <code>+3(Cursor here)</code>).</p> <p>If more code is needed I will update the post.</p> <p>Thanks for your time and help!</p>
1
2016-08-28T17:09:35Z
39,194,825
<p>The problem is that you're setting the cursor, but then the underlying widget sets the cursor the way it normally does. Because you're inserting characters into the widget in the middle of Tkinter processing a key press and release, it gets confused. For example, on the very first keystroke it thinks the cursor should be at position 1, but you've inserted a character after that position so the cursor ends up between characters. </p> <p>The simplest solution is to schedule your change to happen after the default behavior by using <code>after_idle</code>:</p> <pre><code>Body.after_idle(self.InsertTelephoneNumber.icursor, len(Plain)) </code></pre>
2
2016-08-28T19:06:24Z
[ "python", "python-2.7", "function", "tkinter", "cursor" ]
python beautifoulsoup wrong parsing table
39,193,837
<p>I tried to parse the table and write its data to csv, but <strong>beautifoulsoup</strong> <strong>doesn't parse</strong> the table correctly. This is the page: <a href="http://projects.fivethirtyeight.com/2016-election-forecast/arizona/" rel="nofollow">http://projects.fivethirtyeight.com/2016-election-forecast/arizona/</a></p> <p>This is the code I'm using:</p> <pre><code>date=[] pollster=[] grade=[] sample=[] weight=[] clinton=[] trump=[] johnson=[] leader=[] adjusted=[] import requests from bs4 import BeautifulSoup url='http://projects.fivethirtyeight.com/2016-election-forecast/florida/' r = requests.get(url) soup=BeautifulSoup(r.content,"lxml") the_table=soup.find("table", attrs={"class":"t-desktop t-polls"}) rows = the_table.tbody.find_all('tr') for row in rows: if 'data-created' in row.attrs: cols = row.find_all('td') text_cols = [ele.text.strip() for ele in cols] date.append(text_cols[2]) pollster.append(text_cols[3]) grade.append(text_cols[4]) sample.append(text_cols[5]) weight.append(text_cols[6]) clinton.append(text_cols[7]) trump.append(text_cols[8]) johnson.append(text_cols[9]) leader.append(text_cols[10]) adjusted.append(text_cols[11]) import pandas as pd df=pd.DataFrame(date,columns=['date']) df['pollster']=pollster df['grade']=grade df['sample']=sample df['weight']=weight df['clinton']=clinton df['trump']=trump df['johnson']=johnson df['leader']=leader df['adjusted']=adjusted from urllib.parse import urlparse s=urlparse(url) import os f=os.getcwd()+"/"+s.path.split('/')[-2] + '.csv' df.to_csv(f) </code></pre> <p>It saves a csv with <strong>wrong</strong> data:</p> <pre><code>,date ,pollster ,grade,sample ,weight,clinton,trump,johnson,leader ,adjusted 0,Aug. 21-27,USC Dornsife/LA Times, ,"2,545",LV ,44% ,44% , ,Clinton +1 ,Clinton +4 1,Aug. 24-26,Morning Consult , ,"2,007",RV ,39% ,37% ,8% ,Clinton +2 ,Clinton +2 2,Aug. 20-26,USC Dornsife/LA Times, ,"2,460",LV ,45% ,43% , ,Clinton +1 ,Clinton +5 3,Aug. 19-25,Ipsos ,A- ,334 ,LV ,50% ,43% , ,Clinton +7 ,Clinton +7 4,Aug. 19-25,Ipsos ,A- ,500 ,LV ,53% ,31% , ,Clinton +22,Clinton +22 5,Aug. 19-25,Ipsos ,A- ,443 ,LV ,32% ,45% , ,Trump +13 ,Trump +13 6,Aug. 19-25,Ipsos ,A- ,518 ,LV ,61% ,25% , ,Clinton +36,Clinton +36 7,Aug. 19-25,Ipsos ,A- ,392 ,LV ,47% ,41% , ,Clinton +7 ,Clinton +7 8,Aug. 19-25,Ipsos ,A- ,666 ,LV ,49% ,42% , ,Clinton +7 ,Clinton +7 and so on..... </code></pre> <p>If I change the beautifoulsoup parser, still wrong parse. If I <strong>save manually</strong> the table copied with chrome inspector or firefox firebug, <strong>it works</strong>. Here's the correct data csv generated:</p> <pre><code> ,date ,pollster,grade ,sample,weight,clinton,trump,johnson,leader ,adjusted 0 ,Ipsos ,A- ,362 ,LV ,0.67 ,43% ,46% , ,Trump +3 ,Trump +3 1 ,CNN/Opinion Research Corp. ,A- ,809 ,LV ,1.40 ,38% ,45% ,12% ,Trump +7 ,Trump +7 2 ,Ipsos ,A- ,438 ,LV ,0.25 ,39% ,47% , ,Trump +8 ,Trump +8 3 ,YouGov ,B ,"1,095",LV ,0.65 ,42% ,44% ,5% ,Trump +2 ,Trump +1 4 ,OH Predictive Insights / MBQF,C+ ,996 ,LV ,0.44 ,45% ,42% ,4% ,Clinton +3,Clinton +2 5 ,Integrated Web Strategy , ,679 ,LV ,0.35 ,41% ,49% ,3% ,Trump +8 ,Trump +5 6 ,Public Policy Polling ,B+ ,691 ,V ,0.49 ,40% ,44% , ,Trump +4 ,Trump +1 7 ,OH Predictive Insights / MBQF,C+ ,"1,060",LV ,0.16 ,47% ,42% , ,Clinton +4,Clinton +4 8 ,Greenberg Quinlan Rosner ,B- ,300 ,LV ,0.23 ,39% ,45% ,10% ,Trump +6 ,Trump +6 9 ,Public Policy Polling ,B+ ,896 ,V ,0.20 ,38% ,40% ,6% ,Trump +2 ,Tie 10,Behavior Research Center ,A ,564 ,RV ,0.16 ,42% ,35% , ,Clinton +7,Clinton +5 11,Merrill Poll ,B ,701 ,LV ,0.11 ,38% ,38% , ,Tie ,Tie 12,Strategies 360 ,B ,504 ,LV ,0.03 ,42% ,44% , ,Trump +2 ,Tie </code></pre> <p><strong>Why</strong> the whole html from the web makes beatifulsoup wrong parsing?</p> <p>[EDITING: SOLVED] This code extract the <strong>json object</strong> <code>race.stateData</code> from the <strong><em>script</em></strong> tag using a regular expression. Data will be finally parsed.</p> <pre><code>r = requests.get(url) soup = BeautifulSoup(r.content, "lxml") script = soup.body.script.text script = script.replace("\n", "") re_match = re.match('.*race\.stateData = (.*);race\.path', script) str_json = re_match.group(1) j = json.loads(str_json) #parsing data code not relevant.. </code></pre>
0
2016-08-28T17:12:58Z
39,208,741
<p>As you can see into the comments, I solved it extracting the <strong>json object</strong> <code>race.stateData</code> from the <strong>script</strong> tag using a regular expression. Data will be finally parsed.</p>
0
2016-08-29T14:30:32Z
[ "python", "html", "csv", "parsing", "beautifulsoup" ]
How to print the most times a char occurs from a counter in python
39,193,849
<pre><code>Counter(str) print max(Counter(str)) </code></pre> <p>When this prints, it will print the letter in the string that occurs the most, I want to print how many times it occurs not what letter. How do I go about doing this?</p>
1
2016-08-28T17:14:20Z
39,193,867
<p>The <code>collections.Counter</code> object already provides a method for this - <a href="https://docs.python.org/2/library/collections.html#collections.Counter.most_common" rel="nofollow"><code>most_common</code></a>:</p> <blockquote> <p>Return a list of the <code>n</code> most common elements and their counts from the most common to the least. If <code>n</code> is omitted or <code>None</code>, <code>most_common()</code> returns all elements in the counter. Elements with <strong>equal counts</strong> are ordered <strong>arbitrarily</strong></p> </blockquote> <p><em>Emphasis mine</em></p> <pre><code>print Counter(my_str).most_common(1) </code></pre>
3
2016-08-28T17:16:36Z
[ "python", "counter" ]
How to print the most times a char occurs from a counter in python
39,193,849
<pre><code>Counter(str) print max(Counter(str)) </code></pre> <p>When this prints, it will print the letter in the string that occurs the most, I want to print how many times it occurs not what letter. How do I go about doing this?</p>
1
2016-08-28T17:14:20Z
39,193,906
<p>A counter behaves like a dictionary, so this works:</p> <pre><code>max(Counter(s).values()) </code></pre> <p>Comment: Don't use <code>str</code> as your variable, because<br> <code>str</code> is a type in Python.</p>
0
2016-08-28T17:21:22Z
[ "python", "counter" ]
Is there any practical use for the datetime.timezone class in Python 3 standard library?
39,193,888
<p>The documentation for the datetime.timezone class only says:</p> <blockquote> <p>A class that implements the tzinfo abstract base class as a fixed offset from the UTC.</p> </blockquote> <p>And it accepts a timedelta as its argument.</p> <p>I never saw an example using it directly from other's code snippets, although I believe there must be some use of it, otherwise there is no point Python would expose this API. So in what situation would <strong>directly</strong> using this class be advised? What advantage would that be over using a dedicated library, such as pytz? </p>
0
2016-08-28T17:18:55Z
39,194,593
<p>From the <a href="https://docs.python.org/3/library/datetime.html#datetime.timezone" rel="nofollow">Python 3 documentation</a>:</p> <blockquote> <p>The datetime module supplies a simple concrete subclass of tzinfo, timezone, which can represent timezones with fixed offset from UTC such as UTC itself or North American EST and EDT.</p> </blockquote> <p>The basic idea being that for timezones that are simply offsets of UTC time (i.e., UTC +/- some fixed number of minutes), implementing all the methods required for tzinfo objects is more effort than necessary, so you can simply subclass the timezone object with the offset value.</p> <p>The documentation itself also recommends pytz for working with timezones:</p> <blockquote> <p>pytz library brings the IANA timezone database (also known as the Olson database) to Python and its usage is recommended</p> </blockquote>
0
2016-08-28T18:40:28Z
[ "python", "datetime", "timezone", "standard-library", "pytz" ]
python selenium how to get link from google
39,193,913
<p>How do I get a link from Google? I tried the following ways, but none of them worked:</p> <ol> <li><code>find_elements_by_xpath("//*[@class='r']/@href")</code></li> <li><code>driver.find_element_by_xpath("//a").get_attribute("href")</code></li> <li><code>driver.find_element_by_xpath("//a").get_attribute(("href")[2])</code></li> </ol> <p>I am receiving "none"</p> <p>I need to get google link, not link to the site (e.g. not www.stackoverflow.com). It's highlighted on this image:</p> <p><a href="http://i.stack.imgur.com/RGpo6.png" rel="nofollow"><img src="http://i.stack.imgur.com/RGpo6.png" alt="enter image description here"></a></p>
0
2016-08-28T17:21:51Z
39,194,385
<p>You maye have multiple issues here: First and third options are a not a valid xpath. Second options may find more than one matches, so it will return the first that fits, which is not necessarily the one you want. So I suggest:</p> <ol> <li><p>Make <em>find</em> specific enough to locate a proper element. I'd suggest <a href="http://selenium-python.readthedocs.io/locating-elements.html#locating-hyperlinks-by-link-text" rel="nofollow">find_element_by_link_text</a> if you know the name of the link you are going to choose:</p> <pre><code>link = driver.find_element_by_link_text('Stack Overflow') </code></pre></li> <li><p>Given you chose the right link, you should be able to get the attribute:</p> <pre><code>href = link.get_attribute('href') </code></pre></li> <li><p>If the first statement throws an exception (most likely <em>element not found</em>), you may need to wait for the element to appear on the page, as described <a href="http://stackoverflow.com/questions/7781792/selenium-waitforelement">here</a></p></li> </ol>
0
2016-08-28T18:16:54Z
[ "python", "selenium" ]
How to sum list of tuples?
39,193,920
<p>I have a list of tuples:</p> <pre><code>[ (a,1), (a,2), (b,1), (b,3) ] </code></pre> <p>I want to get the sum of both the <code>a</code> and <code>b</code> values. The results should be in this format:</p> <pre><code>[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ] </code></pre> <p>How can I do this?</p>
0
2016-08-28T17:23:28Z
39,193,993
<pre><code>from itertools import groupby [{'key': k, 'value': sum(v for _,v in g)} for k, g in groupby(sorted(lst), key = lambda x: x[0])] # [{'key': 'a', 'value': 3}, {'key': 'b', 'value': 4}] </code></pre>
1
2016-08-28T17:31:05Z
[ "python" ]
How to sum list of tuples?
39,193,920
<p>I have a list of tuples:</p> <pre><code>[ (a,1), (a,2), (b,1), (b,3) ] </code></pre> <p>I want to get the sum of both the <code>a</code> and <code>b</code> values. The results should be in this format:</p> <pre><code>[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ] </code></pre> <p>How can I do this?</p>
0
2016-08-28T17:23:28Z
39,194,004
<pre><code>from collections import defaultdict lst = [("a", 1), ("a", 2), ("b", 1), ("b", 3)] out = defaultdict(list) [out[v[0]].append(v[1]) for v in lst] out = [{"key": k, "value": sum(v)} for k, v in out.iteritems()] print out </code></pre>
1
2016-08-28T17:32:04Z
[ "python" ]
How to sum list of tuples?
39,193,920
<p>I have a list of tuples:</p> <pre><code>[ (a,1), (a,2), (b,1), (b,3) ] </code></pre> <p>I want to get the sum of both the <code>a</code> and <code>b</code> values. The results should be in this format:</p> <pre><code>[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ] </code></pre> <p>How can I do this?</p>
0
2016-08-28T17:23:28Z
39,194,026
<pre><code>from collections import Counter a = [('a', 1), ('a', 2), ('b', 1), ('b', 3)] c = Counter() for tup in a: c = c + Counter(dict([tup])) </code></pre>
0
2016-08-28T17:34:12Z
[ "python" ]
How to sum list of tuples?
39,193,920
<p>I have a list of tuples:</p> <pre><code>[ (a,1), (a,2), (b,1), (b,3) ] </code></pre> <p>I want to get the sum of both the <code>a</code> and <code>b</code> values. The results should be in this format:</p> <pre><code>[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ] </code></pre> <p>How can I do this?</p>
0
2016-08-28T17:23:28Z
39,194,134
<p>You can use <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow"><code>collections.Counter</code></a> to create a <a href="https://en.wikipedia.org/wiki/Multiset" rel="nofollow"><em>multiset</em></a> from the initial list and then modify the result to match your case:</p> <pre><code>from collections import Counter lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)] part = sum((Counter({i[0]: i[1]}) for i in lst), Counter()) # Counter({'b': 4, 'a': 3}) final = [{'key': k, 'value': v} for k, v in part.items()] # [{'key': 'b', 'value': 4}, {'key': 'a', 'value': 3}] </code></pre>
0
2016-08-28T17:46:11Z
[ "python" ]
How to sum list of tuples?
39,193,920
<p>I have a list of tuples:</p> <pre><code>[ (a,1), (a,2), (b,1), (b,3) ] </code></pre> <p>I want to get the sum of both the <code>a</code> and <code>b</code> values. The results should be in this format:</p> <pre><code>[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ] </code></pre> <p>How can I do this?</p>
0
2016-08-28T17:23:28Z
39,194,470
<p>Very similar to answers given already. Little bit longer, but easier to read, IMHO.</p> <pre><code>from collections import defaultdict lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)] dd = defaultdict(int) for name, value in lst: dd[name] += value final = [{'key': k, 'value': v} for k, v in dd.items()] </code></pre> <p>(last line copied from Moses Koledoye's answer)</p>
0
2016-08-28T18:26:22Z
[ "python" ]
Using %systemdrive% in python
39,193,953
<p>I would like to open and work with a file with Python however I would like to use Windows <code>%systemdrive%</code> when referring to a file instead of full path. This piece of code works:</p> <pre><code>if not os.path.isfile('C:\\Work\\test\sample.txt'): </code></pre> <p>This does not:</p> <pre><code>if not os.path.isfile('%systemdrive%\\Work\\test\\sample.txt'): </code></pre> <p>Any idea? Thank you in advance!</p>
0
2016-08-28T17:27:14Z
39,194,118
<p>You can use <a href="https://docs.python.org/3.6/library/os.html?highlight=environment#os.environ" rel="nofollow">os.environ</a></p> <pre><code>import os import os.path fn = r'{0}\Work\test\sample.txt'.format( os.environ['systemdrive'] ) if not os.path.isfile(fn): ... </code></pre>
1
2016-08-28T17:44:23Z
[ "python", "windows" ]
Using %systemdrive% in python
39,193,953
<p>I would like to open and work with a file with Python however I would like to use Windows <code>%systemdrive%</code> when referring to a file instead of full path. This piece of code works:</p> <pre><code>if not os.path.isfile('C:\\Work\\test\sample.txt'): </code></pre> <p>This does not:</p> <pre><code>if not os.path.isfile('%systemdrive%\\Work\\test\\sample.txt'): </code></pre> <p>Any idea? Thank you in advance!</p>
0
2016-08-28T17:27:14Z
39,194,352
<p>There is a dedicated function for solving this problem named <a href="https://docs.python.org/2/library/os.path.html#os.path.expandvars" rel="nofollow"><code>os.path.expandvars</code></a>.</p> <blockquote> <p>Return the argument with environment variables expanded. Substrings of the form <code>$name</code> or <code>${name}</code> are replaced by the value of environment variable name. Malformed variable names and references to non-existing variables are left unchanged.</p> <p>On Windows, <code>%name%</code> expansions are supported in addition to <code>$name</code> and <code>${name}</code>.</p> </blockquote> <pre><code>if not os.path.isfile(os.path.expandvars('%systemdrive%\\Work\\test\\sample.txt')): pass # do something </code></pre>
2
2016-08-28T18:12:49Z
[ "python", "windows" ]
Encoding for OrientDB (can't send a literal string)
39,193,957
<p>I have the next problem. I need to create a vertex with a propertyA with a value 'المساء'. The problem is from python, python CAN'T send the string 'المساء' so...</p> <p>I know I need to do a encode, like the next:</p> <pre><code>&gt;&gt;&gt;a = 'المساء' &gt;&gt;&gt;b = a.encode('cp270') &gt;&gt;&gt;print b &gt;&gt;&gt;'\x9f\xe9\xea\xab\x9f\x98' </code></pre> <p>But with this encode OrientDB won't work. I think that I need an ascii encode. </p> <p>There is the problem (without response): <a href="https://github.com/orientechnologies/orientdb/issues/5860" rel="nofollow">https://github.com/orientechnologies/orientdb/issues/5860</a></p> <p>Anyone that know about OrientDB can help me? Thank in advance!</p>
0
2016-08-28T17:27:29Z
39,202,338
<p>I have tried with this code with orientDb version 2.2.7</p> <pre><code>import pyorient db_name='MyDb' print("connection to the server...") client=pyorient.OrientDB("localhost",2424) client.set_session_token(True) session_id=client.connect("root","root") client.db_open( db_name, "admin", "admin" ) myFunction = 'insert into v(name) values("المساء")' client.command(myFunction); client.db_close() </code></pre> <p>and it worked for me</p> <p><a href="http://i.stack.imgur.com/YNAaG.png" rel="nofollow"><img src="http://i.stack.imgur.com/YNAaG.png" alt="enter image description here"></a></p> <p>Hope it helps.</p>
0
2016-08-29T09:05:33Z
[ "python", "character-encoding", "orientdb" ]
Encoding for OrientDB (can't send a literal string)
39,193,957
<p>I have the next problem. I need to create a vertex with a propertyA with a value 'المساء'. The problem is from python, python CAN'T send the string 'المساء' so...</p> <p>I know I need to do a encode, like the next:</p> <pre><code>&gt;&gt;&gt;a = 'المساء' &gt;&gt;&gt;b = a.encode('cp270') &gt;&gt;&gt;print b &gt;&gt;&gt;'\x9f\xe9\xea\xab\x9f\x98' </code></pre> <p>But with this encode OrientDB won't work. I think that I need an ascii encode. </p> <p>There is the problem (without response): <a href="https://github.com/orientechnologies/orientdb/issues/5860" rel="nofollow">https://github.com/orientechnologies/orientdb/issues/5860</a></p> <p>Anyone that know about OrientDB can help me? Thank in advance!</p>
0
2016-08-28T17:27:29Z
39,245,226
<p>Using python I can do this:</p> <pre><code>&gt;&gt;&gt; a = 'غريبديالى#مخيسةالعز' &gt;&gt;&gt; type(a) &lt;type 'str'&gt; &gt;&gt;&gt; b = a.decode('utf8') &gt;&gt;&gt; b u'\u063a\u0631\u064a\u0628\u062f\u064a\u0627\u0644\u0649#\u0645\u062e\u064a\u0633\u0629\u0627\u0644\u0639\u0632' &gt;&gt;&gt; print b غريبديالى#مخيسةالعز </code></pre> <p>So, if I put a query like the next will create a vertex with the next result:</p> <pre><code>query = 'create vertex v content {"property":"%s"}' %b </code></pre> <p><a href="http://i.stack.imgur.com/JOZXt.png" rel="nofollow"><img src="http://i.stack.imgur.com/JOZXt.png" alt="enter image description here"></a></p>
0
2016-08-31T09:04:47Z
[ "python", "character-encoding", "orientdb" ]
I am trying to understand class and function and can't seem to figure out what is wrong with my code
39,194,006
<p>Calculating the area of a triangle</p> <pre><code>class area: def traingle(self,height,length): self.height=height self.length=length def calculate(self,maths): self.maths= (self.height)*(self.length)*(0.5) def answer(self): print 'Hello, the aswer is %i'%self.maths first= area() first.traingle(4,5) first.calculate print first.answer </code></pre>
1
2016-08-28T17:32:15Z
39,194,065
<p>What about this?</p> <pre><code>import math class Triangle: def __init__(self, height, length): self.height = height self.length = length def calculate(self): return (self.height) * (self.length) * (0.5) def answer(self): print 'Hello, the aswer is %.2f' % self.calculate() first = Triangle(4, 5) first.answer() </code></pre> <p>Remember, to call a method you need to use parenthesis, when you're doing <code>first.answer</code> you're not executing your method, instead you should be doing <code>first.answer()</code></p> <p>Another different solution for this type of problem could be something like this:</p> <pre><code>import math class Triangle: def __init__(self, height, length): self.height = height self.length = length def area(self): return (self.height) * (self.length) * (0.5) class Quad: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height for index, obj in enumerate([Triangle(4, 5), Quad(2, 3)]): print 'Area for {0} {1} = {2:.2f}'.format(obj.__class__, index, obj.area()) </code></pre> <p>In any case, make sure you go through some of the available <a href="http://www.tutorialspoint.com/python/python_classes_objects.htm" rel="nofollow">python tutorials</a> out there in order to understand all the concepts first ;-)</p>
2
2016-08-28T17:38:31Z
[ "python", "oop" ]
Javascript is not recognizing a Flask variable
39,194,047
<p>I'm passing a set of variables into a Flask template, and I would like to first manipulate them with Javascript. The problem is that when I use the <code>{{ var }}</code> syntax, Javascript isn't recognizing it. <a href="http://i.stack.imgur.com/fLkdB.png" rel="nofollow">The errors look like this.</a> The left brackets give an "Identifier or string literal or numeric literal expected" error, and the variable names give an "Expression statement is not assignment or call" error.</p> <p>I use <code>{{ var }}</code> syntax later, within the HTML portion of the document, and when I do that they appear just fine. Also, enclosing it in quotes as I do for a different variable doesn't work either. Anyone know what the issue could be? Thanks.</p>
-1
2016-08-28T17:37:17Z
39,194,123
<p>Jinja2 (flask's templating engine) is a preprocessor, meaning that its output is the real JS and it does not care about you're using it with HTML, JS or whatever, it only prints text.</p> <p>That error you're getting is your text editor trying to help you but it's not smart enough to realize you're writing Jinja2 instead of javascript.</p> <p><strong>Edit</strong>: also, as @davidism says, you have to use jinja2 blocks.</p>
1
2016-08-28T17:44:51Z
[ "javascript", "python", "flask" ]
How to get the image src data through beautifulsoup?
39,194,152
<p>I want to get the image src data of all <code>coming soon</code> movies from this link:- <a href="http://www.fandango.com/moviescomingsoon?GenreFilter=Drama" rel="nofollow">Fandango.com</a> </p> <p>This is the code:-</p> <pre><code>def poster(genre): poster_link = [] request = requests.get(http://www.fandango.com/moviescomingsoon?GenreFilter=genre) content = request.content soup = BeautifulSoup(content, "html.parser") soup2 = soup.find('div', {'class':'movie-ls-group'}) elements = soup2.find_all('img') for element in elements: poster_link.append(element.get('src')) return poster_link </code></pre> <p>When I'm printing the poster_link array then it's giving me <code>None</code> instead of image source.</p>
0
2016-08-28T17:48:40Z
39,194,327
<p>Try this. It shortcuts the subsetting and grabs all of the images that have the proper class.</p> <pre><code>def poster(genre): poster_link = [] request = requests.get('http://www.fandango.com/moviescomingsoon?GenreFilter=%s' %genre) content = request.content soup = BeautifulSoup(content, "html.parser") imgs = soup.find_all('img', {'class': 'visual-thumb'}) for img in imgs: poster_link.append(img.get('data-src')) return poster_link </code></pre>
0
2016-08-28T18:09:52Z
[ "python", "beautifulsoup" ]
How to get the image src data through beautifulsoup?
39,194,152
<p>I want to get the image src data of all <code>coming soon</code> movies from this link:- <a href="http://www.fandango.com/moviescomingsoon?GenreFilter=Drama" rel="nofollow">Fandango.com</a> </p> <p>This is the code:-</p> <pre><code>def poster(genre): poster_link = [] request = requests.get(http://www.fandango.com/moviescomingsoon?GenreFilter=genre) content = request.content soup = BeautifulSoup(content, "html.parser") soup2 = soup.find('div', {'class':'movie-ls-group'}) elements = soup2.find_all('img') for element in elements: poster_link.append(element.get('src')) return poster_link </code></pre> <p>When I'm printing the poster_link array then it's giving me <code>None</code> instead of image source.</p>
0
2016-08-28T17:48:40Z
39,194,658
<p>James's answer is great but I noticed it grabs more than the images for that particular section - it grabs the 'New + Coming Soon' section for the bottom of the page too, which seems to be outside the scope of the genre and appears on other pages. This code restricts the image grab to just the genre-specific coming soon section.</p> <pre><code>def poster(genre): poster_link = [] request = requests.get('http://www.fandango.com/moviescomingsoon?GenreFilter=' + genre) content = request.content soup = BeautifulSoup(content, "html.parser") comingsoon = soup.find_all('div', {'class':'movie-ls-group'}) movies = comingsoon[0].find_all('img', {'class':'visual-thumb'}) for movie in movies: poster_link.append(movie.get('data-src')) return poster_link print (poster('Horror')) </code></pre> <p>You might also want to filter out the 'emptysource.jpg' images in your <code>poster_link</code> array before returning it, as they look like empty placeholders for movies without poster images.</p>
0
2016-08-28T18:46:53Z
[ "python", "beautifulsoup" ]
assertRaises not catching Exception, even when function is passed as callable
39,194,226
<p>When I run the below unit test, I get the following output.</p> <pre><code> ====================================================================== ERROR: test_find_playlist_file_invalid (__main__.TestSpotifyScraperAPI) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/gareth/Dropbox/programming/python/spotify_ripper/test/SpotifyScraperAPITest.py", line 15, in test_find_playlist_file_invalid spotify_scraper_api = SpotifyScraperAPI("non_existent_dir") File "/home/gareth/Dropbox/programming/python/spotify_ripper/SpotifyScraperAPI.py", line 7, in __init__ self.playlist_file = self.find_playlist_file() File "/home/gareth/Dropbox/programming/python/spotify_ripper/SpotifyScraperAPI.py", line 14, in find_playlist_file raise OSError("Given playlist folder does not exist") OSError: Given playlist folder does not exist </code></pre> <p>__</p> <pre><code>import unittest from SpotifyScraperAPI import SpotifyScraperAPI class TestSpotifyScraperAPI(unittest.TestCase): def test_find_playlist_file_invalid(self): spotify_scraper_api = SpotifyScraperAPI("non_existent_dir") self.assertRaises(OSError, spotify_scraper_api.find_playlist_file) if __name__ == '__main__': unittest.main() </code></pre> <p>So it's throwing the correct error, but not being caught, even though I'm passing the function in as a callable? What did I screw up?</p> <p>Thanks in advance!</p>
0
2016-08-28T17:57:05Z
39,194,320
<p>Exception comes from constructor. To assert for it in unittest you may use <code>assertRaises</code> as context manager, and move constructor to context manager body.</p> <pre><code>class TestSpotifyScraperAPI(unittest.TestCase): def test_find_playlist_file_invalid(self): with self.assertRaises(OSError): SpotifyScraperAPI("non_existent_dir") </code></pre>
2
2016-08-28T18:08:55Z
[ "python", "python-3.x" ]
Why can't I see the arguments to the print function imported from future?
39,194,325
<p>I noticed that I cannot use flush with the new python function after I import it using <code>from __future__ import print_function</code>. In my journey to discover why I discovered I can't even inspect what arguments/parameters it takes. Why is it?</p> <ol> <li>First I made sure that the inspect function worked.</li> <li>Then I made sure that the print function was indeed a function.</li> <li>After those two (seemed to pass/check) I tried to inspect it but this failed and returned a weird error.</li> </ol> <p>here is what I did:</p> <pre><code>from __future__ import print_function import inspect def f(a, b=1): pass #print( print_function ) print( inspect.getargspec( f ) ) g = print print('what is print: ', print) print('what is g=print: ', g) print( inspect.getargspec( g ) ) #print( inspect.getargspec( print ) ) #print('Hello', flush=True) </code></pre> <p>and everything passed except inspecting print:</p> <pre><code>ArgSpec(args=['a', 'b'], varargs=None, keywords=None, defaults=(1,)) what is print? &lt;built-in function print&gt; what is g=print? &lt;built-in function print&gt; Traceback (most recent call last): File "print_future.py", line 16, in &lt;module&gt; print( inspect.getargspec( g ) ) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 816, in getargspec raise TypeError('{!r} is not a Python function'.format(func)) TypeError: &lt;built-in function print&gt; is not a Python function </code></pre> <p>Why is that happening?</p> <hr> <p>This is some info of my python and system:</p> <pre><code>Python 2.7.11 (default, Jun 24 2016, 21:50:11) [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre>
1
2016-08-28T18:09:40Z
39,194,404
<p>Extracted from <a href="https://funcsigs.readthedocs.io/en/0.3/#signature" rel="nofollow">signature</a>:</p> <blockquote> <p>Note</p> <p>Some callables may not be introspectable in certain implementations of Python. For example, in CPython, built-in functions defined in C provide no metadata about their arguments.</p> </blockquote> <p>I've posted the signature docs because <a href="https://docs.python.org/3/library/inspect.html#inspect.getargspec" rel="nofollow">inspect.getargspec</a> is deprecated since 3.0</p>
2
2016-08-28T18:19:36Z
[ "python", "python-2.7", "python-3.x", "printing" ]
Why can't I see the arguments to the print function imported from future?
39,194,325
<p>I noticed that I cannot use flush with the new python function after I import it using <code>from __future__ import print_function</code>. In my journey to discover why I discovered I can't even inspect what arguments/parameters it takes. Why is it?</p> <ol> <li>First I made sure that the inspect function worked.</li> <li>Then I made sure that the print function was indeed a function.</li> <li>After those two (seemed to pass/check) I tried to inspect it but this failed and returned a weird error.</li> </ol> <p>here is what I did:</p> <pre><code>from __future__ import print_function import inspect def f(a, b=1): pass #print( print_function ) print( inspect.getargspec( f ) ) g = print print('what is print: ', print) print('what is g=print: ', g) print( inspect.getargspec( g ) ) #print( inspect.getargspec( print ) ) #print('Hello', flush=True) </code></pre> <p>and everything passed except inspecting print:</p> <pre><code>ArgSpec(args=['a', 'b'], varargs=None, keywords=None, defaults=(1,)) what is print? &lt;built-in function print&gt; what is g=print? &lt;built-in function print&gt; Traceback (most recent call last): File "print_future.py", line 16, in &lt;module&gt; print( inspect.getargspec( g ) ) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 816, in getargspec raise TypeError('{!r} is not a Python function'.format(func)) TypeError: &lt;built-in function print&gt; is not a Python function </code></pre> <p>Why is that happening?</p> <hr> <p>This is some info of my python and system:</p> <pre><code>Python 2.7.11 (default, Jun 24 2016, 21:50:11) [GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; </code></pre>
1
2016-08-28T18:09:40Z
39,194,678
<p>The <code>flush</code> keyword was added to print() in 3.3.</p> <p>C functions do not normally carry with them the information needed for introspection. That is simply a fact of how C is defined and compiled. As a substitute, signatures were added to their docstrings. IDLE calltips fall back to the docstring if inspect does not work.</p> <p>In 3.4, a new mechanism was added to include a signature attribute with C-coded function. The new inspect.signature uses it when present. Some C-coded functions have been to converted to include the new attribute, many have not.</p>
1
2016-08-28T18:48:29Z
[ "python", "python-2.7", "python-3.x", "printing" ]
Adapting Tensorflow CIFAR10 model for own data
39,194,335
<p>I am just starting with tensorflow and I thought a good first step would be to adapt CIFAR10 model for my own use. My database are not images but signals and a whole database has a shape of <code>[16400,3000,1,1]</code> (dimensionwise: number of all samples, height, width and number of channels added on purpose). I am already working on this problem with MatConvNet toolbox, so this question is strictly about tensorflow machnism. The database is a ready numpy tensor of the size above, in the code below is my attempt to prepare the data to be readable for the training script</p> <pre><code>from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf import numpy as np IMAGE_SIZE = 3000 data = np.load('/home/tensorflow-master/tensorflow/models/image/cifar10 /konsensop/data.npy') labels = np.load('/home/tensorflow-master/tensorflow/models/image/cifar10/konsensop/labels.npy') labels = labels-1 labels = labels.astype(int) data = tf.cast(data,tf.float32) labels = tf.cast(labels,tf.int64) NUM_CLASSES = 2 NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 10000 NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 6400 def _generate_image_and_label_batch(data_sample, label, in_queue_examples, batch_size, shuffle): num_preprocess_threads = 16 if shuffle: data, label_batch = tf.train.shuffle_batch( [data_sample, label], batch_size=batch_size, num_threads=num_preprocess_threads, capacity=min_queue_examples + batch_size, min_after_dequeue=min_queue_examples) else: data, label_batch = tf.train.batch( [data_sample, label], batch_size=batch_size, num_threads=num_preprocess_threads, capacity=min_queue_examples + batch_size) return data, tf.reshape(label_batch, [batch_size]) def inputs(data,labels, batch_size): for i in xrange(0, data.shape[0]/batch_size): data_sample = data[i,:,:,:] label = labels[i,0] height = 3000 width = 1 min_fraction_of_examples_in_queue = 0.4 min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN* min_fraction_of_examples_in_queue) print('Filling queue with %d data before starting to train' % min_queue_examples) return _generate_image_and_label_batch(data_sample, label, min_queue_examples, batch_size, shuffle=True) </code></pre> <p>I'm trying to load the data I aleady have and generate batches in a way cifar10 model did, but when running the trainer code I get an error in<code>data,labels = konsensop_input.inputs(data,labels,batch_size) UnboundcocalError: local variable 'data' referenced before assigment</code> </p> <pre><code>data = konsensop_input.data labels = konsensop_input.labels def train(): with tf.Graph().as_default(): global_step = tf.Variable(0, trainable = False) data, labels = konsensop_input.inputs(data, labels, batch_size) logits = konsensop_train.inference(data) # calculate loss loss = konsensop.loss(logits, labels) train_op = konsensop.train(loss, global_step) # create a saver saver = tf.train.Saver(tf.all_variables()) #saves all variables in a graph # build the summary operation based on the TF collection of summaries summary_op = tf.merge_all_summaries() # build an initialization operation to run below init = tf.initialize_all_variables() # start running operations on the graph sess = tf.Session(config = tf.ConfigProto(log_device_placement=False)) sess.run(init) # start the queue runners tf.train.start_queue_runners(sess = sess) #co to i po co to""" summary_writer = tf.train.SummaryWriter( FLAGS.train_dir, sess.graph) for step in xrange(FLAGS.max_step): start_time = time.time() _, loss_value = sess.run([train_op, loss]) duration = time.time() - start_time assert not np.isnan(loss_value), 'Model diverged with loss = NaN' if step % 10 == 0: num_examples_per_step = FLAGS.batch_size examples_per_sec = num_examples_per_step / duration sec_per_batch = float(duration) format_str = ('%s: step %d, loss = %.2f (%.1f examples/sec; %.3f sec/batch)') print ( format_str % (datetime.now(), step, loss_value, examples_per_sec, sec_per_batch)) if step % 100 == 0: summary_str = sess.run(summary_op) summary_writer.add_summary(summary_str, step) if step % 1000 == 0 or (step + 1) == FLAGS.max_steps: checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt') saver.save(sess, checkpoint_path, global_step = step) def main(argv=None): train() if __name__=='__main__': tf.app.run() </code></pre> <p>I would like to figure out how to implement a reasonable data feeding technique here</p>
0
2016-08-28T18:11:02Z
39,194,665
<p>For the relatively small data set you want to work with, you might consider just loading it into a big numpy array, then iterating over it in mini-batches, which you feed to the computation graph via <code>tf.placeholder</code>s and the <code>feed_dict</code> mechanism.</p> <p>The mini-batch iteration could look something like this (you should probably add random shuffling after each epoch):</p> <pre><code>def iterate_batches(X, y, batch_size, num_epochs): N = np.size(X, 0) batches_per_epoch = N/float(batch_size) for i in range(num_epochs): for j in range(batches_per_epoch): start, stop = j*batch_size, (j+1)*batch_size yield X[start:stop, :], y[start:stop] </code></pre> <p>(If you are not familiar with Python's <code>yield</code> mechanism, google for Python generators. There a lots of good introductions on the web.)</p> <p>Given that you have a mechanism to load the whole data set into a numpy array <code>X_train, y_train</code>, you can then write your training loop like this</p> <pre><code>train_op = ... for X, y in iterate_batches(X_train, y_train, you_batch_size, your_num_epochs): sess.run([train_op], feed_dict={X_tensor: X, y_tensor: y} </code></pre> <p>Here, <code>X_tensor</code> and <code>y_tensor</code> are <code>tf.placeholder</code>s for the data, that you have to specify in your network architecture.</p>
0
2016-08-28T18:47:16Z
[ "python", "tensorflow", "conv-neural-network" ]
Invert values of colour in CSS
39,194,402
<p>I have a CSS file where there are colours defined for certain elements. I want to invert the colours of these elements using some Python script. The format of colours are</p> <ul> <li>#XXX; or #XXX followed by space</li> <li>#XXXXXX; or #XXXXXX followed by space</li> </ul> <p>I am able to grab the pattern using following regex expression: (\#)([a-fA-F0-9]*)(\;\w)</p> <p>The problem is I am not able to figure out how to use it. I tried sed but it doesn't allow expression evaluation.</p> <p>I may be wrong in assessment of my initial requirement. Any help will be appreciated.</p>
0
2016-08-28T18:19:12Z
39,194,636
<p>I have some pretty basic code that can invert hex.</p> <pre><code># function takes in a hex color and outputs it inverted def invert(color_to_convert): table = string.maketrans('0123456789abcdef', 'fedcba9876543210') return '#' + color_to_convert[1:].lower().translate(table).upper() </code></pre> <p>Because to invert the chars just need to be turned around you can easily you need to switch zeros to f's and f's to zeros.</p>
1
2016-08-28T18:44:56Z
[ "python", "css" ]
Extracting string from an HTML table from a given tab using Python
39,194,407
<p>I need to extract a string value from the HTML table below. I want to loop through the table from a particular tab, and copy the results horizontally into the command line or some file.</p> <p>I am pasting only one row of information here. This table gets updated based on the changes happening on the Gerrits. The result that I want is all the Gerrit number under a new tab For example, if I want to get the Gerrit list from the approval queue, the values should display as shown in the image below.</p> <p><img src="http://i.stack.imgur.com/HYjWV.png" alt="dashboard_image"></p> <p>7897423, 2423343, 34242342, 34234, 57575675</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="#tab1"&gt;&lt;span&gt;Review Queue&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tab2"&gt;&lt;span&gt;Approval Queue&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tab3"&gt;&lt;span&gt;Verification Queue&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tab4"&gt;&lt;span&gt;Merge Queue&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tab5"&gt;&lt;span&gt;Open Queue&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#tab6"&gt;&lt;span&gt;Failed verification&lt;/span&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="tab1"&gt; &lt;h1&gt;Review Queue&lt;/h1&gt; &lt;table class="tablesorter" id="dashboardTable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;&lt;/th&gt; &lt;th&gt;Gerrit&lt;/th&gt; &lt;th&gt;Owner&lt;/th&gt; &lt;th&gt;CR(s)&lt;/th&gt; &lt;th&gt;Project&lt;/th&gt; &lt;th&gt;Dev Branch/PL&lt;/th&gt; &lt;th&gt;Subject&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;th&gt;Days in Queue&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="checkbox" /&gt;&lt;/td&gt; &lt;td&gt; &lt;a href="https://example/1696771"&gt;1696771&lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;a href="http://people.theng/People?id=ponga"&gt;ponga&lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;a href="http://chong/CR/1055680"&gt;1055680&lt;/a&gt; &lt;/td&gt; &lt;td&gt;platform/hardware/kiosk/&lt;/td&gt; &lt;td&gt; hidden-userspace.aix.2.0.dev &lt;/td&gt; &lt;td&gt;display: information regarding display&lt;/td&gt; &lt;td&gt; some info here &lt;/td&gt; &lt;td&gt; 2 &lt;/td&gt; &lt;/tr&gt; </code></pre>
0
2016-08-28T18:20:22Z
39,195,825
<p>What stops you from leveraging BeautifulSoup for this?</p> <p>Lets say you have already read the html (using sgmllib or any other library) into a string variable named html_contents. Since you are not mentioning which column you want to get data from, I am extracting the gerrit number column.</p> <p>You can simply do:</p> <pre><code>from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc, 'html.parser') for tr in soup.tbody: if tr.name == 'tr': print tr.contents[3].contents[1].string </code></pre> <p>Above you can loop in all the tr tags inside the tbody and (assuming all the td tags contained inside the tr have the same structure) their value is extracted, in this case the value of the a tag inside.</p> <p><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#quick-start" rel="nofollow">Read the quick start</a>, it will make your life easier on parsing HTML documents.</p>
0
2016-08-28T21:11:55Z
[ "python", "html", "parsing", "html-table" ]
timeout decorator in python through __init__ params
39,194,479
<p>I want to have a timeout for a function (rest API call) in python &amp; for that I am following <a href="http://stackoverflow.com/a/2282656/5582349">this</a> SO answer. </p> <p>I already have one existing code structure where i want to have a timeout decorator. I am defining a timeout seconds in ".txt" file &amp; passing it as a dict to main function. Something like : </p> <pre><code>class Foo(): def __init__(self, params): self.timeout=params.get['timeout'] .... .... @timeout(self.timeout) #throws an error def bar(arg1,arg2,arg3,argn): pass #handle timeout for this function by getting timeout from __init__ #As answer given in SO , #I need to use the self.timeout, which is throwing an error: ***signal.alarm(seconds) TypeError: an integer is required*** #And also ***@timeout(self.timeout) NameError: name 'self' is not defined*** @timeout(30) #Works fine without any issue def foo_bar(arg1,arg2,arg3,argn): pass </code></pre> <p>What am i missing ? </p>
2
2016-08-28T18:27:36Z
39,194,566
<p>At <code>A</code> the <code>self</code> is not defined because the decorator is outside the method, but self only exists inside the method:</p> <pre><code>@timeout(self.timeout) # &lt;== A def bar(self,arg1,arg2,arg3): pass </code></pre> <p>You can try to set the <code>barTimeout</code> attribute at <code>__init__</code>:</p> <pre><code>class Foo(): def bar(self,arg1,arg2,arg3): pass def __init__(self, params): self.timeout=params.get('timeout') self.barTimeout = timeout(self.timeout)(self.bar) Foo({'timeout':30}).barTimeout(1,2,3) </code></pre>
0
2016-08-28T18:37:16Z
[ "python", "python-2.7", "function", "timeout", "settimeout" ]
Posting Content to Friendica using Python
39,194,527
<p>I'm working on a project that is written in Python and needs to post updates to a Friendica server and interact using various APIs available. However, I have had very limited API usage experience and so I'm unsure of how to code this functionality in Python. There is an example on the Friendica GitHub however the Python example would not work for me. There is a Python3 module <a href="https://bitbucket.org/tobiasd/python-friendica/overview" rel="nofollow">https://bitbucket.org/tobiasd/python-friendica/overview</a>, however when trying to connect using this in a test script as follows:</p> <pre><code>#!/usr/bin/env python3 # -*- coding: utf-8 -*- import friendica # make a new instance of friendica f = friendica.friendica (server = '10.211.55.23/api/statuses/update', username = 'newtest', password = 'klaup8744') # check that we are logged in f.account_verify_credentials() # get the current notifications print (f.ping()) # post something with the default settings f.statuses_update( status = "here is the message you are going to post" ) </code></pre> <p>it would refuse the connection with the following message:</p> <pre><code>Traceback (most recent call last): File "/usr/lib/python3.4/urllib/request.py", line 1182, in do_open h.request(req.get_method(), req.selector, req.data, headers) File "/usr/lib/python3.4/http/client.py", line 1088, in request self._send_request(method, url, body, headers) File "/usr/lib/python3.4/http/client.py", line 1126, in _send_request self.endheaders(body) File "/usr/lib/python3.4/http/client.py", line 1084, in endheaders self._send_output(message_body) File "/usr/lib/python3.4/http/client.py", line 922, in _send_output self.send(msg) File "/usr/lib/python3.4/http/client.py", line 857, in send self.connect() File "/usr/lib/python3.4/http/client.py", line 1223, in connect super().connect() File "/usr/lib/python3.4/http/client.py", line 834, in connect self.timeout, self.source_address) File "/usr/lib/python3.4/socket.py", line 512, in create_connection raise err File "/usr/lib/python3.4/socket.py", line 503, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "test_1.py", line 12, in &lt;module&gt; print (f.ping()) File "/home/sambraidley/Desktop/friendica.py", line 851, in ping res = urlopen(self.protocol()+self.apipath[:-4]+'/ping').read().decode('utf-8') File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.4/urllib/request.py", line 463, in open response = self._open(req, data) File "/usr/lib/python3.4/urllib/request.py", line 481, in _open '_open', req) File "/usr/lib/python3.4/urllib/request.py", line 441, in _call_chain result = func(*args) File "/usr/lib/python3.4/urllib/request.py", line 1225, in https_open context=self._context, check_hostname=self._check_hostname) File "/usr/lib/python3.4/urllib/request.py", line 1184, in do_open raise URLError(err) urllib.error.URLError: &lt;urlopen error [Errno 111] Connection refused&gt; </code></pre> <p>The friendica Python3 module can be found at the following <a href="https://bitbucket.org/tobiasd/python-friendica/src/b0b75ae80a6e747e8724b1ae36972ebfd939beb5/friendica.py?fileviewer=file-view-default" rel="nofollow">https://bitbucket.org/tobiasd/python-friendica/src/b0b75ae80a6e747e8724b1ae36972ebfd939beb5/friendica.py?fileviewer=file-view-default</a></p> <p>My Friendica server is setup within a VM with the address 10.211.55.23, with test credentials of username = 'newtest' and password 'klaup8744' and it is fully working as using the curl example code to post an update worked perfectly, as follows:</p> <pre><code>/usr/bin/curl -u newtest:klaup8744 10.211.55.23/api/statuses/update.xml -d source="Testing" -d status="This is a test status" </code></pre>
1
2016-08-28T18:33:17Z
39,194,915
<p>According to the <a href="https://bitbucket.org/tobiasd/python-friendica/src/b0b75ae80a6e747e8724b1ae36972ebfd939beb5/friendica.py?fileviewer=file-view-default" rel="nofollow">source link</a> you posted, friendica uses https by default. Your successful curl request is using http.<br> Try instantiating friendica it using http:</p> <pre><code>f = friendica.friendica (server = '10.211.55.23/api/statuses/update', username = 'newtest', password = 'klaup8744', useHTTPS=False) </code></pre>
0
2016-08-28T19:17:52Z
[ "python", "api" ]