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
IDLE (Python 3.4) - Execute a script on launch
39,686,711
<p>I've been spending the last week or so creating a simple touch friendly GUI in python3.4 (on the raspberry pi). Now I setup python to run my script on launch, but I ran into the problem, that I couldn't open other programs from within my program (such as the web browser or calculator). However if I use IDLE to execute the script and not the standard python program in the terminal, opening other programs from my scrip works! I already created a .sh file that runs when the Linux Gui starts, which opens up my script in IDLE, however it only opens the file and doesn't execute it.</p> <p>So now here is my question: Can I create a .sh script, which opens IDLE and runs a python script in the IDLE console (I already tried the exec command when launching idle with no results)</p> <p>Right now this is my command, which should execute the loaded file, but only loads it for some reaseon:</p> <pre><code>sudo idle3 -c exec(open('/path/to/my/file.py').read()) </code></pre> <p>Any help is appreciated :)</p>
1
2016-09-25T12:17:47Z
39,687,206
<h3>Use Idle's cli options</h3> <p>You have a few options, of which the best one is to use the <code>-r</code> option. From <code>man idle</code>:</p> <pre><code> -r file Run script from file. </code></pre> <p>This will however only open the <em>interpreter</em> window. Since you also want the editor, this will do pretty much exactly what you describe:</p> <pre><code>idle3 '/path.to/file.py' &amp; idle3 -r '/path.to/file.py' </code></pre> <p>The <em>startup</em> command you need is then:</p> <pre><code>/bin/bash -c "idle3 '/path/to/file.py' &amp; idle3 -r '/path/to/file.py'" </code></pre> <p><a href="http://i.stack.imgur.com/iD0c9.png" rel="nofollow"><img src="http://i.stack.imgur.com/iD0c9.png" alt="![enter image description here"></a></p> <p>The command you tried will not work, since <a href="https://linux.die.net/man/2/idle" rel="nofollow">here</a>, we can read:</p> <blockquote> <p>Only process 0 may call idle(). Any user process, even a process with superuser permission, will receive EPERM. </p> </blockquote> <p>Therefore, we depend on cli options of <code>idle</code>, which luckily provide an option :)</p> <hr> <h3>Alternatively</h3> <p>Another option would be to open the file with <code>idle3</code> wait for the window to appear and simulate <kbd>F5</kbd>:</p> <pre class="lang-sh prettyprint-override"><code>/bin/bash -c "idle3 '/path/to/file.py' &amp; sleep 3 &amp;&amp; xdotool key F5" </code></pre> <p>This would need <a href="https://www.freebsd.org/cgi/man.cgi?query=xdotool&amp;apropos=0&amp;sektion=1&amp;manpath=FreeBSD%208.1-RELEASE%20and%20Ports&amp;format=html" rel="nofollow">xdotool</a> to be installed on your system.</p> <p>An advanced version of this wrapper would open the file with <code>idle</code>, subsequently check if the new window exists, is focussed and simulate <kbd>F5</kbd> with <code>xdotool</code>. </p> <p>These would however be the dirty options, which we luckily don't need :).</p>
0
2016-09-25T13:11:29Z
[ "python", "linux", "shell", "raspberry-pi", "python-idle" ]
Python function that behaves differently depending on the input object types
39,686,720
<p>In Python, can I write a function that takes objects as inputs and performs different calculations depending on the types of the objects?</p> <p>For example, say I have two classes: "circle" and "line". I define a circle object A with a radius and centre position, and a circle object B with a different radius and centre position. I then define a line object C with a direction vector and a point along the line.</p> <p>I would like to write a function that calculates the intersection:</p> <pre><code>def intersect(obj1,obj2): # Returns intersection of two geometric entities </code></pre> <p>If I input the two circles A and B, I want the function to return the area of intersection of A and B. But if I input circle A and line C, I want the output to be the points (if any) where the line crosses the circle. So intersect(obj1,obj2) will need to somehow read the class of obj1 and obj2, and act accordingly.</p>
0
2016-09-25T12:18:32Z
39,686,774
<p>Yes, you can certainly detect the types of your Python objects and execute different behaviour based on that. The built-in <code>type()</code> method will provide the information you need.</p> <p>I should stress that this is rather reverting to the procedural paradigm whereas what you may be better off doing in looking into object orientation (specifically polymorphism).</p> <p>You can also return <em>arbitrary types</em> from a function, so returning the two-dimensional intersection of two circles in one case, and two points of intersection between a circle and line in another, is certainly doable as well.</p> <p>Again, that's addressing the <em>possibility</em>, not the wisdom. It's certainly possible that I could try to cut down a giant Karri tree with a haddock, but the wisdom of such a move would be, at best, dubious.</p> <p>By way of example, the following program shows how to return a different type of value, based on the type of the parameter passed in:</p> <pre><code>def fn(x): if type(x) is int: return 42 if type(x) is list: return [3.14159,2.71828] return None print(fn(1)) print(fn([1,2])) print(fn(42.7)) </code></pre> <p>The output is, as expected:</p> <pre><code>42 [3.14159,2.71828] None </code></pre>
1
2016-09-25T12:24:24Z
[ "python", "oop", "linear-algebra" ]
How can I find and remove elements that have a specific pattern from a list?
39,686,755
<p>I have a list that is something like this:</p> <pre><code>output=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot', '/dev/mapper/vg00-lvol_data'.....] </code></pre> <p>I want to remove all the elements that has the format <code>"/dev/mapper/...."</code>. E.g. here <code>list[1]='/dev/mapper/vg00-lvol_root'</code>. I tried using the index to remove(since in this case the odd no is occupied by the pattern. But that's not the case always). I then tried the logic of converting the elements to strings and then use regex to find the pattern. I thought of running a for loop to extract the list elements to individual strings(all that was complicated). I'm sure there must be an easier way to solve this</p>
-1
2016-09-25T12:22:26Z
39,686,797
<pre><code>l=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot', '/dev/mapper/vg00-lvol_data'] filtered = [ x for x in l if "/dev/mapper/" not in x ] print(filtered) </code></pre> <p>Output:</p> <blockquote> <p>['Filesystem Size Used Avail Use% Mounted on', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot']</p> </blockquote>
1
2016-09-25T12:27:34Z
[ "python", "python-2.7", "python-3.x" ]
How can I find and remove elements that have a specific pattern from a list?
39,686,755
<p>I have a list that is something like this:</p> <pre><code>output=['Filesystem Size Used Avail Use% Mounted on', '/dev/mapper/vg00-lvol_root', ' 976M 356M 570M 39% /', 'tmpfs 1.9G 0 1.9G 0% /dev/shm', '/dev/mapper/vg00-lvol_apps', ' 20G 6.1G 13G 33% /apps', '/dev/sda1 976M 63M 863M 7% /boot', '/dev/mapper/vg00-lvol_data'.....] </code></pre> <p>I want to remove all the elements that has the format <code>"/dev/mapper/...."</code>. E.g. here <code>list[1]='/dev/mapper/vg00-lvol_root'</code>. I tried using the index to remove(since in this case the odd no is occupied by the pattern. But that's not the case always). I then tried the logic of converting the elements to strings and then use regex to find the pattern. I thought of running a for loop to extract the list elements to individual strings(all that was complicated). I'm sure there must be an easier way to solve this</p>
-1
2016-09-25T12:22:26Z
39,686,941
<p>if you have multiple strings need to be check, you may need this.</p> <pre><code>regex=re.compile('^/dev/mapper|^/usr/a') filtered_list = [s for s in my_list if not re.match(regex, s)] </code></pre>
0
2016-09-25T12:42:12Z
[ "python", "python-2.7", "python-3.x" ]
Unable to import csv file to python using the pd.read_csv command
39,686,784
<p>I am trying to read a csv file in Python 3.5 having imported pandas using the pd.read_csv command. However the system returns the following error message:</p> <blockquote> <blockquote> <blockquote> <p>Lung = pd.read_csv('c:\users\LungCapData.csv') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape</p> </blockquote> </blockquote> </blockquote> <p>In the above error message the left parenthesis is highlighted. Could you help me resolve this proble? Thank you!</p>
0
2016-09-25T12:25:43Z
39,687,044
<p>You can try prefix the string with r <code>Lung = pd.read_csv(r'c:\users\LungCapData.csv')</code></p>
1
2016-09-25T12:51:58Z
[ "python", "csv", "pandas" ]
Unable to import csv file to python using the pd.read_csv command
39,686,784
<p>I am trying to read a csv file in Python 3.5 having imported pandas using the pd.read_csv command. However the system returns the following error message:</p> <blockquote> <blockquote> <blockquote> <p>Lung = pd.read_csv('c:\users\LungCapData.csv') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape</p> </blockquote> </blockquote> </blockquote> <p>In the above error message the left parenthesis is highlighted. Could you help me resolve this proble? Thank you!</p>
0
2016-09-25T12:25:43Z
39,973,698
<p>You can try the following:</p> <pre><code>Lung = pd.read_csv(r'c:\users\LungCapData.csv', sep=';') </code></pre> <p>this should split the columns seeing as you seem to have semi-colons as separators.</p>
1
2016-10-11T08:57:53Z
[ "python", "csv", "pandas" ]
Unable to import csv file to python using the pd.read_csv command
39,686,784
<p>I am trying to read a csv file in Python 3.5 having imported pandas using the pd.read_csv command. However the system returns the following error message:</p> <blockquote> <blockquote> <blockquote> <p>Lung = pd.read_csv('c:\users\LungCapData.csv') SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \uXXXX escape</p> </blockquote> </blockquote> </blockquote> <p>In the above error message the left parenthesis is highlighted. Could you help me resolve this proble? Thank you!</p>
0
2016-09-25T12:25:43Z
39,974,631
<p>not familiar with windows platform ,but you can try this with encoding option:</p> <pre><code>Lung = pd.read_csv(r'c:\users\LungCapData.csv', encoding="utf8") </code></pre>
0
2016-10-11T09:50:52Z
[ "python", "csv", "pandas" ]
Getting Column Headers from multiple html 'tbody'
39,686,830
<p>I need to get the column headers from the second tbody in this url.</p> <p><a href="http://bepi.mpob.gov.my/index.php/statistics/price/daily.html" rel="nofollow">http://bepi.mpob.gov.my/index.php/statistics/price/daily.html</a></p> <p>Specifically, i would like to see "september, october"... etc.</p> <p>I am getting the following error:</p> <pre><code>runfile('C:/Python27/Lib/site-packages/xy/workspace/webscrape/mpob1.py', wdir='C:/Python27/Lib/site-packages/xy/workspace/webscrape') Traceback (most recent call last): File "&lt;ipython-input-8-ab4005f51fa3&gt;", line 1, in &lt;module&gt; runfile('C:/Python27/Lib/site-packages/xy/workspace/webscrape/mpob1.py', wdir='C:/Python27/Lib/site-packages/xy/workspace/webscrape') File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile execfile(filename, namespace) File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile exec(compile(scripttext, filename, 'exec'), glob, loc) File "C:/Python27/Lib/site-packages/xy/workspace/webscrape/mpob1.py", line 26, in &lt;module&gt; soup.findAll('tbody', limit=2)[1].findAll('tr').findAll('th')] IndexError: list index out of range </code></pre> <p>can anyone here please help me out? I shall be eternally grateful!</p> <p>have posted my code below:</p> <pre><code>import requests from bs4 import BeautifulSoup import pandas as pd url = "http://bepi.mpob.gov.my/index.php/statistics/price/daily.html" r = requests.get(url) soup = BeautifulSoup(r.text, 'lxml') column_headers = [th.getText() for th in soup.findAll('tbody', limit=2)[1].findAll('tr').findAll('th')] </code></pre>
0
2016-09-25T12:30:13Z
39,687,111
<p>When you click "View Price" button a POST request is sent to the <code>http://bepi.mpob.gov.my/admin2/price_local_daily_view3.php</code> endpoint. Simulate this POST request and parse the resulting HTML:</p> <pre><code>import requests from bs4 import BeautifulSoup with requests.Session() as session: session.get("http://bepi.mpob.gov.my/index.php/statistics/price/daily.html") response = session.post("http://bepi.mpob.gov.my/admin2/price_local_daily_view3.php", data={ "tahun": "2016", "bulan": "9", "Submit2222": "View Price" }) soup = BeautifulSoup(response.content, 'lxml') table = soup.find("table", id="hor-zebra") headers = [td.get_text() for td in table.find_all("tr")[2].find_all("td")] print(headers) </code></pre> <p>Prints the headers of the table:</p> <pre><code>[u'Tarikh', u'September', u'October', u'November', u'December', u'September', u'October', u'November', u'December', u'September', u'October', u'November', u'December'] </code></pre>
1
2016-09-25T12:59:36Z
[ "python", "html", "web-scraping", "html-table" ]
Parallelize groupby with multiple arguments
39,686,957
<p>I found this <a href="http://stackoverflow.com/questions/26187759/parallelize-apply-after-pandas-groupby">question</a> on parallelizing groupby. However, it can't be translated one-to-one into the case where there's multiple arguments - unless I'm mistaken.</p> <p>Is the following a correct way of doing it? Is there a better way? (Especially getting the index appeared quite inefficient).</p> <pre><code>def applyParallel(dfGrouped, func, *args): with Pool(cpu_count() - 2) as p: ret_list = p.starmap(func, zip([group for name, group in dfGrouped], repeat(*args))) index = [name for name, group in dfGrouped] return pd.Series(index=index, data=ret_list) </code></pre> <p>which one would call using <code>applyParallel(df.groupby(foo), someFunc, someArgs)</code>.</p>
0
2016-09-25T12:43:41Z
39,688,494
<p>First caveat, unless your data is fairly large, you may not see much (or any) benefit to parallelization.</p> <p>Rather than working directly with a multiprocessing pool, the easiest way to do this now would be to try <a href="http://dask.pydata.org/en/latest/dataframe-overview.html" rel="nofollow"><code>dask</code></a> - it gives a pandas-like api, mostly managing the parallelism for you.</p> <pre><code>df = pd.DataFrame(np.random.randn(10000000, 10), columns=list('qwertyuiop')) df['key'] = np.random.randint(0, 100, size=len(df)) import dask.dataframe as dd # want a partition size small enough to easily fit into memory # but large enough to make the overhead worth it ddf = dd.from_pandas(df, npartitions=4) %timeit df.groupby('key').sum() 1 loop, best of 3: 1.05 s per loop # calculated in parallel on the 4 partitions %timeit ddf.groupby('key').sum().compute() 1 loop, best of 3: 695 ms per loop </code></pre> <p>Note that by default, dask uses a thread-based scheduler for dataframes, which is faster for functions like <code>sum</code> that release the GIL. If you are applying custom python functions (which will need the GIL), you may see better performance with the multi-processing schedule.</p> <pre><code>dask.set_options(get=dask.multiprocessing.get) </code></pre>
1
2016-09-25T15:18:49Z
[ "python", "pandas" ]
scrapy-splash returns its own headers and not the original headers from the site
39,687,101
<p>I use scrapy-splash to build my spider. Now what I need is to maintain the session, so I use the scrapy.downloadermiddlewares.cookies.CookiesMiddleware and it handles the set-cookie header. I know it handles the set-cookie header because i set COOKIES_DEBUG=True and this causes the printouts by CookeMiddleware regarding set-cookie header. </p> <p>The problem: when I also add Splash to the picture the set-cookie printouts disappear, and in fact what I get as response headers is {'Date': ['Sun, 25 Sep 2016 12:09:55 GMT'], 'Content-Type': ['text/html; charset=utf-8'], 'Server': ['TwistedWeb/16.1.1']} Which is related to splash rendering engine which uses TwistedWeb. </p> <p>Is there any directive to tell the splash also to give me the original response headers?</p>
1
2016-09-25T12:57:35Z
39,691,344
<p>To get original response headers you can write a <a href="http://splash.readthedocs.io/en/stable/scripting-tutorial.html" rel="nofollow">Splash Lua script</a>; see <a href="https://github.com/scrapy-plugins/scrapy-splash#examples" rel="nofollow">examples</a> in scrapy-splash README:</p> <blockquote> <p>Use a Lua script to get an HTML response with cookies, headers, body and method set to correct values; lua_source argument value is cached on Splash server and is not sent with each request (it requires Splash 2.1+):</p> </blockquote> <pre><code>import scrapy from scrapy_splash import SplashRequest script = """ function main(splash) splash:init_cookies(splash.args.cookies) assert(splash:go{ splash.args.url, headers=splash.args.headers, http_method=splash.args.http_method, body=splash.args.body, }) assert(splash:wait(0.5)) local entries = splash:history() local last_response = entries[#entries].response return { url = splash:url(), headers = last_response.headers, http_status = last_response.status, cookies = splash:get_cookies(), html = splash:html(), } end """ class MySpider(scrapy.Spider): # ... yield SplashRequest(url, self.parse_result, endpoint='execute', cache_args=['lua_source'], args={'lua_source': script}, headers={'X-My-Header': 'value'}, ) def parse_result(self, response): # here response.body contains result HTML; # response.headers are filled with headers from last # web page loaded to Splash; # cookies from all responses and from JavaScript are collected # and put into Set-Cookie response header, so that Scrapy # can remember them. </code></pre> <p>scrapy-splash also provides <a href="https://github.com/scrapy-plugins/scrapy-splash#session-handling" rel="nofollow">built-in helpers</a> for cookie handling; they are enabled in this example as soon as scrapy-splash is <a href="https://github.com/scrapy-plugins/scrapy-splash#configuration" rel="nofollow">configured</a> as described in readme. </p>
1
2016-09-25T20:10:33Z
[ "python", "scrapy", "scrapy-splash" ]
python: [try + except] How to make sure all command under try is executed?
39,687,112
<p>This is a very beginners' question. But I cannot find answer...</p> <p>I want to run <strong>ALL</strong> lines under <code>try</code>. If <strong>ANY</strong> lines are unexecutable, run <code>except</code>. </p> <p>For example, I have some codes like this...</p> <pre><code>for i in range(0,100): try: print "a" print "b" print i, C print "d" except: print i, "fail" </code></pre> <p>I want to have <strong>ALL</strong> the lines under <code>try</code> executed. In this example, <code>print C</code> is unexecutable, because <code>C</code> is not pre-defined. </p> <p>Thus, I want to <strong>ONLY</strong> run <code>print i, "fail"</code> under <code>except</code>, because <code>NOT ALL</code> lines under <code>try</code> are executable.</p> <p>To be more clearly, The code above gives me the result: </p> <pre><code>a b 0 0 Fail a b 1 1 Fail a b 2 2 Fail ... </code></pre> <p>But I want to have a result like this:</p> <pre><code>0 Fail 1 Fail 2 Fail ... </code></pre> <p>How can I do this? Thanks. </p> <p><strong>UPDATE:</strong><br> To be more clearly, I am not asking for a result, I am asking for a method. I think there should be some commands to control <code>try</code>. </p>
1
2016-09-25T12:59:43Z
39,687,158
<p>You could alter the code so that it only prints when all expressions are valid:</p> <pre><code>for i in range(0,3): try: print ("a" + "\n" + "b" + "\n" + C + "\n" + "d") except: print (i, "fail") </code></pre> <p>Another variation to the same principle uses a list to store the things to be printed if all is successful:</p> <pre><code>for i in range(0,3): try: collect = [] collect.append("a") collect.append("b") collect.append(C) collect.append("d") print("\n".join(collect)) except: print (i, "fail") </code></pre>
3
2016-09-25T13:05:38Z
[ "python" ]
python: [try + except] How to make sure all command under try is executed?
39,687,112
<p>This is a very beginners' question. But I cannot find answer...</p> <p>I want to run <strong>ALL</strong> lines under <code>try</code>. If <strong>ANY</strong> lines are unexecutable, run <code>except</code>. </p> <p>For example, I have some codes like this...</p> <pre><code>for i in range(0,100): try: print "a" print "b" print i, C print "d" except: print i, "fail" </code></pre> <p>I want to have <strong>ALL</strong> the lines under <code>try</code> executed. In this example, <code>print C</code> is unexecutable, because <code>C</code> is not pre-defined. </p> <p>Thus, I want to <strong>ONLY</strong> run <code>print i, "fail"</code> under <code>except</code>, because <code>NOT ALL</code> lines under <code>try</code> are executable.</p> <p>To be more clearly, The code above gives me the result: </p> <pre><code>a b 0 0 Fail a b 1 1 Fail a b 2 2 Fail ... </code></pre> <p>But I want to have a result like this:</p> <pre><code>0 Fail 1 Fail 2 Fail ... </code></pre> <p>How can I do this? Thanks. </p> <p><strong>UPDATE:</strong><br> To be more clearly, I am not asking for a result, I am asking for a method. I think there should be some commands to control <code>try</code>. </p>
1
2016-09-25T12:59:43Z
39,687,198
<p>This is very similar to what @trincot posted, not sure if it would meet your requirements.</p> <p>Basically, move all of your prints to a separate function and call that in your try.</p> <pre><code>def printer(i=None, C=None): print "a" print "b" print i, C print "d" for i in range(0,100): try: printer(i, C) except: print i, "fail" </code></pre>
0
2016-09-25T13:10:31Z
[ "python" ]
python: [try + except] How to make sure all command under try is executed?
39,687,112
<p>This is a very beginners' question. But I cannot find answer...</p> <p>I want to run <strong>ALL</strong> lines under <code>try</code>. If <strong>ANY</strong> lines are unexecutable, run <code>except</code>. </p> <p>For example, I have some codes like this...</p> <pre><code>for i in range(0,100): try: print "a" print "b" print i, C print "d" except: print i, "fail" </code></pre> <p>I want to have <strong>ALL</strong> the lines under <code>try</code> executed. In this example, <code>print C</code> is unexecutable, because <code>C</code> is not pre-defined. </p> <p>Thus, I want to <strong>ONLY</strong> run <code>print i, "fail"</code> under <code>except</code>, because <code>NOT ALL</code> lines under <code>try</code> are executable.</p> <p>To be more clearly, The code above gives me the result: </p> <pre><code>a b 0 0 Fail a b 1 1 Fail a b 2 2 Fail ... </code></pre> <p>But I want to have a result like this:</p> <pre><code>0 Fail 1 Fail 2 Fail ... </code></pre> <p>How can I do this? Thanks. </p> <p><strong>UPDATE:</strong><br> To be more clearly, I am not asking for a result, I am asking for a method. I think there should be some commands to control <code>try</code>. </p>
1
2016-09-25T12:59:43Z
39,687,283
<p>You could temporarily redirect stdout and only print in the except: </p> <pre><code>import sys from StringIO import StringIO for i in range(0,100): sys.stdout = StringIO() try: print "a" print "b" print i, C print "d" except Exception as e: sys.stdout = sys.__stdout__ print i, "fail" # or print e sys.stdout = sys.__stdout__ </code></pre> <p>Which would give you:</p> <pre><code>0 fail 1 fail 2 fail 3 fail 4 fail 5 fail 6 fail 7 fail 8 fail 9 fail 10 fail 11 fail 12 fail 13 fail 14 fail 15 fail 16 fail 17 fail 18 fail 19 fail 20 fail 21 fail 22 fail 23 fail 24 fail 25 fail 26 fail 27 fail 28 fail 29 fail 30 fail 31 fail 32 fail 33 fail 34 fail 35 fail 36 fail 37 fail 38 fail 39 fail 40 fail 41 fail 42 fail 43 fail 44 fail 45 fail 46 fail 47 fail 48 fail 49 fail 50 fail 51 fail 52 fail 53 fail 54 fail 55 fail 56 fail 57 fail 58 fail 59 fail 60 fail 61 fail 62 fail 63 fail 64 fail 65 fail 66 fail 67 fail 68 fail 69 fail 70 fail 71 fail 72 fail 73 fail 74 fail 75 fail 76 fail 77 fail 78 fail 79 fail 80 fail 81 fail 82 fail 83 fail 84 fail 85 fail 86 fail 87 fail 88 fail 89 fail 90 fail 91 fail 92 fail 93 fail 94 fail 95 fail 96 fail 97 fail 98 fail 99 fail </code></pre> <p>But there are no doubt much better ways to do whatever it is you are trying to do in your real logic.</p> <p>Bar seeing into the future you cannot print in real time if all calls are going to be successful as you have not seen them all so you would need to store the output and see if there were any errors.</p> <pre><code>import sys from StringIO import StringIO stdo = StringIO() errs = False for i in range(0, 100): sys.stdout = stdo try: print "a" print "b" print i print "d" except Exception as e: sys.stdout = sys.__stdout__ errs = True print i, "fail" sys.stdout = stdo sys.stdout = sys.__stdout__ if not errs: print(stdo.getvalue()) </code></pre> <p>Any error will show in real time but you will have to wait until the end to see if all are successful.</p>
1
2016-09-25T13:21:22Z
[ "python" ]
Populating SQLite table with JSON data, getting: sqlite3.OperationalError: near "x": syntax error
39,687,292
<p>I have a SQLite database with four tables named restaurants, bars, attractions, and lodging. Each table has 3 columns named id, name, and description. I am trying to populate the database with data from a JSON file that looks like this:</p> <pre><code>{ "restaurants": [ {"id": "ChIJ8xR18JUn5IgRfwJJByM-quU", "name": "Columbia", "description": "Traditional Spanish restaurant, a branch of a long-standing local chain dating back to 1905."}, ], "bars": [ {"id": "ChIJ8aLBaJYn5IgR60p2CS_RHIw", "name": "Harrys", "description": "Chain outpost serving up Creole dishes in a leafy courtyard or on a balcony overlooking the bay."}, ], "attractions": [ {"id": "ChIJvRwErpUn5IgRaFNPl9Lv0eY", "name": "Flagler", "description": "Flagler College was founded in 1968. Formerly one of Henry Flagler's hotels, the college is allegedly home to many spirits. Tours are offered"}, ], "lodging": [ {"id": "ChIJz8NmD5Yn5IgRfgnWL-djaSM", "name": "Hemingway", "description": "Cottage-style B&amp;B offering a gourmet breakfast &amp; 6 rooms with private baths &amp; traditional decor."}, ] } </code></pre> <p>Whenever the script tries to execute the query, I get <code>sqlite3.OperationalError: near "x": syntax error</code> where x is a random word from one of the descriptions. An example error looks like this: <code>sqlite3.OperationalError: near "Spanish": syntax error</code>. The word is not always Spanish but it is always a word from one of the descriptions.</p> <p>I have tried a couple different methods but always get the same result, here is one method I have tried:</p> <pre><code>import sqlite3 import json places = json.load(open('locations.json')) db = sqlite3.connect('data.db') for place, data in places.items(): table = place for detail in data: query = 'INSERT OR IGNORE INTO ' + place + ' VALUES (?, ?, ?), (' \ + detail['id'] + ',' + detail['name'] + ',' + detail['description'] + ')' c = db.cursor() c.execute(query) c.close() </code></pre> <p>And I also tried writing the query like this:</p> <pre><code>query = 'INSERT OR IGNORE INTO {} VALUES ({}, {}, {})'\ .format(table, detail['id'], detail['name'], detail['description']) </code></pre>
0
2016-09-25T13:22:10Z
39,687,329
<p>Your current problem is the <em>missing quotes</em> around the string values in the query.</p> <p>You need to <em>properly parameterize your query</em> letting the database driver worry about the type conversions, putting quotes properly and escaping the parameters:</p> <pre><code>query = """ INSERT OR IGNORE INTO {} VALUES (?, ?, ?)""".format(table) c.execute(query, (detail['id'], detail['name'], detail['description'])) </code></pre> <p>Note that the <a href="http://stackoverflow.com/questions/3247183/variable-table-name-in-sqlite">table name cannot be parameterized</a> - we have to use string formatting to insert it into the query - make sure the table name is coming from a source you trust or/and properly validate it.</p>
3
2016-09-25T13:26:05Z
[ "python", "sql", "json", "python-3.x", "sqlite3" ]
python dicom -- getting pixel value from dicom file
39,687,295
<p>I was trying to get the pixelvalues of a dicom file in python using the dicom library.</p> <p>But it returns only an array with zeros. </p> <p>My code was like this:</p> <pre><code>import dicom import numpy ds=pydicom.read_file("sample.dcm") print(ds.pixel_array) </code></pre> <p>and the results is</p> <pre><code> [[0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0] ..., [0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0] [0 0 0 ..., 0 0 0]] </code></pre> <p>Do you have any idea how to get the values of the pixels?</p> <p>Thanks a lot in advance.</p> <p>Andras</p>
1
2016-09-25T13:22:24Z
39,689,711
<p>The code as written should work. It is possible that the beginning and end of the array are truly zeros.</p> <p>It is usually more meaningful to look at something in the middle of the image.</p> <p>E.g.:</p> <pre><code>midrow = ds.Rows // 2 midcol = ds.Columns // 2 print(ds.pixel_array[midrow-20:midrow+20, midcol-20:midcol+20]) </code></pre> <p>If it is truly zeros everywhere, then that is either the true image or some kind of bug. Perhaps reading with a dicom viewer can help if that hasn't been tried.</p>
1
2016-09-25T17:25:59Z
[ "python", "numpy", "pixel", "dicom" ]
Receiving the 404 error in getting of static django files
39,687,314
<p>Please help to understand what I do wrong.</p> <p>I have in my settings.py :</p> <pre><code>PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/' </code></pre> <p>And in index.html :</p> <pre><code>{% load static %} &lt;link rel="stylesheet" type="text/css" href="{% static "/css/table.css" %}"&gt; </code></pre> <p>But I still have the error 404 :</p> <pre><code>"GET /var/cardsite/cardsite/static/css/table.css HTTP/1.1" 404 1696 </code></pre> <p>I have this file :</p> <pre><code>ls -la /var/cardsite/cardsite/static/css/table.css -rw-r--r-- 1 root root 77 Sep 25 16:15 /var/cardsite/cardsite/static/css/table.css </code></pre> <p>So what is going on?</p> <p>P.S. My project stored on "/var/cardsite" and I want to make static folder on each application, like in example is default application "cardsite"</p> <p>thanks</p>
0
2016-09-25T13:24:42Z
39,687,376
<p>Read this <a href="https://docs.djangoproject.com/en/1.10/howto/static-files/" rel="nofollow">Django_Docs</a><br> You must also have a <code>STATIC_ROOT</code> option set before you can use the static files, heres some help add this to your code:</p> <pre><code>STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/' # Here you can add all the directories from where you want to use your js, css etc STATICFILES_DIRS = [ # This can be same as the static url os.path.join(PROJECT_ROOT, "static"), # also any other dir you wanna use "/any/other/static/path/you/wanna/use", ] # This is the static root dir from where django uses the files from. STATIC_ROOT = os.path.join(PROJECT_ROOT, "static_root") </code></pre> <p>you will also need to specify it in the <code>urls.py</code> file, just add the following code to the <code>urls.py</code> file:</p> <pre><code>from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) </code></pre> <p>after you add this, run the command:</p> <pre><code>python manage.py collectstatic </code></pre> <p>This will copy all the statics you need to the static root dir.</p>
1
2016-09-25T13:33:20Z
[ "python", "html", "css", "django", "static" ]
Find difference in list with identical values
39,687,380
<p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p> <p>example</p> <pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y'] b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y'] </code></pre> <p>How my problem is, both <code>'a task'</code> and <code>'another task'</code> both are followed by a <code>'j'</code></p> <pre><code>[x for x in b if x not in a] ['a task'] </code></pre> <p>Because both <code>a</code> and <code>b</code> contain <code>'j'</code>, it is removed from the list.</p> <p>How would I make so that I end up with </p> <pre><code>['a task', 'j'] </code></pre>
0
2016-09-25T13:33:32Z
39,687,410
<p>For <strong>simple list</strong> - what you ask is simply searching for that next item in the list:</p> <pre><code>&gt;&gt;&gt; a = ['cool task', 'b', 'another task', 'j', 'better task', 'y'] &gt;&gt;&gt; b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y'] &gt;&gt;&gt; c = [[x, b[b.index(x) + 1]] for x in b if x not in a] &gt;&gt;&gt; c [['a task', 'j']] </code></pre> <p>But I think you are actually aiming at using dictionary or tuples.</p> <p><strong>Tuples:</strong></p> <pre><code>&gt;&gt;&gt; a = [('cool task', 'b'), ('another task', 'j'), ('better task', 'y')] &gt;&gt;&gt; b = [('cool task', 'b'), ('a task', 'j'), ('another task', 'j'), ('better task', 'y')] &gt;&gt;&gt; c = [x for x in b if x not in a] &gt;&gt;&gt; c [('a task', 'j')] </code></pre> <p><strong>Dictionaries:</strong></p> <pre><code>&gt;&gt;&gt; a = {'cool task': 'b', 'another task': 'j', 'better task': 'y'} &gt;&gt;&gt; b = {'cool task': 'b', 'a task': 'j', 'another task': 'j', 'better task': 'y'} &gt;&gt;&gt; c = [(x, b[x]) for x in b if x not in a] &gt;&gt;&gt; c [('a task', 'j')] </code></pre>
1
2016-09-25T13:36:57Z
[ "python" ]
Find difference in list with identical values
39,687,380
<p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p> <p>example</p> <pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y'] b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y'] </code></pre> <p>How my problem is, both <code>'a task'</code> and <code>'another task'</code> both are followed by a <code>'j'</code></p> <pre><code>[x for x in b if x not in a] ['a task'] </code></pre> <p>Because both <code>a</code> and <code>b</code> contain <code>'j'</code>, it is removed from the list.</p> <p>How would I make so that I end up with </p> <pre><code>['a task', 'j'] </code></pre>
0
2016-09-25T13:33:32Z
39,687,513
<p>Depending on your purposes, you could possibly use <code>Counter</code> from the <a href="https://docs.python.org/3.6/library/collections.html" rel="nofollow">collections module</a>:</p> <pre><code>&gt;&gt;&gt; from collections import Counter &gt;&gt;&gt; a = Counter(['cool task', 'b', 'another task', 'j', 'better task', 'y']) &gt;&gt;&gt; b = Counter(['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y']) &gt;&gt;&gt; b-a Counter({'j': 1, 'a task': 1}) &gt;&gt;&gt; list((b-a).keys()) ['j', 'a task'] </code></pre>
0
2016-09-25T13:46:31Z
[ "python" ]
Find difference in list with identical values
39,687,380
<p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p> <p>example</p> <pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y'] b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y'] </code></pre> <p>How my problem is, both <code>'a task'</code> and <code>'another task'</code> both are followed by a <code>'j'</code></p> <pre><code>[x for x in b if x not in a] ['a task'] </code></pre> <p>Because both <code>a</code> and <code>b</code> contain <code>'j'</code>, it is removed from the list.</p> <p>How would I make so that I end up with </p> <pre><code>['a task', 'j'] </code></pre>
0
2016-09-25T13:33:32Z
39,687,534
<p>You could use the <a href="https://docs.python.org/3/library/difflib.html#sequencematcher-objects" rel="nofollow"><code>difflib.SequenceMatcher()</code> class</a> to enumerate added, removed and changed entries:</p> <pre><code>&gt;&gt;&gt; from difflib import SequenceMatcher &gt;&gt;&gt; matcher = SequenceMatcher(a=a, b=b) &gt;&gt;&gt; added = [] &gt;&gt;&gt; for tag, i1, i2, j1, j2 in matcher.get_opcodes(): ... if tag == 'insert': ... added += b[j1:j2] ... &gt;&gt;&gt; added ['a task', 'j'] </code></pre> <p>The above only focuses on added entries; if you need to know about entries that were <em>removed</em> or altered, then there are opcodes for those events too, see the <a href="https://docs.python.org/3/library/difflib.html#difflib.SequenceMatcher.get_opcodes" rel="nofollow"><code>SequenceMatcher.get_opcodes()</code> method documentation</a>.</p> <p>However, if your entries are always <em>paired</em>, then just produce sets with tuples from them (using <a href="http://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list">pair-wise iteration</a>); you can then do any set operations on these:</p> <pre><code>aset = set(zip(*([iter(a)] * 2))) bset = set(zip(*([iter(b)] * 2))) difference = bset - aset </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; aset = set(zip(*([iter(a)] * 2))) &gt;&gt;&gt; bset = set(zip(*([iter(b)] * 2))) &gt;&gt;&gt; aset {('another task', 'j'), ('cool task', 'b'), ('better task', 'y')} &gt;&gt;&gt; bset {('a task', 'j'), ('another task', 'j'), ('cool task', 'b'), ('better task', 'y')} &gt;&gt;&gt; bset - aset {('a task', 'j')} </code></pre>
1
2016-09-25T13:47:37Z
[ "python" ]
Find difference in list with identical values
39,687,380
<p>I need to be able to find differences in list that may have identical values to one another besides two added elements</p> <p>example</p> <pre><code>a = ['cool task', 'b', 'another task', 'j', 'better task', 'y'] b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y'] </code></pre> <p>How my problem is, both <code>'a task'</code> and <code>'another task'</code> both are followed by a <code>'j'</code></p> <pre><code>[x for x in b if x not in a] ['a task'] </code></pre> <p>Because both <code>a</code> and <code>b</code> contain <code>'j'</code>, it is removed from the list.</p> <p>How would I make so that I end up with </p> <pre><code>['a task', 'j'] </code></pre>
0
2016-09-25T13:33:32Z
39,687,769
<p>it works as you want:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- def difference(a, b): a, b = (lambda x, y: (y, x) if len(set(x)) &gt; len(set(y)) else (x, y)) (a, b) a_result = list(a) b_result = list(b) for z in range(len(a)): if a[z] in b: a_result.remove(a[z]) b_result.remove(a[z]) return a_result, b_result # or # return a_result if len(set(a_result)) &gt; len(set(b_result)) else b_result def main(): a = ['cool task', 'b', 'another task', 'j', 'better task', 'y'] b = ['cool task', 'b', 'a task', 'j', 'another task', 'j', 'better task', 'y'] print(difference(a, b)) if __name__ == "__main__": main() </code></pre>
0
2016-09-25T14:10:45Z
[ "python" ]
Tornado: How to get and return large data with less memory usage?
39,687,451
<p>I have web-crawler and http interface for it.</p> <p>Crawler gets grouped urls as dictionary. I need to return a result in the same format in JSON. But I was faced with a large memory usage, which is not returned to the operating system. How can I implement this solution without large memory usage?</p> <p>Code: </p> <pre><code>#!/usr/bin/env python # coding=utf-8 import collections import tornado.web import tornado.ioloop import tornado.queues import tornado.httpclient class ResponseError(Exception): pass class Crawler(object): client = tornado.httpclient.AsyncHTTPClient() def __init__(self, groups, concurrency=10, retries=3, validators=None): self.groups = groups self.concurrency = concurrency self.retries = retries self.validators = validators or [] self.requests = tornado.queues.Queue() self.responses = collections.defaultdict(list) async def worker(self): while True: await self.consume() async def validate(self, response): for validator in self.validators: validator(response) async def save(self, response): self.responses[response.request.group].append(response.body.decode('utf-8')) async def consume(self): async for request in self.requests: try: response = await self.client.fetch(request, raise_error=False) await self.validate(response) await self.save(response) except ResponseError: if request.retries &lt; self.retries: request.retries += 1 await self.requests.put(request) finally: self.requests.task_done() async def produce(self): for group, urls in self.groups.items(): for url in urls: request = tornado.httpclient.HTTPRequest(url) request.group = group request.retries = 0 await self.requests.put(request) async def fetch(self): await self.produce() for __ in range(self.concurrency): tornado.ioloop.IOLoop.current().spawn_callback(self.worker) await self.requests.join() class MainHandler(tornado.web.RequestHandler): async def get(self): urls = [] with open('urls') as f: # mock for line in f: urls.append(line.strip()) crawler = Crawler({'default': urls}) await crawler.fetch() self.write(crawler.responses) if __name__ == '__main__': app = tornado.web.Application( (tornado.web.url(r'/', MainHandler),), debug=True ) app.listen(8000) tornado.ioloop.IOLoop.current().start() </code></pre>
0
2016-09-25T13:40:26Z
39,691,452
<p>It looks to me like most of the memory usage is devoted to <code>self.responses</code>. Since you seem to be ordering responses by "group" before writing them to a file, I can understand why you do it this way. One idea is to store them in a database (MySQL or MongoDB or whatever) with the "group" as column or field value in the database record.</p> <p>The database might be the final destination of your data, or else it might be a temporary place to store the data until crawler.fetch completes. Then, query all the data from the database, ordered by "group", and write it to the file.</p> <p>This doesn't <em>solve</em> the problem, it just means that the database process is responsible for most of your memory usage, instead of the Python process. This may be preferable for you, however.</p>
0
2016-09-25T20:21:06Z
[ "python", "tornado" ]
python error in decoding base64 string
39,687,484
<p>I'm trying to unzip a base64 string,</p> <p>this is the code I'm using</p> <pre><code>def unzip_string(s) : s1 = base64.decodestring(urllib.unquote(s)) sio = StringIO.StringIO(s1) gzf = gzip.GzipFile(fileobj=sio) guff = gzf.read() return json.loads(guff) </code></pre> <p>i'm getting error Error: Incorrect padding</p> <p>where I try to unzip the same string using node.js code it works without a problem.</p> <p>where:</p> <pre><code>s == H4sIAAAAAAAAA22PW0/CQBCF/8s81wQosdA3TESJhhhb9cHwMN1O6Ybtbt0LhDT97+5yU4yPc+bMnO90YCyyDaSfHRimieQSG4IUaldABC1qbAykHbQsrzWZWokSUumEiMCQ3nJGCy9ADH0EFvWarJ+eHv11v4qgEIptqHyTlovzWes0q9HQ3X87Lh80Msp5gDhqzGlN0or9B1pWU5ldxV72c2/ODg0C7lUXu/U2p8XLpY35+6Mmtsn4WqLILFrnTRUKQxFwk7+fSL23+zX215VD/jE16CeojIzhSi5kpQ6xzVkIz76wuSmHRVINRuVtheMxDuLJJB5Nk5hRMkriaTGJh8MDn5LWv8v3bejzvFjez15/5EsNbuZo7FzpHepyJoTaBWqrHfX9N0/UAJ7qAQAA.bi0I1YDZ3V6AXu6aYTGO1JWi5tE5CoZli7aa6bFtqM4 </code></pre> <p>I've seen some suggestions to add '=' and other magic but it just results in the gzip module failing to open the file.</p> <p>any ideas?</p>
1
2016-09-25T13:43:51Z
39,687,677
<p>This worked for me (Python 3). The padding is indeed important, as you've seen in other answers:</p> <pre><code>import base64 import zlib import json s = b'H4sIAAAAAAAAA22PW0/CQBCF/8s81wQosdA3TESJhhhb9cHwMN1O6Ybtbt0LhDT97+5yU4yPc+bMnO90YCyyDaSfHRimieQSG4IUaldABC1qbAykHbQsrzWZWokSUumEiMCQ3nJGCy9ADH0EFvWarJ+eHv11v4qgEIptqHyTlovzWes0q9HQ3X87Lh80Msp5gDhqzGlN0or9B1pWU5ldxV72c2/ODg0C7lUXu/U2p8XLpY35+6Mmtsn4WqLILFrnTRUKQxFwk7+fSL23+zX215VD/jE16CeojIzhSi5kpQ6xzVkIz76wuSmHRVINRuVtheMxDuLJJB5Nk5hRMkriaTGJh8MDn5LWv8v3bejzvFjez15/5EsNbuZo7FzpHepyJoTaBWqrHfX9N0/UAJ7qAQAA.bi0I1YDZ3V6AXu6aYTGO1JWi5tE5CoZli7aa6bFtqM4' decoded = base64.urlsafe_b64decode(s + b'=') uncompressed = zlib.decompress(decoded, 16 + zlib.MAX_WBITS) unjsoned = json.loads(uncompressed.decode('utf-8')) print(unjsoned) </code></pre> <p>The <code>zlib.decompress(decoded, 16 + zlib.MAX_WBITS)</code> is a slightly more compact way to un-gzip a byte string.</p>
0
2016-09-25T14:01:49Z
[ "python", "base64", "gzip" ]
Weird behavior of send() and recv()
39,687,586
<p>SORRY FOR BAD ENGLISH</p> <p>Why if I have two <strong><code>send()</code></strong>-s on the server, and two <strong><code>recv()</code></strong>-s on the client, sometimes the first <code>recv()</code> will get the content of the 2nd <code>send()</code> from the server, without taking just the content of the first one and let the other <code>recv()</code> to take the "due and proper" content of the other <code>send()</code>?</p> <p>How can I get this work in an other way?</p>
1
2016-09-25T13:53:17Z
39,687,703
<p>Most probably you use SOCK_STREAM type socket. This is a TCP socket and that means that you push data to one side and it gets from the other side in the same order and without missing chunks, but there are no delimiters. So <code>send()</code> just sends data and <code>recv()</code> receives all the data available to the current moment.</p> <p>You can use SOCK_DGRAM and then UDP will be used. But in such case every <code>send()</code> will send a datagram and <code>recv()</code> will receive it. But you are not guaranteed that your datagrams will not be shuffled or lost, so you will have to deal with such problems yourself. There is also a limit on maximal datagram size.</p> <p>Or you can stick to TCP connection but then you have to send delimiters yourself.</p>
0
2016-09-25T14:05:36Z
[ "python" ]
Weird behavior of send() and recv()
39,687,586
<p>SORRY FOR BAD ENGLISH</p> <p>Why if I have two <strong><code>send()</code></strong>-s on the server, and two <strong><code>recv()</code></strong>-s on the client, sometimes the first <code>recv()</code> will get the content of the 2nd <code>send()</code> from the server, without taking just the content of the first one and let the other <code>recv()</code> to take the "due and proper" content of the other <code>send()</code>?</p> <p>How can I get this work in an other way?</p>
1
2016-09-25T13:53:17Z
39,687,709
<p>This is by design.</p> <p>A TCP stream is a channel on which you can send bytes between two endpoints but the transmission is stream-based, not message based.</p> <p>If you want to send messages then you need to encode them... for example by prepending a "size" field that will inform the receiver how many bytes to expect for the body.</p> <p>If you send 100 bytes and then other 100 bytes it's well possible that the receiver will instead see 200 at once, or even 50 + 150 in two different read commands. If you want message boundaries then you have to put them in the data yourself.</p> <p>There is a lower layer (datagrams) that allows to send messages, however they are limited in size and delivery is not guaranteed (i.e. it's possible that a message will get lost, that will be duplicated or that two messages you send will arrive in different order). TCP stream is built on top of this datagram service and implements all the logic needed to transfer data reliably between the two endpoints.</p> <p>As an alternative there are libraries designed to provide reliable message-passing between endpoints, like <a href="http://zeromq.org/" rel="nofollow">ZeroMQ</a>.</p>
1
2016-09-25T14:05:49Z
[ "python" ]
Python parsing html mismatched tag error
39,687,612
<pre><code>30 &lt;li class="start_1"&gt; 31 &lt;input type="checkbox" name="word_ids[]" value="34" class="list_check"&gt; 32 &lt;/li&gt; </code></pre> <p>This is a part of html file that I want to parse. But when I applied </p> <pre><code>uh = open('1.htm','r') data = uh.read() print data tree = ET.fromstring(data) </code></pre> <p>It showed</p> <blockquote> <p>xml.etree.ElementTree.ParseError: mismatched tag: line 32, column 18</p> </blockquote> <p>I don't know what is going wrong?</p>
0
2016-09-25T13:55:32Z
39,687,645
<p>You are trying to parse HTML with an <em>XML parser</em>; the latter doesn't have a concept of <code>&lt;input&gt;</code> not having a closing tag.</p> <p>Use an actual HTML parser; if you want to access the result with an ElementTree-compatible API, use the <code>lxml</code> project, which <a href="http://lxml.de/lxmlhtml.html" rel="nofollow">includes an HTML parser</a>. Otherwise, use <a href="https://www.crummy.com/software/BeautifulSoup/bs4/" rel="nofollow">BeautifulSoup</a> (which can use <code>lxml</code> under the hood as the parsing engine).</p>
0
2016-09-25T13:59:07Z
[ "python", "html", "parsing" ]
Python parsing html mismatched tag error
39,687,612
<pre><code>30 &lt;li class="start_1"&gt; 31 &lt;input type="checkbox" name="word_ids[]" value="34" class="list_check"&gt; 32 &lt;/li&gt; </code></pre> <p>This is a part of html file that I want to parse. But when I applied </p> <pre><code>uh = open('1.htm','r') data = uh.read() print data tree = ET.fromstring(data) </code></pre> <p>It showed</p> <blockquote> <p>xml.etree.ElementTree.ParseError: mismatched tag: line 32, column 18</p> </blockquote> <p>I don't know what is going wrong?</p>
0
2016-09-25T13:55:32Z
39,687,962
<p>To parse HTML in Python i use lxml:</p> <pre><code>import lxml.html // html string dom = '&lt;li class="start_1"&gt;...&lt;/li&gt;' // get the root node root_node = lxml.html.fromstring(dom) </code></pre> <p>after that you can play with it, for example using xpath:</p> <pre><code>nodes = root_node.xpath("//*") </code></pre>
0
2016-09-25T14:28:44Z
[ "python", "html", "parsing" ]
What the difference between dict_proxy in python2 and mappingproxy in python3?
39,687,713
<p>I notice when I create class in python2 it stores attributes in <code>dict_proxy</code> object: </p> <pre><code>&gt;&gt;&gt; class A(object): ... pass &gt;&gt;&gt; A.__dict__ dict_proxy({....}) </code></pre> <p>But in python3 <code>__dict__</code> returns <code>mappingproxy</code>: </p> <pre><code>&gt;&gt;&gt; class A(object): ... pass &gt;&gt;&gt; A.__dict__ mappingproxy({....}) </code></pre> <p>Is there any difference between two of them?</p>
2
2016-09-25T14:06:09Z
39,687,741
<p>There is no real difference, it <a href="https://hg.python.org/cpython/diff/c3a0197256ee/Objects/descrobject.c" rel="nofollow">just got renamed</a>.</p> <p>When it was proposed to expose the type in the <code>typing</code> module in <a href="http://bugs.python.org/issue14386" rel="nofollow">issue #14386</a>, the object was renamed too:</p> <blockquote> <p>I'd like to bikeshed a little on the name. I think it should be MappingProxy. (We don't use "view" much but the place where we do use it, for keys/values/items views, is very different I think. Also collections.abc already defines MappingView as the base class for KeysView and friends.)</p> </blockquote> <p>and</p> <blockquote> <p>Anyway, you are not the first one who remarks that we already use "view" to define something else, so I wrote a new patch to use the "mappingproxy" name (exposed as types.MappingProxyType).</p> </blockquote> <p>The change <a href="https://docs.python.org/3/whatsnew/3.3.html#types" rel="nofollow">made it into Python 3.3</a>, so in Python 3.2 you'll still see the old name.</p>
4
2016-09-25T14:08:22Z
[ "python", "python-3.x", "python-2.x", "python-internals" ]
finding variable in list
39,687,768
<p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p> <pre><code>list = ["a", "b", "c", "d"] list2 = [1,2,3,4] </code></pre> <p>With these lists, if the user inputs "a" then the computer works out that it is the first string in the list and picks out "1" from list2, or if they inputted "c", then it finds "3". However, due to the lists expanding and shrinking regularly, I can't use:</p> <pre><code>if input == list[0]: variable = list2[0] etc </code></pre> <p>I tried doing:</p> <pre><code>y = 0 x = 1 while x == 1: if input == list[y]: variable = list2[y] x = 2 else: y = y + 1 </code></pre> <p>but that didn't work, so is there anyway that this can be done? or am I being a mong and missing the obvious...</p>
0
2016-09-25T14:10:43Z
39,687,817
<pre><code>list1 = ["a", "b", "c", "d"] list2 = [1,2,3,4] needle = "c" for item1, item2 in zip(list1, list2): if item1 == needle: print(item2) </code></pre>
0
2016-09-25T14:15:52Z
[ "python", "list", "python-3.x" ]
finding variable in list
39,687,768
<p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p> <pre><code>list = ["a", "b", "c", "d"] list2 = [1,2,3,4] </code></pre> <p>With these lists, if the user inputs "a" then the computer works out that it is the first string in the list and picks out "1" from list2, or if they inputted "c", then it finds "3". However, due to the lists expanding and shrinking regularly, I can't use:</p> <pre><code>if input == list[0]: variable = list2[0] etc </code></pre> <p>I tried doing:</p> <pre><code>y = 0 x = 1 while x == 1: if input == list[y]: variable = list2[y] x = 2 else: y = y + 1 </code></pre> <p>but that didn't work, so is there anyway that this can be done? or am I being a mong and missing the obvious...</p>
0
2016-09-25T14:10:43Z
39,687,843
<h2>Option 1</h2> <p>This is probably the simplest solution:</p> <pre><code>&gt;&gt;&gt; list1 = ["a", "b", "c", "d"] &gt;&gt;&gt; list2 = [1, 2, 3, 4] &gt;&gt;&gt; &gt;&gt;&gt; mapping = dict(zip(list1, list2)) &gt;&gt;&gt; &gt;&gt;&gt; mapping['b'] 2 </code></pre> <p>BTW, to understand what happened:</p> <pre><code>&gt;&gt;&gt; zip(list1, list2) [('a', 1), ('b', 2), ('c', 3), ('d', 4)] &gt;&gt;&gt; dict(zip(list1, list2)) {'a': 1, 'c': 3, 'b': 2, 'd': 4} </code></pre> <h2>Option 2</h2> <p>Anyway, you asked how to get the index in the list. Use <code>index</code>:</p> <pre><code>&gt;&gt;&gt; list1.index('c') 2 </code></pre> <p>And then:</p> <pre><code>&gt;&gt;&gt; list2[list1.index('c')] 3 </code></pre> <hr> <p>Also... don't name your lists <code>list</code> because that way you are "hiding" the builtin <code>list</code>.</p>
0
2016-09-25T14:17:39Z
[ "python", "list", "python-3.x" ]
finding variable in list
39,687,768
<p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p> <pre><code>list = ["a", "b", "c", "d"] list2 = [1,2,3,4] </code></pre> <p>With these lists, if the user inputs "a" then the computer works out that it is the first string in the list and picks out "1" from list2, or if they inputted "c", then it finds "3". However, due to the lists expanding and shrinking regularly, I can't use:</p> <pre><code>if input == list[0]: variable = list2[0] etc </code></pre> <p>I tried doing:</p> <pre><code>y = 0 x = 1 while x == 1: if input == list[y]: variable = list2[y] x = 2 else: y = y + 1 </code></pre> <p>but that didn't work, so is there anyway that this can be done? or am I being a mong and missing the obvious...</p>
0
2016-09-25T14:10:43Z
39,687,848
<p>Here's a simple version of what I think you're trying to accomplish:</p> <pre><code>a = ['a', 'b', 'c', 'd'] b = [1, 2, 3, 4] ret = input("Search: ") try: idx = a.index(ret) print(b[idx]) except ValueError: print("Item not found") </code></pre>
0
2016-09-25T14:17:54Z
[ "python", "list", "python-3.x" ]
finding variable in list
39,687,768
<p>I am trying to retrieve a word from a list; I am asking the user to input a word which is part of a list, I then want to find the position of the word in that list, for example,</p> <pre><code>list = ["a", "b", "c", "d"] list2 = [1,2,3,4] </code></pre> <p>With these lists, if the user inputs "a" then the computer works out that it is the first string in the list and picks out "1" from list2, or if they inputted "c", then it finds "3". However, due to the lists expanding and shrinking regularly, I can't use:</p> <pre><code>if input == list[0]: variable = list2[0] etc </code></pre> <p>I tried doing:</p> <pre><code>y = 0 x = 1 while x == 1: if input == list[y]: variable = list2[y] x = 2 else: y = y + 1 </code></pre> <p>but that didn't work, so is there anyway that this can be done? or am I being a mong and missing the obvious...</p>
0
2016-09-25T14:10:43Z
39,687,919
<pre><code>list1 = ["a", "b", "c", "d"] list2 = [1,2,3,4] x = input() if x in list1 : print list2[list1.index(x)] else : print "Error" </code></pre>
0
2016-09-25T14:25:10Z
[ "python", "list", "python-3.x" ]
How to replace properly certain matches on QScintilla widget?
39,687,797
<p>I got this little mcve code:</p> <pre><code>import sys import re from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtCore import Qt from PyQt5.Qsci import QsciScintilla from PyQt5 import Qsci class FloatSlider(QtWidgets.QWidget): value_changed = QtCore.pyqtSignal(float) def __init__(self, value=0.0, parent=None): super().__init__(parent) self.slider = QtWidgets.QSlider(Qt.Horizontal) self.label = QtWidgets.QLabel() self.label.setAlignment(Qt.AlignCenter) self.adjust(value) layout = QtWidgets.QHBoxLayout() layout.addWidget(self.slider) layout.addWidget(self.label) self.slider.valueChanged.connect(self.on_value_changed) self.setLayout(layout) self.setWindowTitle("Adjust number") def adjust(self, value): width = 100 # TODO: Adjust it properly depending on input value self.slider.setRange(value - width, value + width) self.slider.setSingleStep(1) self.slider.setValue(value) self.label.setText(str(float(value))) def on_value_changed(self, value): # vmax, vmin = self.slider.minimum(), self.slider.maximum() # value = 2 * value / (vmax - vmin) self.label.setText(str(float(value))) self.value_changed.emit(value) class SimpleEditor(QsciScintilla): def __init__(self, language=None, parent=None): super().__init__(parent) self.slider = FloatSlider(value=0.0) self.slider.value_changed.connect(self.float_value_changed) font = QtGui.QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) fontmetrics = QtGui.QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, fontmetrics.width("00000") + 6) self.setMarginLineNumbers(0, True) self.setMarginsBackgroundColor(QtGui.QColor("#cccccc")) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QtGui.QColor("#E8E8FF")) if language: self.lexer = getattr(Qsci, 'QsciLexer' + language)() self.setLexer(self.lexer) self.SendScintilla(QsciScintilla.SCI_FOLDALL, True) self.setAutoCompletionThreshold(1) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setFolding(QsciScintilla.BoxedTreeFoldStyle) # Signals/Slots self.cursorPositionChanged.connect(self.on_cursor_position_changed) self.copyAvailable.connect(self.on_copy_available) self.indicatorClicked.connect(self.on_indicator_clicked) self.indicatorReleased.connect(self.on_indicator_released) self.linesChanged.connect(self.on_lines_changed) self.marginClicked.connect(self.on_margin_clicked) self.modificationAttempted.connect(self.on_modification_attempted) self.modificationChanged.connect(self.on_modification_changed) self.selectionChanged.connect(self.on_selection_changed) self.textChanged.connect(self.on_text_changed) self.userListActivated.connect(self.on_user_list_activated) def float_value_changed(self, v): print(v) def on_cursor_position_changed(self, line, index): text = self.text(line) for match in re.finditer('(?:^|(?&lt;=\W))\d+(?:\.\d+)?(?=$|\W)', text): start, end = match.span() if start &lt;= index &lt;= end: pos = self.positionFromLineIndex(line, start) x = self.SendScintilla( QsciScintilla.SCI_POINTXFROMPOSITION, 0, pos) y = self.SendScintilla( QsciScintilla.SCI_POINTYFROMPOSITION, 0, pos) point = self.mapToGlobal(QtCore.QPoint(x, y)) num = float(match.group()) message = 'number: %s' % num self.slider.setWindowTitle('line: {0}'.format(line)) self.slider.adjust(num) self.slider.move(point + QtCore.QPoint(0, 20)) self.slider.show() break def on_copy_available(self, yes): print('-' * 80) print("on_copy_available") def on_indicator_clicked(self, line, index, state): print("on_indicator_clicked") def on_indicator_released(self, line, index, state): print("on_indicator_released") def on_lines_changed(self): print("on_lines_changed") def on_margin_clicked(self, margin, line, state): print("on_margin_clicked") def on_modification_attempted(self): print("on_modification_attempted") def on_modification_changed(self): print("on_modification_changed") def on_selection_changed(self): print("on_selection_changed") def on_text_changed(self): print("on_text_changed") def on_user_list_activated(self, id, text): print("on_user_list_activated") def show_requirements(): print(sys.version) print(QtCore.QT_VERSION_STR) print(QtCore.PYQT_VERSION_STR) if __name__ == "__main__": show_requirements() app = QtWidgets.QApplication(sys.argv) ex = QtWidgets.QWidget() hlayout = QtWidgets.QHBoxLayout() ed = SimpleEditor("JavaScript") hlayout.addWidget(ed) ed.setText("""#ifdef GL_ES precision mediump float; #endif #extension GL_OES_standard_derivatives : enable uniform float time; uniform vec2 mouse; uniform vec2 resolution; void main( void ) { vec2 st = ( gl_FragCoord.xy / resolution.xy ); vec2 lefbot = step(vec2(0.1), st); float pct = lefbot.x*lefbot.y; vec2 rigtop = step(vec2(0.1), 1.-st); pct *= rigtop.x*rigtop.y; vec3 color = vec3(pct); gl_FragColor = vec4( color, 1.0 );""") ex.setLayout(hlayout) ex.show() ex.resize(800, 600) sys.exit(app.exec_()) </code></pre> <p>There are several issues I don't know how to address:</p> <ul> <li>My slider widget is changing the widget width every time I change values, I tried <code>addStrecht(1)</code> but it didn't work as I intended as there was too much empty space between widgets (ie: layout arrangement -> slider|strecht|label)</li> <li>Once I type a numeric value on the QScintilla widget the FloatSlider widget will appear and that's definitely something I don't want. I'd like it to appear only when I press such numeric value with the left mouse button or any other combination (ie: ctrl+left_mouse)</li> <li>I don't know how to replace properly the QScintilla text (regex match) on realtime. Ideally only the QScintilla matched text should be modified, for instance, I don't want to replace the whole text because the visual effect would be quite creepy</li> </ul> <p>It didn't feel like opening 3 different questions for these little doubts was ok so I've decided to gather them in the same thread. Hopefully that's ok</p>
1
2016-09-25T14:13:21Z
39,689,109
<p>On the second bullet point: I think you should give up the idea of having a separate window/dialog for the slider. It should instead be a popup that stays on top of the editor until you click outside it or press escape (i.e. like a tooltip, or context menu).</p> <p>To give you an idea of how this might look (but without attempting to solve any of the other potential issues), try something like this:</p> <pre><code>class FloatSlider(QtWidgets.QFrame): value_changed = QtCore.pyqtSignal(float) def __init__(self, value=0.0): super().__init__() ... self.setFrameShape(QtWidgets.QFrame.Box) self.setFrameShadow(QtWidgets.QFrame.Plain) self.setParent(None, QtCore.Qt.Popup) self.setFocusPolicy(QtCore.Qt.NoFocus) def adjust(self, value): ... self.slider.setFocus() </code></pre>
1
2016-09-25T16:22:12Z
[ "python", "python-3.x", "pyqt", "qscintilla" ]
How to replace properly certain matches on QScintilla widget?
39,687,797
<p>I got this little mcve code:</p> <pre><code>import sys import re from PyQt5 import QtGui, QtWidgets, QtCore from PyQt5.QtCore import Qt from PyQt5.Qsci import QsciScintilla from PyQt5 import Qsci class FloatSlider(QtWidgets.QWidget): value_changed = QtCore.pyqtSignal(float) def __init__(self, value=0.0, parent=None): super().__init__(parent) self.slider = QtWidgets.QSlider(Qt.Horizontal) self.label = QtWidgets.QLabel() self.label.setAlignment(Qt.AlignCenter) self.adjust(value) layout = QtWidgets.QHBoxLayout() layout.addWidget(self.slider) layout.addWidget(self.label) self.slider.valueChanged.connect(self.on_value_changed) self.setLayout(layout) self.setWindowTitle("Adjust number") def adjust(self, value): width = 100 # TODO: Adjust it properly depending on input value self.slider.setRange(value - width, value + width) self.slider.setSingleStep(1) self.slider.setValue(value) self.label.setText(str(float(value))) def on_value_changed(self, value): # vmax, vmin = self.slider.minimum(), self.slider.maximum() # value = 2 * value / (vmax - vmin) self.label.setText(str(float(value))) self.value_changed.emit(value) class SimpleEditor(QsciScintilla): def __init__(self, language=None, parent=None): super().__init__(parent) self.slider = FloatSlider(value=0.0) self.slider.value_changed.connect(self.float_value_changed) font = QtGui.QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) fontmetrics = QtGui.QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(0, fontmetrics.width("00000") + 6) self.setMarginLineNumbers(0, True) self.setMarginsBackgroundColor(QtGui.QColor("#cccccc")) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QtGui.QColor("#E8E8FF")) if language: self.lexer = getattr(Qsci, 'QsciLexer' + language)() self.setLexer(self.lexer) self.SendScintilla(QsciScintilla.SCI_FOLDALL, True) self.setAutoCompletionThreshold(1) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setFolding(QsciScintilla.BoxedTreeFoldStyle) # Signals/Slots self.cursorPositionChanged.connect(self.on_cursor_position_changed) self.copyAvailable.connect(self.on_copy_available) self.indicatorClicked.connect(self.on_indicator_clicked) self.indicatorReleased.connect(self.on_indicator_released) self.linesChanged.connect(self.on_lines_changed) self.marginClicked.connect(self.on_margin_clicked) self.modificationAttempted.connect(self.on_modification_attempted) self.modificationChanged.connect(self.on_modification_changed) self.selectionChanged.connect(self.on_selection_changed) self.textChanged.connect(self.on_text_changed) self.userListActivated.connect(self.on_user_list_activated) def float_value_changed(self, v): print(v) def on_cursor_position_changed(self, line, index): text = self.text(line) for match in re.finditer('(?:^|(?&lt;=\W))\d+(?:\.\d+)?(?=$|\W)', text): start, end = match.span() if start &lt;= index &lt;= end: pos = self.positionFromLineIndex(line, start) x = self.SendScintilla( QsciScintilla.SCI_POINTXFROMPOSITION, 0, pos) y = self.SendScintilla( QsciScintilla.SCI_POINTYFROMPOSITION, 0, pos) point = self.mapToGlobal(QtCore.QPoint(x, y)) num = float(match.group()) message = 'number: %s' % num self.slider.setWindowTitle('line: {0}'.format(line)) self.slider.adjust(num) self.slider.move(point + QtCore.QPoint(0, 20)) self.slider.show() break def on_copy_available(self, yes): print('-' * 80) print("on_copy_available") def on_indicator_clicked(self, line, index, state): print("on_indicator_clicked") def on_indicator_released(self, line, index, state): print("on_indicator_released") def on_lines_changed(self): print("on_lines_changed") def on_margin_clicked(self, margin, line, state): print("on_margin_clicked") def on_modification_attempted(self): print("on_modification_attempted") def on_modification_changed(self): print("on_modification_changed") def on_selection_changed(self): print("on_selection_changed") def on_text_changed(self): print("on_text_changed") def on_user_list_activated(self, id, text): print("on_user_list_activated") def show_requirements(): print(sys.version) print(QtCore.QT_VERSION_STR) print(QtCore.PYQT_VERSION_STR) if __name__ == "__main__": show_requirements() app = QtWidgets.QApplication(sys.argv) ex = QtWidgets.QWidget() hlayout = QtWidgets.QHBoxLayout() ed = SimpleEditor("JavaScript") hlayout.addWidget(ed) ed.setText("""#ifdef GL_ES precision mediump float; #endif #extension GL_OES_standard_derivatives : enable uniform float time; uniform vec2 mouse; uniform vec2 resolution; void main( void ) { vec2 st = ( gl_FragCoord.xy / resolution.xy ); vec2 lefbot = step(vec2(0.1), st); float pct = lefbot.x*lefbot.y; vec2 rigtop = step(vec2(0.1), 1.-st); pct *= rigtop.x*rigtop.y; vec3 color = vec3(pct); gl_FragColor = vec4( color, 1.0 );""") ex.setLayout(hlayout) ex.show() ex.resize(800, 600) sys.exit(app.exec_()) </code></pre> <p>There are several issues I don't know how to address:</p> <ul> <li>My slider widget is changing the widget width every time I change values, I tried <code>addStrecht(1)</code> but it didn't work as I intended as there was too much empty space between widgets (ie: layout arrangement -> slider|strecht|label)</li> <li>Once I type a numeric value on the QScintilla widget the FloatSlider widget will appear and that's definitely something I don't want. I'd like it to appear only when I press such numeric value with the left mouse button or any other combination (ie: ctrl+left_mouse)</li> <li>I don't know how to replace properly the QScintilla text (regex match) on realtime. Ideally only the QScintilla matched text should be modified, for instance, I don't want to replace the whole text because the visual effect would be quite creepy</li> </ul> <p>It didn't feel like opening 3 different questions for these little doubts was ok so I've decided to gather them in the same thread. Hopefully that's ok</p>
1
2016-09-25T14:13:21Z
39,732,180
<ul> <li>Use <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qwidget.html#setFixedWidth" rel="nofollow">setFixedWidth</a> to avoid either the slider or label changing width on every change</li> <li>You shouldn't use <code>on_cursor_position_changed</code> event, instead just use <code>mouseReleaseEvent</code></li> <li>A good way to replace certain matches at certain position would be instead using <code>setText</code> using <code>insertAt</code> and <code>SCI_DELETERANGE</code> methods. For more information check <a href="http://pyqt.sourceforge.net/Docs/QScintilla2/index.html" rel="nofollow">QScintilla docs</a></li> </ul>
0
2016-09-27T18:46:49Z
[ "python", "python-3.x", "pyqt", "qscintilla" ]
XPath returns empty list. Why is it ignoring targeted div element?
39,687,878
<p>I'm a newbee to XPath and Scrapy. I'm trying to target a node which does not have a unique class (i.e. <code>class="pubBody"</code>). </p> <p>Already tried: <a href="http://stackoverflow.com/questions/28163626/xpath-not-contains-a-and-b">xpath not contains A and B</a></p> <p>This should be a simple task but XPath just misses the second item. I am doing this from the scrapy shell. On the command prompt:</p> <p>scrapy shell "<a href="http://www.sciencedirect.com/science/journal/00221694/" rel="nofollow">http://www.sciencedirect.com/science/journal/00221694/</a>"</p> <p>I am looking for the second div:</p> <pre><code>&lt;div id="issueListHeader" class="pubBody"&gt;...&lt; /div&gt; &lt;div class="pubBody"&gt;... &lt; /div&gt; </code></pre> <p>I can only get the first but not the second. The best answers to similar questions suggested trying something like:</p> <pre><code>hxs.xpath('//div[contains(@class,"pubBody") and not(contains(@id,"issueListHeader"))]') </code></pre> <p>but this returns an empty list for some reason. Any help please? Must be missing something silly, I've tried this for days!</p> <p>Other details:</p> <p>Once in the scrapy shell:</p> <pre><code>import scrapy xs = scrapy.Selector(response) hxs.xpath('//div[@class="pubBody"]') </code></pre> <p>Which works only for the first div element:</p> <pre><code>[&lt;Selector xpath='//div[@class="pubBody"]' data='&lt;div id="issueListHeader" class="pubBody'&gt;] </code></pre> <p>For the failed second div element I've also tried:</p> <pre><code>hxs.xpath('//div[@class="pubBody" and not(@id="issueListHeader")]').extract_first() hxs.xpath('//div[starts-with(@class, "pubBody") and not(re:test(@id, "issueListHeader"))]') </code></pre> <p>Also directly copied the XPath from Chrome, but also returns '[]':</p> <pre><code>hxs.xpath('//*[@id="issueList"]/div/form/div[2]') </code></pre>
1
2016-09-25T14:20:32Z
39,688,035
<p>I suspect the problem is that the source for the page you'r trying to parse (<a href="http://www.sciencedirect.com/science/journal/00221694/" rel="nofollow">http://www.sciencedirect.com/science/journal/00221694/</a>) is not valid XML due to the <code>&lt;link ...&gt;</code> nodes/elements/tags not having closing tags. There may be other problems, but those are the first ones I found.</p> <p>I'm rusty on Javascript, but you may try navigating down the DOM down to a lower level in the page (ie. body or some other node closer to the elements you're trying to target) and then perform the XPath from that level.</p> <p><strong>UPDATE:</strong> I just tried removing the <code>&lt;head&gt;</code> of the document and passing it through an XML parser and it still breaks on sever <code>&lt;input&gt;</code> nodes that are not closed. Unless I'm forgetting some special JavaScript XML/XPath rules methods that dismiss closing tags I suspect you might be better suited to use something like JQuery to find the elements you're looking for.</p>
0
2016-09-25T14:35:38Z
[ "python", "html", "xpath", "scrapy", "html-parsing" ]
XPath returns empty list. Why is it ignoring targeted div element?
39,687,878
<p>I'm a newbee to XPath and Scrapy. I'm trying to target a node which does not have a unique class (i.e. <code>class="pubBody"</code>). </p> <p>Already tried: <a href="http://stackoverflow.com/questions/28163626/xpath-not-contains-a-and-b">xpath not contains A and B</a></p> <p>This should be a simple task but XPath just misses the second item. I am doing this from the scrapy shell. On the command prompt:</p> <p>scrapy shell "<a href="http://www.sciencedirect.com/science/journal/00221694/" rel="nofollow">http://www.sciencedirect.com/science/journal/00221694/</a>"</p> <p>I am looking for the second div:</p> <pre><code>&lt;div id="issueListHeader" class="pubBody"&gt;...&lt; /div&gt; &lt;div class="pubBody"&gt;... &lt; /div&gt; </code></pre> <p>I can only get the first but not the second. The best answers to similar questions suggested trying something like:</p> <pre><code>hxs.xpath('//div[contains(@class,"pubBody") and not(contains(@id,"issueListHeader"))]') </code></pre> <p>but this returns an empty list for some reason. Any help please? Must be missing something silly, I've tried this for days!</p> <p>Other details:</p> <p>Once in the scrapy shell:</p> <pre><code>import scrapy xs = scrapy.Selector(response) hxs.xpath('//div[@class="pubBody"]') </code></pre> <p>Which works only for the first div element:</p> <pre><code>[&lt;Selector xpath='//div[@class="pubBody"]' data='&lt;div id="issueListHeader" class="pubBody'&gt;] </code></pre> <p>For the failed second div element I've also tried:</p> <pre><code>hxs.xpath('//div[@class="pubBody" and not(@id="issueListHeader")]').extract_first() hxs.xpath('//div[starts-with(@class, "pubBody") and not(re:test(@id, "issueListHeader"))]') </code></pre> <p>Also directly copied the XPath from Chrome, but also returns '[]':</p> <pre><code>hxs.xpath('//*[@id="issueList"]/div/form/div[2]') </code></pre>
1
2016-09-25T14:20:32Z
39,688,065
<p>The problem is that the <em>HTML is very far from being well-formed on this page</em>. To demonstrate, see how the same exact CSS selector is producing 0 results with Scrapy and producing 94 in <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow"><code>BeautifulSoup</code></a>:</p> <pre><code>In [1]: from bs4 import BeautifulSoup In [2]: soup = BeautifulSoup(response.body, 'html5lib') # note: "html5lib" has to be installed In [3]: len(soup.select(".article h4 a")) Out[3]: 94 In [4]: len(response.css(".article h4 a")) Out[4]: 0 </code></pre> <p>Same goes for the <code>pubBody</code> element you are trying to locate:</p> <pre><code>In [6]: len(response.css(".pubBody")) Out[6]: 1 In [7]: len(soup.select(".pubBody")) Out[7]: 2 </code></pre> <p>So, try hooking up <code>BeautifulSoup</code> to fix/clean up the HTML - ideally through a <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#writing-your-own-downloader-middleware" rel="nofollow">middleware</a>.</p> <hr> <p>I've created a simple <a href="https://github.com/alecxe/scrapy-beautifulsoup" rel="nofollow"><code>scrapy_beautifulsoup</code> middleware</a> to easily hook up into the project:</p> <ul> <li><p>install it via pip:</p> <pre><code>pip install scrapy-beautifulsoup </code></pre></li> <li><p>configure the middleware in <code>settings.py</code>:</p> <pre><code>DOWNLOADER_MIDDLEWARES = { 'scrapy_beautifulsoup.middleware.BeautifulSoupMiddleware': 543 } BEAUTIFULSOUP_PARSER = "html5lib" </code></pre></li> </ul> <p>Profit.</p>
1
2016-09-25T14:38:15Z
[ "python", "html", "xpath", "scrapy", "html-parsing" ]
calculating result of a function for a column of a dataframe in python
39,687,917
<p>I am working on a dataframe in python to calculate the distance between a location and <code>LATITUDE</code> and <code>LONGITUDE</code> column in the dataframe. When I run the code below, there is no error:</p> <pre><code>lLat= 43.679194 lLon= -79.633352 LCentroid= (lLat, lLon) # getDistanceBetween gets two centroids and calculate the distance dfTowers['distance']= HL.getDistanceBetween(LCentroid, dfTowers.index.get_level_values('LATITUDE')[0], dfTowers.index.get_level_values('LONGITUDE')[0])) </code></pre> <p>but when I use the below one, there is an error </p> <pre><code>lLat= 43.679194 lLon= -79.633352 LCentroid= (lLat, lLon) dfTowers['distance']= HL.getDistanceBetween(LCentroid, dfTowers.index.get_level_values('LATITUDE'), dfTowers.index.get_level_values('LONGITUDE'))) </code></pre> <p>and the error is:</p> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-43-065640ee0e20&gt; in &lt;module&gt;() 5 6 dfTowers['distance']= HL.getDistanceBetween(LCentroid, (dfTowers.index.get_level_values('LATITUDE'), ----&gt; 7 dfTowers.index.get_level_values('LONGITUDE'))) C:\Users\x190523\Documents\python exercice\HomeLocation.pyc in getDistanceBetween(c1, c2) TypeError: a float is required </code></pre>
1
2016-09-25T14:24:40Z
39,688,383
<p>Because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.get_level_values.html" rel="nofollow"><code>get_level_values</code></a> return a "vector" of labels. In your first example, you access the vector and appropriately retrieve the value. In your second example, you pass the entire vector and <code>getDistanceBetween</code> doesn't know what to do with it.</p> <p>Edit: Now to compute it for all rows, we don't need any of the syntax fr above </p> <pre><code># add the new column, initialized to NaN dfTowers['distance'] = np.nan for row_name, row in dfTowers.iterrows(): row['distance'] = HL.getDistanceBetween(LCentroid, row['LATITUDE'], row['LONGITUDE']) </code></pre>
1
2016-09-25T15:06:57Z
[ "python", "function", "pandas", "dataframe" ]
PyInstaller lib not found
39,687,975
<p>I made a simple python[3.5.2] program using tkinter. When I use pyinstaller[3.2] on it it gives me a ton of 'lib not found' warnings. Example:</p> <blockquote> <p>2999 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\python\python.exe</p> <p>3031 WARNING: lib not found: api-ms-win-crt-heap-l1-1-0.dll dependency of c:\python\python.exe</p> <p>3218 WARNING: lib not found: api-ms-win-crt-runtime-l1-1-0.dll dependency of c:\python\VCRUNTIME140.dll</p> <p>3312 WARNING: lib not found: api-ms-win-crt-convert-l1-1-0.dll dependency of c:\python\VCRUNTIME140.dll</p> <p>6494 WARNING: lib not found: api-ms-win-crt-heap-l1-1-0.dll dependency of c:\python\DLLs_hashlib.pyd</p> <p>7271 WARNING: lib not found: api-ms-win-crt-stdio-l1-1-0.dll dependency of c:\python\DLLs\unicodedata.pyd</p> </blockquote> <p>.bat file I use to make executables is</p> <blockquote> <p>@echo off</p> <p>set /p file_name="Enter file name: "</p> <p>pyinstaller %0..\%file_name%\%file_name%.py --onefile --windowed --distpath %0..\%file_name% --name=%file_name%</p> <p>del %file_name%.spec</p> <p>rmdir /s /q build</p> <p>echo.</p> <p>pause</p> </blockquote> <p>What am I doing wrong? Windows 10 64bit</p>
0
2016-09-25T14:29:37Z
40,001,914
<p>Just had this problem myself. The problem is that pyinstaller is not fully compatible Windows 10. The only solution currently is to download the Windows 10 SDK (a 2GB download). </p> <p>See more here: <a href="https://github.com/pyinstaller/pyinstaller/issues/1566" rel="nofollow">https://github.com/pyinstaller/pyinstaller/issues/1566</a></p>
0
2016-10-12T14:59:44Z
[ "python", "python-3.x", "dll", "tkinter", "pyinstaller" ]
Drawing on tkinter canvas from command line
39,688,049
<p>I read some tutorial (basic) on tkinter and learned how to create a mainloop and add gui elements to that. Also learned how to bind actions to button widgets.</p> <p>Now I would like to do this: </p> <ol> <li>launch the tkinter canvas</li> <li>be able to read command from the console and update the canvas after those commands.</li> </ol> <p>example: I write command with arguments on the console and some graphics elements is being added to the canvas (and canvas is updated after).</p> <p>Is something possible, maybe threding related? Can you point me in one direction which you think is the most reasonable to follow?</p>
-1
2016-09-25T14:36:33Z
39,688,374
<p>Here's a simple demo of grabbing user input from the console via the standard <code>input</code> function. This technique is a little clunky, since we have to explicitly tell Tkinter to fetch the input string by clicking on a Button (or some other GUI event), but that might not be a big deal for your application.</p> <pre><code>import tkinter as tk root = tk.Tk() stuff = tk.StringVar() display = tk.Label(root, textvariable=stuff) display.pack() def get_input(): s = input("CMD: ") stuff.set(s) tk.Button(root, text="Get input", command=get_input).pack() root.mainloop() </code></pre> <p>When you click on the <code>"Get input"</code> Button, the "CMD: " prompt will be printed in the console window. Once the input is entered, the string is copied to the Label. Bad Things™ will happen if you click the button again before the input line is entered. :)</p>
0
2016-09-25T15:06:25Z
[ "python", "canvas", "tkinter" ]
Drawing on tkinter canvas from command line
39,688,049
<p>I read some tutorial (basic) on tkinter and learned how to create a mainloop and add gui elements to that. Also learned how to bind actions to button widgets.</p> <p>Now I would like to do this: </p> <ol> <li>launch the tkinter canvas</li> <li>be able to read command from the console and update the canvas after those commands.</li> </ol> <p>example: I write command with arguments on the console and some graphics elements is being added to the canvas (and canvas is updated after).</p> <p>Is something possible, maybe threding related? Can you point me in one direction which you think is the most reasonable to follow?</p>
-1
2016-09-25T14:36:33Z
39,688,717
<p>Came up with this:</p> <pre><code>from Tkinter import * import random root = Tk() width = 800 height = 600 def key(event): s = raw_input("CMD: ") if s == 'quit': root.destroy() if s == 'l': x1 = random.randint(0,width) x2 = random.randint(0,width) y1 = random.randint(0,height) y2 = random.randint(0,height) frame.create_line(x1,y1,x2,y2) frame.focus_force() frame = Canvas(root, width=width, height=height) frame.bind("&lt;Key&gt;", key) frame.pack() frame.focus_set() root.mainloop() </code></pre> <p>In this way it is a bit complicated because before entering something on the console I have to get the focus back clicking on its window. Maybe it would be nicer to read command from Tkinter directly and then opening dialogs for setting up command parameters.</p>
0
2016-09-25T15:41:59Z
[ "python", "canvas", "tkinter" ]
Downloading pdf from a site after submitting a form with beautifulsoup
39,688,059
<p>I am currently writing a crawler script with python.I am aware of beautifulsoup packages and have did some simple crawlers.currently am writing a crawler for a site which has four dropdown, after select the four dropdown if I press the download button a pdf will be downloaded.I have tried it by requests with this script.</p> <pre><code>post_data = { 'select name 1' : 'value 1', 'select name 2' : 'value 2', 'select name 3' : 'value 3', 'select name 4' : 'value 4', } r = requests.post("http://mydemosite.aspx",data=post_data) </code></pre> <p>which is not working.I want to use Beautifulsoup to select the four dropdown and make a virtual formsubmit and get the appropriate pdf.Is it possible to acheive this(subbmitting a form) with beautiful soup.</p>
0
2016-09-25T14:37:46Z
39,688,129
<p>In general, yes, it is possible, but this really depends on a target web-site and what is involved in submitting a form. </p> <p>If this is a regular HTML form with no javascript involved, you can use packages like <a href="https://github.com/jmcarp/robobrowser" rel="nofollow"><code>RoboBrowser</code></a> or <a href="https://github.com/hickford/MechanicalSoup" rel="nofollow"><code>MechanicalSoup</code></a> which make form submissions easy. These packages are based on <code>requests</code> and <code>BeautifulSoup</code> and you would have access to the "soup" object if needed as well.</p>
1
2016-09-25T14:45:18Z
[ "python", "pdf", "beautifulsoup" ]
asyncio: prevent task from being cancelled twice
39,688,070
<p>Sometimes, my coroutine cleanup code includes some blocking parts (in the <code>asyncio</code> sense, i.e. they may yield).</p> <p>I try to design them carefully, so they don't block indefinitely. So "by contract", coroutine must never be interrupted once it's inside its cleanup fragment.</p> <p>Unfortunately, I can't find a way to prevent this, and bad things occur when it happens (whether it's caused by actual double <code>cancel</code> call; or when it's almost finished by itself, doing cleanup, and happens to be cancelled from elsewhere).</p> <p>Theoretically, I can delegate cleanup to some other function, protect it with a <code>shield</code>, and surround it with <code>try</code>-<code>except</code> loop, but it's just ugly.</p> <p>Is there a Pythonic way to do so?</p> <pre><code>#!/usr/bin/env python3 import asyncio @asyncio.coroutine def foo(): """ This is the function in question, with blocking cleanup fragment. """ try: yield from asyncio.sleep(1) except asyncio.CancelledError: print("Interrupted during work") raise finally: print("I need just a couple more seconds to cleanup!") try: # upload results to the database, whatever yield from asyncio.sleep(1) except asyncio.CancelledError: print("Interrupted during cleanup :(") else: print("All cleaned up!") @asyncio.coroutine def interrupt_during_work(): # this is a good example, all cleanup # finishes successfully t = asyncio.async(foo()) try: yield from asyncio.wait_for(t, 0.5) except asyncio.TimeoutError: pass else: assert False, "should've been timed out" t.cancel() # wait for finish try: yield from t except asyncio.CancelledError: pass @asyncio.coroutine def interrupt_during_cleanup(): # here, cleanup is interrupted t = asyncio.async(foo()) try: yield from asyncio.wait_for(t, 1.5) except asyncio.TimeoutError: pass else: assert False, "should've been timed out" t.cancel() # wait for finish try: yield from t except asyncio.CancelledError: pass @asyncio.coroutine def double_cancel(): # cleanup is interrupted here as well t = asyncio.async(foo()) try: yield from asyncio.wait_for(t, 0.5) except asyncio.TimeoutError: pass else: assert False, "should've been timed out" t.cancel() try: yield from asyncio.wait_for(t, 0.5) except asyncio.TimeoutError: pass else: assert False, "should've been timed out" # although double cancel is easy to avoid in # this particular example, it might not be so obvious # in more complex code t.cancel() # wait for finish try: yield from t except asyncio.CancelledError: pass @asyncio.coroutine def comain(): print("1. Interrupt during work") yield from interrupt_during_work() print("2. Interrupt during cleanup") yield from interrupt_during_cleanup() print("3. Double cancel") yield from double_cancel() def main(): loop = asyncio.get_event_loop() task = loop.create_task(comain()) loop.run_until_complete(task) if __name__ == "__main__": main() </code></pre>
0
2016-09-25T14:38:52Z
39,692,502
<p>I ended up writing a simple function that provides a stronger shield, so to speak.</p> <p>Unlike <code>asyncio.shield</code>, which protects the callee, but raises <code>CancelledError</code> in its caller, this function suppresses <code>CancelledError</code> altogether.</p> <p>The drawback is that this function doesn't allow you to handle <code>CancelledError</code> later. You won't see whether it has ever happened. Something <em>slightly</em> more complex would be required to do so.</p> <pre><code>@asyncio.coroutine def super_shield(arg, *, loop=None): arg = asyncio.async(arg) while True: try: return (yield from asyncio.shield(arg, loop=loop)) except asyncio.CancelledError: continue </code></pre>
1
2016-09-25T22:42:19Z
[ "python", "python-asyncio", "coroutine" ]
Flushing PyGaze keypress
39,688,123
<p><code>self.keyboard.get_key()</code> (from <a href="http://www.pygaze.org/" rel="nofollow">the PyGaze library</a>) holds a screen until a key is pressed.</p> <p>How can I flush/clear the contents of the a key press prior to this call? </p> <p>At the moment a previous key press is carried into the function where I call <code>self.keyboard.get_key()</code>.</p>
0
2016-09-25T14:44:36Z
39,726,363
<p>In order to flush any keypresses in PyGaze the following should be added to the <code>get_key</code> function <code>self.keyboard.get_key(flush=True)</code>.</p>
0
2016-09-27T13:45:09Z
[ "python", "keypress" ]
Cleanest way to combine reduce and map in Python
39,688,133
<p>I'm doing a little deep learning, and I want to grab the values of all hidden layers. So I end up writing functions like this:</p> <pre><code>def forward_pass(x, ws, bs): activations = [] u = x for w, b in zip(ws, bs): u = np.maximum(0, u.dot(w)+b) activations.append(u) return activations </code></pre> <p>If I didn't have to get the intermediate values, I'd use the much less verbose form:</p> <pre><code>out = reduce(lambda u, (w, b): np.maximum(0, u.dot(w)+b), zip(ws, bs), x) </code></pre> <p>Bam. All one line, nice and compact. But I can't keep any of the intermediate values.</p> <p>So, what is there any way to have my cake (nice compact one-liner) and eat it too (return intermediate values)?</p> <p><strong>Edit: My conclusions so far:</strong><br> In Python 2.x, there is no clean one-liner for this.<br> In Python 3, there is <code>itertools.accumulate</code>, but it is still not really clean because it doesn't accept an "initial" input, as <code>reduce</code> does.<br> In Python 4, I hereby request a "map-reduce comprehension": </p> <pre><code>activations = [u=np.maximum(0, u.dot(w)+b) for w, b in zip(ws, bs) from u=x] </code></pre> <p>Which would also give a useful job to that <code>from</code> keyword, which normally just sits around doing nothing after all the imports are done.</p>
1
2016-09-25T14:45:29Z
39,688,465
<p>In general, <a href="https://docs.python.org/3/library/itertools.html#module-itertools" rel="nofollow"><em>itertools.accumulate()</em></a> will do what <a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="nofollow"><em>reduce()</em></a> does but will give you the intermediate values as well. That said, accumulate does not support <em>start</em> value so it make not be applicable in your case.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; import operator, functools, itertools &gt;&gt;&gt; functools.reduce(operator.mul, range(1, 11)) 3628800 &gt;&gt;&gt; list(itertools.accumulate(range(1, 11), operator.mul)) [1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800] </code></pre>
2
2016-09-25T15:15:59Z
[ "python", "numpy", "deep-learning", "reduce" ]
Cleanest way to combine reduce and map in Python
39,688,133
<p>I'm doing a little deep learning, and I want to grab the values of all hidden layers. So I end up writing functions like this:</p> <pre><code>def forward_pass(x, ws, bs): activations = [] u = x for w, b in zip(ws, bs): u = np.maximum(0, u.dot(w)+b) activations.append(u) return activations </code></pre> <p>If I didn't have to get the intermediate values, I'd use the much less verbose form:</p> <pre><code>out = reduce(lambda u, (w, b): np.maximum(0, u.dot(w)+b), zip(ws, bs), x) </code></pre> <p>Bam. All one line, nice and compact. But I can't keep any of the intermediate values.</p> <p>So, what is there any way to have my cake (nice compact one-liner) and eat it too (return intermediate values)?</p> <p><strong>Edit: My conclusions so far:</strong><br> In Python 2.x, there is no clean one-liner for this.<br> In Python 3, there is <code>itertools.accumulate</code>, but it is still not really clean because it doesn't accept an "initial" input, as <code>reduce</code> does.<br> In Python 4, I hereby request a "map-reduce comprehension": </p> <pre><code>activations = [u=np.maximum(0, u.dot(w)+b) for w, b in zip(ws, bs) from u=x] </code></pre> <p>Which would also give a useful job to that <code>from</code> keyword, which normally just sits around doing nothing after all the imports are done.</p>
1
2016-09-25T14:45:29Z
39,689,554
<p>The <code>dot</code> tells me you are using one or more numpy arrays. So I'll try:</p> <pre><code>In [28]: b=np.array([1,2,3]) In [29]: x=np.arange(9).reshape(3,3) In [30]: ws=[x,x,x] In [31]: forward_pass(x,ws,bs) Out[31]: [array([[ 16, 19, 22], [ 43, 55, 67], [ 70, 91, 112]]), array([[ 191, 248, 305], [ 569, 734, 899], [ 947, 1220, 1493]]), array([[ 2577, 3321, 4065], [ 7599, 9801, 12003], [12621, 16281, 19941]])] </code></pre> <p>In py3 I have to write the <code>reduce</code> solution as:</p> <pre><code>In [32]: functools.reduce(lambda u, wb: np.maximum(0, u.dot(wb[0])+wb[1]), zip(ws, bs), x) Out[32]: array([[ 2577, 3321, 4065], [ 7599, 9801, 12003], [12621, 16281, 19941]]) </code></pre> <p>That intermediate value <code>u</code> that is passed from one evaluation to the next makes a list comprehension tricky.</p> <p><code>accumulate</code> uses the first item as the start. I can work around that with a function like</p> <pre><code>def foo(u, wb): if u[0] is None: u=x # x from global return np.maximum(0, u.dot(wb[0])+wb[1]) </code></pre> <p>Then I need to add extra start values to <code>ws</code> and <code>bs</code>:</p> <pre><code>In [56]: list(itertools.accumulate(zip([None,x,x,x], np.array([0,1,2,3])), foo)) Out[56]: [(None, 0), array([[ 16, 19, 22], [ 43, 55, 67], [ 70, 91, 112]]), array([[ 191, 248, 305], [ 569, 734, 899], [ 947, 1220, 1493]]), array([[ 2577, 3321, 4065], [ 7599, 9801, 12003], [12621, 16281, 19941]])] </code></pre> <p>Here's a list comprehension version, using an external <code>u</code>:</p> <pre><code>In [66]: u=x.copy() In [67]: def foo1(wb): ...: v = np.maximum(0, u.dot(wb[0])+wb[1]) ...: u[:]=v ...: return v ...: In [68]: [foo1(wb) for wb in zip(ws,bs)] Out[68]: [array([[ 16, 19, 22], [ 43, 55, 67], [ 70, 91, 112]]), array([[ 191, 248, 305], [ 569, 734, 899], [ 947, 1220, 1493]]), array([[ 2577, 3321, 4065], [ 7599, 9801, 12003], [12621, 16281, 19941]])] </code></pre> <p>No real advantage over the original loop with <code>append</code>.</p> <p><code>numpy.ufunc</code> have an <code>accumulate</code> method, but that isn't easy to use with custom Python functions. So there is a <code>np.maximum.accumulate</code>, but I'm not sure how that could be used in this case. (also <code>np.cumsum</code> which is <code>np.add.accumulate</code>).</p>
2
2016-09-25T17:07:17Z
[ "python", "numpy", "deep-learning", "reduce" ]
Cleanest way to combine reduce and map in Python
39,688,133
<p>I'm doing a little deep learning, and I want to grab the values of all hidden layers. So I end up writing functions like this:</p> <pre><code>def forward_pass(x, ws, bs): activations = [] u = x for w, b in zip(ws, bs): u = np.maximum(0, u.dot(w)+b) activations.append(u) return activations </code></pre> <p>If I didn't have to get the intermediate values, I'd use the much less verbose form:</p> <pre><code>out = reduce(lambda u, (w, b): np.maximum(0, u.dot(w)+b), zip(ws, bs), x) </code></pre> <p>Bam. All one line, nice and compact. But I can't keep any of the intermediate values.</p> <p>So, what is there any way to have my cake (nice compact one-liner) and eat it too (return intermediate values)?</p> <p><strong>Edit: My conclusions so far:</strong><br> In Python 2.x, there is no clean one-liner for this.<br> In Python 3, there is <code>itertools.accumulate</code>, but it is still not really clean because it doesn't accept an "initial" input, as <code>reduce</code> does.<br> In Python 4, I hereby request a "map-reduce comprehension": </p> <pre><code>activations = [u=np.maximum(0, u.dot(w)+b) for w, b in zip(ws, bs) from u=x] </code></pre> <p>Which would also give a useful job to that <code>from</code> keyword, which normally just sits around doing nothing after all the imports are done.</p>
1
2016-09-25T14:45:29Z
40,133,207
<p>In Python 2.x, there is no clean one-liner for this. </p> <p>In Python 3, there is itertools.accumulate, but it is still not really clean because it doesn't accept an "initial" input, as reduce does. </p> <p>Here is a function that, while not as nice as a built-in comprehension syntax, does the job.</p> <pre><code>def reducemap(func, sequence, initial=None, include_zeroth = False): """ A version of reduce that also returns the intermediate values. :param func: A function of the form x_i_plus_1 = f(x_i, params_i) Where: x_i is the value passed through the reduce. params_i is the i'th element of sequence x_i_plus_i is the value that will be passed to the next step :param sequence: A list of parameters to feed at each step of the reduce. :param initial: Optionally, an initial value (else the first element of the sequence will be taken as the initial) :param include_zeroth: Include the initial value in the returned list. :return: A list of length: len(sequence), (or len(sequence)+1 if include_zeroth is True) containing the computed result of each iteration. """ if initial is None: val = sequence[0] sequence = sequence[1:] else: val = initial results = [val] if include_zeroth else [] for s in sequence: val = func(val, s) results.append(val) return results </code></pre> <p>Tests:</p> <pre><code>assert reducemap(lambda a, b: a+b, [1, 2, -4, 3, 6, -7], initial=0) == [1, 3, -1, 2, 8, 1] assert reducemap(lambda a, b: a+b, [1, 2, -4, 3, 6, -7]) == [3, -1, 2, 8, 1] assert reducemap(lambda a, b: a+b, [1, 2, -4, 3, 6, -7], include_zeroth=True) == [1, 3, -1, 2, 8, 1] </code></pre>
0
2016-10-19T13:45:44Z
[ "python", "numpy", "deep-learning", "reduce" ]
I'm having trouble converting a Raster to an Array
39,688,318
<p>I'm currently having some trouble converting a raster to an array. Ultimately I would like to convert a raster from an integer to a float32 so that I can run a gdal_calc however, I could not change the type properly in order to do this. </p> <p>SO, I would appreciate any help that someone could provide. Here is my script, very short.</p> <pre><code>import gdal import numpy as np import math import osgeo import os import scipy # Open Rasters hvRaster = gdal.Open("C:\\Users\\moses\\Desktop\\Calc_Test\\IMG-HV-ALOS2110871010-160611-HBQR1.5RUA.img") vhRaster = gdal.Open("C:\\Users\\moses\\Desktop\\Calc_Test\\IMG-VH-ALOS2110871010-160611-HBQR1.5RUA.img") # Get Raster Band hvRasterBand = hvRaster.GetRasterBand(1) vhRasterBand = vhRaster.GetRasterBand(1) # Convert Raster to Array hvArray = np.array(hvRaster.GetRasterBand(1).ReadAsArray()) vhArray = np.array(vhRaster.GetRasterBand(1).ReadAsArray()) print hvArray print vhArray </code></pre> <p>Thank you in advance,</p> <p>Moses</p>
0
2016-09-25T15:01:02Z
39,820,842
<p>The method ReadAsArray() will create a numpy.ndarray with a dtype of the raster dataset. Your goal is to transform an integer dtype to a float32. The simplest way to do this is to use the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="nofollow">astype()</a> method for ndarray.</p> <pre><code># Convert Raster to Array hvArray = hvRaster.GetRasterBand(1).ReadAsArray().astype(np.float32) vhArray = vhRaster.GetRasterBand(1).ReadAsArray().astype(np.float32) </code></pre>
2
2016-10-02T19:32:25Z
[ "python", "arrays", "numpy", "raster", "gdal" ]
Django - Can't import app names - Unresolved Reference
39,688,351
<p>I'm starting with a project and I suddenly can't import App names. <strong>PyCharm</strong> says that app is <code>Unresolved Reference</code> and when I try to start shell and import app, it says that it's unrecognized. </p> <p>Do you know where could be the problem? I've checked whether the correct <code>venv</code> is activated.</p> <p><a href="http://i.stack.imgur.com/LVLIC.png" rel="nofollow"><img src="http://i.stack.imgur.com/LVLIC.png" alt="enter image description here"></a></p> <p>SHELL:</p> <pre><code>&gt;&gt;&gt; from ProductSpyWeb import Api Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; ImportError: cannot import name Api </code></pre> <p><strong>APPS in Settings.py</strong></p> <pre><code>INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MainApp', 'Api', ] </code></pre>
1
2016-09-25T15:04:11Z
39,689,785
<p>You probably want to use <code>import Api</code> - the same way you just have <code>Api</code> in <code>INSTALLED_APPS</code> instead of <code>ProductSpyWeb.Api</code>.</p> <p>Assuming that you aren't doing anything strange with your Python path, when you use <code>from ProductSpyWeb import Api</code> from the Django shell it's trying to import from <code>ProductSpyProject/ProductSpyWeb/ProductSpyWeb/Api</code>.</p>
2
2016-09-25T17:33:16Z
[ "python", "django" ]
Spotipy - list index out of range
39,688,358
<p>Writing a Spotipy script to return album tracks from a given album I'm occasionally getting the error: </p> <pre><code> album_id = results["albums"]["items"][0]["uri"] IndexError: list index out of range </code></pre> <p>The error tends to happen for more popular artists looping over all of their albums. I'm guessing results list has either reached it's limit or it's getting out of sequence somehow. Either way I'm not sure how to fix it as I'm pretty sure I got the album_id line off the Spotipy website. Any ideas?</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import spotipy sp = spotipy.Spotify() sp.trace = False def get_artist_albums(artist): results = sp.search(q = "artist:" + artist, type = "artist") items = results["artists"]["items"] artist = items[0] # print artist albums = [] albumsTitles = [] results = sp.artist_albums(artist["id"], album_type = "album") albums.extend(results["items"]) while results["next"]: results = sp.next(results) albums.extend(results["items"]) seen = set() # to avoid dups albums.sort(key = lambda album:album["name"].lower()) for album in albums: albumTitle = album["name"] if albumTitle not in seen: print((" " + albumTitle)) seen.add(albumTitle) albumsTitles.append(albumTitle) # return albumsTitles return albumsTitles def get_albums_tracks(album): albumtracks = [] results = sp.search(q = "album:" + album, type = "album") # get the first album uri album_id = results["albums"]["items"][0]["uri"] # get album tracks tracks = sp.album_tracks(album_id) c = 1 # print album for track in tracks["items"]: # print "#%s %s" %(c, track["name"]) albumtracks.append(track["name"]) c +=1 return albumtracks # 3 album band - ok phosgoreAlbums = get_artist_albums("Phosgore") for item in phosgoreAlbums: print get_albums_tracks(item) print "" # 6 album band - ok # (well technically 2, but's let not get into that night now) joyDivisionAlbums = get_artist_albums("Joy Division") for item in joyDivisionAlbums: print get_albums_tracks(item) print "" # 34 albums - falls over cherAlbums = get_artist_albums("Cher") for item in cherAlbums: print get_albums_tracks(item) print "" # 38 album band - falls over theCureAlbums = get_artist_albums("The Cure") for item in theCureAlbums: print get_albums_tracks(item) print "" # 43 album band - falls over aliceCooperAlbums = get_artist_albums("Alice Cooper") for item in aliceCooperAlbums: print get_albums_tracks(item) print "" </code></pre>
4
2016-09-25T15:05:04Z
39,688,379
<p><code>results["albums"]["items"]</code> is simply an empty list, so there is no element at index <code>0</code>. You could test for that before trying to index into it:</p> <pre><code>if not results["albums"]["items"]: # no albums found, so no tracks either return [] album_id = results["albums"]["items"][0]["uri"] </code></pre>
4
2016-09-25T15:06:38Z
[ "python", "list", "python-2.7", "spotipy" ]
Marking certain days in date indexed pandas dataframes
39,688,434
<p>I've got a dataframe which is date indexed (d-m-y). I wanted to create a binary feature column which denotes if a date is the second Saturday of the month.<br> What I've got so far is this: </p> <pre><code>def get_second_true(x): second = None for index, is_true in enumerate(x): if is_true and second is None: return index if is_true and second is not None: second = True second_saturdays = df.groupby(['month', 'year']).apply( lambda x: x.index.weekday == 6 ).apply(get_second_true) </code></pre> <p>I'm unable to get this back into a series which relates to the original dataframe's index in such a way that each row has a label of whether it is a second Saturday or not.</p> <p>This feels like a common enough scenario, but I am unable to find the term used for doing such a thing. I've looked at <code>unstack</code> and <code>reset_index</code> but I don't understand them in enough depth to know if this can be done using them, or if multilevel indexing is even needed at all.</p>
1
2016-09-25T15:12:21Z
39,688,532
<p>The day is second Saturday of the month if weekday == 6 and day of the moth > 7 and day of the month &lt;= 14</p>
2
2016-09-25T15:22:41Z
[ "python", "pandas", "dataframe" ]
Marking certain days in date indexed pandas dataframes
39,688,434
<p>I've got a dataframe which is date indexed (d-m-y). I wanted to create a binary feature column which denotes if a date is the second Saturday of the month.<br> What I've got so far is this: </p> <pre><code>def get_second_true(x): second = None for index, is_true in enumerate(x): if is_true and second is None: return index if is_true and second is not None: second = True second_saturdays = df.groupby(['month', 'year']).apply( lambda x: x.index.weekday == 6 ).apply(get_second_true) </code></pre> <p>I'm unable to get this back into a series which relates to the original dataframe's index in such a way that each row has a label of whether it is a second Saturday or not.</p> <p>This feels like a common enough scenario, but I am unable to find the term used for doing such a thing. I've looked at <code>unstack</code> and <code>reset_index</code> but I don't understand them in enough depth to know if this can be done using them, or if multilevel indexing is even needed at all.</p>
1
2016-09-25T15:12:21Z
39,688,666
<p>There is a special frequency in pandas like <code>WOM-2SUN</code> (Week-Of-Month: 2nd Sunday), so you can do it this way:</p> <pre><code>In [88]: df = pd.DataFrame({'date':pd.date_range('2000-01-01', periods=365)}) In [89]: df Out[89]: date 0 2000-01-01 1 2000-01-02 2 2000-01-03 3 2000-01-04 4 2000-01-05 5 2000-01-06 6 2000-01-07 7 2000-01-08 8 2000-01-09 9 2000-01-10 .. ... 355 2000-12-21 356 2000-12-22 357 2000-12-23 358 2000-12-24 359 2000-12-25 360 2000-12-26 361 2000-12-27 362 2000-12-28 363 2000-12-29 364 2000-12-30 [365 rows x 1 columns] In [90]: df.ix[df.date.isin(pd.date_range(start=df.date.min(), end=df.date.max(), freq='WOM-2SUN'))] Out[90]: date 8 2000-01-09 43 2000-02-13 71 2000-03-12 99 2000-04-09 134 2000-05-14 162 2000-06-11 190 2000-07-09 225 2000-08-13 253 2000-09-10 281 2000-10-08 316 2000-11-12 344 2000-12-10 </code></pre>
3
2016-09-25T15:37:02Z
[ "python", "pandas", "dataframe" ]
How to get class name of the WebElement in Python Selenium?
39,688,512
<p>I use Selenium webdriver to scrap a table taken from web page, written in JavaScript. I am iterating on a list of table rows. Each row may be of different class. I want to get the name of this class, so that I can choose appropriate action for each row.</p> <pre><code>table_body=table.find_element_by_tag_name('tbody') rows=table_body.find_elements_by_tag_name('tr') for row in rows: if(row.GetClassName()=="date"): Action1() else: Action2() </code></pre> <p>Is this possible with Selenium? Or suggest another approach.</p>
0
2016-09-25T15:20:19Z
39,688,529
<p><a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webelement.WebElement.get_attribute" rel="nofollow"><code>.get_attribute()</code> method</a> is what you are looking for:</p> <pre><code>row.get_attribute("class") </code></pre>
2
2016-09-25T15:22:31Z
[ "python", "selenium-webdriver" ]
How to Webscrape data from a classic asp website using python. I am having trouble getting the result after submitting the POST form
39,688,562
<p>I am beginner in Web scraping and I have become very much interested in the process. I set for myself a Project that can keep me motivated till I completed the project.</p> <h1>My Project</h1> <p>My Aim is to write a Python Program that goes to my university results page(which happens to be a " xx.asp") and enters my</p> <ol> <li>MY EXAM NO </li> <li>MY COURSE </li> <li>SEMESTER and submit it to the website.</li> </ol> <p>Clicking on the submit button leads to another "yy.asp" page in which my results are displayed. But I am having a lot of trouble doing the same.</p> <h2>Some Sample Data to try it out</h2> <p><strong>The Results Website:</strong> <a href="http://result.pondiuni.edu.in/candidate.asp" rel="nofollow">http://result.pondiuni.edu.in/candidate.asp</a></p> <p><strong>Register Number:</strong> 15te1218</p> <p><strong>Degree:</strong> BTHEE</p> <p><strong>Exam:</strong> Second</p> <p>Could anyone give me directions of how I am to accomplish the task?</p> <p>I have written a sample program that I am not really proud of or nor does it work as I wanted. The following is the code that I wrote. I am a beginner so sorry if I did something terribly wrong. Please correct me and would be awesome if you could guide me to solve the problem.</p> <p>The website is a .asp website not .aspx. I have provided sample data so that you can see whats happening where we submit a request to the website.</p> <h2>The Code</h2> <pre><code>import requests with requests.Session() as c: url='http://result.pondiuni.edu.in/candidate.asp' url2='http://result.pondiuni.edu.in/ResultDisp.asp' TXTREGNO='15te1218' CMBDEGREE='BTHEE~\BTHEE\result.mdb' CMBEXAMNO='B' DPATH='\BTHEE\result.mdb' DNAME='BTHEE' TXTEXAMNO='B' c.get(url) payload = { 'txtregno':TXTREGNO, 'cmbdegree':CMBDEGREE, 'cmbexamno':CMBEXAMNO, 'dpath':DPATH, 'dname':DNAME, 'txtexamno':TXTEXAMNO } post_request = requests.post(url, data=payload) page=c.get(url2) </code></pre> <p>I have no idea what to do next so that I can retrieve my result page(displayed in <code>url2</code> from the code). All the data is entered in link <code>url</code> in the program(the starting link were all the info is entered) from where after submitting takes is to <code>url2</code> the results page. Please help me make this program.</p> <p>I took all the post form parameters from Chrome's Network Tab.</p>
1
2016-09-25T15:26:44Z
39,692,270
<p>You are way over complicating it and you have <em>carriage returns</em> in your post data so that could never work:</p> <pre><code>In [1]: s = "BTHEE~\BTHEE\result.mdb" In [2]: print(s) # where did "\result.mdb" go? esult.mdbHEE In [3]: s = r"BTHEE~\BTHEE\result.mdb" # raw string In [4]: print(s) BTHEE~\BTHEE\result.mdb </code></pre> <p>So fix you form data and just post to get to your results:</p> <pre><code>import requests data = {"txtregno": "15te1218", "cmbdegree": r"BTHEE~\BTHEE\result.mdb", # use raw strings "cmbexamno": "B", "dpath": r"\BTHEE\result.mdb", "dname": "BTHEE", "txtexamno": "B"} results_page = requests.post("http://result.pondiuni.edu.in/ResultDisp.asp", data=data).content </code></pre>
1
2016-09-25T22:03:17Z
[ "python", "html", "forms", "web", "web-scraping" ]
How to Webscrape data from a classic asp website using python. I am having trouble getting the result after submitting the POST form
39,688,562
<p>I am beginner in Web scraping and I have become very much interested in the process. I set for myself a Project that can keep me motivated till I completed the project.</p> <h1>My Project</h1> <p>My Aim is to write a Python Program that goes to my university results page(which happens to be a " xx.asp") and enters my</p> <ol> <li>MY EXAM NO </li> <li>MY COURSE </li> <li>SEMESTER and submit it to the website.</li> </ol> <p>Clicking on the submit button leads to another "yy.asp" page in which my results are displayed. But I am having a lot of trouble doing the same.</p> <h2>Some Sample Data to try it out</h2> <p><strong>The Results Website:</strong> <a href="http://result.pondiuni.edu.in/candidate.asp" rel="nofollow">http://result.pondiuni.edu.in/candidate.asp</a></p> <p><strong>Register Number:</strong> 15te1218</p> <p><strong>Degree:</strong> BTHEE</p> <p><strong>Exam:</strong> Second</p> <p>Could anyone give me directions of how I am to accomplish the task?</p> <p>I have written a sample program that I am not really proud of or nor does it work as I wanted. The following is the code that I wrote. I am a beginner so sorry if I did something terribly wrong. Please correct me and would be awesome if you could guide me to solve the problem.</p> <p>The website is a .asp website not .aspx. I have provided sample data so that you can see whats happening where we submit a request to the website.</p> <h2>The Code</h2> <pre><code>import requests with requests.Session() as c: url='http://result.pondiuni.edu.in/candidate.asp' url2='http://result.pondiuni.edu.in/ResultDisp.asp' TXTREGNO='15te1218' CMBDEGREE='BTHEE~\BTHEE\result.mdb' CMBEXAMNO='B' DPATH='\BTHEE\result.mdb' DNAME='BTHEE' TXTEXAMNO='B' c.get(url) payload = { 'txtregno':TXTREGNO, 'cmbdegree':CMBDEGREE, 'cmbexamno':CMBEXAMNO, 'dpath':DPATH, 'dname':DNAME, 'txtexamno':TXTEXAMNO } post_request = requests.post(url, data=payload) page=c.get(url2) </code></pre> <p>I have no idea what to do next so that I can retrieve my result page(displayed in <code>url2</code> from the code). All the data is entered in link <code>url</code> in the program(the starting link were all the info is entered) from where after submitting takes is to <code>url2</code> the results page. Please help me make this program.</p> <p>I took all the post form parameters from Chrome's Network Tab.</p>
1
2016-09-25T15:26:44Z
39,692,721
<p>To add to the answer already given, you can use bs4.BeautifulSoup to find the data you need in the result page afterwards.</p> <pre><code>#!\usr\bin\env python import requests from bs4 import BeautifulSoup payload = {'txtregno': '15te1218', 'cmbdegree': r'BTHEE~\BTHEE\result.mdb', 'cmbexamno': 'B', 'dpath': r'\BTHEE\result.mdb', 'dname': 'BTHEE', 'txtexamno': 'B'} results_page = requests.get('http://result.pondiuni.edu.in/ResultDisp.asp', data = payload) soup = BeautifulSoup(results_page.text, 'html.parser') SubjectElem = soup.select("td[width='66%'] font") MarkElem = soup.select("font[color='DarkGreen'] b") Subject = [] Mark = [] for i in range(len(SubjectElem)): Subject.append(SubjectElem[i].text) Mark.append(MarkElem[i].text) Transcript = dict(zip(Subject, Mark)) </code></pre> <p>This will give a dictionary with the subject as a key and mark as a value.</p>
-1
2016-09-25T23:16:40Z
[ "python", "html", "forms", "web", "web-scraping" ]
python - How to avoid multiple running instances of the same function
39,688,594
<p>In my python script I have a <code>core dumped</code>, and I think it's because the same function is called twice at the same time.</p> <p>The function is the reading of a Vte terminal in a gtk window</p> <pre><code>def term(self, dPluzz, donnees=None): text = str(self.v.get_text(lambda *a: True).rstrip()) [...] print "Here is the time " + str(time.time()) def terminal(self): self.v = vte.Terminal() self.v.set_emulation('xterm') self.v.connect ("child-exited", lambda term: self.verif(self, dPluzz)) self.v.connect("contents-changed", self.term) </code></pre> <p>Result:</p> <pre><code>Here is the time 1474816913.68 Here is the time 1474816913.68 Erreur de segmentation (core dumped) </code></pre> <p>How to avoid the double executing of the function?</p>
0
2016-09-25T15:29:07Z
39,688,880
<p>The double execution must be the consequence of the <code>contents-changed</code> event triggering twice.</p> <p>You could just check in your <code>term</code> function whether it has already been executed before, and exit if so.</p> <p>Add these two lines at the start of the <code>term</code> function:</p> <pre><code> if hasattr(self, 'term_has_executed'): return self.term_has_executed = True </code></pre>
1
2016-09-25T15:57:16Z
[ "python", "function" ]
Python: heapq.heappop() gives strange result
39,688,599
<p>I'm trying to use the Python module <code>heapq</code> in my program but I ran into a strange problem using <code>heapq.heappop()</code>. The function does not appear to return the smallest element in the heap. Take a look at the following code:</p> <pre><code>Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import heapq &gt;&gt;&gt; list = [[1326, 'a'], [654, 'b']] &gt;&gt;&gt; print heapq.heappop(list) [1326, 'a'] &gt;&gt;&gt; print heapq.heappop(list) [654, 'b'] </code></pre> <p>Should <code>heappop()</code> not return <code>[654, 'b']</code> first and then <code>[1326, 'a']</code>?</p>
1
2016-09-25T15:29:43Z
39,688,627
<p>You should <a href="https://docs.python.org/2/library/heapq.html#heapq.heapify" rel="nofollow">"heapify"</a> the list first (an in-place operation):</p> <pre><code>In [1]: import heapq In [2]: l = [[1326, 'a'], [654, 'b']] In [3]: heapq.heapify(l) In [4]: heapq.heappop(l) Out[4]: [654, 'b'] In [5]: heapq.heappop(l) Out[5]: [1326, 'a'] </code></pre> <p>And, avoid naming your list as <code>list</code> - you are <em>shadowing</em> the built-in <code>list</code> keyword.</p>
1
2016-09-25T15:33:09Z
[ "python", "heap", "result", "pop" ]
Django: import Topic Issue, word Topic shows instead of title?
39,688,618
<p>Hey guys I just began working through the Django section in the Python Crash Course. I'm making a learning log in which you can add entries. I followed the book but I'm having one odd issue. When I add a new topic instead of the title for a new topic I literally get the word Topic</p> <p><a href="http://i.stack.imgur.com/HN4VA.png" rel="nofollow"><img src="http://i.stack.imgur.com/HN4VA.png" alt="Topic Issue"></a></p> <p>My code is so far as follows, under admin.py </p> <pre><code>from django.contrib import admin from learning_logs.models import Topic admin.site.register(Topic) </code></pre> <p>This is my models.py </p> <pre><code>from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about """ text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def _str_(self): """Returns a string representation of the model """ return self.text </code></pre> <p>the code matches the book, any idea why this is happening? </p>
0
2016-09-25T15:32:28Z
39,688,718
<p>You need two underscores for the str method, not one:</p> <pre><code># No def _str_(self): pass # Yes def __str__(self): pass </code></pre>
2
2016-09-25T15:42:01Z
[ "python", "django", "django-models" ]
How to perform tensor production in Python/numpy?
39,688,774
<p>I have two numpy 2D-arrays and I want to perform this:</p> <pre><code>a_ij * b_ik = c_ijk </code></pre> <p>How can I make it with numpy?</p>
1
2016-09-25T15:46:50Z
39,688,953
<p>c_ijk = numpy.tensordot(a_ij,b_ik, axes=0)</p>
-1
2016-09-25T16:04:41Z
[ "python", "numpy" ]
How to perform tensor production in Python/numpy?
39,688,774
<p>I have two numpy 2D-arrays and I want to perform this:</p> <pre><code>a_ij * b_ik = c_ijk </code></pre> <p>How can I make it with numpy?</p>
1
2016-09-25T15:46:50Z
39,688,962
<p><code>einsum</code> is tailor made for this task</p> <pre><code>a_ij * b_ik = c_ijk c = np.einsum('ij,ik-&gt;ijk', a, b) </code></pre> <p>===================</p> <p>But as Divakar shows, no summation is implied, so plain multiplication works just as well, <code>a[...,None]*b[:,None,:]</code>.</p>
4
2016-09-25T16:05:35Z
[ "python", "numpy" ]
How to take input from stdin, display something using curses and output to stdout?
39,688,790
<p>I'm trying to make a python script that takes input from stdin, displays GUI in terminal using curses and then when user finishes interaction outputs the result to the stdout. Good example of this behaviour is <a href="https://github.com/garybernhardt/selecta" rel="nofollow">selecta</a> but it's written in ruby.</p> <p>I can't make curses display anything. This is minimal (it only displays one character and waits for one character) example of what I tried so far:</p> <pre><code>import os, sys import curses c = None old_out = sys.__stdout__ old_in = sys.__stdin__ old_err = sys.__stderr__ sys.__stdout__ = sys.stdout = open('/dev/tty', 'w') sys.__stdin__ = sys.stdin = open('/dev/tty') sys.__stderr__ = sys.stderr = open('/dev/tty') def show_a(s): global c s.addch(ord('a')) c = s.getch() curses.wrapper(show_a) sys.stdin.flush() sys.stdout.flush() sys.stderr.flush() sys.stdin.close() sys.stdout.close() sys.stderr.close() sys.__stdout__ = sys.stdout = old_out sys.__stdin__ = sys.stdin = old_in sys.__stderr__ = sys.stderr = old_err print(c) </code></pre> <p>When I try to use <code>echo $(python3 show_a.py)</code> nothing is displayed but after pressing any key its number is displayed:</p> <p><a href="http://i.stack.imgur.com/lOsvS.png" rel="nofollow"><img src="http://i.stack.imgur.com/lOsvS.png" alt="curses displays nothing in terminal"></a></p> <p>Is something like this even possible using curses, if so how to do this?</p>
1
2016-09-25T15:48:53Z
40,069,233
<p>It doesn't work because the <code>print</code> statement is writing to the same standard output as <a href="https://docs.python.org/2/library/curses.html#curses.wrapper" rel="nofollow"><code>curses.wrapper</code></a>. You can either defer that <code>print</code> until after you have restored <code>sys.stdout</code>, or you could use the <code>file=</code> property something like this:</p> <pre><code>printf(s.getch(), file=old_out) </code></pre> <p>For the other (ordering) problem, it sounds as if you need to amend the code to do a <a href="https://docs.python.org/2/library/curses.html#curses.window.refresh" rel="nofollow"><em>refresh</em></a> after the <code>getch</code> (to make curses display it), and depending on what version of curses, a <em>flush</em> of the standard output would then be helpful.</p> <p>Further reading:</p> <ul> <li><a href="http://stackoverflow.com/questions/6796492/temporarily-redirect-stdout-stderr">Temporarily Redirect stdout/stderr</a></li> </ul>
1
2016-10-16T10:24:28Z
[ "python", "curses", "python-curses" ]
Django REST Framework Serializer returning object instead of data
39,688,876
<p>I am writing a simple database for the condo I live in which has a list of people, units, unit type (home vs parking space), and unitholder (join table for many-to-many relationship between a person and a unit) - one person can be the owner of a unit type of "home" while renting a parking space.</p> <p>This is my model:</p> <pre><code>class Person(models.Model): first_name = models.CharField(max_length=30, null=False) last_name = models.CharField(max_length=30, null=False) phone = models.CharField(max_length=20) email = models.EmailField(max_length=20) class UnitType(models.Model): description = models.CharField(max_length=30) class Unit(models.Model): unit_number = models.IntegerField(null=False, unique=True) unit_type = models.ForeignKey(UnitType, null=False) unitholders = models.ManyToManyField(Person, through='UnitHolder') class UnitHolderType(models.Model): description = models.CharField(max_length=30) class UnitHolder(models.Model): person = models.ForeignKey(Person) unit = models.ForeignKey(Unit) unitholder_type = models.ForeignKey(UnitHolderType) </code></pre> <p>This is my view:</p> <pre><code>class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer class UnitHolderTypeViewSet(viewsets.ModelViewSet): queryset = UnitHolderType.objects.all() serializer_class = UnitHolderTypeSerializer class UnitViewSet(viewsets.ModelViewSet): queryset = Unit.objects.all() serializer_class = UnitSerializer class UnitHolderViewSet(viewsets.ModelViewSet): queryset = UnitHolder.objects.all() serializer_class = UnitHolderSerializer class UnitTypeViewSet(viewsets.ModelViewSet): queryset = UnitType.objects.all() serializer_class = UnitTypeSerializer </code></pre> <p>This is my serializer:</p> <pre><code>class UnitSerializer(serializers.ModelSerializer): unit_type = serializers.SlugRelatedField( queryset=UnitType.objects.all(), slug_field='description' ) class Meta: model = Unit fields = ('unit_number', 'unit_type', 'unitholders') class UnitTypeSerializer(serializers.ModelSerializer): class Meta: model = UnitType class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person class UnitHolderSerializer(serializers.ModelSerializer): person = serializers.PrimaryKeyRelatedField(many=False, read_only=True) unit = serializers.PrimaryKeyRelatedField(many=False, read_only=True) class Meta: model = UnitHolder fields = ('person', 'unit', 'unitholder_type') class UnitHolderTypeSerializer(serializers.ModelSerializer): class Meta: model = UnitHolderType </code></pre> <p>The problem:</p> <p>When I query the /units endpoint like the following:</p> <pre><code>u = requests.get('http://localhost:8000/units').json() </code></pre> <p>My response looks like this:</p> <pre><code>[{'unit_type': 'Home', 'unit_number': 614, 'unitholders': [1]}] </code></pre> <p>What I want back is something like this:</p> <pre><code>[ { 'unit_type': 'Home', 'unit_number': 614, 'unitholders': [ { 'id: 1, 'first_name': 'myfirstname', 'last_name': 'mylastname', 'unitholder_type': 'renter' } ] } ] </code></pre> <p>I'm pretty sure my problem is in my UnitSerializer but I am brand new to DRF and read the through the documentation but still can't seem to figure it out. </p>
1
2016-09-25T15:57:01Z
39,689,102
<p>Perhaps you must doing somethings so:</p> <pre><code>class UnitHolderViewSet(viewsets.ModelViewSet): queryset = UnitHolder.objects.all() unitholders = UnitHolderSerializer(read_only=True, many=True) </code></pre> <p><a href="http://stackoverflow.com/questions/33182092/django-rest-framework-serializing-many-to-many-field">Django rest framework serializing many to many field</a></p>
0
2016-09-25T16:21:07Z
[ "python", "json", "django", "django-rest-framework" ]
Django REST Framework Serializer returning object instead of data
39,688,876
<p>I am writing a simple database for the condo I live in which has a list of people, units, unit type (home vs parking space), and unitholder (join table for many-to-many relationship between a person and a unit) - one person can be the owner of a unit type of "home" while renting a parking space.</p> <p>This is my model:</p> <pre><code>class Person(models.Model): first_name = models.CharField(max_length=30, null=False) last_name = models.CharField(max_length=30, null=False) phone = models.CharField(max_length=20) email = models.EmailField(max_length=20) class UnitType(models.Model): description = models.CharField(max_length=30) class Unit(models.Model): unit_number = models.IntegerField(null=False, unique=True) unit_type = models.ForeignKey(UnitType, null=False) unitholders = models.ManyToManyField(Person, through='UnitHolder') class UnitHolderType(models.Model): description = models.CharField(max_length=30) class UnitHolder(models.Model): person = models.ForeignKey(Person) unit = models.ForeignKey(Unit) unitholder_type = models.ForeignKey(UnitHolderType) </code></pre> <p>This is my view:</p> <pre><code>class PersonViewSet(viewsets.ModelViewSet): queryset = Person.objects.all() serializer_class = PersonSerializer class UnitHolderTypeViewSet(viewsets.ModelViewSet): queryset = UnitHolderType.objects.all() serializer_class = UnitHolderTypeSerializer class UnitViewSet(viewsets.ModelViewSet): queryset = Unit.objects.all() serializer_class = UnitSerializer class UnitHolderViewSet(viewsets.ModelViewSet): queryset = UnitHolder.objects.all() serializer_class = UnitHolderSerializer class UnitTypeViewSet(viewsets.ModelViewSet): queryset = UnitType.objects.all() serializer_class = UnitTypeSerializer </code></pre> <p>This is my serializer:</p> <pre><code>class UnitSerializer(serializers.ModelSerializer): unit_type = serializers.SlugRelatedField( queryset=UnitType.objects.all(), slug_field='description' ) class Meta: model = Unit fields = ('unit_number', 'unit_type', 'unitholders') class UnitTypeSerializer(serializers.ModelSerializer): class Meta: model = UnitType class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person class UnitHolderSerializer(serializers.ModelSerializer): person = serializers.PrimaryKeyRelatedField(many=False, read_only=True) unit = serializers.PrimaryKeyRelatedField(many=False, read_only=True) class Meta: model = UnitHolder fields = ('person', 'unit', 'unitholder_type') class UnitHolderTypeSerializer(serializers.ModelSerializer): class Meta: model = UnitHolderType </code></pre> <p>The problem:</p> <p>When I query the /units endpoint like the following:</p> <pre><code>u = requests.get('http://localhost:8000/units').json() </code></pre> <p>My response looks like this:</p> <pre><code>[{'unit_type': 'Home', 'unit_number': 614, 'unitholders': [1]}] </code></pre> <p>What I want back is something like this:</p> <pre><code>[ { 'unit_type': 'Home', 'unit_number': 614, 'unitholders': [ { 'id: 1, 'first_name': 'myfirstname', 'last_name': 'mylastname', 'unitholder_type': 'renter' } ] } ] </code></pre> <p>I'm pretty sure my problem is in my UnitSerializer but I am brand new to DRF and read the through the documentation but still can't seem to figure it out. </p>
1
2016-09-25T15:57:01Z
39,689,779
<p>An easy solution would be using <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization" rel="nofollow"><code>depth</code></a> option:</p> <pre><code>class UnitSerializer(serializers.ModelSerializer): unit_type = serializers.SlugRelatedField( queryset=UnitType.objects.all(), slug_field='description' ) class Meta: model = Unit fields = ('unit_number', 'unit_type', 'unitholders') depth = 1 </code></pre> <p>This will serialize all nested relations 1 level deep. If you want to have fine control over how each nested field gets serialized, you can list their serializers explicitly:</p> <pre><code>class UnitSerializer(serializers.ModelSerializer): unit_type = serializers.SlugRelatedField( queryset=UnitType.objects.all(), slug_field='description' ) unitholders = UnitHolderSerializer(many=True) class Meta: model = Unit fields = ('unit_number', 'unit_type', 'unitholders') </code></pre> <p>Also as a side note, you need to look into modifying your querysets inside views to <a href="https://docs.djangoproject.com/en/1.10/topics/db/optimization/#retrieve-everything-at-once-if-you-know-you-will-need-it" rel="nofollow">prefetch related objects</a>, otherwise you will destroy the app performance very quickly (using something like <a href="https://github.com/jazzband/django-debug-toolbar" rel="nofollow">django-debug-toolbar</a> for monitoring generated queries is very convenient): </p> <pre><code>class UnitViewSet(viewsets.ModelViewSet): queryset = Unit.objects.all().select_related('unit_type').prefetch_related('unitholders') serializer_class = UnitSerializer </code></pre>
2
2016-09-25T17:32:21Z
[ "python", "json", "django", "django-rest-framework" ]
Python - tf-idf predict a new document similarity
39,688,927
<p>Inspired by <strong><a href="http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity">this</a></strong> answer, I'm trying to find cosine similarity between a trained trained tf-idf vectorizer and a new document, and return the similar documents.</p> <p>The code below finds the cosine similarity of the <strong>first vector</strong> and not a new query</p> <pre><code>&gt;&gt;&gt; from sklearn.metrics.pairwise import linear_kernel &gt;&gt;&gt; cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten() &gt;&gt;&gt; cosine_similarities array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602, 0.04457106, 0.03293218]) </code></pre> <p>Since my train data is huge, looping through the entire trained vectorizer sounds like a bad idea. How can I infer the vector of a new document, and find the related docs, same as the code below?</p> <pre><code>&gt;&gt;&gt; related_docs_indices = cosine_similarities.argsort()[:-5:-1] &gt;&gt;&gt; related_docs_indices array([ 0, 958, 10576, 3277]) &gt;&gt;&gt; cosine_similarities[related_docs_indices] array([ 1. , 0.54967926, 0.32902194, 0.2825788 ]) </code></pre>
3
2016-09-25T16:02:15Z
39,689,190
<p>For huge data sets, there is a solution called <strong>Text Clustering By Concept</strong>. search engines use this Technic,</p> <p>At first step, you cluster your documents to some groups(e.g 50 cluster), then each cluster has a representative document(that contain some words that have some useful information about it's cluster)<br /> At second step, for calculating cosine similarity between New Document and you data set, you loop through all representative(50 numbers) and find top near representatives(e.g 2 representative)<br /> At final step, you can loop through all documents in selected representative and find nearest cosine similarity</p> <p>With this Technic, you can reduce the number of loops and improve performace, You can read more tecnincs in some chapter of this book: <a href="http://nlp.stanford.edu/IR-book/html/htmledition/irbook.html" rel="nofollow">http://nlp.stanford.edu/IR-book/html/htmledition/irbook.html</a></p>
0
2016-09-25T16:29:57Z
[ "python", "machine-learning", "scikit-learn", "tf-idf", "document-classification" ]
Python - tf-idf predict a new document similarity
39,688,927
<p>Inspired by <strong><a href="http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity">this</a></strong> answer, I'm trying to find cosine similarity between a trained trained tf-idf vectorizer and a new document, and return the similar documents.</p> <p>The code below finds the cosine similarity of the <strong>first vector</strong> and not a new query</p> <pre><code>&gt;&gt;&gt; from sklearn.metrics.pairwise import linear_kernel &gt;&gt;&gt; cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten() &gt;&gt;&gt; cosine_similarities array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602, 0.04457106, 0.03293218]) </code></pre> <p>Since my train data is huge, looping through the entire trained vectorizer sounds like a bad idea. How can I infer the vector of a new document, and find the related docs, same as the code below?</p> <pre><code>&gt;&gt;&gt; related_docs_indices = cosine_similarities.argsort()[:-5:-1] &gt;&gt;&gt; related_docs_indices array([ 0, 958, 10576, 3277]) &gt;&gt;&gt; cosine_similarities[related_docs_indices] array([ 1. , 0.54967926, 0.32902194, 0.2825788 ]) </code></pre>
3
2016-09-25T16:02:15Z
39,698,351
<p>You should take a look at <a href="https://radimrehurek.com/gensim/tutorial.html" rel="nofollow">gensim</a>. Example starting code looks like this:</p> <pre><code>from gensim import corpora, models, similarities dictionary = corpora.Dictionary(line.lower().split() for line in open('corpus.txt')) corpus = [dictionary.doc2bow(line.lower().split()) for line in open('corpus.txt')] tfidf = models.TfidfModel(corpus) index = similarities.SparseMatrixSimilarity(tfidf[corpus], num_features=12) </code></pre> <p>At prediction time you first get the vector for the new doc:</p> <pre><code>doc = "Human computer interaction" vec_bow = dictionary.doc2bow(doc.lower().split()) vec_tfidf = tfidf[vec_bow] </code></pre> <p>Then get the similarities (sorted by most similar):</p> <pre><code>sims = index[vec_tfidf] # perform a similarity query against the corpus print(list(enumerate(sims))) # print (document_number, document_similarity) 2-tuples </code></pre> <p>This does a linear scan like you wanted to do but they have a more optimized implementation. If the speed is not enough then you can look into approximate similarity search (Annoy, Falconn, NMSLIB).</p>
1
2016-09-26T08:48:00Z
[ "python", "machine-learning", "scikit-learn", "tf-idf", "document-classification" ]
Python - tf-idf predict a new document similarity
39,688,927
<p>Inspired by <strong><a href="http://stackoverflow.com/questions/12118720/python-tf-idf-cosine-to-find-document-similarity">this</a></strong> answer, I'm trying to find cosine similarity between a trained trained tf-idf vectorizer and a new document, and return the similar documents.</p> <p>The code below finds the cosine similarity of the <strong>first vector</strong> and not a new query</p> <pre><code>&gt;&gt;&gt; from sklearn.metrics.pairwise import linear_kernel &gt;&gt;&gt; cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten() &gt;&gt;&gt; cosine_similarities array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602, 0.04457106, 0.03293218]) </code></pre> <p>Since my train data is huge, looping through the entire trained vectorizer sounds like a bad idea. How can I infer the vector of a new document, and find the related docs, same as the code below?</p> <pre><code>&gt;&gt;&gt; related_docs_indices = cosine_similarities.argsort()[:-5:-1] &gt;&gt;&gt; related_docs_indices array([ 0, 958, 10576, 3277]) &gt;&gt;&gt; cosine_similarities[related_docs_indices] array([ 1. , 0.54967926, 0.32902194, 0.2825788 ]) </code></pre>
3
2016-09-25T16:02:15Z
39,700,863
<p>This problem can be partially addressed by combining the <strong>vector space model</strong> (which is the tf-idf &amp; cosine similarity) together with the <strong>boolean model</strong>. These are concepts of information theory and they are used (and nicely explained) in <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/scoring-theory.html" rel="nofollow">ElasticSearch</a>- a pretty good search engine.</p> <p>The idea is simple: you store your documents as inverted indices. Which is comparable to the words present at the end of a book, which hold a reference to the pages (documents) they were mentioned in.</p> <p>Instead of calculating the tf-idf vector for all document it will only calculate it for documents that have at least one (or specify a threshold) of the words in common. This can be simply done by looping over the words in the queried document, finding the documents that also have this word using the inverted index and calculate the similarity for those.</p>
2
2016-09-26T10:49:39Z
[ "python", "machine-learning", "scikit-learn", "tf-idf", "document-classification" ]
Set bias in CNN
39,688,985
<p>I have two massive numpy arrays of weights and biases for a CNN. I can set weights for each layer (using <code>set_weights</code>) but I don't see a way to set the bias for each layer. How do I do this?</p>
2
2016-09-25T16:08:13Z
39,691,438
<p>You do this by using <code>layer.set_weights(weights)</code>. From the documentation:</p> <blockquote> <pre><code>weights: a list of Numpy arrays. The number of arrays and their shape must match number of the dimensions of the weights of the layer (i.e. it should match the output of `get_weights`). </code></pre> </blockquote> <p>You don't just put the weights for the filter in there but for <em>each</em> parameter the layer has. The order in which you have to put in the weights depends on <code>layer.weights</code>. You may look at the code or print the names of the weights of the layer by doing something like</p> <pre><code> print([p.name for p in layer.weights]) </code></pre>
0
2016-09-25T20:20:12Z
[ "python", "deep-learning", "keras" ]
How can i take the output of one python script as user input for another python script
39,689,012
<p>i have written a code (python 2.7) that goes to a website <a href="http://www.cricbuzz.com/live-cricket-scorecard/16822/ind-vs-nz-1st-test-new-zealand-tour-of-india-2016" rel="nofollow">Cricket score</a> and then takes out some data out of it to display just its score .It also periodically repeats and keeps running because the scores keep changing. i have also written a code for taking a message input from user and send that message as an sms to my number .</p> <p>i want to club these two so that the scores printed on my screen serve as the message input for sending live scores to me.</p> <p>codes are</p> <p><strong>sms.py</strong></p> <pre><code> import urllib2 import cookielib from getpass import getpass import sys import os from stat import * import sched, time import requests from bs4 import BeautifulSoup s = sched.scheduler(time.time, time.sleep) from urllib2 import Request #from livematch import function #this sends the desired input message to my number number = raw_input('enter number you want to message: ') message = raw_input('enter text: ' ) #this declares my credentials if __name__ == "__main__": username = "9876543210" passwd = "abcdefghij" message = "+".join(message.split(' ')) #logging into the sms site url ='http://site24.way2sms.com/Login1.action?' data = 'username='+username+'&amp;password='+passwd+'&amp;Submit=Sign+in' #For cookies cj= cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) #Adding header details opener.addheaders=[('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120')] try: usock =opener.open(url, data) except IOError: print "error" #return() jession_id =str(cj).split('~')[1].split(' ')[0] send_sms_url = 'http://site24.way2sms.com/smstoss.action?' send_sms_data = 'ssaction=ss&amp;Token='+jession_id+'&amp;mobile='+number+'&amp;message='+message+'&amp;msgLen=136' opener.addheaders=[('Referer', 'http://site25.way2sms.com/sendSMS?Token='+jession_id)] try: sms_sent_page = opener.open(send_sms_url,send_sms_data) except IOError: print "error" #return() print "success" #return () </code></pre> <p><strong>livematch.py</strong></p> <pre><code> import sched, time import requests from bs4 import BeautifulSoup s = sched.scheduler(time.time, time.sleep) from urllib2 import Request url=raw_input('enter the desired score card url here : ') req=Request(url) def do_something(sc) : #global x r=requests.get(url) soup=BeautifulSoup(r.content) for i in soup.find_all("div",{"id":"innings_1"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) for i in soup.find_all("div",{"id":"innings_2"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) for i in soup.find_all("div",{"id":"innings_3"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) for i in soup.find_all("div",{"id":"innings_4"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) # do your stuff #do what ever s.enter(5, 1, do_something, (sc,)) s.enter(5, 1, do_something, (s,)) s.run() </code></pre> <p>note that instead of using 9876543210 as username and abcdefghij as password use the credentials of actual account.</p> <p>sign up at way2sms.com for those credentials</p>
1
2016-09-25T16:10:13Z
39,689,306
<p>If you want to call a completly independed python script in via your python script take a look at <code>subprocess</code> module. You could use <code>subprocess.call</code> or <code>subprocess.Popen</code>.</p>
0
2016-09-25T16:43:06Z
[ "python", "python-2.7", "windows-10" ]
How can i take the output of one python script as user input for another python script
39,689,012
<p>i have written a code (python 2.7) that goes to a website <a href="http://www.cricbuzz.com/live-cricket-scorecard/16822/ind-vs-nz-1st-test-new-zealand-tour-of-india-2016" rel="nofollow">Cricket score</a> and then takes out some data out of it to display just its score .It also periodically repeats and keeps running because the scores keep changing. i have also written a code for taking a message input from user and send that message as an sms to my number .</p> <p>i want to club these two so that the scores printed on my screen serve as the message input for sending live scores to me.</p> <p>codes are</p> <p><strong>sms.py</strong></p> <pre><code> import urllib2 import cookielib from getpass import getpass import sys import os from stat import * import sched, time import requests from bs4 import BeautifulSoup s = sched.scheduler(time.time, time.sleep) from urllib2 import Request #from livematch import function #this sends the desired input message to my number number = raw_input('enter number you want to message: ') message = raw_input('enter text: ' ) #this declares my credentials if __name__ == "__main__": username = "9876543210" passwd = "abcdefghij" message = "+".join(message.split(' ')) #logging into the sms site url ='http://site24.way2sms.com/Login1.action?' data = 'username='+username+'&amp;password='+passwd+'&amp;Submit=Sign+in' #For cookies cj= cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) #Adding header details opener.addheaders=[('User-Agent','Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120')] try: usock =opener.open(url, data) except IOError: print "error" #return() jession_id =str(cj).split('~')[1].split(' ')[0] send_sms_url = 'http://site24.way2sms.com/smstoss.action?' send_sms_data = 'ssaction=ss&amp;Token='+jession_id+'&amp;mobile='+number+'&amp;message='+message+'&amp;msgLen=136' opener.addheaders=[('Referer', 'http://site25.way2sms.com/sendSMS?Token='+jession_id)] try: sms_sent_page = opener.open(send_sms_url,send_sms_data) except IOError: print "error" #return() print "success" #return () </code></pre> <p><strong>livematch.py</strong></p> <pre><code> import sched, time import requests from bs4 import BeautifulSoup s = sched.scheduler(time.time, time.sleep) from urllib2 import Request url=raw_input('enter the desired score card url here : ') req=Request(url) def do_something(sc) : #global x r=requests.get(url) soup=BeautifulSoup(r.content) for i in soup.find_all("div",{"id":"innings_1"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) for i in soup.find_all("div",{"id":"innings_2"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) for i in soup.find_all("div",{"id":"innings_3"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) for i in soup.find_all("div",{"id":"innings_4"}): x=i.text.find('Batsman') in_1=i.text print(in_1[0:x]) # do your stuff #do what ever s.enter(5, 1, do_something, (sc,)) s.enter(5, 1, do_something, (s,)) s.run() </code></pre> <p>note that instead of using 9876543210 as username and abcdefghij as password use the credentials of actual account.</p> <p>sign up at way2sms.com for those credentials</p>
1
2016-09-25T16:10:13Z
39,689,391
<p>It is hard to answer without having a look at your code. But it seems that using piping with subprocess would be an appropriate solution. </p> <p>See the answer on this post: <a href="http://stackoverflow.com/questions/32812157/python-subprocess-stdout-readline-doesnt/32812754#32812754">python subprocess.stdout.readline doesn&#39;t</a></p>
0
2016-09-25T16:51:26Z
[ "python", "python-2.7", "windows-10" ]
Tkinter: Only allow one Toplevel window instance
39,689,046
<p>I have a tkinter program with multiple windows. Here is the full code in case it's entirety is needed.</p> <pre><code>import tkinter as tk import tkinter.scrolledtext as tkst from tkinter import ttk import logging import time def popupmsg(msg): popup = tk.Toplevel() popup.wm_title("!") label = ttk.Label(popup, text=msg) label.pack(side="top", fill="x", pady=10) b1 = ttk.Button(popup, text="Okay", command=popup.destroy) b1.pack() popup.mainloop() def test1(): root.logger.error("Test") def toggle(self): t_btn = self.t_btn if t_btn.config('text')[-1] == 'Start': t_btn.config(text='Stop') def startloop(): if root.flag: now = time.strftime("%c") root.logger.error(now) root.after(30000, startloop) else: root.flag = True return startloop() else: t_btn.config(text='Start') root.logger.error("Loop stopped") root.flag = False class TextHandler(logging.Handler): def __init__(self, text): # run the regular Handler __init__ logging.Handler.__init__(self) # Store a reference to the Text it will log to self.text = text def emit(self, record): msg = self.format(record) def append(): self.text.configure(state='normal') self.text.insert(tk.END, msg + '\n') self.text.configure(state='disabled') # Autoscroll to the bottom self.text.yview(tk.END) # This is necessary because we can't modify the Text from other threads self.text.after(0, append) def create(self): # Create textLogger topframe = tk.Frame(root) topframe.pack(side=tk.TOP) st = tkst.ScrolledText(topframe, bg="#00A09E", fg="white", state='disabled') st.configure(font='TkFixedFont') st.pack() self.text_handler = TextHandler(st) # Add the handler to logger root.logger = logging.getLogger() root.logger.addHandler(self.text_handler) def stop(self): root.flag = False def start(self): if root.flag: root.logger.error("error") root.after(1000, self.start) else: root.logger.error("Loop stopped") root.flag = True return def loop(self): self.start() class HomePage(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.menubar = tk.Menu(container) # Create taskbar/menu file = tk.Menu(self.menubar) file.add_command(label="Run", command=lambda: test1()) file.add_command(label="Stop", command=lambda: test1()) file.add_separator() file.add_command(label="Settings", command=lambda: Settings()) file.add_separator() file.add_command(label="Quit", command=quit) self.menubar.add_cascade(label="File", menu=file) self.master.config(menu=self.menubar) #logger and main loop th = TextHandler("none") th.create() root.flag = True root.logger.error("Welcome to ShiptScraper!") bottomframe = tk.Frame(self) bottomframe.pack(side=tk.BOTTOM) topframe = tk.Frame(self) topframe.pack(side=tk.TOP) self.t_btn = tk.Button(text="Start", highlightbackground="#56B426", command=lambda: toggle(self)) self.t_btn.pack(pady=5) self.exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) self.exitButton.pack() root.setting = False class Settings(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.wm_title("Settings") print(Settings.state(self)) exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=self.destroy) exitButton.pack() class Help(tk.Toplevel): def __init__(self, parent): tk.Toplevel.__init__(self, parent) self.wm_title("Help") exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) exitButton.pack() if __name__ == "__main__": root = tk.Tk() root.configure(background="#56B426") root.wm_title("ShiptScraper") app = HomePage(root) app.mainloop() </code></pre> <p>Basically my problem is that clicking the command <code>Settings</code> from the menu brings up a new <code>Settings</code> window each time it's clicked. I can't figure out how make it so it can detect if one window instance is already open or not. I've tried using <code>state()</code> as a check in a method in the <code>HomePage</code> class like</p> <pre><code>#in it's respective place as shown above file.add_command(label="Settings", command=lambda: self.open(Settings)) #outside the init as a method def open(self, window): if window.state(self) != 'normal': window() </code></pre> <p>This returns this error</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__ return self.func(*args) File "/Users/user/pythonProjects/ShiptScraper/ShiptScraperGUI.py", line 112, in &lt;lambda&gt; file.add_command(label="Settings", command=lambda: self.open(Settings)) File "/Users/user/pythonProjects/ShiptScraper/ShiptScraperGUI.py", line 139, in open if window.state(self) != 'normal': File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1826, in wm_state return self.tk.call('wm', 'state', self._w, newstate) _tkinter.TclError: window ".4319455216" isn't a top-level window </code></pre> <p>I've tried using the <code>winfo_exists()</code> method, but it seems like unless I've already destroyed the window (which I haven't if it hasn't been opened yet) this won't do me any good. Nonetheless here's one of those combo's I've tried</p> <pre><code>def open(self, window): if window.winfo_exists(self) != 1: window() </code></pre> <p>This of course does nothing. I'm not going to go through every other wrong combination. I've tried because honestly at this point, I can't remember them all. </p> <p>I have also tried defining these <code>open</code> methods as functions outside of any class and they don't work there either, usually because of confusion of <code>self</code> keywords not being defined outside a class, but needing to be a parameter of the <code>winfo_exists()</code> and <code>state()</code> methods. </p> <p>I'm also thinking that my problem, in using these functions as methods in the HomePage class, is because whenever I'm referencing <code>self</code>, it's checking <code>HomePage</code>, not whatever window I'm passing as an argument in the method. I'm not really sure though, which is why I'm here.</p> <p>Really, what I'm trying to do is just create a standard method in my <code>HomePage</code> window that controls how the menu (and possibly buttons later) opens a window. This would logically (in my own psuedocode) be:</p> <pre><code>def open(window) if window does not exist: open an instance of window </code></pre> <p>Is this possible, Or is there a better approach to window management I should be taking?</p> <p><strong>Edit:</strong> I originally neglected to mention that my OS is Mac OSX running Mavericks. Apparently this may be an OSX issue. Also, if you're going to downvote this question at least comment and tell me why/how I can revise it to make it better.</p> <p>I've now tried these combinations</p> <pre><code>class Settings(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.wm_title("Settings") # added grab_set() self.grab_set() # print(Settings.state(self)) exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=self.destroy) exitButton.pack() </code></pre> <p>and</p> <pre><code>class Settings(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.wm_title("Settings") # added grab_set() self.grab_set() self.focus() # print(Settings.state(self)) exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=self.destroy) exitButton.pack() </code></pre> <p>and</p> <pre><code>class Settings(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.wm_title("Settings") # added grab_set() self.attributes("-topmost", True) # print(Settings.state(self)) exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=self.destroy) exitButton.pack() </code></pre> <p>and</p> <p>class Settings(tk.Toplevel):</p> <pre><code>def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.wm_title("Settings") # added grab_set() self.after(1, lambda: self.focus_force()) # print(Settings.state(self)) exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=self.destroy) exitButton.pack() </code></pre> <p><strong>Edit #2:</strong></p> <p>I've come up with a workaround... I hate it. But it works, at least for now. I'm definitely still hoping for a better solution.</p> <pre><code>import tkinter as tk import tkinter.scrolledtext as tkst from tkinter import ttk import logging import time def popupmsg(msg): popup = tk.Toplevel() popup.wm_title("!") label = ttk.Label(popup, text=msg) label.pack(side="top", fill="x", pady=10) b1 = ttk.Button(popup, text="Okay", command=popup.destroy) b1.pack() popup.mainloop() def test1(): root.logger.error("Test") def toggle(self): t_btn = self.t_btn if t_btn.config('text')[-1] == 'Start': t_btn.config(text='Stop') def startloop(): if root.flag: now = time.strftime("%c") root.logger.error(now) root.after(30000, startloop) else: root.flag = True return startloop() else: t_btn.config(text='Start') root.logger.error("Loop stopped") root.flag = False class TextHandler(logging.Handler): def __init__(self, text): # run the regular Handler __init__ logging.Handler.__init__(self) # Store a reference to the Text it will log to self.text = text def emit(self, record): msg = self.format(record) def append(): self.text.configure(state='normal') self.text.insert(tk.END, msg + '\n') self.text.configure(state='disabled') # Autoscroll to the bottom self.text.yview(tk.END) # This is necessary because we can't modify the Text from other threads self.text.after(0, append) def create(self): # Create textLogger topframe = tk.Frame(root) topframe.pack(side=tk.TOP) st = tkst.ScrolledText(topframe, bg="#00A09E", fg="white", state='disabled') st.configure(font='TkFixedFont') st.pack() self.text_handler = TextHandler(st) # Add the handler to logger root.logger = logging.getLogger() root.logger.addHandler(self.text_handler) def stop(self): root.flag = False def start(self): if root.flag: root.logger.error("error") root.after(1000, self.start) else: root.logger.error("Loop stopped") root.flag = True return def loop(self): self.start() class HomePage(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) # NEW added a flag for the Settings window root.settings = False self.menubar = tk.Menu(container) # Create taskbar/menu file = tk.Menu(self.menubar) file.add_command(label="Run", command=lambda: test1()) file.add_command(label="Stop", command=lambda: test1()) file.add_separator() # NEW now calling a method from Settings instead of Settings itself file.add_command(label="Settings", command=lambda: Settings().open()) file.add_separator() file.add_command(label="Quit", command=quit) self.menubar.add_cascade(label="File", menu=file) self.master.config(menu=self.menubar) #logger and main loop th = TextHandler("none") th.create() root.flag = True root.logger.error("Welcome to ShiptScraper!") bottomframe = tk.Frame(self) bottomframe.pack(side=tk.BOTTOM) topframe = tk.Frame(self) topframe.pack(side=tk.TOP) self.t_btn = tk.Button(text="Start", highlightbackground="#56B426", command=lambda: toggle(self)) self.t_btn.pack(pady=5) self.exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) self.exitButton.pack() root.setting = False class Settings(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) # NEW 'open' method which is being called. This checks the root.setting flag added in the HomePage class def open(self): #NEW if root setting is false, continue creation of of Settings window if not root.setting: self.wm_title("Settings") # added grab_set() Settings.grab_set(self) #NEW edited the exitButton command, see close function below exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=lambda: close()) exitButton.pack() root.setting = True #NEW if the root.settings flag is TRUE this cancels window creation else: self.destroy() #NEW when close() is called it resets the root.setting flag to false, then destroys the window def close(): root.setting = False self.destroy() class Help(tk.Toplevel): def __init__(self, parent): tk.Toplevel.__init__(self, parent) self.wm_title("Help") exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) exitButton.pack() if __name__ == "__main__": root = tk.Tk() root.configure(background="#56B426") root.wm_title("ShiptScraper") app = HomePage(root) app.mainloop() </code></pre> <p>This feels like a complete and utter hack, I feel dirty looking at it and even dirtier for creating this abomination... but it works, for now at least</p> <p><strong>EDIT 3:</strong></p> <p>Added the protocol for window close in Jacob's answer. Had forgotten to account for that. This is the last version I'll share unless I come up with a better approach.</p> <pre><code>import tkinter as tk import tkinter.scrolledtext as tkst from tkinter import ttk import logging import time def popupmsg(msg): popup = tk.Toplevel() popup.wm_title("!") label = ttk.Label(popup, text=msg) label.pack(side="top", fill="x", pady=10) b1 = ttk.Button(popup, text="Okay", command=popup.destroy) b1.pack() popup.mainloop() def test1(): root.logger.error("Test") def toggle(self): t_btn = self.t_btn if t_btn.config('text')[-1] == 'Start': t_btn.config(text='Stop') def startloop(): if root.flag: now = time.strftime("%c") root.logger.error(now) root.after(30000, startloop) else: root.flag = True return startloop() else: t_btn.config(text='Start') root.logger.error("Loop stopped") root.flag = False class TextHandler(logging.Handler): def __init__(self, text): # run the regular Handler __init__ logging.Handler.__init__(self) # Store a reference to the Text it will log to self.text = text def emit(self, record): msg = self.format(record) def append(): self.text.configure(state='normal') self.text.insert(tk.END, msg + '\n') self.text.configure(state='disabled') # Autoscroll to the bottom self.text.yview(tk.END) # This is necessary because we can't modify the Text from other threads self.text.after(0, append) def create(self): # Create textLogger topframe = tk.Frame(root) topframe.pack(side=tk.TOP) st = tkst.ScrolledText(topframe, bg="#00A09E", fg="white", state='disabled') st.configure(font='TkFixedFont') st.pack() self.text_handler = TextHandler(st) # Add the handler to logger root.logger = logging.getLogger() root.logger.addHandler(self.text_handler) def stop(self): root.flag = False def start(self): if root.flag: root.logger.error("error") root.after(1000, self.start) else: root.logger.error("Loop stopped") root.flag = True return def loop(self): self.start() class HomePage(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) # NEW added a flag for the Settings window root.setting = True self.menubar = tk.Menu(container) # Create taskbar/menu file = tk.Menu(self.menubar) file.add_command(label="Run", command=lambda: test1()) file.add_command(label="Stop", command=lambda: test1()) file.add_separator() # NEW now calling a method from Settings instead of Settings itself file.add_command(label="Settings", command=lambda: Settings().open()) file.add_separator() file.add_command(label="Quit", command=quit) self.menubar.add_cascade(label="File", menu=file) self.master.config(menu=self.menubar) #logger and main loop th = TextHandler("none") th.create() root.flag = True root.logger.error("Welcome to ShiptScraper!") bottomframe = tk.Frame(self) bottomframe.pack(side=tk.BOTTOM) topframe = tk.Frame(self) topframe.pack(side=tk.TOP) self.t_btn = tk.Button(text="Start", highlightbackground="#56B426", command=lambda: toggle(self)) self.t_btn.pack(pady=5) self.exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) self.exitButton.pack() class Settings(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) # NEW 'open' method which is being called. This checks the root.setting flag added in the HomePage class def open(self): #NEW when close() is called it resets the root.setting flag to false, then destroys the window def close_TopLevel(): root.setting = True self.destroy() #NEW if root setting is false, continue creation of of Settings window if root.setting: self.wm_title("Settings") #NEW adjust window close protocol and change root.setting to FALSE self.protocol('WM_DELETE_WINDOW', close_TopLevel) root.setting = False #NEW edited the exitButton command, see close function below exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=lambda: close_TopLevel()) exitButton.pack() #NEW if the root.settings flag is TRUE this cancels window creation else: print('shit') self.destroy() class Help(tk.Toplevel): def __init__(self, parent): tk.Toplevel.__init__(self, parent) self.wm_title("Help") exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) exitButton.pack() if __name__ == "__main__": root = tk.Tk() root.configure(background="#56B426") root.wm_title("ShiptScraper") app = HomePage(root) app.mainloop() </code></pre>
1
2016-09-25T16:14:44Z
39,689,243
<p><code>tkinter</code>'s <code>grab_set()</code> is exactly made for that.</p> <p>Change the code section below into:</p> <pre><code>class Settings(tk.Toplevel): def __init__(self, master=None): tk.Toplevel.__init__(self, master) self.wm_title("Settings") # added grab_set() self.grab_set() # print(Settings.state(self)) exitButton = tk.Button(self, text="Exit", highlightbackground="#56B426", command=self.destroy) exitButton.pack() </code></pre> <p>Now when you open the settings window, the main window will not react on button clicks while the settings window exists.</p> <p>See also <a href="http://effbot.org/tkinterbook/tkinter-dialog-windows.htm" rel="nofollow">here</a>.</p> <hr> <h2>EDIT</h2> <h3>Trickery and deceit</h3> <p>Since there seems to be a bug in Tkinter / OSX concerning the use of <code>grab_set()</code> which works fine on Linux (Ubuntu 16.04), here some trickery and deceit.</p> <p>I edited your code a bit. For simplicity reasons of the example, I added the Toplevel window to the <code>HomePage</code>-class. I marked the changes <code>##</code>.</p> <p>The concept:</p> <ul> <li><p>Add a variable to your class, representing the fact that the Settings window exists (or not):</p> <pre><code>self.check = False </code></pre></li> <li><p>If the Settings window is called, the value changes:</p> <pre><code>self.check = True </code></pre></li> <li><p>The function to call the Settings window is now passive. No additional Settings windows will appear:</p> <pre><code> def call_settings(self): if self.check == False: self.settings_window() </code></pre></li> <li><p>We add a protocol to the Settings window, to run a command if the window stops to exist:</p> <pre><code>self.settingswin.protocol('WM_DELETE_WINDOW', self.close_Toplevel) </code></pre></li> <li><p>Then the called function will reset <code>self.check</code>:</p> <pre><code>def close_Toplevel(self): self.check = False self.settingswin.destroy() </code></pre> <p>This will work no matter how the Settings window was closed.</p></li> </ul> <h3>The edited code:</h3> <pre class="lang-py prettyprint-override"><code>import tkinter as tk import tkinter.scrolledtext as tkst from tkinter import ttk import logging import time def popupmsg(msg): popup = tk.Toplevel() popup.wm_title("!") label = ttk.Label(popup, text=msg) label.pack(side="top", fill="x", pady=10) b1 = ttk.Button(popup, text="Okay", command=popup.destroy) b1.pack() popup.mainloop() def test1(): root.logger.error("Test") def toggle(self): t_btn = self.t_btn if t_btn.config('text')[-1] == 'Start': t_btn.config(text='Stop') def startloop(): if root.flag: now = time.strftime("%c") root.logger.error(now) root.after(30000, startloop) else: root.flag = True return startloop() else: t_btn.config(text='Start') root.logger.error("Loop stopped") root.flag = False class TextHandler(logging.Handler): def __init__(self, text): # run the regular Handler __init__ logging.Handler.__init__(self) # Store a reference to the Text it will log to self.text = text def emit(self, record): msg = self.format(record) def append(): self.text.configure(state='normal') self.text.insert(tk.END, msg + '\n') self.text.configure(state='disabled') # Autoscroll to the bottom self.text.yview(tk.END) # This is necessary because we can't modify the Text from other threads self.text.after(0, append) def create(self): # Create textLogger topframe = tk.Frame(root) topframe.pack(side=tk.TOP) st = tkst.ScrolledText(topframe, bg="#00A09E", fg="white", state='disabled') st.configure(font='TkFixedFont') st.pack() self.text_handler = TextHandler(st) # Add the handler to logger root.logger = logging.getLogger() root.logger.addHandler(self.text_handler) def stop(self): root.flag = False def start(self): if root.flag: root.logger.error("error") root.after(1000, self.start) else: root.logger.error("Loop stopped") root.flag = True return def loop(self): self.start() class HomePage(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent) container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.menubar = tk.Menu(container) self.check = False ### new # Create taskbar/menu file = tk.Menu(self.menubar) file.add_command(label="Run", command=lambda: test1()) file.add_command(label="Stop", command=lambda: test1()) file.add_separator() file.add_command(label="Settings", command=self.call_settings) #### new, changed command to run the function file.add_separator() file.add_command(label="Quit", command=quit) self.menubar.add_cascade(label="File", menu=file) self.master.config(menu=self.menubar) #logger and main loop th = TextHandler("none") th.create() root.flag = True root.logger.error("Welcome to ShiptScraper!") bottomframe = tk.Frame(self) bottomframe.pack(side=tk.BOTTOM) topframe = tk.Frame(self) topframe.pack(side=tk.TOP) self.t_btn = tk.Button(text="Start", highlightbackground="#56B426", command=lambda: toggle(self)) self.t_btn.pack(pady=5) self.exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) self.exitButton.pack() root.setting = False ########## changed def call_settings(self): if self.check == False: self.settings_window() ########## def settings_window(self): self.check = True self.settingswin = tk.Toplevel() self.settingswin.wm_title("Settings") self.settingswin.protocol('WM_DELETE_WINDOW', self.close_Toplevel) ##### new exitButton = tk.Button(self.settingswin, text="Exit", highlightbackground="#56B426", command=self.close_Toplevel) exitButton.pack() def close_Toplevel(self): # New, this runs when the Toplevel window closes, either by button or else self.check = False self.settingswin.destroy() class Help(tk.Toplevel): def __init__(self, parent): tk.Toplevel.__init__(self, parent) self.wm_title("Help") exitButton = tk.Button(text="Exit", highlightbackground="#56B426", command=quit) exitButton.pack() if __name__ == "__main__": root = tk.Tk() root.configure(background="#56B426") root.wm_title("ShiptScraper") app = HomePage(root) app.mainloop() </code></pre> <h3>Note</h3> <p>Once we have triggered the existence of the Settings window, we can do a lot more of course, disable all buttons on the mainwindow for example. This way, we created our own version of <code>grab_set()</code> but even more flexibel.</p>
1
2016-09-25T16:36:05Z
[ "python", "tkinter" ]
Can someone explain this expression: a[len(a):] = [x] equivalent to list.append(x)
39,689,099
<p>I'm at the very beginning of learning Python 3. Getting to know the language basics. There is a method to the list data type:</p> <pre><code>list.append(x) </code></pre> <p>and in the tutorial it is said to be equivalent to this expression:</p> <pre><code>a[len(a):] = [x] </code></pre> <p>Can someone please explain this expression? I can't grasp the <strong>len(a):</strong> part. It's a slice right? From the last item to the last? Can't make sense of it.</p> <p>I'm aware this is very newbie, sorry. I'm determined to learn Python for Blender scripting and the Game Engine, and want to understand well all the constructs.</p>
2
2016-09-25T16:20:52Z
39,689,182
<p>Think back to how slices work: <code>a[beginning:end]</code>. If you do not supply one of them, then you get all the list from <code>beginning</code> or all the way to <code>end</code>.</p> <p>What that means is if I ask for <code>a[2:]</code>, I will get the list from the index <code>2</code> all the way to the end of the list and <code>len(a)</code> is an index right after the last element of the array... so <code>a[len(a):]</code> is basically an empty array positioned right after the last element of the array.</p> <p>Say you have <code>a = [0,1,2]</code>, and you do <code>a[3:] = [3,4,5]</code>, what you're telling Python is that right after <code>[0,1,2</code> and right before <code>]</code>, there should be <code>3,4,5</code>. Thus <code>a</code> will become <code>[0,1,2,3,4,5]</code> and after that step <code>a[3:]</code> will indeed be equal to <code>[3,4,5]</code> just as you declared.</p> <p>Edit: as chepner commented, any index greater than or equal to <code>len(a)</code> will work just as well. For instance, <code>a = [0,1,2]</code> and <code>a[42:] = [3,4,5]</code> will also result in <code>a</code> becoming <code>[0,1,2,3,4,5]</code>.</p>
9
2016-09-25T16:28:57Z
[ "python", "list", "python-3.x" ]
Can someone explain this expression: a[len(a):] = [x] equivalent to list.append(x)
39,689,099
<p>I'm at the very beginning of learning Python 3. Getting to know the language basics. There is a method to the list data type:</p> <pre><code>list.append(x) </code></pre> <p>and in the tutorial it is said to be equivalent to this expression:</p> <pre><code>a[len(a):] = [x] </code></pre> <p>Can someone please explain this expression? I can't grasp the <strong>len(a):</strong> part. It's a slice right? From the last item to the last? Can't make sense of it.</p> <p>I'm aware this is very newbie, sorry. I'm determined to learn Python for Blender scripting and the Game Engine, and want to understand well all the constructs.</p>
2
2016-09-25T16:20:52Z
39,689,210
<p>One could generally state that <code>l[len(l):] = [1]</code> is similar to <code>append</code>, <em><a href="https://docs.python.org/3/tutorial/datastructures.html" rel="nofollow">and that is what is stated in the docs</a></em>, but, that is a <em>special case</em> that holds true only when the right hand side <em>has a single element</em>. </p> <p>In the more <em>general case</em> it is safer to state that it is equivalent to <code>extend</code> for the following reasons:</p> <p>Append takes an <em>object</em> and appends that to the end; with slice assignment you <strong>extend</strong> a list with the given iterable on the right hand side:</p> <pre><code>l[len(l):] = [1, 2, 3] </code></pre> <p>is equivalent to:</p> <pre><code>l.extend([1, 2, 3]) </code></pre> <p>The same argument to <code>append</code> would cause <code>[1, 2, 3]</code> to be appended as an object at the end of <code>l</code>. In this scenario <code>len(l)</code> is simply used in order for the extending of the list to be performed at the end of <code>l</code>.</p> <p>Some examples to illustrate their difference:</p> <pre><code>l = [1, 2] l[len(l):] = [1, 2] # l becomes [1, 2, 1, 2] l.extend([1, 2]) # l becomes [1, 2, 1, 2, 1, 2] l.append([1, 2]) # l becomes [1, 2, 1, 2, 1, 2, [1, 2]] </code></pre> <p>As you note, <code>l.append(&lt;iterable&gt;)</code> doesn't actually append each value in the iterable, it appends the iterable itself.</p>
5
2016-09-25T16:32:12Z
[ "python", "list", "python-3.x" ]
python: using output from method's class inside another class
39,689,134
<p>I am trying to develop my first app with PyQt5 (a memory game).</p> <p>I have created two classes: <strong>MainApplication</strong>, which inherits from QMainWindow, and <strong>GridWidget</strong>, which inherits from QWidget. My aim is to let the user specify a folder with some images (jpg) using the fileMenu of the menuBar.</p> <p>So, in the <strong>MainApplication</strong> I created the method <strong>showDialog</strong> which connects to the fileMenu and outputs a list of filenames (names of the images within the selected folder), stored in a list variable. I would like to be able to pass this to the <strong>GridWidget</strong>, so that it can creates and fill the grid.</p> <p>I am kind of new to OOP programming, so maybe the organization of my script is not the best, and I am open to suggestions to improve it. My idea was to add <strong>GridWidget</strong> into <strong>MainApplication</strong>, but I don't know how to pass the output of <strong>showDialog</strong> to this. Any suggestion would be appreciated.</p> <p>Here is my code so far:</p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Memory game My first memory game in PyQt5. author: Umberto Minora last edited: September 2016 """ import os, sys, glob from PyQt5.QtWidgets import (QMainWindow, QWidget, QGridLayout, QPushButton, QApplication, QAction, QFileDialog) from PyQt5.QtGui import QPixmap class MainApplication(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.statusBar() openFile = QAction('Open', self) openFile.setStatusTip('Search image folder') openFile.triggered.connect(self.showDialog) menubar = self.menuBar() fileMenu = menubar.addMenu('&amp;File') fileMenu.addAction(openFile) self.form_widget = GridWidget(self) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Memory Game!') self.show() def showDialog(self): folder = str(QFileDialog.getExistingDirectory(self, "Select Directory", '/home', QFileDialog.ShowDirsOnly)) images = glob.glob(os.path.join(folder, '*.jpg')) if images: return images * 2 class GridWidget(QWidget): def __init__(self): super().__init__() grid = QGridLayout() self.setLayout(grid) names = self.showDialog() # DA SISTEMARE!!!!!! positions = [(i,j) for i in range(int(len(names)/2)) for j in range(int(len(names)/2))] for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) grid.addWidget(button, *position) if __name__ == '__main__': app = QApplication(sys.argv) ex = MainApplication() sys.exit(app.exec_()) </code></pre> <p><strong>EDIT</strong></p> <p>Thanks to <strong>@ekhumoro</strong>'s answer, now the code is working. Here is the code I am actually running (it's not the complete game, just an initial import of images from a folder).</p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Memory game 2 My first memory game in PyQt5. author: Umberto Minora last edited: September 2016 """ import os, sys, glob, math from PyQt5.QtWidgets import (QMainWindow, QWidget, QGridLayout, QPushButton, QApplication, QAction, QFileDialog, QLabel) from PyQt5.QtGui import QPixmap class MainApplication(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.statusBar() openFile = QAction('Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Search image folder') openFile.triggered.connect(self.showDialog) menubar = self.menuBar() self.fileMenu = menubar.addMenu('&amp;File') self.fileMenu.addAction(openFile) self.gridWidget = QWidget(self) self.gridLayout = QGridLayout(self.gridWidget) self.setCentralWidget(self.gridWidget) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Memory Game!') self.show() def populateGrid(self, images): names = images * 2 n_cols = math.ceil(math.sqrt(len(names))) n_rows = math.ceil(math.sqrt(len(names))) positions = [(i,j) for i in range(n_cols) for j in range(n_rows)] for position, name in zip(positions, names): if name == '': continue pixmap = QPixmap(name) scaled = pixmap.scaled(pixmap.width()/3, pixmap.height()/3) del(pixmap) lbl = QLabel(self) lbl.setPixmap(scaled) self.gridLayout.addWidget(lbl, *position) def showDialog(self): folder = str(QFileDialog.getExistingDirectory(self, "Select Directory", '.', QFileDialog.ShowDirsOnly)) images = glob.glob(os.path.join(folder, '*.jpg')) if images: self.populateGrid(images) if __name__ == '__main__': app = QApplication(sys.argv) ex = MainApplication() sys.exit(app.exec_()) </code></pre>
0
2016-09-25T16:24:41Z
39,689,457
<p>I think it will be simpler if you keep everything in one class. You should make each child widget an attribute of the class, so you can access them later using <code>self</code> within the methods of the class. All the program logic will go in the methods - so it's just a matter of calling methods in response to signals and events.</p> <p>Here is what the class should look like:</p> <pre><code>class MainApplication(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.statusBar() openFile = QAction('Open', self) openFile.setStatusTip('Search image folder') openFile.triggered.connect(self.showDialog) menubar = self.menuBar() self.fileMenu = menubar.addMenu('&amp;File') self.fileMenu.addAction(openFile) self.gridWidget = QWidget(self) self.gridLayout = QGridLayout(self.gridWidget) self.setCentralWidget(self.gridWidget) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Memory Game!') self.show() def populateGrid(self, images): names = images * 2 positions = [(i,j) for i in range(int(len(names)/2)) for j in range(int(len(names)/2))] for position, name in zip(positions, names): if name == '': continue button = QPushButton(name) self.gridLayout.addWidget(button, *position) def showDialog(self): folder = str(QFileDialog.getExistingDirectory(self, "Select Directory", '/home', QFileDialog.ShowDirsOnly)) images = glob.glob(os.path.join(folder, '*.jpg')) if images: self.populateGrid(images) </code></pre>
1
2016-09-25T16:57:58Z
[ "python", "python-3.x", "oop", "pyqt", "pyqt5" ]
How to check for multiple values in dict in Python
39,689,143
<pre><code>dict1 = {'galaxy': 5, 'apple': 6, 'nokia': 5} </code></pre> <p>Is there is a way to show the keys in a dict with the same values in a dict?</p> <pre><code>target_value = 5 new_dict = {} for key, value in dict1: if value == target_value: new_dict[key] = value </code></pre> <p>desired output:</p> <pre><code>dict1 = {'galaxy':5, 'nokia':5} </code></pre>
-2
2016-09-25T16:25:13Z
39,689,217
<p>If I understand you correctly, you're looking for something like that:</p> <pre><code>&gt;&gt;&gt; d = {'galaxy': 5, 'apple': 6, 'nokia': 5} &gt;&gt;&gt; { k:v for k,v in d.items() if v==5 } {'nokia': 5, 'galaxy': 5} </code></pre>
2
2016-09-25T16:33:00Z
[ "python", "dictionary" ]
Update a null values in countryside column in a data frame with reference to valid countrycode column from another data frame using python
39,689,145
<p>I have two data frames: Disaster, CountryInfo Disaster has a column country code which has some null values for example: Disaster:</p> <pre><code> 1.**Country** - **Country_code** 2.India - Null 3.Afghanistan - AFD 4.India - IND 5.United States - Null </code></pre> <p>CountryInfo:</p> <pre><code>0.**CountryName** - **ISO** 1.India - IND 2.Afganistan - AFD 3.United States - US </code></pre> <p>I need to fill the country code with reference to the country name.Can anyone suggest a solution for this? </p>
0
2016-09-25T16:25:18Z
39,690,406
<p>You can simply use <code>map</code> with a <code>Series</code>. </p> <p>With this approach all values are overwritten not only non <code>NaN</code>.</p> <pre><code># Test data disaster = pd.DataFrame({'Country': ['India', 'Afghanistan', 'India', 'United States'], 'Country_code': [np.nan, 'AFD', 'IND', np.nan]}) country = pd.DataFrame({'Country': ['India', 'Afghanistan', 'United States'], 'Country_code': ['IND', 'AFD', 'US']}) # Transforming country into a Series in order to be able to map it directly country_se = country.set_index('Country').loc[:, 'Country_code'] # Map disaster['Country_code'] = disaster['Country'].map(country_se) print(disaster) # Country Country_code # 0 India IND # 1 Afghanistan AFD # 2 India IND # 3 United States US </code></pre> <p>You can filter on <code>NaN</code> if you do not want to overwrite all values.</p> <pre><code>disaster.loc[pd.isnull(disaster['Country_code']), 'Country_code'] = disaster['Country'].map(country_se) </code></pre>
0
2016-09-25T18:35:54Z
[ "python", "python-2.7", "pandas" ]
Python 'Object has no attribute'
39,689,268
<p>Code gives the following error:</p> <p>"'module' Object has no attribute 'checkNone'"</p> <p>Dir setup:</p> <pre><code>+main.py Sorcery +Check.py </code></pre> <p>main.py</p> <pre><code>from Sorcery import Check check = Check.checkNone(None); </code></pre> <p>Check.py</p> <pre><code>class Check: def checkNone(content): if content == None: print("None!") else: print("Check!") return content </code></pre>
-3
2016-09-25T16:38:06Z
39,691,440
<p>First, rename the <code>Check.py</code> to anything you like, e.g.,<code>jacs.py</code>. Inside <code>jacs.py</code>, change <code>Class Check: def checkNone(content):</code> to <code>Class Check(object): def checkNone(self, content):</code>.<br> Then, in <code>main.py</code>, begin with </p> <pre><code>from Sorcery.jacs import Check output = Check.checkNone(None) </code></pre>
1
2016-09-25T20:20:21Z
[ "python", "object", "module" ]
How to clear a cached query?
39,689,315
<p>I'm using the following method to cache the result of a SQL query:</p> <pre><code>db(my_query).select(cache=(cache.ram, 3600), cacheable=True) </code></pre> <p>In some cases I want to clear this cache before it expires, which could be done by using <code>cache.ram.clear(key)</code> but I actually don't know the key generated by the DAL in the previous code.</p> <p>I understand <code>cache=(cache.ram, 0)</code> will clear the cache too, but I also have the overhead of executing the query.</p> <p>How can I achieve this?</p>
1
2016-09-25T16:44:06Z
39,689,987
<p>The cache key is a bit complicated to replicate (it is the MD5 hash of the database URI plus the SQL generated for the query). As an alternative, since you have <code>cacheable=True</code>, you can call <code>cache.ram</code> directly with your own key:</p> <pre><code>rows = cache.ram('my_query', lambda: db(my_query).select(cacheable=True), 3600) </code></pre>
2
2016-09-25T17:56:55Z
[ "python", "python-2.7", "web2py", "pydal" ]
Anaconda install Matlab Engine on Linux
39,689,320
<p>I'm trying to install <code>Matlab Engine for Python</code> on CentOS 7 for Matlab R2016a using anaconda python 3.4.</p> <p>I executed the following commands:</p> <pre><code>source activate py34 # Default is python 3.5 python setup.py install </code></pre> <p>The output is:</p> <pre><code>running install running build running build_py running install_lib creating /root/.local/lib/python2.7/site-packages/matlab creating /root/.local/lib/python2.7/site-packages/matlab/_internal copying build/lib/matlab/_internal/mlarray_sequence.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/_internal copying build/lib/matlab/_internal/__init__.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/_internal copying build/lib/matlab/_internal/mlarray_utils.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/_internal copying build/lib/matlab/mlarray.py -&gt; /root/.local/lib/python2.7/site-packages/matlab creating /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/engineerror.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/futureresult.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/fevalfuture.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/basefuture.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/matlabengine.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/__init__.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/enginesession.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/_arch.txt -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/engine/matlabfuture.py -&gt; /root/.local/lib/python2.7/site-packages/matlab/engine copying build/lib/matlab/mlexceptions.py -&gt; /root/.local/lib/python2.7/site-packages/matlab copying build/lib/matlab/__init__.py -&gt; /root/.local/lib/python2.7/site-packages/matlab byte-compiling /root/.local/lib/python2.7/site-packages/matlab/_internal/mlarray_sequence.py to mlarray_sequence.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/_internal/__init__.py to __init__.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/_internal/mlarray_utils.py to mlarray_utils.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/mlarray.py to mlarray.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/engineerror.py to engineerror.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/futureresult.py to futureresult.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/fevalfuture.py to fevalfuture.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/basefuture.py to basefuture.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/matlabengine.py to matlabengine.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/__init__.py to __init__.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/enginesession.py to enginesession.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/engine/matlabfuture.py to matlabfuture.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/mlexceptions.py to mlexceptions.pyc byte-compiling /root/.local/lib/python2.7/site-packages/matlab/__init__.py to __init__.pyc running install_egg_info Writing /root/.local/lib/python2.7/site-packages/matlabengineforpython-R2016a-py2.7.egg-info </code></pre> <p>It somehow install matlab engine into system's python version other than anaconda's <code>py34</code> virtual env. I noticed <a href="http://stackoverflow.com/questions/33357739/problems-installing-matlab-engine-for-python-with-anaconda">this</a> on OSX and it does work on my mac! Anyone can help with this on CentOS?</p>
1
2016-09-25T16:44:30Z
39,759,581
<p>After so many tortures I finally solved this in a simple way. Instead of configure system to use anaconda's python by modifying .bash_profile, you can add an alternative to python command:</p> <pre><code> sudo update-alternatives --install /usr/bin/python python ~/anaconda3/envs/py34/bin/python 2 update-alternatives --display python cd /usr/local/MATLAB/R2016a/extern/engines/python/ sudo python setup.py install </code></pre>
1
2016-09-29T00:30:57Z
[ "python", "matlab", "anaconda" ]
Python function/argument 'not defined' error
39,689,329
<p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br> Thanks in advance. </p> <pre><code>hourly_pay_rate = 7.50 commission_rate = 0.05 withholding_rate = 0.25 def startup_message(): print('''This program calculates the salesperson's pay. Five values are displayed. Hourly pay, commission, gross pay, withholding, and net pay.\n''') def main(): startup_message() name = input('Enter name: ') sales_amount = float(input('Enter sales amount: ')) hours_worked = float(input('Enter hours worked: ')) hourly_pay_amount = hours_worked * hourly_pay_rate commission_amount = sales_amount * commission_rate gross_pay = hourly_pay_rate + commission_rate withholding = gross_pay * withholding_rate net_pay = gross_pay - withholding display_results#&lt;-----'not defined' error for calculations def display_results(): #(parameters) print('Hourly pay amount is: ', \ format(hourly_pay_amount, ',.2f')) print('Commission amount is: ', \ format(commission_amount, ',.2f')) print('Gross pay is: ', \ format(gross_pay, ',.2f')) print('Withholding amount is: ', \ format(withholding, ',.2f')) print('Net pay is: ', \ format(net_pay, ',.2f')) main() input('\nPress ENTER to continue...') </code></pre>
-2
2016-09-25T16:45:44Z
39,689,353
<p>Your <code>display_result</code> is unindented. Correct the indentation and it should work</p> <pre><code>def main(): startup_message() name = input('Enter name: ') sales_amount = float(input('Enter sales amount: ')) hours_worked = float(input('Enter hours worked: ')) hourly_pay_amount = hours_worked * hourly_pay_rate commission_amount = sales_amount * commission_rate gross_pay = hourly_pay_rate + commission_rate withholding = gross_pay * withholding_rate net_pay = gross_pay - withholding display_results()#&lt;-----'not defined' error for calculations </code></pre>
1
2016-09-25T16:47:47Z
[ "python", "undefined" ]
Python function/argument 'not defined' error
39,689,329
<p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br> Thanks in advance. </p> <pre><code>hourly_pay_rate = 7.50 commission_rate = 0.05 withholding_rate = 0.25 def startup_message(): print('''This program calculates the salesperson's pay. Five values are displayed. Hourly pay, commission, gross pay, withholding, and net pay.\n''') def main(): startup_message() name = input('Enter name: ') sales_amount = float(input('Enter sales amount: ')) hours_worked = float(input('Enter hours worked: ')) hourly_pay_amount = hours_worked * hourly_pay_rate commission_amount = sales_amount * commission_rate gross_pay = hourly_pay_rate + commission_rate withholding = gross_pay * withholding_rate net_pay = gross_pay - withholding display_results#&lt;-----'not defined' error for calculations def display_results(): #(parameters) print('Hourly pay amount is: ', \ format(hourly_pay_amount, ',.2f')) print('Commission amount is: ', \ format(commission_amount, ',.2f')) print('Gross pay is: ', \ format(gross_pay, ',.2f')) print('Withholding amount is: ', \ format(withholding, ',.2f')) print('Net pay is: ', \ format(net_pay, ',.2f')) main() input('\nPress ENTER to continue...') </code></pre>
-2
2016-09-25T16:45:44Z
39,689,373
<p>First, to call <code>display_results</code>, you need to provide an empty set of parentheses:</p> <pre><code>display_results() </code></pre> <p>It appears you have an indentation error as well, as it seems you intended to call <code>display_results()</code> from <em>inside</em> the call to <code>main</code>:</p> <pre><code>def main(): startup_message() # ... net_pay = gross_pay - withholding display_results() </code></pre> <p>Without the indentation, you were attempting to access the name <code>display_results</code> immediately after defining <code>main</code>, but <em>before</em> you actually defined <code>display_results</code>.</p>
2
2016-09-25T16:49:13Z
[ "python", "undefined" ]
Python function/argument 'not defined' error
39,689,329
<p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br> Thanks in advance. </p> <pre><code>hourly_pay_rate = 7.50 commission_rate = 0.05 withholding_rate = 0.25 def startup_message(): print('''This program calculates the salesperson's pay. Five values are displayed. Hourly pay, commission, gross pay, withholding, and net pay.\n''') def main(): startup_message() name = input('Enter name: ') sales_amount = float(input('Enter sales amount: ')) hours_worked = float(input('Enter hours worked: ')) hourly_pay_amount = hours_worked * hourly_pay_rate commission_amount = sales_amount * commission_rate gross_pay = hourly_pay_rate + commission_rate withholding = gross_pay * withholding_rate net_pay = gross_pay - withholding display_results#&lt;-----'not defined' error for calculations def display_results(): #(parameters) print('Hourly pay amount is: ', \ format(hourly_pay_amount, ',.2f')) print('Commission amount is: ', \ format(commission_amount, ',.2f')) print('Gross pay is: ', \ format(gross_pay, ',.2f')) print('Withholding amount is: ', \ format(withholding, ',.2f')) print('Net pay is: ', \ format(net_pay, ',.2f')) main() input('\nPress ENTER to continue...') </code></pre>
-2
2016-09-25T16:45:44Z
39,689,378
<p>Indent and execute <code>()</code> the function.</p> <pre><code>def main(): startup_message() name = input('Enter name: ') sales_amount = float(input('Enter sales amount: ')) hours_worked = float(input('Enter hours worked: ')) hourly_pay_amount = hours_worked * hourly_pay_rate commission_amount = sales_amount * commission_rate gross_pay = hourly_pay_rate + commission_rate withholding = gross_pay * withholding_rate net_pay = gross_pay - withholding display_results() #&lt;-----'not defined' error for calculations </code></pre>
1
2016-09-25T16:50:13Z
[ "python", "undefined" ]
Python function/argument 'not defined' error
39,689,329
<p>I'm very new to coding, and am working on an assignment in Python 3.5.2 and am getting a 'display_results not defined' error. Am I placing it in the wrong section?<br> Thanks in advance. </p> <pre><code>hourly_pay_rate = 7.50 commission_rate = 0.05 withholding_rate = 0.25 def startup_message(): print('''This program calculates the salesperson's pay. Five values are displayed. Hourly pay, commission, gross pay, withholding, and net pay.\n''') def main(): startup_message() name = input('Enter name: ') sales_amount = float(input('Enter sales amount: ')) hours_worked = float(input('Enter hours worked: ')) hourly_pay_amount = hours_worked * hourly_pay_rate commission_amount = sales_amount * commission_rate gross_pay = hourly_pay_rate + commission_rate withholding = gross_pay * withholding_rate net_pay = gross_pay - withholding display_results#&lt;-----'not defined' error for calculations def display_results(): #(parameters) print('Hourly pay amount is: ', \ format(hourly_pay_amount, ',.2f')) print('Commission amount is: ', \ format(commission_amount, ',.2f')) print('Gross pay is: ', \ format(gross_pay, ',.2f')) print('Withholding amount is: ', \ format(withholding, ',.2f')) print('Net pay is: ', \ format(net_pay, ',.2f')) main() input('\nPress ENTER to continue...') </code></pre>
-2
2016-09-25T16:45:44Z
39,689,686
<p>Look at this very short program:</p> <pre><code>def main(): r = 2 + 2 show_result def show_result(): print("The result of 2+2 is {}", format(r)) main() </code></pre> <p><strong>This program will not work!!</strong> However, if you can fix all the bugs in this program you will have understood how to fix most of the problems in your longer example.</p> <p>Here is an annotated solution:</p> <pre><code>def main(): r = 2 + 2 show_result(r) # Must indent. Include brackets and pass the # variable def show_result(r): # Include a parameter list. print("The result of 2+2 is: {}".format(r)) # format is a string method main() </code></pre> <p>You need to indent and pass parameters to <code>display_results</code> and use the <a href="https://docs.python.org/3.5/library/string.html#format-specification-mini-language" rel="nofollow">correct syntax for format strings</a>. In your case something like:</p> <pre><code>print('Hourly pay amount is: {.2f}'.format(hourly_pay_amount)) </code></pre>
0
2016-09-25T17:23:01Z
[ "python", "undefined" ]
Plotting bar plot in Seaborn Python with rotated xlabels
39,689,352
<p>How can I plot a simple bar graph in Seaborn without any statistics? The data set is simply names and values.</p> <pre><code>import pandas df = pandas.DataFrame({"name": ["Bob Johnson", "Mary Cramer", "Joe Ellis"], "vals": [1,2,3]}) </code></pre> <p>I would like to plot this as a bar graph with xlabels pulled from <code>name</code> column and y-axis values from <code>vals</code> and have x-axis labels rotated 45 degrees. How can it be done? Using <code>sns.barplot</code> like:</p> <pre><code>sns.barplot(x="name", y="vals", data=df) </code></pre> <p>will compute statistics that are not relevant here. </p>
-1
2016-09-25T16:47:46Z
39,689,464
<p>You mean like that (<strong>set_xticklabels</strong> approach):</p> <pre><code>import pandas df = pandas.DataFrame({"name": ["Bob Johnson", "Mary Cramer", "Joe Ellis"], "vals": [1,2,3]}) g = sns.barplot(x='name', y='vals', data=df) g.set_xticklabels(g.get_xticklabels(), rotation=45) </code></pre> <hr> <p>Or probably <strong>plt.xticks</strong> approach can help:</p> <pre><code>import pandas import matplotlib.pylab as plt df = pandas.DataFrame({"name": ["Bob Johnson", "Mary Cramer", "Joe Ellis"], "vals": [1,2,3]}) bar_plot = sns.barplot(x='name', y='vals', data=df) plt.xticks(rotation=45) plt.show() </code></pre>
1
2016-09-25T16:58:32Z
[ "python", "matplotlib", "bar-chart", "seaborn" ]
How to add characters to a variable/integer name - Python
39,689,407
<p>There might be a question like this but I can't find it. I want to be to add the name of a variable/integer. e.g.</p> <pre><code>num = 5 chr(0x2075) </code></pre> <p>Now the 2nd line would return 5 in superscript but I want to put the word num into the Unicode instead so something like <code>chr(0x207+num)</code> would return 5 in superscript.</p> <p>Any ideas? Thanks in advance</p>
-2
2016-09-25T16:52:36Z
39,689,833
<pre><code>chr(0x2070 + num) </code></pre> <p>As given in the comment, if you want to get the character at U+207x, this is correct. </p> <p>But this is <strong><em>not</em></strong> the proper way to find the superscript of a number, because U+2071 is <code>ⁱ</code> (superscript "i") while U+2072 and U+2073 are not yet assigned. </p> <pre><code>&gt;&gt;&gt; chr(0x2070 + 1) 'ⁱ' </code></pre> <p>The real superscripts <code>¹</code> (U+00B9), <code>²</code> (U+00B2), <code>³</code> (U+00B3) are out of place.</p> <pre><code>&gt;&gt;&gt; chr(0xb9), chr(0xb2), chr(0xb3) ('¹', '²', '³') </code></pre> <p>Unfortunately, like most things Unicode, the only sane solution here is to hard code it:</p> <pre><code>def superscript_single_digit_number(x): return u'⁰¹²³⁴⁵⁶⁷⁸⁹'[x] </code></pre>
1
2016-09-25T17:38:34Z
[ "python", "variables", "unicode" ]
How to access Local variables of functions when the function call has finished in python?
39,689,434
<p>I found on the net that local variables of functions can't be accessed from outside when the function call has finished.I try to execute the program but it throws an error that variable is not defined. My code is</p> <pre><code>xyz=list() n=0 def length(g): i=0 n=g v=input("no of") while i&lt;v: c=input("Enter the 1st dimension:") j=input("Enter the 2nd dimension:") i=i+1 xyz.append(c) xyz.append(j) return c return j return n def prod(): global c for i in xyz: if n&lt;c and n&lt;j: print "Upload another" elif n==c and n==j: print "Accepted" else: print "Crop it" length(input("ENter the length")) prod() print xyz </code></pre> <p>It throws error like this</p> <blockquote> <p>Traceback (most recent call last): File "C:\Python27\pic.py", line 32, in prod() `File "C:\Python27\pic.py", line 21, in prod if n </blockquote>
-1
2016-09-25T16:55:47Z
39,689,541
<p>I guess this is what you would want to do</p> <pre><code>xyz=list() n=0 def length(g): i=0 n=g v=input("no of") global xyz while i&lt;v: c=input("Enter the 1st dimension:") j=input("Enter the 2nd dimension:") i=i+1 xyz.append(c) xyz.append(j) return c,j,n def prod(): global xyz c,j,n = length(input("ENter the length")) for i in xyz: if n&lt;c and n&lt;j: print "Upload another" elif n==c and n==j: print "Accepted" else: print "Crop it" prod() print xyz </code></pre> <p><strong><em>Output</em></strong></p> <pre><code>ENter the length 2 no of 2 Enter the 1st dimension: 1 Enter the 2nd dimension: 2 Crop it Crop it [1, 2] </code></pre>
0
2016-09-25T17:06:20Z
[ "python", "function", "global-variables", "local-variables" ]
Applying condition and update on same column
39,689,504
<p>I have written the following statement to update a column in DataFrame (df)</p> <pre><code> score 0 6800 1 7200 2 580 3 6730 </code></pre> <p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p> <p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is greater than 999 else keep unchanged. However, i get the following result.</p> <pre><code>0 680.0 1 720.0 2 NaN 3 673.0 </code></pre> <p>Also, I want the result as Integers.</p> <p>my expected output</p> <pre><code>0 680 1 720 2 580 3 673 </code></pre> <p><strong>Update</strong></p> <p>the following worked for me</p> <pre><code>df["score"] = np.where(df["score"] &gt; 999, df["score"]/10, df["score"]).astype(int) </code></pre>
1
2016-09-25T17:03:13Z
39,689,615
<p>The value for index 2 will not satisfy your filter condition (i.e. <code>&gt; 999</code>) and will yield a <code>NaN</code>, as per the <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html#series" rel="nofollow">documentation</a>:</p> <blockquote> <p>Note: <code>NaN</code> (not a number) is the standard missing data marker used in pandas </p> </blockquote>
-1
2016-09-25T17:13:36Z
[ "python", "pandas" ]
Applying condition and update on same column
39,689,504
<p>I have written the following statement to update a column in DataFrame (df)</p> <pre><code> score 0 6800 1 7200 2 580 3 6730 </code></pre> <p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p> <p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is greater than 999 else keep unchanged. However, i get the following result.</p> <pre><code>0 680.0 1 720.0 2 NaN 3 673.0 </code></pre> <p>Also, I want the result as Integers.</p> <p>my expected output</p> <pre><code>0 680 1 720 2 580 3 673 </code></pre> <p><strong>Update</strong></p> <p>the following worked for me</p> <pre><code>df["score"] = np.where(df["score"] &gt; 999, df["score"]/10, df["score"]).astype(int) </code></pre>
1
2016-09-25T17:03:13Z
39,689,659
<p>Use the <code>other</code> argument to the method <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html" rel="nofollow"><code>where</code></a>:</p> <pre><code>(df["score"]/10).where(df["score"] &gt; 999, other=df["score"]) 0 680.0 1 720.0 2 580.0 3 673.0 </code></pre>
1
2016-09-25T17:19:19Z
[ "python", "pandas" ]
Applying condition and update on same column
39,689,504
<p>I have written the following statement to update a column in DataFrame (df)</p> <pre><code> score 0 6800 1 7200 2 580 3 6730 </code></pre> <p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p> <p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is greater than 999 else keep unchanged. However, i get the following result.</p> <pre><code>0 680.0 1 720.0 2 NaN 3 673.0 </code></pre> <p>Also, I want the result as Integers.</p> <p>my expected output</p> <pre><code>0 680 1 720 2 580 3 673 </code></pre> <p><strong>Update</strong></p> <p>the following worked for me</p> <pre><code>df["score"] = np.where(df["score"] &gt; 999, df["score"]/10, df["score"]).astype(int) </code></pre>
1
2016-09-25T17:03:13Z
39,690,749
<p>The following worked for me</p> <p>df["score"] = np.where(df["score"] > 999, df["score"]/10, df["score"]).astype(int)</p>
0
2016-09-25T19:10:00Z
[ "python", "pandas" ]
Applying condition and update on same column
39,689,504
<p>I have written the following statement to update a column in DataFrame (df)</p> <pre><code> score 0 6800 1 7200 2 580 3 6730 </code></pre> <p>df["score"] = (df["score"]/10).where(df["score"] > 999)</p> <p>The idea is to clean up the score column to remove the extra '0' at the end, only if the number is greater than 999 else keep unchanged. However, i get the following result.</p> <pre><code>0 680.0 1 720.0 2 NaN 3 673.0 </code></pre> <p>Also, I want the result as Integers.</p> <p>my expected output</p> <pre><code>0 680 1 720 2 580 3 673 </code></pre> <p><strong>Update</strong></p> <p>the following worked for me</p> <pre><code>df["score"] = np.where(df["score"] &gt; 999, df["score"]/10, df["score"]).astype(int) </code></pre>
1
2016-09-25T17:03:13Z
39,691,661
<h2>Solution</h2> <p>Do as in <code>numpy</code>, and use <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">masks</a>:</p> <pre><code>df['score'][df['score']&gt;999] /= 10 </code></pre> <p>For legibility you could do:</p> <pre><code>f = df['score'] f[f&gt;999] /= 10 </code></pre> <h2>Explanation</h2> <p><code>df['score']&gt;999</code> will create a mask, a <code>bool</code> array of the same shape as <code>df['score']</code> with <code>True</code>/<code>False</code> values at the positions of the values fulfilling/not fulfilling the given condition. E.g., in the example above:</p> <pre><code>In [27]: df['score']&gt;999 Out[27]: 0 True 1 True 2 False 3 True Name: score, dtype: bool </code></pre> <p>You can use this mask to index the array/dataframe directly, to extract only matching elements:</p> <pre><code>In [28]: df['score'][df['score']&gt;999] Out[28]: 0 6800 1 7200 3 6730 Name: score, dtype: int64 </code></pre> <p>We divide all matching elements by ten and directly assign the result, using <code>/= 10</code>:</p> <pre><code>In [29]: df['score'][df['score']&gt;999] /= 10 In [30]: df['score'] Out[30]: 0 680 1 720 2 580 3 673 Name: score, dtype: int64 </code></pre>
3
2016-09-25T20:44:47Z
[ "python", "pandas" ]
From perl to python
39,689,510
<p>I've got some code that I've translated from perl into python, but I am having a time trying to figure out this last part. </p> <pre><code>my $bashcode=&lt;&lt;'__bash__'; . /opt/qip/etc/qiprc; . /opt/sybase/sybase.sh perl -mdata::dumper -e 'print dumper \%env'; __bash__ my $var1; eval qx(bash -c "$bashcode"); </code></pre> <p>While I understand (a bit) what this is doing, I can't seem to find out how to do this in python. Any help would be greatly appreciated.</p>
0
2016-09-25T17:03:45Z
39,689,580
<p>Your program is generating a script and running it.</p> <p>A first python approximation is:</p> <pre><code>import os script=""". /opt/qip/etc/qiprc; . /opt/sybase/sybase.sh perl -mdata::dumper -e 'print dumper \%env'; """ os.system(script) </code></pre> <p>As you can see, perl is still being used inside your script which is using the module data::dumper. If you want to use python here, you may need the equivalent module.</p>
1
2016-09-25T17:11:13Z
[ "python", "perl" ]
From perl to python
39,689,510
<p>I've got some code that I've translated from perl into python, but I am having a time trying to figure out this last part. </p> <pre><code>my $bashcode=&lt;&lt;'__bash__'; . /opt/qip/etc/qiprc; . /opt/sybase/sybase.sh perl -mdata::dumper -e 'print dumper \%env'; __bash__ my $var1; eval qx(bash -c "$bashcode"); </code></pre> <p>While I understand (a bit) what this is doing, I can't seem to find out how to do this in python. Any help would be greatly appreciated.</p>
0
2016-09-25T17:03:45Z
39,689,599
<p>This part:</p> <pre><code>my $bashcode=&lt;&lt;'__bash__'; . /opt/qip/etc/qiprc; . /opt/sybase/sybase.sh perl -mdata::dumper -e 'print dumper \%env'; __bash__ </code></pre> <p>Is a here doc and you would do this in Python:</p> <pre><code>bashcode="""\ . /opt/qip/etc/qiprc; . /opt/sybase/sybase.sh perl -mdata::dumper -e 'print dumper \%env'; """ </code></pre> <p>You would shell out to Bash using something like <a href="https://docs.python.org/2/library/os.html#os.system" rel="nofollow">os.system</a> or <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow">subprocess.check_output</a>.</p> <p>The result of that is then fed to <code>eval</code> to be run as Perl code. </p> <p>(The wisdom, and the result of the <code>eval</code> is dependant on what these Bash commands produce. It would appear that those commands are producing a Perl script. Obviously, that will not execute in Python. Python also has eval. Use <code>eval</code> in any language cautiously.)</p> <p>The use of <code>\%env</code> in Perl would seem to indicate access to the environment of the host. However, the actual Perl variable to access the OS environment hash is <code>ENV</code> in uppercase. In Bash, you access the environment with a lowercase <code>env</code></p> <p>To access the host environment in Python, use <a href="https://docs.python.org/2/library/os.html#process-parameters" rel="nofollow">os.environ</a></p>
0
2016-09-25T17:12:43Z
[ "python", "perl" ]
Simple image rotation with Python and DOM using RapydScript
39,689,555
<p>I have this code write in Python and works fine with Brython. This code rotate image in this case a cog. How Can I change it, and what change to work with RapydScript? I am new at programming so please have patience :D</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;!-- load Brython --&gt; &lt;script src="http://brython.info/src/brython_dist.js"&gt;&lt;/script&gt; &lt;!-- the main script; after loading, Brython will run all 'text/python3' scripts --&gt; &lt;script type='text/python'&gt; from browser import window, timer, document, html import time &lt;!-- I know that here, I must use this t0 = Date.now() --&gt; t0 = time.time() def user_agent(): """ Helper function for determining the user agent """ if window.navigator.userAgent.find('Chrome'): return 'chrome' elif window.navigator.userAgent.find('Firefox'): return 'firefox' elif window.navigator.userAgent.find('MSIE'): return 'msie' elif window.navigator.userAgent.find('Opera'): return 'opera' # Dict Mapping UserAgents to Transform Property names rotate_property = { 'chrome':'WebkitTransform', 'firefox':'MozTransform', 'msie':'msTransform', 'opera':'OTransform' } degrees = 0 def animation_step(elem_id): """ Called every 30msec to increase the rotatation of the element. """ global degrees, tm # Get the right property name according to the useragent agent = user_agent() prop = rotate_property.get(agent,'transform') # Get the element by id el = document[elem_id] # Set the rotation of the element setattr(el.style, prop, "rotate("+str(degrees)+"deg)") document['status'].innerHTML = "rotate("+str(degrees)+" deg)" # Increase the rotation degrees += 1 if degrees &gt; 360: # Stops the animation after 360 steps timer.clear_interval(tm) degrees = 0 # Start the animation tm = timer.set_interval(lambda id='img1':animation_step(id),30) document['status3'].innerHTML = "Time of execution python code("+str(time.time()-t0)+" ms)" &lt;!-- I know that here i must use this: "Time of execution python code", Date.now()-t0, "ms") --&gt; &lt;/script&gt; &lt;/head&gt; &lt;!-- After the page has finished loading, run bootstrap Brython by running the Brython function. The argument '1' tells Brython to print error messages to the console. --&gt; &lt;body onload='brython(1)'&gt; &lt;img id="img1" src="cog1.png" alt="cog1"&gt; &lt;script&gt;animation_step("img1",30);&lt;/script&gt; &lt;h2 style="width:200px;" id="status"&gt;&lt;/h2&gt; &lt;h2 style="width:800px;" id="status3"&gt;&lt;/h2&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
2016-09-25T17:07:28Z
39,690,411
<p>I'm not too familiar with Brython, but right away I can tell you that to port it to RapydScript you simply need to drop most of the unnecessary abstractions that I see the code importing, since RapydScript is closer to native JavaScript. As far as having the RapydScript code in the browser, you have a couple options:</p> <ul> <li>(recommended) compile your code ahead of time and include the .js file in your html (similar to Babel, UglifyJS, etc.), this way the code will run much faster and won't require you to include the compiler in the page</li> <li>use an in-browser RapydScript compiler (this one seems to be the most up-to-date if you don't want to tinker with compilation: <a href="https://github.com/adousen/RapydScript-pyjTransformer" rel="nofollow">https://github.com/adousen/RapydScript-pyjTransformer</a>) and include the code inside <code>&lt;script type="text/pyj"&gt;</code> tag similar to what you have done in the example.</li> </ul> <p>Now, assuming you pick the recommended option above, the next step is to drop the Brython boilerplate from the code, here is what your logic would look like in RapydScript (note that I also refactored it a little, removing the unnecessary 2-stage rotate method resolution and unneeded lambda call):</p> <pre><code>t0 = Date.now() def rotate_property(): """ Helper function mapping user agents to transform proeprty names """ if 'Chrome' in window.navigator.userAgent: return 'webkitTransform' elif 'Firefox' in window.navigator.userAgent: return 'MozTransform' elif 'MSIE' in window.navigator.userAgent: return 'msTransform' elif 'Opera' in window.navigator.userAgent: return 'OTransform' return 'transform' degrees = 0 def animation_step(elem_id='img1'): """ Called every 30msec to increase the rotatation of the element. """ nonlocal degrees # Get the right property name according to the useragent prop = rotate_property() # Get the element by id el = document.getElementById(elem_id) # Set the rotation of the element el.style[prop] = "rotate(" + degrees + "deg)" document.getElementById('status').innerHTML = "rotate(" + degrees + "deg)" # Increase the rotation degrees += 1 if degrees &gt; 360: # Stops the animation after 360 steps clearInterval(tm) degrees = 0 # Start the animation tm = setInterval(animation_step, 30) document.getElementById('status3').innerHTML = "Time of execution python code(" + (Date.now() - t0) + " ms)" </code></pre> <p>A few things to note:</p> <ul> <li>imports are no longer needed, RapydScript doesn't need boilerplate to interact with JavaScript</li> <li>Pythonic <code>timer.set_interval</code> and <code>timer.clear_interval</code> have been replaced with JavaScript equivalents (setInterval and clearInterval)</li> <li><code>document</code> you see in my code is the DOM itself, <code>document</code> you have in Brython code is a wrapper around it, hence accessing it works a bit differently</li> <li>RapydScript dropped <code>global</code> a long time ago in favor of Python 3's safer <code>nonlocal</code>, which is what I used in the code instead</li> <li>instead of <code>time</code> module, RapydScript has direct access to JavaScript's <code>Date</code> class, which I used in the code to time it</li> <li>I would also recommend moving <code>prop = rotate_property()</code> call outside the function, since the user agent won't change between function calls (in this case the operation is relatively cheap, but for more complex logic this will improve your performance)</li> <li>you seem to be launching Brython from HTML via body <code>onload</code>, get rid of that as well as the line that says <code>&lt;script&gt;animation_step("img1",30);&lt;/script&gt;</code>, the above code should trigger for you automatically as soon as page loads courtesy of setInterval call</li> <li>since RapydScript uses unicode characters to avoid name collisions, you need to tell HTML to treat the document as unicode by adding this line to head: <code>&lt;meta charset="UTF-8"&gt;</code></li> <li>for future reference, none of your <code>onload</code> calls to RapydScript will work, because unlike Brython, RapydScript protects itself in its own scope, invisible to the outside (this has been the accepted practice in JavaScript world for a long time), your options for making <code>onload</code> work are: <ul> <li>(not recommended) compile the file with <code>-b</code> flag to omit the self-protecting scope</li> <li>(recommended) inside your code, attach your functions to the global <code>window</code> object if you want them accessible from outside</li> </ul></li> </ul> <p>Your actual html code that calls the compiled version of the above code would then look like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;img id="img1" src="cog1.png" alt="cog1"&gt; &lt;h2 style="width:200px;" id="status"&gt;&lt;/h2&gt; &lt;h2 style="width:800px;" id="status3"&gt;&lt;/h2&gt; &lt;script src="myfile.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
2016-09-25T18:36:30Z
[ "python", "rapydscript" ]
Why do I get a 'list index out of range' error for the below code using a for loop:
39,689,662
<p>Problem Statement: Given a nested list nl consisting of a set of integers, write a python script to find the sum of alternate elements of the sub-lists.</p> <pre><code>nl = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] sum = 0 n = 0 j=[] for ele in nl: for i in ele: j.append(i) for a in j: sum = sum + j[n] n = n + 2 print(sum) </code></pre> <p>When I run this code, I get an error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\ARUDRAVA\Contacts\Desktop\lists Assigment\assigment2.py",line 14, in &lt;module&gt; sum = sum + j[n] IndexError: list index out of range </code></pre> <p>Why is this error generated?</p>
-2
2016-09-25T17:19:46Z
39,689,836
<p>Your outer loops look like this:</p> <pre><code>for ele in nl: for i in ele: j.append(i) # inner loop. </code></pre> <p>The first time the inner loop is reached, only one element has been appended to the list <code>j</code>. The second time the inner loop is reached, two elements have been appended to <code>j</code>, so the second time the loop is reached, <code>j</code> is <code>[1,2]</code>. </p> <p>It seems from your comment that you think that when the inner loop is reached, that <code>j</code> contains all 12 numbers from <code>nl</code>. That's not correct. Perhaps you meant for the "inner loop" to come after the two outside loops and not inside them.</p> <p>Let's it is the second time that the inner loop is reached <code>j=[1,2]</code>, and suppose <code>n=0</code> (it might be larger than this but it can't be smaller)</p> <p>Let's check the inner loop</p> <pre><code> for a in j: sum = sum + j[n] n = n + 2 </code></pre> <p>Because j has two elements, it will loop twice:</p> <p>The first time through the loop it adds <code>j[0]</code> to sum, and sets <code>n=0+2</code></p> <p>The second time through the loop it tries to add <code>j[2]</code> to sum, which is a IndexError. </p> <p>You will need to rethink the logic of your program. <em>Good Luck!</em></p>
0
2016-09-25T17:38:44Z
[ "python", "python-3.x" ]
Why do I get a 'list index out of range' error for the below code using a for loop:
39,689,662
<p>Problem Statement: Given a nested list nl consisting of a set of integers, write a python script to find the sum of alternate elements of the sub-lists.</p> <pre><code>nl = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] sum = 0 n = 0 j=[] for ele in nl: for i in ele: j.append(i) for a in j: sum = sum + j[n] n = n + 2 print(sum) </code></pre> <p>When I run this code, I get an error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\ARUDRAVA\Contacts\Desktop\lists Assigment\assigment2.py",line 14, in &lt;module&gt; sum = sum + j[n] IndexError: list index out of range </code></pre> <p>Why is this error generated?</p>
-2
2016-09-25T17:19:46Z
39,689,847
<p>This is how it's usually done in Python:</p> <pre><code>nl = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] total = sum(number for sublist in nl for number in sublist) </code></pre> <p>Don't name the variable <code>sum</code> - that would "hide" a built-in function. Exactly the function you need in fact.</p> <hr> <p>Anyway, the error in your code was here:</p> <pre><code>sum = sum + j[n] </code></pre> <p>It should have been:</p> <pre><code>sum = sum + a </code></pre>
2
2016-09-25T17:39:57Z
[ "python", "python-3.x" ]
Snake game in pygame: body growth function
39,689,667
<p>I am writing the Snake in pygame, but I not have a very clear idea of how to implement the growing functionality of the snake. I made a list ("lista_cobra") containing the head coordinates (which is about 30x30 pixels), and thought about making another list from this, containing the last positions of the head, excluding the last segment, and so draw a picture of the body snake ("corpito" also of 30x30 pixels), from there, every point accumulated. This idea does not work very well when put into practice, because the way I thought the body can not make the characteristic movement of the Snake. My question is how to grow the body from the previous coordinates of the head while keeping the characteristic movement of the body?</p> <pre><code>#-*- coding: latin1 -*- import pygame, sys, os, random, math, time from pygame.locals import * pygame.init() ##### Cores ###### preto = (0, 0, 0) vermelho = (255, 0, 0) ################## ################## dimensao = [800, 600] tela = pygame.display.set_mode(dimensao) ######### Objetos ########### gramado = pygame.image.load(os.path.join("images", "fundocobrinha.jpg")) paredes = pygame.image.load(os.path.join("images", "paredes.png")) comp = pygame.image.load(os.path.join("images", "comidacobra.png")) comp = pygame.transform.scale(comp, (18, 20)) cabeca = pygame.image.load(os.path.join("images", "cabecadacobra.png")) corpito = pygame.image.load(os.path.join("images", "corpodacobra.png")) corpo = pygame.transform.rotate(cabeca, 0) caminhodafonte = os.path.join("fonte", "lunchds.ttf") fonte = pygame.font.Font(caminhodafonte, 22) fonte_fim = pygame.font.Font(caminhodafonte, 25) ############################# ###### Distancia ######### def distancia(x, y, x2, y2): distancia = math.sqrt(((x2 - x) ** 2) + ((y2 - y) ** 2)) return distancia ########################## ########### cobra ############# pontos = 0 vidas = 3 raio_cobra = 12 raio_corpo = 12 x = [130] y = [130] def cobrinha(): global x, y, corpo, direcao, x_modificado, y_modificado tela.blit(corpo, (x[0] - raio_cobra, y[0] - raio_cobra)) if direcao == "direita": corpo = pygame.transform.rotate(cabeca, 0) x_modificado = 3 y_modificado = 0 elif direcao == "esquerda": corpo = pygame.transform.rotate(cabeca, 180) x_modificado = -3 y_modificado = 0 elif direcao == "cima": corpo = pygame.transform.rotate(cabeca, 90) y_modificado = -3 x_modificado = 0 elif direcao == "baixo": corpo = pygame.transform.rotate(cabeca, 270) y_modificado = 3 x_modificado = 0 x[0] += x_modificado y[0] += y_modificado ################################ ###### Comida da Cobra ######### raio_cCobra = 4 nova_comida = True x2 = 0 y2 = 0 def comida(): global x2, y2, comp, nova_comida if nova_comida: x2 = random.randint(47, 747) y2 = random.randint(56, 548) nova_comida = False tela.blit(comp, (x2 - raio_cCobra, y2 - raio_cCobra)) ################################ ########## Informações de status ############# def status_de_jogo(): global pontos, fonte p = fonte.render("Pontos: " + str(pontos), True, preto) tela.blit(p, (45,37)) v = fonte.render("Vidas :" + str(vidas), True, preto) tela.blit(v, (45,61)) ############################### ######## mensagen de tela ###### def mensagem_de_tela(): mensagem_de_texto = fonte_fim.render("Fim de Jogo, pressione C para jogar ou Q para sair.", True, vermelho) tela.blit(mensagem_de_texto,[55,200]) ################################ ######################################## Loop principal ################################################### def loop_jogo(): global x, y, x2, x2, vidas, pontos, distancia, corpo, raio_cCobra, raio_cobra, counter, nova_comida, lista_cobra,lista_corpo, direcao direcao = "direita" lista_cobra = [] clock = pygame.time.Clock() sair_do_jogo = False fim_de_jogo = False while not sair_do_jogo: while fim_de_jogo == True: mensagem_de_tela() pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: sair_do_jogo = True fim_de_jogo = False if event.key == pygame.K_c: loop_jogo() #### Capturando todos os eventos durante a execução #### for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: direcao = "direita" elif event.key == pygame.K_LEFT: direcao = "esquerda" elif event.key == pygame.K_UP: direcao = "cima" elif event.key == pygame.K_DOWN: direcao = "baixo" if event.type == QUIT: sair_do_jogo = True ####### posição da cabeça da cobra ########### cabeca_cobra = [] cabeca_cobra.append(x[0]) cabeca_cobra.append(y[0]) lista_cobra.append(cabeca_cobra) tela.blit(gramado, (0, 0)) tela.blit(paredes, (0, 0)) comida() cobrinha() status_de_jogo() clock.tick(60) fps = clock.get_fps() pygame.display.set_caption("Shazam Caraí II ## FPS: %.2f" %fps) ########## Se bater nas paredes ################## if (x[0] &gt;= 751 or x[0] &lt;= 44) or (y[0] &gt;= 553 or y[0] &lt;= 42): vidas -= 1 x = 400 y = 300 ################################################## if distancia(int(x[0]), int(y[0]), x2, y2) &lt; (raio_cobra + raio_cCobra): nova_comida = True pontos += 1 if vidas == 0: fim_de_jogo = True mensagem_de_tela() pygame.display.flip() ########################################################################################################### loop_jogo() </code></pre>
0
2016-09-25T17:20:22Z
39,691,311
<p>I couldn't read your source, but I'd give it a try.</p> <p>The body of the snake consists of the positions in <code>lista_cobra</code>. Let the length of the snake be stored in a variable <code>len_cobra</code>. Now when the head moves on, the new position of the head has to be added at the top of <code>lista_cobra</code>:</p> <pre><code>lista_cobra.insert(0, head_cobra) </code></pre> <p>But the list now has to be truncated again to the length of the cobra </p> <pre><code>lista_cobra = lista_cobra[:len_cobra] </code></pre> <p>Now back to your question: How to grow the snake? That's easily done by increasing <code>len_cobra</code> by one each time the specific event occurs (usually after some moves). The rest is already taken care of. </p>
0
2016-09-25T20:07:24Z
[ "python", "python-2.7", "pygame" ]
Python make a number loop within a range
39,689,676
<p>So I saw this post, <a href="http://stackoverflow.com/q/5996881/6759115">on limiting numbers,</a> but I noticed it would cut a number off if it wasn't within the range.</p> <p>Is there a way to do this like so:</p> <p><code>variable = 25</code></p> <p>If your range is 1-20, can <code>variable</code> become 5?</p> <p>Or if <code>variable = 41</code>, have it become 1?</p> <p>I have tried this:</p> <pre><code> def loop(number, maxn, minn): if number &gt; maxn: number = maxn - number return number </code></pre> <p>With a range of 0-20, and a number of 40, I got -20?!?</p>
-1
2016-09-25T17:21:38Z
39,689,723
<p>One option would be to set <code>variable = (|variable| % (MAX - MIN + 1)) + MIN</code>. This will give you a number that is between <code>MIN</code> and <code>MAX</code>, inclusively.</p> <p>Note that this only works consistently if <code>variable</code>, <code>MAX</code> and <code>MIN</code> are non-negative integers, and <code>MAX &gt;= MIN &gt;= 0</code>.</p> <p>The reasoning behind this is as follows: <code>|variable| % (MAX - MIN + 1)</code> is necessarily non-negative, given that <code>MAX - MIN + 1</code> and <code>|variable|</code> are non-negative, and so the modulos must be non-negative. Thus the lowest it can be is zero. We add <code>MIN</code> after, so the number at its lowest in total can be <code>MIN</code>.</p> <p>At most, <code>|variable| % (MAX - MIN + 1)</code> is <code>MAX - MIN</code>, due again to the nature of the modulos operator. Adding <code>MIN</code> afterwards gives us <code>MAX</code>. Thus the highest output will be <code>MAX</code>.</p> <p>No <code>variable</code> will give a number that is lower than <code>MIN</code> or higher than <code>MAX</code>, and there is always an equal number of <code>variable</code> such that <code>n = (|variable| % (MAX - MIN + 1)) + MIN</code>, for all <code>n</code> between <code>MIN</code> and <code>MAX</code> inclusively.</p>
0
2016-09-25T17:27:16Z
[ "python" ]
Python make a number loop within a range
39,689,676
<p>So I saw this post, <a href="http://stackoverflow.com/q/5996881/6759115">on limiting numbers,</a> but I noticed it would cut a number off if it wasn't within the range.</p> <p>Is there a way to do this like so:</p> <p><code>variable = 25</code></p> <p>If your range is 1-20, can <code>variable</code> become 5?</p> <p>Or if <code>variable = 41</code>, have it become 1?</p> <p>I have tried this:</p> <pre><code> def loop(number, maxn, minn): if number &gt; maxn: number = maxn - number return number </code></pre> <p>With a range of 0-20, and a number of 40, I got -20?!?</p>
-1
2016-09-25T17:21:38Z
39,689,865
<p>Just figured it out.</p> <pre><code>def loop(n, minn, maxn): while n &gt; maxn: n = n - (maxn - minn) while n &lt; minn: n = n + (maxn - minn) return n </code></pre> <p>I think that should work for most cases, including negative numbers and ranges.</p>
0
2016-09-25T17:43:07Z
[ "python" ]
Python make a number loop within a range
39,689,676
<p>So I saw this post, <a href="http://stackoverflow.com/q/5996881/6759115">on limiting numbers,</a> but I noticed it would cut a number off if it wasn't within the range.</p> <p>Is there a way to do this like so:</p> <p><code>variable = 25</code></p> <p>If your range is 1-20, can <code>variable</code> become 5?</p> <p>Or if <code>variable = 41</code>, have it become 1?</p> <p>I have tried this:</p> <pre><code> def loop(number, maxn, minn): if number &gt; maxn: number = maxn - number return number </code></pre> <p>With a range of 0-20, and a number of 40, I got -20?!?</p>
-1
2016-09-25T17:21:38Z
39,695,430
<p>Loops can potentially take a long time to run. This happens when <code>maxn</code> and <code>minn</code> are close together and <code>n</code> is far from either.</p> <p>To flat out calculate it:</p> <pre><code>def loop(n, maxn, minn): # maxn must be greater than minn maxn += 1 # range needed includes minn but stops just before maxn; # to include maxn in the range, bump the value used up # by one. r = maxn - minn # get a range x = n - minn # adjust so that calculations center on zero x = x % r # modulo by range, x = x + minn # undo the adjustment from earlier return x </code></pre> <p>Or minimized:</p> <pre><code>def loop(n, maxn, minn): return ((n - minn) % (maxn - minn + 1)) + minn </code></pre>
0
2016-09-26T05:44:32Z
[ "python" ]
Python serialize HTTPFlow object (MITM)
39,689,678
<p>I am using <a href="http://docs.mitmproxy.org/en/stable/introduction.html" rel="nofollow">mitmproxy</a>, a python man-in-the-middle (MITM) proxy for HTTP, to modify on the fly the HTTP request of a certain website.</p> <p><strong>Goal:</strong></p> <p>For test purposes, when it receives an HTTP request, it should save it (it receives a <a href="http://docs.mitmproxy.org/en/stable/dev/models.html#mitmproxy.models.HTTPFlow" rel="nofollow">HTTPFlow</a> object) and the next time the same request will be made i need to resent the exact same <em>data/html/header/resourses/ecc..</em> to the browser.</p> <p><strong>Problem:</strong></p> <p>The obvious solution is to serialize the object but <strong>it isn't serializable</strong>! </p> <p>I cannot simply <strong>keep it in memory</strong> because i need to restart the proxy during the tests</p> <p>What can i do to achieve my goal?</p> <p><strong>Details:</strong></p> <p>I have already tried <em>pickle</em>, <em>cPickle</em> and <em>marshal</em> with the following errors:</p> <blockquote> <ul> <li><p>a class that defines __slots__ without defining __getstate__ cannot be pickled</p></li> <li><p>can't pickle CDataGCP objects</p></li> <li>ValueError: unmarshallable object</li> </ul> </blockquote> <p><strong>Ideas</strong>:</p> <ul> <li>1) how much is it a bad idea to change the original object <strong>to make it serializable</strong>? and how can i do it?</li> <li>2) what if the main process <strong>communicate with a second always-alive python process</strong> which simply keep the object in memory? are they still need to comunicate obj serializing them?</li> </ul>
0
2016-09-25T17:21:57Z
39,918,745
<p>Found solution (the HTTPFlow obj has a method to get the state)</p> <p>Imports</p> <pre><code>from mitmproxy.models import HTTPFlow from mitmproxy.models import HTTPResponse </code></pre> <p>Save state:</p> <pre><code>cached_state = http_flow_response.response.get_state() </code></pre> <p>Load state:</p> <pre><code># create the obj http_response = HTTPResponse( cached_state['http_version'], # "HTTP/1.1" cached_state['status_code'], # 200 cached_state['reason'], # "Ok" cached_state['headers'], # Headers(content_type="...") cached_state['content']) # str # send the obj http_flow_request.reply(cached_http_response) </code></pre>
0
2016-10-07T13:42:43Z
[ "python", "serialization", "ipc", "mitmproxy" ]
Python While Loops Asterisk
39,689,746
<p>Re-type and run, note incorrect behavior. Then fix errors in the code, which should print num_stars asterisks.</p> <pre><code>while num_printed != num_stars: print('*') </code></pre> <p>Below is the code which I have entered. I am getting an infinite loop hence no answer. Please help me out! Thanks!</p> <pre><code>num_stars = 3 num_printed = 0 while(num_printed != num_stars): print(num_stars*'*') </code></pre>
-1
2016-09-25T17:29:18Z
39,689,808
<p>You'll want either:</p> <pre><code>num_stars = 3 print(num_stars * '*') </code></pre> <p>or:</p> <pre><code>num_stars = 3 num_printed = 0 while(num_printed &lt; num_stars): print('*') num_printed += 1 </code></pre> <p>Depending on what you're trying to do.</p>
1
2016-09-25T17:36:04Z
[ "python", "loops", "while-loop" ]
Install mac : 1 error generated (error: '_GStaticAssertCompileTimeAssertion_0' declared as an array)
39,689,752
<p>I'm trying to install kivy on mac OSX 10.11.2 for a couple of hours now. What I did (as explained here: <a href="https://kivy.org/docs/installation/installation-osx.html" rel="nofollow">https://kivy.org/docs/installation/installation-osx.html</a>):</p> <pre><code>$ brew install sdl2 sdl2_image sdl2_ttf sdl2_mixer gstreamer $ pip install -I Cython==0.23 $ USE_OSX_FRAMEWORKS=0 pip install kivy </code></pre> <p>The first two commands worked perfectly fine. The last command give me this error:</p> <pre><code>16 warnings and 1 error generated. error: command '/usr/bin/clang' failed with exit status 1 </code></pre> <p>When I look above the only error I get is:</p> <pre><code>In file included from /usr/local/Cellar/glib/2.48.2/include/glib-2.0/glib/galloca.h:32: /usr/local/Cellar/glib/2.48.2/include/glib-2.0/glib/gtypes.h:422:3: error: '_GStaticAssertCompileTimeAssertion_0' declared as an array with a negative size G_STATIC_ASSERT(sizeof (unsigned long long) == sizeof (guint64)); ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /usr/local/Cellar/glib/2.48.2/include/glib-2.0/glib/gmacros.h:232:103: note: expanded from macro 'G_STATIC_ASSERT' #define G_STATIC_ASSERT(expr) typedef char G_PASTE (_GStaticAssertCompileTimeAssertion_, __COUNTER__)[(expr) ? 1 : -1] G_GNUC_UNUSED ^~~~~~~~~~~~~~~ </code></pre> <p>Could you help me? Let me know if you need more info. Thank you very much!</p>
0
2016-09-25T17:29:35Z
39,957,871
<p>I had the same problem trying to install with CLI. It appears kivy installation with .app file worked. Follow this guide:</p> <ul> <li><a href="https://kivy.org/docs/installation/installation-osx.html" rel="nofollow">https://kivy.org/docs/installation/installation-osx.html</a></li> </ul> <p>then you should be able to import kivy. But I am sorry I can't help you more with this issue ^^</p>
0
2016-10-10T12:04:11Z
[ "python", "osx", "install", "kivy" ]
Implement ASN1 structure properly using pyasn1
39,689,890
<p>I am new to ASN1 and want to implement this structure using pyasn1</p> <pre><code> ECPrivateKey ::= SEQUENCE { version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), privateKey OCTET STRING, parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, publicKey [1] BIT STRING OPTIONAL } </code></pre> <p>here is the code I am using </p> <pre><code>from pyasn1.type import univ, namedtype, tag class ZKey(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('id', univ.Integer()), namedtype.NamedType('priv', univ.OctetString()), namedtype.OptionalNamedType( 'ECParam', univ.ObjectIdentifier().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0) ) ), namedtype.OptionalNamedType( 'pub', univ.BitString().subtype( implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1) ))) </code></pre> <p>upon encoding using this sequence I get result <a href="https://lapo.it/asn1js/#30150201010407666F6F2D62617280032A0305810203A8" rel="nofollow">like</a>, when I want the structure to be something like <a href="https://lapo.it/asn1js/#30770201010420713C94CCA8FF45C600673470C98947440CCEBCA65ED67E90D83CC6EECE721C46A00A06082A8648CE3D030107A14403420004D8409A7A6A074EDBA2723C37C1BFDEF5B65C8266BCD4DA7D4F660379D50B7730E57C1FA668E7BD1A504BA7E1627BFB5CDF61F85AA8C2E7F9DC722D09CC9B131E" rel="nofollow">this</a>. What am I missing? Thank You in advance</p>
0
2016-09-25T17:46:31Z
39,945,199
<p>I guess in the ASN.1 module you are working with, EXPLICIT tagging mode is the default. So in your pyasn1 code you should use explicit tagging as well. </p> <p>Here's slightly fixed code that should work as you want:</p> <pre><code>from pyasn1.type import univ, namedtype, tag from pyasn1.codec.der.encoder import encode import base64 class ZKey(univ.Sequence): componentType = namedtype.NamedTypes( namedtype.NamedType('id', univ.Integer()), namedtype.NamedType('priv', univ.OctetString()), namedtype.OptionalNamedType( 'ECParam', univ.ObjectIdentifier().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0) ) ), namedtype.OptionalNamedType( 'pub', univ.BitString().subtype( explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 1) ) ) ) zKey = ZKey() zKey['id'] = 123 zKey['priv'] = 'foo bar' zKey['ECParam'] = '1.3.6.1' zKey['pub'] = [1,0,1,1] substrate = encode(zKey) print(base64.encodebytes(substrate)) </code></pre>
0
2016-10-09T15:22:06Z
[ "python", "python-3.x", "pyasn1" ]