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
Words.word() from nltk corpus seemingly contains strange non-valid words
38,907,413
<p>This code loops through every word in word.words() from the nltk library, then pushes the word into an array. Then it checks every word in the array to see if it is an actual word by using the same library and somehow many words are strange words that aren't real at all, like "adighe". What's going on here?</p> <pre><code>import nltk from nltk.corpus import words test_array = [] for i in words.words(): i = i.lower() test_array.append(i) for i in test_array: if i not in words.words(): print(i) </code></pre>
0
2016-08-11T23:06:00Z
38,907,493
<p>I don't think there's anything mysterious going on here. The first such example I found is "Aani", "the dog-headed ape sacred to the Egyptian god Thoth". Since it's a proper noun, "Aani" is in the word list and "aani" isn't.</p> <p>According to dictionary.com, "Adighe" is an alternative spelling of "Adygei", which is another proper noun meaning a region of Russia. Since it's also a language I suppose you might argue that "adighe" should also be allowed. This particular word list will argue that it shouldn't.</p>
0
2016-08-11T23:12:58Z
[ "python", "nltk", "corpus" ]
Pip install error missing 'libxml/xmlversion.h'
38,907,503
<p>I need to install the python package xmlsec(<a href="https://pypi.python.org/pypi/xmlsec" rel="nofollow">https://pypi.python.org/pypi/xmlsec</a>) and when I try running</p> <pre><code>pip install xmlsec </code></pre> <p>It gives me this error: </p> <pre><code>src\xmlsec\constants.c(266) : fatal error C1083: Cannot open include file: 'libxml/xmlversion.h': No such file or directory </code></pre> <p>When I first researched this error I found numerous answers that it had to do with the installed lxml package. After trying:</p> <pre><code>pip install --upgrade lxml </code></pre> <p>It wasn't able to upgrade and so I uninstalled lxml and installed it again but there was an IO error. In the end I downloaded the lxml file from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml</a> and placed it in my python directory and installed it as the answer from this question did: <a href="http://stackoverflow.com/questions/30493031/solved-installing-lxml-libxml2-libxslt-on-windows-8-1">SOLVED: Installing lxml, libxml2, libxslt on Windows 8.1</a></p> <p>It uploaded successfully and when running pip upgrade, it says it is up to date.</p> <p><strong>The same error though still persists from trying to install xmlsec though with 'libxml/xmlversion.h' missing. Does anyone know what else can be the problem here?</strong></p> <p>Note: I'm using python 2.7 on windows</p>
0
2016-08-11T23:14:58Z
38,907,674
<p>You may need to install the header files for <code>libxml</code> and <code>libxml-sec</code>. You do not indicate which platform you are running on. If you run on ubuntu you need to <code>sudo apt-get install libxml2-dev libxmlsec1-dev</code>. </p>
0
2016-08-11T23:35:01Z
[ "python", "python-2.7", "pip", "python-module", "python-packaging" ]
With a gzip dataframe, how can I read/decompress this line by line?
38,907,550
<p>I have an extremely large dataframe saved as a <code>gzip</code> file. The data also needs a good deal of manipulation before being saved. </p> <p>One could try to convert this entire gzip dataframe into text format, save this to a variable, parse/clean the data, and then save as a <code>.csv</code> file via <code>pandas.read_csv()</code>. However, this is extremely memory intensive. </p> <p>I would like to read/decompress this file line by line (as this would be the most memory-efficient solution, I think), parse this (e.g. with regex <code>re</code> or perhaps a <code>pandas</code> solution) and then save each line into a pandas dataframe. </p> <p>Python has a <code>gzip</code> library for this:</p> <pre><code>with gzip.open('filename.gzip', 'rb') as input_file: reader = reader(input_file, delimiter="\t") data = [row for row in reader] df = pd.DataFrame(data) </code></pre> <p>However, this seems to drop all information into the 'reader' variable, and then parses. How can one do this in a more (memory) efficient manner? </p> <p>Should I be using a different library instead of <code>gzip</code>?</p>
0
2016-08-11T23:21:25Z
38,907,586
<p>Perhaps extract your data with <code>gunzip -c</code>, pipe it to your Python script and work with standard input there:</p> <pre><code>$ gunzip -c source.gz | python ./line_parser.py | gzip -c - &gt; destination.gz </code></pre> <p>In the Python script <code>line_parser.py</code>:</p> <pre><code>#!/usr/bin/env python import sys for line in sys.stdin: sys.stdout.write(line) </code></pre> <p>Replace <code>sys.stdout.write(line)</code> with code to process each line in your custom way.</p>
0
2016-08-11T23:25:37Z
[ "python", "pandas", "memory-management", "dataframe", "gzip" ]
With a gzip dataframe, how can I read/decompress this line by line?
38,907,550
<p>I have an extremely large dataframe saved as a <code>gzip</code> file. The data also needs a good deal of manipulation before being saved. </p> <p>One could try to convert this entire gzip dataframe into text format, save this to a variable, parse/clean the data, and then save as a <code>.csv</code> file via <code>pandas.read_csv()</code>. However, this is extremely memory intensive. </p> <p>I would like to read/decompress this file line by line (as this would be the most memory-efficient solution, I think), parse this (e.g. with regex <code>re</code> or perhaps a <code>pandas</code> solution) and then save each line into a pandas dataframe. </p> <p>Python has a <code>gzip</code> library for this:</p> <pre><code>with gzip.open('filename.gzip', 'rb') as input_file: reader = reader(input_file, delimiter="\t") data = [row for row in reader] df = pd.DataFrame(data) </code></pre> <p>However, this seems to drop all information into the 'reader' variable, and then parses. How can one do this in a more (memory) efficient manner? </p> <p>Should I be using a different library instead of <code>gzip</code>?</p>
0
2016-08-11T23:21:25Z
38,907,669
<p>Have you considered using <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-hdf5" rel="nofollow">HDFStore</a>:</p> <blockquote> <p>HDFStore is a dict-like object which reads and writes pandas using the high performance HDF5 format using the excellent PyTables library. See the cookbook for some advanced strategies</p> </blockquote> <p><strong>Create Store, save DataFrame and close store.</strong></p> <pre><code># Note compression. store = pd.HDFStore('my_store.h5', mode='w', comp_level=9, complib='blosc') with store: store['my_dataframe'] = df </code></pre> <p><strong>Reopen store, retrieve dataframe and close store.</strong></p> <pre><code>with pd.HDFStore('my_store.h5', mode='r') as store: df = store.get('my_dataframe') </code></pre>
0
2016-08-11T23:34:19Z
[ "python", "pandas", "memory-management", "dataframe", "gzip" ]
With a gzip dataframe, how can I read/decompress this line by line?
38,907,550
<p>I have an extremely large dataframe saved as a <code>gzip</code> file. The data also needs a good deal of manipulation before being saved. </p> <p>One could try to convert this entire gzip dataframe into text format, save this to a variable, parse/clean the data, and then save as a <code>.csv</code> file via <code>pandas.read_csv()</code>. However, this is extremely memory intensive. </p> <p>I would like to read/decompress this file line by line (as this would be the most memory-efficient solution, I think), parse this (e.g. with regex <code>re</code> or perhaps a <code>pandas</code> solution) and then save each line into a pandas dataframe. </p> <p>Python has a <code>gzip</code> library for this:</p> <pre><code>with gzip.open('filename.gzip', 'rb') as input_file: reader = reader(input_file, delimiter="\t") data = [row for row in reader] df = pd.DataFrame(data) </code></pre> <p>However, this seems to drop all information into the 'reader' variable, and then parses. How can one do this in a more (memory) efficient manner? </p> <p>Should I be using a different library instead of <code>gzip</code>?</p>
0
2016-08-11T23:21:25Z
39,316,254
<p>It's not quite clear what do you want to do with your huge GZIP file. IIUC you can't read the whole data into memory, because your GZIP file is huge. So the only option you have is to process your data in chunks. </p> <p>Assuming that you want to read your data from the GZIP file, process it and write it to compressed HDF5 file:</p> <pre><code>hdf_key = 'my_hdf_ID' cols_to_index = ['colA','colZ'] # list of indexed columns, use `cols_to_index=True` if you want to index ALL columns store = pd.HDFStore('/path/to/filename.h5') chunksize = 10**5 for chunk in pd.read_csv('filename.gz', sep='\s*', chunksize=chunksize): # process data in the `chunk` DF # don't index data columns in each iteration - we'll do it later store.append(hdf_key, chunk, data_columns=cols_to_index, index=False, complib='blosc', complevel=4) # index data columns in HDFStore store.create_table_index(hdf_key, columns=cols_to_index, optlevel=9, kind='full') store.close() </code></pre>
1
2016-09-04T11:09:53Z
[ "python", "pandas", "memory-management", "dataframe", "gzip" ]
Quick remote logging system?
38,907,637
<p>I want to be about to quickly insert some logging into some testing using either (Linux) command line or Python. I don't want to do anything system wide (e.g. re-configuring syslogd).</p> <p>I've done something like this before by doing:</p> <p>wget URL/logme?im=module_name&amp;msg=hello_world</p> <p>And then just parsing the server log file. It's a bit hackish and you have to URL encode all your data. Surely someone has a better way by now.</p> <p>Is there a better way to quickly get some remote logging?</p>
0
2016-08-11T23:30:47Z
38,929,289
<p>You can use a remote syslog server: rsyslog or the python package loggerglue implements the syslog protocol as decribed in rfc5424 and rfc5425. . When you use a port above 1024 you can run it as a non-root user. </p> <p>Within the python logging module you have a SyslogHandler which also supports the syslog remote logging.</p> <pre><code>import logging import logging.handlers my_logger = logging.getLogger('MyLogger') my_logger.setLevel(logging.DEBUG) handler = logging.handlers.SysLogHandler(address = ('127.0.0.1',514)) my_logger.addHandler(handler) my_logger.debug('this is debug') my_logger.critical('this is critical') </code></pre>
1
2016-08-13T04:45:12Z
[ "python", "linux", "logging", "command-line" ]
Python loop through folders and rename files
38,907,645
<p>I am trying to go through a bunch of folders and go into each one and rename specific files to different names. I got stuck on just the loop through folders part.</p> <p>My file system looks as follows:</p> <pre><code>Root Directory Folder File1 File2 File3 Folder File1 File2 File3 </code></pre> <p>The code I have is:</p> <pre><code>os.chdir(rootDir) for folder in os.listdir(): print(folder) os.chdir(rootDir + 'folder') for f in os.listdir(): print(f) os.chdir(rootDir) </code></pre> <p>So in my mind it will go through the folders then enter the folder and list the files inside then go back to the root directory </p>
0
2016-08-11T23:31:49Z
38,907,740
<p>You need <code>os.walk</code>. It returns a 3-tuple (dirpath, dirnames, filenames) that you can iterate.</p>
1
2016-08-11T23:43:45Z
[ "python", "operating-system" ]
Python loop through folders and rename files
38,907,645
<p>I am trying to go through a bunch of folders and go into each one and rename specific files to different names. I got stuck on just the loop through folders part.</p> <p>My file system looks as follows:</p> <pre><code>Root Directory Folder File1 File2 File3 Folder File1 File2 File3 </code></pre> <p>The code I have is:</p> <pre><code>os.chdir(rootDir) for folder in os.listdir(): print(folder) os.chdir(rootDir + 'folder') for f in os.listdir(): print(f) os.chdir(rootDir) </code></pre> <p>So in my mind it will go through the folders then enter the folder and list the files inside then go back to the root directory </p>
0
2016-08-11T23:31:49Z
38,907,763
<p>Have a look at <code>os.walk</code></p> <pre><code>import os for dir, subdirs, files in os.walk("."): for f in files: f_new = f + 'bak' os.rename(os.path.join(root, f), os.path.join(root, f_new)) </code></pre>
1
2016-08-11T23:46:43Z
[ "python", "operating-system" ]
Python loop through folders and rename files
38,907,645
<p>I am trying to go through a bunch of folders and go into each one and rename specific files to different names. I got stuck on just the loop through folders part.</p> <p>My file system looks as follows:</p> <pre><code>Root Directory Folder File1 File2 File3 Folder File1 File2 File3 </code></pre> <p>The code I have is:</p> <pre><code>os.chdir(rootDir) for folder in os.listdir(): print(folder) os.chdir(rootDir + 'folder') for f in os.listdir(): print(f) os.chdir(rootDir) </code></pre> <p>So in my mind it will go through the folders then enter the folder and list the files inside then go back to the root directory </p>
0
2016-08-11T23:31:49Z
38,907,787
<pre><code>def change_files(root_dir,target_files,rename_fn): for fname in os.listdir(root_path): path = os.path.join(root_path,fname) if fname in target_files: new_name = rename_fn(fname) os.move(path,os.path.join(root_path,new_name) def rename_file(old_name): return old_name.replace("txt","log") change_files("/home/target/dir",["File1.txt","File2.txt"],rename_file) </code></pre>
0
2016-08-11T23:49:18Z
[ "python", "operating-system" ]
Pygame through SSH does not register keystrokes (Raspberry Pi 3)
38,907,681
<p>So I got raspi 3 and simple 8x8 LED matrix. After some playing with it I decided to make a simple snake game (displaying on that matrix) with pygame's events, I have no prior experience with pygame. There is no screen/display connected besides the led matrix.</p> <p>So the problem at first was "pygame.error: video system not initialized", though I think i got it fixed by setting an env variable: <code>os.putenv('DISPLAY', ':0.0')</code> Now that I got it working I run it...and nothing happens, like no keystrokes are registered. <a href="http://i.stack.imgur.com/ZwZEb.png" rel="nofollow">Just this "junk", I don't know how to call it</a> The dot on LED matrix is not moving. If i alter the snake's x or y position somewhere in the loop it moves as intended.</p> <p>My code: </p> <pre><code>#!/usr/bin/python2 import pygame import max7219.led as led from max7219.font import proportional, SINCLAIR_FONT, TINY_FONT, CP437_FONT import numpy as nqp import os SIZE = (8, 8) class Board: def __init__(self, size, snake): "Board object for snake game" self.matrix = np.zeros(size, dtype=np.int8) self.device = led.matrix() self.snake = snake def draw(self): #add snake self.matrix = np.zeros(SIZE, dtype=np.int8) self.matrix[self.snake.x][self.snake.y] = 1 for x in range(8): for y in range(8): self.device.pixel(x, y, self.matrix[x][y], redraw=False) self.device.flush() def light(self, x, y): "light specified pixel" self.matrix[x][y] = 1 def dim(self, x, y): "off specified pixel" self.matrix[x][y] = 0 class Snake: def __init__(self): "Object representing an ingame snake" self.length = 1 self.x = 3 self.y = 3 if __name__=="__main__": os.putenv('DISPLAY', ':0.0') pygame.init() snake = Snake() board = Board(SIZE, snake) done = False while not done: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: snake.y -= 1 elif event.key == pygame.K_DOWN: snake.y += 1 elif event.key == pygame.K_LEFT: snake.x -= 1 elif event.key == pygame.K_RIGHT: snake.x += 1 board.draw() </code></pre> <p>I'm using pygame because I don't know anything else (Well I can't use pygame either but I just don't know of any alternatives). If it can be done simpler I will be happy to do it. Thank You in advance!</p>
1
2016-08-11T23:37:02Z
38,908,145
<p>You should be able to use curses. Here's a simple example:</p> <pre><code>import curses def main(screen): key = '' while key != 'q': key = screen.getkey() screen.addstr(0, 0, 'key: {:&lt;10}'.format(key)) if __name__ == '__main__': curses.wrapper(main) </code></pre> <p>You'll see that your key presses are registered - they're just strings.</p> <p>However, this runs in blocking mode. Assuming that your code needs to do other things, you can turn <code>nodelay</code> on:</p> <pre><code>def main(screen): screen.nodelay(True) key = '' while key != 'q': try: key = screen.getkey() except curses.error: pass # no keypress was ready else: screen.addstr(0, 0, 'key: {:&lt;10}'.format(key)) </code></pre> <p>In your scenario you probably would put this inside your game loop that's drawing out to your 8x8 display, so it would look something like this:</p> <pre><code> game = SnakeGame() while game.not_done: try: key = screen.getkey() except curses.error: key = None if key == 'KEY_UP': game.turn_up() elif key == 'KEY_DOWN': game.turn_down() elif key == 'KEY_LEFT': game.turn_left() elif key == 'KEY_RIGHT': game.turn_right() game.tick() </code></pre> <p>One thing to note - this approach <em>will</em> take 100% of your CPU, so if you don't have some other way to limit what your app is doing it can cause you some problems. You could extend this approach using threading/multiprocessing, if you find that to be something that you need.</p>
0
2016-08-12T00:39:41Z
[ "python", "ssh", "raspberry-pi", "pygame", "led" ]
Image filtering in Python (image normalization)
38,907,731
<p>I want to write code that does image filtering. I use simple 3x3 kernel and then use <code>scipy.ndimage.filters.convolve()</code> function. After filtering, range of the values is -1.27 to 1.12. How to normalize data after filtering? Do I need to crop values (values less then zero set to zero, and greater than 1 set to 1), or use linear normalization? Is it OK if values after filtering are greater than range [0,1]?</p>
0
2016-08-11T23:42:34Z
38,915,462
<pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x = np.random.randn(10) &gt;&gt;&gt; x array([-0.15827641, -0.90237627, 0.74738448, 0.80802178, 0.48720684, 0.56213483, -0.34239788, 1.75621007, 0.63168393, 0.99192999]) </code></pre> <p>You could clip out values outside your range although you would lose that information:</p> <pre><code>&gt;&gt;&gt; np.clip(x,0,1) array([ 0. , 0. , 0.74738448, 0.80802178, 0.48720684, 0.56213483, 0. , 1. , 0.63168393, 0.99192999]) </code></pre> <p>To preserve the scaling, you can linearly renormalise into the range 0 to 1:</p> <pre><code>&gt;&gt;&gt; (x - np.min(x))/(np.max(x) - np.min(x)) array([ 0.27988553, 0. , 0.6205406 , 0.64334869, 0.52267744, 0.55086084, 0.21063013, 1. , 0.57702102, 0.71252388]) </code></pre> <blockquote> <p>Is it OK if values after filtering are greater than range [0,1]?</p> </blockquote> <p>This is really dependant on your use case for the filtered image.</p>
1
2016-08-12T10:14:38Z
[ "python", "image", "numpy", "filtering" ]
Efficient way to find index of interval
38,907,775
<p>I'm writing a spline class in Python. The method to calculate the the spline interpolated value requires the index of the closest x data points. Currently a simplified version looks like this:</p> <pre><code>def evaluate(x): for ii in range(N): # N = len(x_data) if x_data[ii] &lt;= x &lt;= x_data[ii+1]: return calc(x,ii) </code></pre> <p>So it iterates through the list of <code>x_data</code> points until it finds the lower index <code>ii</code> of interval in which <code>x</code> lies and uses that in the function <code>calc</code>, which performs the spline interpolation. While functional, it seems like this would be inefficient for large <code>x_data</code> arrays if <code>x</code> is close to the end of the data set. Is there a more efficient or elegant way to perform the same functionality, which does not require every interval to be checked iteratively?</p> <p>Note: <code>x_data</code> may be assumed to be sorted so <code>x_data[ii] &lt; x_data[ii+1]</code>, but is not necessarily equally spaced. </p>
2
2016-08-11T23:47:44Z
38,907,810
<p>this is exactly what bisect is for <a href="https://docs.python.org/2/library/bisect.html" rel="nofollow">https://docs.python.org/2/library/bisect.html</a></p> <pre><code>from bisect import bisect index = bisect(x_data,x) #I dont think you actually need the value of the 2 closest but if you do here it is point_less = x_data[index-1] # note this will break if its index 0 so you probably want a special case for that point_more = x_data[index] closest_value = min([point_less,point_more],key=lambda y:abs(x-y)) </code></pre> <p>alternatively you should use binary search(in fact im pretty sure thats what bisect uses under the hood) .... it should be worst case <code>O(log n)</code> (assuming your input array is already sorted) </p>
4
2016-08-11T23:52:08Z
[ "python" ]
Python BeautifulSoup scrape nth-type of elements
38,907,788
<p>recently I started to scrape some multiple pages but structure of page is really difficult to scrape. It has a lot of "nth type of" elements which haven't classes for each self. But their parents share same class. I am working with BeautifulSoup and it was great until I saw this awful code...</p> <pre><code>&lt;div class="detail-50"&gt; &lt;div class="detail-panel-wrap"&gt; &lt;h3&gt;Contact details&lt;/h3&gt; Website: &lt;a href="http://www.somewebsitefrompage.com"&gt;http://www.somewebsitefrompage.com&lt;/a&gt;&lt;br /&gt;Email: &lt;a href="mailto:somemailfrompage.com"&gt;somemailfrompage.com&lt;/a&gt;&lt;br /&gt;Tel: 11111111 111 &lt;/div&gt; &lt;/div&gt; </code></pre> <p>For now it seems ok, but I want to scrape Website, Email and Tel. separately. I tried with many methods such as</p> <pre><code>website = soup.select('div.detail-panel-wrap')[1].text` </code></pre> <p>But isn't working.. Now here comes huge problem when other elements have same class as contact details:</p> <pre><code>&lt;div class="detail-50"&gt; &lt;div class="detail-panel-wrap"&gt; &lt;h3&gt;Public address&lt;/h3&gt; Mr Martin Austin, Some street, Some city, some ZIP &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This one is for Address, also I need that scraped too. There are many other 'div' names as these two. Does anybody have resolving solution? If someone didn't understood, I can explain it better, sorry for bad explanation.. </p> <p><strong>UPDATE</strong><br> With some selector software I have found out how it should be, but it's difficult in python to write it.. Here is how to find Telephone from page:</p> <pre><code>div#ContentPlaceHolderDefault_cp_content_ctl00_CharityDetails_4_TabContainer1_tpOverview_plContact.detail-panel div.detail-50:nth-of-type(1) div.detail-panel-wrap </code></pre> <p>This one is for Address </p> <pre><code>div#ContentPlaceHolderDefault_cp_content_ctl00_CharityDetails_4_TabContainer1_tpOverview_plContact.detail-panel div.detail-50:nth-of-type(2) div.detail-panel-wrap </code></pre> <p>This one for Website</p> <pre><code>div.detail-50 a:nth-of-type(1) </code></pre> <p>And this one for contact email</p> <pre><code>div.detail-panel-wrap a:nth-of-type(2) </code></pre> <p>Note: <code>ContentPlaceHolderDefault_cp_content_ctl00_CharityDetails_4_TabContainer1_tpOverview_plContact</code></p> <p>is parent div class at the top of all of these.</p> <p>Anybody have an idea how to write those in BS4 Python?</p>
1
2016-08-11T23:49:24Z
38,908,075
<p>If there are multiple <em>divs</em> with class <em>detail-panel-wrap</em>, you can use the <em>h3</em> text to get the ones you want:</p> <pre><code>contact = soup.find("h3", text="Contact details").parent address = soup.find("h3", text="Public address").parent </code></pre> <p>If we run it on a sample, you can see we get both divs:</p> <pre><code>In [22]: html = """ ....: &lt;div class="detail-50"&gt; ....: &lt;div class="detail-panel-wrap"&gt; ....: &lt;h3&gt;Contact details&lt;/h3&gt; ....: Website: &lt;a href="http://www.somewebsitefrompage.com"&gt;http://www.somewebsitefrompage.com&lt;/a&gt;&lt;br /&gt;Email: &lt;a href="mailto:somemailfrompage.com"&gt;somemailfrompage.com&lt;/a&gt;&lt;br /&gt;Tel: 11111111 111 ....: &lt;/div&gt; ....: &lt;/div&gt; ....: &lt;div class="detail-50"&gt; ....: &lt;div class="detail-panel-wrap"&gt; ....: &lt;h3&gt;Public address&lt;/h3&gt; ....: Mr Martin Austin, Some street, Some city, some ZIP ....: &lt;/div&gt; ....: &lt;/div&gt; ....: &lt;div class="detail-panel-wrap"&gt; ....: &lt; h3&gt;foo/h3&gt; ....: &lt;/div&gt; ....: &lt;div class="detail-panel-wrap"&gt; ....: &lt;h3&gt;bar/h3&gt; ....: &lt;/div&gt; ....: &lt;/div&gt; ....: """ In [23]: from bs4 import BeautifulSoup In [24]: soup = BeautifulSoup(html,"lxml") In [25]: contact = soup.find("h3", text="Contact details").parent In [26]: address = soup.find("h3", text="Public address").parent In [27]: print(contact) &lt;div class="detail-panel-wrap"&gt; &lt;h3&gt;Contact details&lt;/h3&gt; Website: &lt;a href="http://www.somewebsitefrompage.com"&gt;http://www.somewebsitefrompage.com&lt;/a&gt;&lt;br/&gt;Email: &lt;a href="mailto:somemailfrompage.com"&gt;somemailfrompage.com&lt;/a&gt;&lt;br/&gt;Tel: 11111111 111 &lt;/div&gt; In [28]: print(address) &lt;div class="detail-panel-wrap"&gt; &lt;h3&gt;Public address&lt;/h3&gt; Mr Martin Austin, Some street, Some city, some ZIP &lt;/div&gt; </code></pre> <p>There may be other ways but without seeing the full html structure it is not possible to know.</p> <p>For your edit, you simply have to use the selectors with <em>select_one</em>:</p> <pre><code> telephone = soup.select_one("#ContentPlaceHolderDefault_cp_content_ctl00_CharityDetails_4_TabContainer1_tpOverview_plContact.detail-panel div.detail-50:nth-of-type(1) div.detail-panel-wrap") address = soup.select_one("#ContentPlaceHolderDefault_cp_content_ctl00_CharityDetails_4_TabContainer1_tpOverview_plContact.detail-panel div.detail-50:nth-of-type(2) div.detail-panel-wrap") website = soup.select_one("div.detail-50 a:nth-of-type(1)") email = soup.select_one("div.detail-panel-wrap a:nth-of-type(2)") </code></pre> <p>But there is no guarantee just because the selectors work in chrome tools etc.. that they will work on the source you get back.</p>
0
2016-08-12T00:28:19Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Passing arguments in the __init__ method
38,907,808
<p>I have the following code:</p> <pre><code>class database: def __init__(self): self.db_port = 3306 self.db_host = "mysql.rs.org' </code></pre> <p>I thought we had to initialize the class by passing arguments to the <code>__init__</code> method, like so:</p> <pre><code>class database: def __init__(self, db_port, db_host): self.db_port = db_port self.db_host = db_host </code></pre> <p>Which one should I use?</p>
-1
2016-08-11T23:51:57Z
38,907,868
<p>Doing it the first way will make all your <em>database</em> objects to be the same. Doing it the other way will let you to set the attributes to anything you want as you create them. Both are fine to do but the second one is more dynamic. It all depends if your program will ever need a <em>database</em> object with different <em>db_port</em> and <em>db_host</em> than 3306 and "mysql.rs.org'.</p>
1
2016-08-11T23:59:44Z
[ "python", "class" ]
Using two theano functions together
38,907,891
<p>If I had something like:</p> <pre><code>import theano.tensor as T from theano import function a = T.dscalar('a') b = T.dscalar('b') first_func = a * b second_func = a - b first = function([a, b], first_func) second = function([a, b], second_func) </code></pre> <p>and I wanted to create a third function that was <code>first_func(1,2) + second_func(3,4)</code>, is there a way to do this and create a function that is passed these two smaller functions as input?</p> <p>I want to do something like:</p> <pre><code>third_func = first(a, b) + second(a,b) third = function([a, b], third_func) </code></pre> <p>but this does not work. What is the correct way to break my functions into smaller functions?</p>
0
2016-08-12T00:02:56Z
38,927,889
<p>I guess the only way to decompose function is in-terms of tensor variables, rather than function calls. This should work:</p> <pre><code>import theano.tensor as T from theano import function a = T.dscalar('a') b = T.dscalar('b') first_func = a * b second_func = a - b first = function([a, b], first_func) second = function([a, b], second_func) third_func = first_func + second_func third = function([a, b], third_func) </code></pre> <p><code>third_func = first(a, b) + second(a,b)</code> does not work because function call need real values whereas <code>a</code> and <code>b</code> are tensor/symbolic variables. Basically one should define mathematical operations with tensors and then use function to evaluate values of these tensors.</p>
1
2016-08-12T23:56:12Z
[ "python", "theano" ]
Is there a way to use python to do specific things in an application?
38,907,987
<p>Like for example first open Safari</p> <pre><code>os.system("open /Applications/Safari.app") </code></pre> <p>Then go to a user inputs something else and it will be inputed into the search bar and searched.</p> <p>Also for this example</p> <pre><code>os.system("open /Applications/Messages.app") </code></pre> <p>Then send a message to someone.</p> <p>And this example if possible:</p> <pre><code>os.system("open /Applications/Dictionary.app") </code></pre> <p>And search for a word?</p> <p>Thank you so much :D</p>
2
2016-08-12T00:14:52Z
38,908,067
<p>That's not how it works. In your example, you're just using python to execute a shell command. Once the program opens, it's not going to just give you information about what is happening unless it is specifically designed to do so or supports some sort of api.</p>
1
2016-08-12T00:26:54Z
[ "python", "operating-system" ]
Is there a way to use python to do specific things in an application?
38,907,987
<p>Like for example first open Safari</p> <pre><code>os.system("open /Applications/Safari.app") </code></pre> <p>Then go to a user inputs something else and it will be inputed into the search bar and searched.</p> <p>Also for this example</p> <pre><code>os.system("open /Applications/Messages.app") </code></pre> <p>Then send a message to someone.</p> <p>And this example if possible:</p> <pre><code>os.system("open /Applications/Dictionary.app") </code></pre> <p>And search for a word?</p> <p>Thank you so much :D</p>
2
2016-08-12T00:14:52Z
38,908,258
<p>If you want to automate web task - look at <a href="http://selenium-python.readthedocs.io/getting-started.html" rel="nofollow">selenium</a></p> <blockquote> <p>Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. Through Selenium Python API you can access all functionalities of Selenium WebDriver in an intuitive way.</p> </blockquote> <p>Selenium Python bindings provide a convenient API to access Selenium WebDrivers like Firefox, Ie, Chrome, Remote etc.</p> <p>Here is a link to what is <a href="http://www.seleniumhq.org/docs/01_introducing_selenium.jsp" rel="nofollow">selenium and webdrivers</a></p> <p>see you can do this:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title elem = driver.find_element_by_name("q") elem.clear() elem.send_keys("pycon") elem.send_keys(Keys.RETURN) assert "No results found." not in driver.page_source driver.close() </code></pre> <p>see <a href="http://selenium-python.readthedocs.io/getting-started.html#example-explained" rel="nofollow">here for a breakdown of the code</a></p> <p>For your message example you can use <a href="https://pypi.python.org/pypi/Skype4Py/" rel="nofollow">Skype4Py API</a></p>
1
2016-08-12T00:54:57Z
[ "python", "operating-system" ]
Is there a way to use python to do specific things in an application?
38,907,987
<p>Like for example first open Safari</p> <pre><code>os.system("open /Applications/Safari.app") </code></pre> <p>Then go to a user inputs something else and it will be inputed into the search bar and searched.</p> <p>Also for this example</p> <pre><code>os.system("open /Applications/Messages.app") </code></pre> <p>Then send a message to someone.</p> <p>And this example if possible:</p> <pre><code>os.system("open /Applications/Dictionary.app") </code></pre> <p>And search for a word?</p> <p>Thank you so much :D</p>
2
2016-08-12T00:14:52Z
38,908,306
<p>Those are all OS X apps, so I'm going to take a leap and assume you're using a Mac. The Automator app might be more appropriate for this task as it basically helps you easily write AppleScript applications.</p>
0
2016-08-12T01:02:29Z
[ "python", "operating-system" ]
Is there a way to use python to do specific things in an application?
38,907,987
<p>Like for example first open Safari</p> <pre><code>os.system("open /Applications/Safari.app") </code></pre> <p>Then go to a user inputs something else and it will be inputed into the search bar and searched.</p> <p>Also for this example</p> <pre><code>os.system("open /Applications/Messages.app") </code></pre> <p>Then send a message to someone.</p> <p>And this example if possible:</p> <pre><code>os.system("open /Applications/Dictionary.app") </code></pre> <p>And search for a word?</p> <p>Thank you so much :D</p>
2
2016-08-12T00:14:52Z
38,908,865
<p>For Web Automation: </p> <ol> <li><p><a href="http://selenium-python.readthedocs.io/" rel="nofollow">Selenium Python Bindings</a><br>I have a detailed example <a href="https://github.com/kingmak/SeleniumPythonBindingsForChrome/blob/master/example.py" rel="nofollow">here</a> along with some helpful links.</p></li> <li><p><a href="https://splinter.readthedocs.io/en/latest/" rel="nofollow">Splinter</a> (simpler than selenium)</p></li> </ol>
0
2016-08-12T02:18:52Z
[ "python", "operating-system" ]
What is this called: creating numpy matrix from several vectors
38,907,993
<p>I have 4 individual numpy vectors with the shape (10, ), and I want to join them together to form a matrix (10, 4).</p> <p>What is this transformation called?</p>
0
2016-08-12T00:15:27Z
38,908,009
<p>It's called <code>stack</code>.</p> <pre><code>&gt; import numpy as np &gt; a = np.arange(10) &gt; b = np.stack((a, a, a, a), axis=1) &gt; np.shape(b) (10, 4) &gt; b array([[0, 0, 0, 0], [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5], [6, 6, 6, 6], [7, 7, 7, 7], [8, 8, 8, 8], [9, 9, 9, 9]]) </code></pre> <p>You could also (in this case) use e.g. <code>np.array([a, a, a, a]).T</code>.</p>
1
2016-08-12T00:18:45Z
[ "python", "numpy", "matrix", "vector" ]
What is this called: creating numpy matrix from several vectors
38,907,993
<p>I have 4 individual numpy vectors with the shape (10, ), and I want to join them together to form a matrix (10, 4).</p> <p>What is this transformation called?</p>
0
2016-08-12T00:15:27Z
38,908,147
<p>You could also create a new array from the collection and transpose the result.</p> <pre><code>np.random.seed(0) a1 = np.random.randint(1, 10, 10) a2 = np.random.randint(1, 10, 10) a3 = np.random.randint(1, 10, 10) a4 = np.random.randint(1, 10, 10) &gt;&gt;&gt; np.array([a1, a2, a3, a4]).T array([[6, 7, 9, 2], [1, 9, 5, 4], [4, 9, 4, 4], [4, 2, 1, 4], [8, 7, 4, 8], [4, 8, 6, 1], [6, 8, 1, 2], [3, 9, 3, 1], [5, 2, 4, 5], [8, 6, 9, 8]]) </code></pre>
0
2016-08-12T00:40:07Z
[ "python", "numpy", "matrix", "vector" ]
tkinter python function takes 1 argument, given 2
38,908,004
<p>I'm getting this error when I try to run my code:</p> <pre><code>File "./countdown.py", line 36, in &lt;module&gt; app = Application(root) File "./countdown.py", line 16, in __init__ self.create_buttons(self) TypeError: create_buttons() takes exactly 1 argument (2 given) </code></pre> <p>Here's my code:</p> <pre><code>import Tkinter as tk class Application(tk.Frame): """Countdown app - simple timer""" def __init__(self, master): """initialize frame""" tk.Frame.__init__(self, master) #super(Application, self).__init__(master) self.grid() self.create_buttons(self) def create_buttons(self): self.startBttn = Button(app, text = "Start") self.startBttn.grid() self.stopBttn = Button(app, text = "Stop") self.stopBttn.grid() self.resetBttn = Button(app, text = "Reset") self.resetBttn.grid() ### Main Code ### # create the root window using Tk - an object of tkinter class root = tk.Tk() # modify the prog. window (set size, title, etc.) root.title("Countdown") root.geometry("200x100") #instantiate Application app = Application(root) </code></pre> <p>I've been looking for an answer to this for a while but haven't been able to apply other people's solutions to my code- any ideas? If I remove the tk. before Frame in the class Application declaration I get an error that says Frame not found. If I use <strong>super(Application, self).__init__(master)</strong> instead of the line above it, I get a type error must be class not class object. </p>
0
2016-08-12T00:17:34Z
38,908,020
<p>Don't explicitly pass <code>self</code> when calling a bound method. Call it like this:</p> <pre><code>self.create_buttons() </code></pre> <p>By calling the method with <code>self.create_buttons(self)</code> the function receives <em>two</em> arguments: the implicit <code>self</code> that is passed when calling a bound method (Python does this automatically), and the explicit <code>self</code> that you pass in the method call.</p> <hr> <p>There are also some other problems with <code>create_buttons()</code> which you can fix with this code:</p> <pre><code> def create_buttons(self): self.startBttn = tk.Button(self, text = "Start") self.startBttn.grid() self.stopBttn = tk.Button(self, text = "Stop") self.stopBttn.grid() self.resetBttn = tk.Button(self, text = "Reset") self.resetBttn.grid() </code></pre> <p>The changes are that you need to use <code>tk.Button</code> to reference the <code>Button</code> class, and to pass <code>self</code> to <code>tk.Button</code> which is a reference to the parent frame. Here <code>self</code> is the <code>Application</code> instance which is a subclass of <code>tk.Frame</code> - hence <code>self</code> is a frame.</p> <p>Finally you need to add a call to <code>mainloop()</code>:</p> <pre><code>#instantiate Application app = Application(root) root.mainloop() </code></pre> <hr> <p>Regarding the problem with <code>super</code>, the tkinter classes are of the "old-style" type and do not support <code>super()</code>. Therefore you must call the base class with <code>tk.Frame.__init__(self, master)</code>.</p> <p>There is a workaround by using multiple inheritance and including <code>object</code> as a base class. If you declare <code>Application</code> as :</p> <pre><code>class Application(tk.Frame, object): def __init__(self, master): """initialize frame""" super(Application, self).__init__(master) </code></pre> <p>then you can use <code>super()</code>, but it's hardly worth the effort.</p>
3
2016-08-12T00:20:29Z
[ "python", "tkinter" ]
next-tab and previous-tab buttons in Django-crispy-forms
38,908,091
<p>I have tried Django-crispy-forms and really love it, I have created a form, which is splitting into 4 tabs (due to so many fields). </p> <p>Now, I would like to add next-tab and previous-tab buttons to navigate between tab, can you show me how to do that with Django-crispy-forms?</p> <p>Thank you! </p>
0
2016-08-12T00:30:56Z
39,048,202
<p>I found the solution , I don't think it's a good one so please take a look and feel free to suggest another way. Thank you !</p> <pre><code>class ProfileForm(forms.ModelForm): helper = FormHelper() helper.form_tag = False helper.layout = Layout( TabHolder( Tab( '1. Personal Information', 'first_name', 'last_name', 'address', 'city', 'zip_code', 'state', 'email', 'phone_number', 'how_did_you_hear_about_us', Button('Next', 'Next', css_class="btnNext") ), Tab( '2. Education Background', 'the_highest_qualification', 'school_graduated', 'year_of_graduation', Button('Previous', 'Previous', css_class="btnPrevious"), Button('Next', 'Next', css_class="btnNext") ), Tab( '3. Work Experience', 'job_title', 'company', 'location', 'from_time', 'to_time', 'resume', Button('Previous', 'Previous', css_class="btnPrevious"), Button('Next', 'Next', css_class="btnNext") ), Tab( '4. Application Question', 'are_you_18_years_of_age_or_older', 'are_you_eligible_to_work_in_US', Button('Previous', 'Previous', css_class="btnPrevious"), Button('Next', 'Next', css_class="btnNext") ), Tab( '5. Account', 'password1', 'password2', Button('Previous', 'Previous', css_class="btnPrevious"), StrictButton('Register', css_class='btn-primary', type='submit'), ) ) ) </code></pre> <p>In the HTML template, put this: </p> <pre><code> &lt;script&gt; $('.btnNext').click(function(){ $('.nav-tabs &gt; .active').next('li').find('a').trigger('click'); }); $('.btnPrevious').click(function(){ $('.nav-tabs &gt; .active').prev('li').find('a').trigger('click'); }); &lt;/script&gt; </code></pre>
1
2016-08-19T21:56:26Z
[ "python", "django", "django-crispy-forms" ]
python function, json.loads() : No JSON object could be decoded
38,908,114
<p>The code is very simple:</p> <pre><code>import requests import json r = requests.get('https://www.baidu.com/') r.encoding = 'utf-8' json.loads(r.text,'utf-8') </code></pre> <p>I always recieve this error information:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#57&gt;", line 1, in &lt;module&gt; json.loads(r.text,'utf-8') File "C:\Python27\lib\json\__init__.py", line 352, in loads return cls(encoding=encoding, **kw).decode(s) File "C:\Python27\lib\json\decoder.py", line 364, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded </code></pre> <p>Can anyone help me solving this problem? Thanks!</p>
0
2016-08-12T00:33:48Z
38,921,551
<p>This code will help you to figure out what's going on ;)</p> <pre><code>import requests import json r = requests.get('https://www.baidu.com/') r.encoding = 'utf-8' try: foo = json.loads(r.text, 'utf-8') print "Yay, I got a json from baidu!" except Exception, e: print "Why didn't i get a json from baidu? Maybe it wasn't a json..." print "What is it then? It seems is a {0} whose length is {1}".format( r.text.__class__, len(r.text) ) </code></pre>
0
2016-08-12T15:29:44Z
[ "python", "json" ]
Is it possible to re-enter an existing name scope in TensorFlow?
38,908,128
<p>Entering a name scope of the same name twice:</p> <pre><code>c = tf.constant(1) with tf.name_scope("test"): a = tf.add(c, c) with tf.name_scope("test"): b = tf.add(a, a) </code></pre> <p>results in two name scopes being created: <code>test</code> and <code>test_1</code>.</p> <p>Is it possible to re-enter a scope in a separate context manager instead of creating a new one?</p>
1
2016-08-12T00:36:08Z
38,908,142
<p>It turns out to be really easy actually. Looking into <code>framework/ops.py</code> of TensorFlow reveals that adding "/" to the name of the scope does not make the scope name unique, effectively re-entering an existing scope. For instance:</p> <pre><code>c = tf.constant(1) with tf.name_scope("test"): a = tf.add(c, c) with tf.name_scope("test/"): b = tf.add(a, a) </code></pre>
0
2016-08-12T00:39:12Z
[ "python", "tensorflow" ]
Is it possible to re-enter an existing name scope in TensorFlow?
38,908,128
<p>Entering a name scope of the same name twice:</p> <pre><code>c = tf.constant(1) with tf.name_scope("test"): a = tf.add(c, c) with tf.name_scope("test"): b = tf.add(a, a) </code></pre> <p>results in two name scopes being created: <code>test</code> and <code>test_1</code>.</p> <p>Is it possible to re-enter a scope in a separate context manager instead of creating a new one?</p>
1
2016-08-12T00:36:08Z
38,908,388
<p>While the solution you suggested in <a href="http://stackoverflow.com/a/38908142/3574081">your answer</a> will work today, it relies on an internal implementation detail of <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#name_scope" rel="nofollow"><code>tf.name_scope()</code></a>, and so might not always work. Instead, the recommended way to re-enter a scope is to <em>capture</em> it in the first <code>with</code> statement, and use that value in the second one, as follows:</p> <pre><code>c = tf.constant(1) with tf.name_scope("test") as scope: a = tf.add(c, c) with tf.name_scope(scope): b = tf.add(a, a) </code></pre> <p>You can also pass the captured <code>scope</code> as the name of an operator, which is how we typically represent the output of a function that is build from a composition of other operators:</p> <pre><code>c = tf.constant(1) with tf.name_scope("test") as scope: a = tf.add(c, c) return tf.add(a, a, name=scope) # return value gets the scope prefix as its name. </code></pre>
1
2016-08-12T01:12:22Z
[ "python", "tensorflow" ]
Can't get tkinter's StringVar's trace method to work
38,908,143
<p>Whenever I try to run my code, which looks a bit like this:</p> <pre><code>from tkinter import OptionMenu, StringVar, Tk class Foo(OptionMenu): def __init__(self, master, options): self.bar = StringVar() self.bar.set(options[0]) self.bar.trace("w", lambda: self.mouseCallback("foobar")) super().__init__(master, self.bar, *options) def mouseCallback(self, baz): print(baz) def mainCycle(): while True: root.update() if __name__ == "__main__": opts = ["A", "LONG", "LIST", "OF", "OPTIONS"] root = Tk() foobarbaz = Foo(root, opts) foobarbaz.pack() mainCycle() </code></pre> <p>I get the following error:</p> <pre><code>Exception in Tkinter callback Traceback (most recent call last): File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__ return self.func(*args) File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 3285, in __call__ self.__var.set(self.__value) File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 260, in set return self._tk.globalsetvar(self._name, value) _tkinter.TclError: can't set "PY_VAR0": </code></pre> <p>And even after a lot of "Stack Overflowing", I still can't get it to work. How can I avoid/fix this error?</p>
0
2016-08-12T00:39:22Z
38,908,402
<p>The signature of the callback function for StringVar.trace() should be something like <code>def callback(*args)</code>, therefore the lambda you use in StringVar.trace() should be changed to:</p> <pre><code>self.bar.trace("w", lambda *args: self.mouseCallback("foobar")) </code></pre>
2
2016-08-12T01:14:41Z
[ "python", "python-3.x", "tkinter" ]
Including multiple paths in Django's request.path { if } statement
38,908,256
<p>I have a header that belongs on every page except for the home page path and my blog page path, but I can't seem to get an 'or' statement to work. Any ideas are appreciated. Thank you.</p> <p><strong>This works</strong></p> <pre><code>{% if request.path != '/' %} ... {% endif %} </code></pre> <p><strong>This doesn't, but is what I need</strong></p> <pre><code>{% if request.path != '/' or request.path != '/news' %} ... {% endif %} </code></pre>
0
2016-08-12T00:54:31Z
38,908,471
<p>The condition <code>request.path != '/' or request.path != '/news'</code> will always return True (<code>request.path</code> will always differ from one or another value). You need to use <code>and</code> in your case:</p> <pre><code>{% if request.path != '/' and request.path != '/news' %} ... {% endif %} </code></pre>
3
2016-08-12T01:27:01Z
[ "python", "django", "django-templates" ]
Persistent Calculated Fields in Django
38,908,261
<p>In MS SQL Server there is a feature to create a calculated column: a table column that is calculated on the fly at retrieval time. This more-or-less maps on to using a method on a Django model to retrieve a calculated value (the common example being retrieving Full Name, based on stored Forename/Surname fields).</p> <p>For expensive operations, SQL Server provides a <code>Persisted</code> option. This populates the table column with the results of the calculation, and updates those results when the table is updated - a very useful feature when the calculation is not quick but does not change often compared to access.</p> <p>However, in Django I cannot find a way to duplicate this functionality. Am I missing something obvious? My best guess would be some sort of custom Field that takes a function as a parameter, but I couldn't see a pre-existing one of those. Is there a better way?</p>
3
2016-08-12T00:55:37Z
38,909,642
<p>One approach is just to use a regular model field that is calculated whenever an object is saved, e.g.,:</p> <pre><code>class MyModel(models.Model): first_name = models.CharField(max_length=255) surname = models.CharField(max_length=255) # This is your 'persisted' field full_name = models.CharField(max_length=255, blank=True) def save(self, *args, **kwargs): # set the full name whenever the object is saved self.full_name = '{} {}'.format(self.first_name, self.surname) super(MyModel, self).save(*args, **kwargs) </code></pre> <p>You could make this special field <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.readonly_fields" rel="nofollow">read-only</a> in the admin and similarly <a href="https://docs.djangoproject.com/en/stable/topics/forms/modelforms/#selecting-the-fields-to-use" rel="nofollow">exclude it</a> from any model forms.</p>
3
2016-08-12T03:55:23Z
[ "python", "django" ]
Slice column in panda database and averaging results
38,908,362
<p>If I have a pandas database such as:</p> <pre><code>timestamp label value new etc. a 1 3.5 b 2 5 a 5 ... b 6 ... a 2 ... b 4 ... </code></pre> <p>I want the new column to be the average of the last two a's and the last two b's... so for the first it would be the average of 5 and 2 to get 3.5. It will be sorted by the timestamp. I know I could use a groupby to get the average of all the a's or all the b's but I'm not sure how to get an average of just the last two. I'm kinda new to python and coding so this might not be possible idk. </p> <p>Edit: I should also mention this is not for a class or anything this is just for something I'm doing on my own and that this will be on a very large dataset. I'm just using this as an example. Also I would want each A and each B to have its own value for the last 2 average so the dimension of the new column will be the same as the others. So for the third line it would be the average of 2 and whatever the next a would be in the data set.</p>
1
2016-08-12T01:08:44Z
38,908,447
<p><em>Edited to reflect a change in the question specifying the last two, not the ones following the first, and that you wanted the same dimensionality with values repeated.</em></p> <pre><code>import pandas as pd data = {'label': ['a','b','a','b','a','b'], 'value':[1,2,5,6,2,4]} df = pd.DataFrame(data) grouped = df.groupby('label') results = {'label':[], 'tail_mean':[]} for item, grp in grouped: subset_mean = grp.tail(2).mean()[0] results['label'].append(item) results['tail_mean'].append(subset_mean) res_df = pd.DataFrame(results) df = df.merge(res_df, on='label', how='left') </code></pre> <p>Outputs:</p> <pre><code>&gt;&gt; res_df label tail_mean 0 a 3.5 1 b 5.0 &gt;&gt; df label value tail_mean 0 a 1 3.5 1 b 2 5.0 2 a 5 3.5 3 b 6 5.0 4 a 2 3.5 5 b 4 5.0 </code></pre> <p>Now you have a dataframe of your results only, if you need them, plus a column with it merged back into the main dataframe. Someone else posted a more succinct way to get to the results dataframe; probably no reason to do it the longer way I showed here unless you also need to perform more operations like this that you could do inside the same loop.</p>
0
2016-08-12T01:23:09Z
[ "python", "pandas" ]
Slice column in panda database and averaging results
38,908,362
<p>If I have a pandas database such as:</p> <pre><code>timestamp label value new etc. a 1 3.5 b 2 5 a 5 ... b 6 ... a 2 ... b 4 ... </code></pre> <p>I want the new column to be the average of the last two a's and the last two b's... so for the first it would be the average of 5 and 2 to get 3.5. It will be sorted by the timestamp. I know I could use a groupby to get the average of all the a's or all the b's but I'm not sure how to get an average of just the last two. I'm kinda new to python and coding so this might not be possible idk. </p> <p>Edit: I should also mention this is not for a class or anything this is just for something I'm doing on my own and that this will be on a very large dataset. I'm just using this as an example. Also I would want each A and each B to have its own value for the last 2 average so the dimension of the new column will be the same as the others. So for the third line it would be the average of 2 and whatever the next a would be in the data set.</p>
1
2016-08-12T01:08:44Z
38,911,385
<p>IIUC one way (among many) to do that:</p> <pre><code>In [139]: df.groupby('label').tail(2).groupby('label').mean().reset_index() Out[139]: label value 0 a 3.5 1 b 5.0 </code></pre>
0
2016-08-12T06:33:16Z
[ "python", "pandas" ]
How to make nosetests use dotted syntax?
38,908,369
<p>Is there a way to make <a href="http://nose.readthedocs.io/en/latest/" rel="nofollow">nosetests</a> print:</p> <pre><code>ERROR: product.test.lib.test_csv_tools:CSVToolsTest.test_missing_header_csv </code></pre> <p>instead of:</p> <pre><code>ERROR: test_missing_header_csv (product.test.lib.test_csv_tools.CSVToolsTest) </code></pre> <p>Then I could easily copy it and run the single test(s) that failed. Would be quite handy.</p>
1
2016-08-12T01:10:01Z
38,908,404
<p>I think you should be looking <a href="https://nose-plugins.jottit.com/" rel="nofollow">for a specific nose plugin</a> that provides this kind of output. For example, the <a href="https://pypi.python.org/pypi/nose_runnable_test_names" rel="nofollow"><code>nose_runnable_test_names</code></a> sounds close to what you are asking about.</p>
1
2016-08-12T01:15:33Z
[ "python", "nose" ]
Kafka not interacting with kaka-python code in docker
38,908,464
<p>So I started a kafka and zookeeper instance on the host. Now I want to interact with it via two dockers - producer and consumer </p> <p>The code in the PRODUCER docker is:</p> <pre><code>from kafka import KafkaProducer import time producer = KafkaProducer(bootstrap_servers=['localhost:9092']) i = 0 while 1: # "kafkaesque" is the name of our topic producer.send("stupid", str(i)) i += 1 time.sleep(1) </code></pre> <p>The code for CONSUMER docker is:</p> <pre><code>from kafka import KafkaConsumer consumer = KafkaConsumer(bootstrap_servers=['localhost:9092']) consumer.subscribe(['stupid']) for message in consumer: print (message.value) </code></pre> <p>The Dockerfile for CONSUMER is:</p> <pre><code>FROM debian:jessie RUN apt-get update &amp;&amp; apt-get -y upgrade RUN apt-get install -y python-setuptools RUN apt-get install -y python-pip RUN pip install kafka-python ADD . /Consumer WORKDIR /Consumer CMD ["python", "consumer.py"] </code></pre> <p>The Dockerfile for PRODUCER is:</p> <pre><code>FROM debian:jessie RUN apt-get update &amp;&amp; apt-get -y upgrade RUN apt-get install -y python-setuptools RUN apt-get install -y python-pip RUN pip install kafka-python ADD . /Producer WORKDIR /Producer CMD ["python","counter.py"] </code></pre> <p>Now i built both of them, and when I run it, like this:</p> <pre><code>docker run consumer docker run producer </code></pre> <p>Then for each of then I get this error:</p> <pre><code>Traceback (most recent call last): File "consumer.py", line 3, in &lt;module&gt; consumer = KafkaConsumer(bootstrap_servers=['localhost:9092']) File "/usr/local/lib/python2.7/dist-packages/kafka/consumer/group.py", line 284, in __init__ self._client = KafkaClient(metrics=self._metrics, **self.config) File "/usr/local/lib/python2.7/dist-packages/kafka/client_async.py", line 202, in __init__ self.config['api_version'] = self.check_version(timeout=check_timeout) File "/usr/local/lib/python2.7/dist-packages/kafka/client_async.py", line 791, in check_version raise Errors.NoBrokersAvailable() kafka.errors.NoBrokersAvailable: NoBrokersAvailable </code></pre> <p>**</p> <blockquote> <p>But when I run each of them on the host machine, they work perfectly.</p> </blockquote> <p>** </p> <p>Can someone point out, how to solve this. I have some idea, as in the network port of the docker is not able to interact with the network port of the host, but i have tried EXPOSE and -p each of which is not helping me.</p>
0
2016-08-12T01:25:36Z
39,553,858
<p>Try:</p> <pre><code>(bootstrap_servers=[], api_version=(0, 9))) </code></pre>
-1
2016-09-18T03:43:59Z
[ "python", "docker", "apache-kafka" ]
Matrix Multiplication outputting incorrect image
38,908,500
<p>I have an image matrix which I am scaling down and then scaling back to its original values.</p> <p>The image is first read into an array of size (150,200,3).</p> <pre><code>image_data = ndimage.imread(image_file,mode='RGB').astype(float) </code></pre> <p>Next I am scaling the pixel values down and then back to their original values. Also, I cast the float array back to an integer array.</p> <pre><code> image_data = (image_data - (255.0 / 2)) / 255.0 image_data = (image_data * 255.0) + (255.0 / 2) image_data = image_data.astype(int) </code></pre> <p>Now I save the image in the file initial.jpg.</p> <pre><code> image0 = PILImage.fromarray(image_data,mode='RGB') image0.save('Tests/Initial.jpg') </code></pre> <p>The saved Image looks like this...</p> <p><a href="http://i.stack.imgur.com/HegoJ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/HegoJ.jpg" alt="enter image description here"></a></p> <p>However, If I remove the matrix multiplication and casting (the middle three lines of code). I save an image that looks like this. This is the correct file.</p> <p><a href="http://i.stack.imgur.com/gTAOu.png" rel="nofollow"><img src="http://i.stack.imgur.com/gTAOu.png" alt="enter image description here"></a></p> <p>I have verified the matrices and the modified matrices are identical to the original so I am confused why the images would not be identical as well.</p>
0
2016-08-12T01:32:10Z
38,908,567
<p>It is found that image arrays can only be saved properly if they are of type uint8. So change</p> <p><code>image_data = image_data.astype(int)</code></p> <p>to</p> <p><code>image_data = image_data.astype(np.uint8)</code></p>
0
2016-08-12T01:41:22Z
[ "python", "arrays", "image", "numpy", "matrix" ]
Is there a prettier way to get an integer inputs?
38,908,556
<p>Normally, the way to accept an integer input from the user is given by:</p> <pre><code>x = int(input('Enter a value: ')) </code></pre> <p>But in my opinion, this casting of a string to an integer is somewhat ugly. Is there a direct and perhaps prettier way to do this? (Of course I know I could just make my own 'pretty' function; perhaps there's a way that's built into the language?).</p>
0
2016-08-12T01:39:12Z
38,908,641
<pre><code>def pretty_input(prompt): return int(input(prompt)) x = pretty_input("Enter a value: ") </code></pre>
4
2016-08-12T01:51:49Z
[ "python", "python-3.x" ]
Identify <br> tags
38,908,561
<p>I'm trying to walk down a sibling structure of <code>&lt;a&gt;</code> tags and there are <code>&lt;br&gt;</code> tags inbetween. When I try to get elem.name of a <code>br</code> tag, I get an error. Is there a way to skip these <code>br</code> tags?</p> <p>Currently, I do <code>html = html.replace('&lt;br&gt;','\n')</code> before parsing, but that causes bsoup to insert ^M characters with the newlines.</p> <pre><code> r = requests.get(url, headers=headers) # page = r.text.replace('&lt;br&gt;','\n') soup = bsoup(r.text, 'html.parser') soup = soup.find('div', id='listAlbum') albums = soup.find_all('div', class_='album') for album in albums: name = album.text.replace('"','').replace(':','').rstrip() print(name) albumtask(name) song = album.next_sibling while song.name != 'div' and song.name != 'script': if song.name != 'a' or song.get('id'): song = song.next_sibling continue t = threading.Thread(target=tsong, args=(song,)) t.start() song = song.next_sibling while song.is_empty_element: song = song.next_sibling time.sleep(0.2) </code></pre> <p>&nbsp;</p> <pre><code>&lt;div id="listAlbum"&gt; &lt;a id="1545"&gt;&lt;/a&gt;&lt;div class="album"&gt;album: &lt;b&gt;"Pablo Honey"&lt;/b&gt; (1993)&lt;span&gt;&amp;nbsp;&amp;nbsp;&lt;a href="http://www.amazon.com/gp/search?ie=UTF8&amp;amp;keywords=RADIOHEAD+Pablo+Honey&amp;amp;tag=azlyricsunive-20&amp;amp;index=music&amp;amp;linkCode=ur2&amp;amp;camp=1789&amp;amp;creative=9325" rel="external"&gt;&lt;img width="30" height="18" src="http://images.azlyrics.com/amn.png" alt="buy this CD or download MP3s at amazon.com!"&gt;&lt;/a&gt;&lt;/span&gt;&lt;/div&gt; &lt;a href="../lyrics/radiohead/you.html" target="_blank"&gt;You&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/creep.html" target="_blank"&gt;Creep&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/howdoyou.html" target="_blank"&gt;How Do You?&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/stopwhispering.html" target="_blank"&gt;Stop Whispering&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/thinkingaboutyou.html" target="_blank"&gt;Thinking About You&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/anyonecanplayguitar.html" target="_blank"&gt;Anyone Can Play Guitar&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/ripcord.html" target="_blank"&gt;Ripcord&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/vegetable.html" target="_blank"&gt;Vegetable&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/proveyourself.html" target="_blank"&gt;Prove Yourself&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/icant.html" target="_blank"&gt;I Can't&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/lurgee.html" target="_blank"&gt;Lurgee&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/blowout.html" target="_blank"&gt;Blow Out&lt;/a&gt;&lt;br&gt; &lt;a id="1543"&gt;&lt;/a&gt;&lt;div class="album"&gt;EP: &lt;b&gt;"My Iron Lung"&lt;/b&gt; (1994)&lt;span&gt;&amp;nbsp;&amp;nbsp;&lt;a href="http://www.amazon.com/gp/search?ie=UTF8&amp;amp;keywords=RADIOHEAD+My+Iron+Lung&amp;amp;tag=azlyricsunive-20&amp;amp;index=music&amp;amp;linkCode=ur2&amp;amp;camp=1789&amp;amp;creative=9325" rel="external"&gt;&lt;img width="30" height="18" src="http://images.azlyrics.com/amn.png" alt="buy this CD or download MP3s at amazon.com!"&gt;&lt;/a&gt;&lt;/span&gt;&lt;/div&gt; &lt;a href="../lyrics/radiohead/myironlung.html" target="_blank"&gt;My Iron Lung&lt;/a&gt;&lt;br&gt; </code></pre> <p>And it continues like that.</p>
0
2016-08-12T01:39:47Z
38,909,352
<p>I would iterate over every album first - these are the elements matching the <code>#listAlbum .album</code> CSS selector. Now, for every album, <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-next-siblings-and-find-next-sibling" rel="nofollow">find all <code>a</code> following siblings</a> and iterate over them collecting song titles. When encounter an element with an <code>id</code>, break. Implementation:</p> <pre><code>from collections import defaultdict from pprint import pprint from bs4 import BeautifulSoup data = """ &lt;div id="listAlbum"&gt; &lt;a id="1545"&gt;&lt;/a&gt;&lt;div class="album"&gt;album: &lt;b&gt;"Pablo Honey"&lt;/b&gt; (1993)&lt;span&gt;&amp;nbsp;&amp;nbsp;&lt;a href="http://www.amazon.com/gp/search?ie=UTF8&amp;amp;keywords=RADIOHEAD+Pablo+Honey&amp;amp;tag=azlyricsunive-20&amp;amp;index=music&amp;amp;linkCode=ur2&amp;amp;camp=1789&amp;amp;creative=9325" rel="external"&gt;&lt;img width="30" height="18" src="http://images.azlyrics.com/amn.png" alt="buy this CD or download MP3s at amazon.com!"&gt;&lt;/a&gt;&lt;/span&gt;&lt;/div&gt; &lt;a href="../lyrics/radiohead/you.html" target="_blank"&gt;You&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/creep.html" target="_blank"&gt;Creep&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/howdoyou.html" target="_blank"&gt;How Do You?&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/stopwhispering.html" target="_blank"&gt;Stop Whispering&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/thinkingaboutyou.html" target="_blank"&gt;Thinking About You&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/anyonecanplayguitar.html" target="_blank"&gt;Anyone Can Play Guitar&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/ripcord.html" target="_blank"&gt;Ripcord&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/vegetable.html" target="_blank"&gt;Vegetable&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/proveyourself.html" target="_blank"&gt;Prove Yourself&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/icant.html" target="_blank"&gt;I Can't&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/lurgee.html" target="_blank"&gt;Lurgee&lt;/a&gt;&lt;br&gt; &lt;a href="../lyrics/radiohead/blowout.html" target="_blank"&gt;Blow Out&lt;/a&gt;&lt;br&gt; &lt;a id="1543"&gt;&lt;/a&gt;&lt;div class="album"&gt;EP: &lt;b&gt;"My Iron Lung"&lt;/b&gt; (1994)&lt;span&gt;&amp;nbsp;&amp;nbsp;&lt;a href="http://www.amazon.com/gp/search?ie=UTF8&amp;amp;keywords=RADIOHEAD+My+Iron+Lung&amp;amp;tag=azlyricsunive-20&amp;amp;index=music&amp;amp;linkCode=ur2&amp;amp;camp=1789&amp;amp;creative=9325" rel="external"&gt;&lt;img width="30" height="18" src="http://images.azlyrics.com/amn.png" alt="buy this CD or download MP3s at amazon.com!"&gt;&lt;/a&gt;&lt;/span&gt;&lt;/div&gt; &lt;a href="../lyrics/radiohead/myironlung.html" target="_blank"&gt;My Iron Lung&lt;/a&gt;&lt;br&gt; &lt;/div&gt;""" soup = BeautifulSoup(data, "html5lib") albums = defaultdict(list) for album in soup.select("#listAlbum .album"): album_title = album.get_text().strip() for song in album.find_next_siblings("a"): if "id" in song.attrs: break song_title = song.get_text(strip=True) albums[album_title].append(song_title) pprint(dict(albums)) </code></pre> <p>Prints:</p> <pre><code>{'EP: "My Iron Lung" (1994)': ['My Iron Lung'], 'album: "Pablo Honey" (1993)': ['You', 'Creep', 'How Do You?', 'Stop Whispering', 'Thinking About You', 'Anyone Can Play Guitar', 'Ripcord', 'Vegetable', 'Prove Yourself', "I Can't", 'Lurgee', 'Blow Out']} </code></pre>
1
2016-08-12T03:19:25Z
[ "python", "beautifulsoup" ]
Class Population Counter. How to put the program all into one
38,908,575
<p>I am trying to develop a class population counter. The problem is that when I run it 2 program come up. I wanted my program to be all in one. The counter keeps coming in a separate program and i can't transfer it into my actual program. How do I do this?</p> <p>Here is my attached files, I am using Python</p> <pre><code>import pickle import os.path from tkinter import * import tkinter.messagebox import tkinter as tk population = 0 def counter_label(label): population = 0 def count(): global population population +=1 label.config(text=str(population)) root = tk.Tk() label = tk.Label(root) label.pack() counter_label(label) button = tk.Button(root, text='Population Count', command=count).pack() root.mainloop() class Class: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname class ClassPopulation: def __init__(self): window = Tk() window.title("Class population") self.firstnameVar = StringVar() self.lastnameVar = StringVar() frame1 = Frame(window) frame1.pack() Label(frame1, text = "First name").grid(row = 1, column = 1, sticky = W) Entry(frame1, textvariable = self.firstnameVar, width = 40).grid(row = 1, column = 2) frame2 = Frame(window) frame2.pack() Label(frame2, text = "Last name").grid(row = 1, column = 1, sticky = W) Entry(frame2, textvariable = self.lastnameVar, width = 40).grid(row = 1, column = 2) frame3 = Frame(window) frame3.pack() Button(frame3, text = "Add to classlist", command = self.processAdd).grid(row = 1, column = 1) frame4 = Frame(window) frame4.pack() Label(frame4, text = "Population Count").grid(row = 1, column = 1, sticky = W) frame5 = Frame(window) frame5.pack() Label(frame5, text = "0").grid(row = 1, column = 1, sticky = W) self.classList = self.loadClass() self.current = 0 if len(self.classList) &gt; 0: self.setClass() def saveClass(self): outfile = open("Population.dat", "wb") pickle.dump(self.classList, outfile) tkinter.messagebox.showinfo("Class Population","New name registered") outfile.close() def loadClass(self): if not os.path.isfile("Population.dat"): return [] # Return an empty list try: infile = open("Population.dat", "rb") classList = pickle.load(infile) except EOFError: classList = [] infile.close() return classList def processAdd(self): classList = Class(self.firstnameVar.get(), self.lastnameVar.get()) self.classList.append(classList) self.saveClass() def setClass(self): self.firstnameVar.set(self.classList[self.current].firstname) self.lastnameVar.set(self.classList[self.current].lastname) ClassPopulation() </code></pre>
0
2016-08-12T01:43:03Z
38,910,206
<p>I think two windows are coming up is because the program runs <code>Tk()</code> twice - one <code>root = tk.Tk()</code> and another in <code>window = Tk()</code>. If you pass your <code>root</code> Tkinter instance to the class <code>ClassPopulation</code>, then it should show one single window.</p> <p>[EDIT]</p> <pre><code>class Class: def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname class ClassPopulation: def __init__(self, root_window): window = self.root_window window.title("Class population") population = 0 def counter_label(label): population = 0 def count(): global population population +=1 label.config(text=str(population)) root = Tk() label = tk.Label(root) label.pack() ClassPopulation( root ) counter_label(label) root.mainloop() </code></pre>
1
2016-08-12T04:55:11Z
[ "python", "python-2.7", "python-3.x" ]
Why doesn't this instance of this class's method take this argument?
38,908,590
<p>My question is why I can't make a object of the class giving it an integer as an argument. It totally ignores the value that I pass as an argument to it. Yet, if I call the area function from the class and pass the same number into it's parentheses it will output the desired result of 144.</p> <p>My best guess from what I have read so far is that the way the classes function is coded is incorrect for what I am hoping that it will achieve. Do I need to have the area function take it's argument like: <code>self.length</code> ?</p> <pre><code># -*- coding: utf-8 -*- class square: sides = 4 def __init__(self, length): self.length = length def area(self, length): return length * length box = square(12) print(box.area()) </code></pre> <p>Output: <code>TypeError: area() missing 1 required positional argument: 'length'</code></p> <p>Shouldn't the object that is created save the value that is given to it for the duration of that objects life? Why does it throw another error when I tell it to print from the area method a second time if the calls looked like this?</p> <pre><code>print(box.area(12)) output:144 print(box.area()) output: &lt;bound method square_shape.area of &lt;__main__.square_shape object at 0x7f5f88355b70&gt;&gt; </code></pre> <p>I'm sorry if this question is a little oddly phrased but I'm simply looking for as much information as I can get and attempting to gain a better understanding of what I'm doing here. Other questions on this subject didn't give a good grasp of what I'm trying to figure out.</p>
0
2016-08-12T01:44:42Z
38,908,618
<p>You are thinking of self.length. length (without a "self." in front of it) is just a local variable. If it's an argument, you need to provide it.</p> <p>What you probably want is: <code> def area(self): return self.length * self.length </code></p>
4
2016-08-12T01:48:47Z
[ "python", "function", "class", "python-3.x", "variables" ]
Why doesn't this instance of this class's method take this argument?
38,908,590
<p>My question is why I can't make a object of the class giving it an integer as an argument. It totally ignores the value that I pass as an argument to it. Yet, if I call the area function from the class and pass the same number into it's parentheses it will output the desired result of 144.</p> <p>My best guess from what I have read so far is that the way the classes function is coded is incorrect for what I am hoping that it will achieve. Do I need to have the area function take it's argument like: <code>self.length</code> ?</p> <pre><code># -*- coding: utf-8 -*- class square: sides = 4 def __init__(self, length): self.length = length def area(self, length): return length * length box = square(12) print(box.area()) </code></pre> <p>Output: <code>TypeError: area() missing 1 required positional argument: 'length'</code></p> <p>Shouldn't the object that is created save the value that is given to it for the duration of that objects life? Why does it throw another error when I tell it to print from the area method a second time if the calls looked like this?</p> <pre><code>print(box.area(12)) output:144 print(box.area()) output: &lt;bound method square_shape.area of &lt;__main__.square_shape object at 0x7f5f88355b70&gt;&gt; </code></pre> <p>I'm sorry if this question is a little oddly phrased but I'm simply looking for as much information as I can get and attempting to gain a better understanding of what I'm doing here. Other questions on this subject didn't give a good grasp of what I'm trying to figure out.</p>
0
2016-08-12T01:44:42Z
38,908,666
<p>Your <code>area</code> takes the <code>self</code> argument, which is enough to access <code>self.length</code>:</p> <pre><code>... def area(self): return self.length * self.length </code></pre> <p>Then you can call <code>square(3).area()</code> and get <code>9</code>.</p> <p>Your current declaration requires an <em>explicit</em> length argument, something like <code>square(3).area(4)</code> which would produce <code>16</code>.</p> <p>One of the key tenets of OOP is that <em>methods</em> have access to object's (or often said <em>instance's</em>) state, and can operate on that state, instead of passing it explicitly. </p> <p>In Python, the parameter normally named <code>self</code> is used to pass the object in question to the method. The <code>area</code> method operates on <code>square</code>'s <code>length</code>; you access it as <code>self.length</code>. That <code>self</code> is an instance of <code>square</code>, the thing that e.g. <code>square(3)</code> returns.</p>
1
2016-08-12T01:54:57Z
[ "python", "function", "class", "python-3.x", "variables" ]
How to overwrite identical column names when performing an "outer" join in Pandas?
38,908,600
<p>I am trying to merge/join two csv's, based on a unique <code>city</code>/<code>country</code>/<code>state</code> column combination using Pandas. However, when I try to do this using an outer join, I am getting extra columns when instead I would prefer to have the "right" side of my join overwrite the columns in the "left" side of the join. Any suggestions?</p> <p><strong>Here is my attempt, with an example:</strong></p> <p>These are my csv's:</p> <p>My "left" csv file:</p> <pre><code>| city | country | state | pop | lat | long | |--------------+---------+-------+----------+---------+---------| | beijing | cn | 22 | 456 | 456 | 456 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 123 | 123 | 123 | </code></pre> <p>My "right" csv file:</p> <pre><code>| city | country | state | pop | lat | long | |-------------+---------+-------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | | beijing | cn | 22 | 11716620 | 39.907 | 116.397 | | mexico city | mx | 9 | 12294193 | 19.428 | -99.128 | </code></pre> <p>and I want this result:</p> <pre><code>| city | country | state | pop | lat | long | |--------------+---------+-------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | | beijing | cn | 22 | 11716620 | 39.907 | 116.397 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 12294193 | 19.428 | -99.128 | </code></pre> <p>Note that <code>mexico city</code> and <code>beijing</code> are considered matches, based on their <code>city</code>, <code>country</code>, and <code>state</code> columns. Also note that on these matching rows, each column from my "left" csv is overwritten by the matching column from my "right" csv.</p> <p>So here is my attempt using Pandas and dataframes:</p> <pre><code>left = pd.read_csv('left.csv') right = pd.read_csv('right.csv') result = pd.merge(left, right, on=['city', 'country', 'state'], how='outer') </code></pre> <p>Unfortunately, here is my result:</p> <pre><code>| city | country | state | pop_x | lat_x | long_x | pop_y | lat_y | long_y | |--------------+---------+-------+----------+-----------+------------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | 32707 | 33.219442 | -86.823907 | | albertville | us | al | | 34.26313 | -86.21066 | | 34.26313 | -86.21066 | | beijing | cn | 22 | 456 | 456 | 456 | 11716620 | 39.907 | 116.397 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 123 | 123 | 123 | 12294193 | 19.428 | -99.128 | | mumbai | in | 16 | 12691836 | 19.073 | 72.883 | 12691836 | 19.073 | 72.883 | | shanghai | cn | 23 | 22315474 | 31.222 | 121.458 | 22315474 | 31.222 | 121.458 | </code></pre> <p>As shown above, the columns that are not being used for the join, and which have the same name, are renamed with a <code>_x</code> suffix for the "left" dataframe and a <code>_y</code> suffix for the "right" dataframe.</p> <p>Is there a simple way to make the columns from the "right" dataframe to overwrite the columns from the "left" dataframe when matched?</p> <hr> <p>Although there seem to be similar questions already out there, I still can't seem to find an answer. For example, I tried implementing the solution based on <a href="http://stackoverflow.com/questions/25145317/pandas-merge-two-dataframes-with-identical-column-names">this question</a>:</p> <pre><code>left = pd.read_csv('left.csv') right = pd.read_csv('right.csv') left = left.set_index(['city','country','state']) right = right.set_index(['city','country','state']) left.update(right) </code></pre> <p>But <code>update</code> only performs left joins, so the resulting dataframe only has the same rows from the left dataframe, so it is missing cities like <code>adamsville</code> and <code>alabaster</code> above.</p>
1
2016-08-12T01:45:43Z
38,908,965
<p>Since the column names for both dataframes are the same you could stack them and then do a drop_duplicates or groupby </p> <p>For example:</p> <pre><code>result = pd.concat([left, right]).reset_index() result.drop_duplicates(['city','country','state'], keep='first', inplace=True) </code></pre> <p>or:</p> <pre><code>df_stacked = pd.concat([left, right]).reset_index() result = df_stacked.groupby(['city','country','state']).first() </code></pre> <p>Calling first will take the values from the "left" df over the "right" df because we're stacking the "left" df on top of the "right" df and resetting the index</p> <p>Using groupby will allow you to perform more complex selects on the aggregated records if you don't want to just take the first or last record. </p> <p><strong>EDIT:</strong></p> <p>Just realized you want the "right" df to overwrite the "left" df, in that case...</p> <pre><code>df_stacked = pd.concat([right, left]).reset_index() result = df_stacked.groupby(['city','country','state']).first() </code></pre> <p>This methodology only works if the "left" and "right" dataframes don't contain duplicate records to start.</p> <hr> <p>And for the record, to get to the csv solution in the example above, we can perform the following:</p> <pre><code>result = result.reset_index() # sort our descending population, and if populations are equal (or NaN), sort by ascending city name result = result.sort_values(['pop', 'city'], ascending=[False, True]) result.drop('index', axis=1, inplace=True) result.to_csv('result.csv', index=False) </code></pre>
1
2016-08-12T02:32:49Z
[ "python", "csv", "pandas", "join" ]
How to overwrite identical column names when performing an "outer" join in Pandas?
38,908,600
<p>I am trying to merge/join two csv's, based on a unique <code>city</code>/<code>country</code>/<code>state</code> column combination using Pandas. However, when I try to do this using an outer join, I am getting extra columns when instead I would prefer to have the "right" side of my join overwrite the columns in the "left" side of the join. Any suggestions?</p> <p><strong>Here is my attempt, with an example:</strong></p> <p>These are my csv's:</p> <p>My "left" csv file:</p> <pre><code>| city | country | state | pop | lat | long | |--------------+---------+-------+----------+---------+---------| | beijing | cn | 22 | 456 | 456 | 456 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 123 | 123 | 123 | </code></pre> <p>My "right" csv file:</p> <pre><code>| city | country | state | pop | lat | long | |-------------+---------+-------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | | beijing | cn | 22 | 11716620 | 39.907 | 116.397 | | mexico city | mx | 9 | 12294193 | 19.428 | -99.128 | </code></pre> <p>and I want this result:</p> <pre><code>| city | country | state | pop | lat | long | |--------------+---------+-------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | | beijing | cn | 22 | 11716620 | 39.907 | 116.397 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 12294193 | 19.428 | -99.128 | </code></pre> <p>Note that <code>mexico city</code> and <code>beijing</code> are considered matches, based on their <code>city</code>, <code>country</code>, and <code>state</code> columns. Also note that on these matching rows, each column from my "left" csv is overwritten by the matching column from my "right" csv.</p> <p>So here is my attempt using Pandas and dataframes:</p> <pre><code>left = pd.read_csv('left.csv') right = pd.read_csv('right.csv') result = pd.merge(left, right, on=['city', 'country', 'state'], how='outer') </code></pre> <p>Unfortunately, here is my result:</p> <pre><code>| city | country | state | pop_x | lat_x | long_x | pop_y | lat_y | long_y | |--------------+---------+-------+----------+-----------+------------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | 32707 | 33.219442 | -86.823907 | | albertville | us | al | | 34.26313 | -86.21066 | | 34.26313 | -86.21066 | | beijing | cn | 22 | 456 | 456 | 456 | 11716620 | 39.907 | 116.397 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 123 | 123 | 123 | 12294193 | 19.428 | -99.128 | | mumbai | in | 16 | 12691836 | 19.073 | 72.883 | 12691836 | 19.073 | 72.883 | | shanghai | cn | 23 | 22315474 | 31.222 | 121.458 | 22315474 | 31.222 | 121.458 | </code></pre> <p>As shown above, the columns that are not being used for the join, and which have the same name, are renamed with a <code>_x</code> suffix for the "left" dataframe and a <code>_y</code> suffix for the "right" dataframe.</p> <p>Is there a simple way to make the columns from the "right" dataframe to overwrite the columns from the "left" dataframe when matched?</p> <hr> <p>Although there seem to be similar questions already out there, I still can't seem to find an answer. For example, I tried implementing the solution based on <a href="http://stackoverflow.com/questions/25145317/pandas-merge-two-dataframes-with-identical-column-names">this question</a>:</p> <pre><code>left = pd.read_csv('left.csv') right = pd.read_csv('right.csv') left = left.set_index(['city','country','state']) right = right.set_index(['city','country','state']) left.update(right) </code></pre> <p>But <code>update</code> only performs left joins, so the resulting dataframe only has the same rows from the left dataframe, so it is missing cities like <code>adamsville</code> and <code>alabaster</code> above.</p>
1
2016-08-12T01:45:43Z
38,909,252
<p>Try:</p> <pre><code>res = pd.concat([left, right], ignore_index=True) res = res.drop(res[res['city'].duplicated(keep='last')].index, axis=0) </code></pre>
0
2016-08-12T03:11:01Z
[ "python", "csv", "pandas", "join" ]
How to overwrite identical column names when performing an "outer" join in Pandas?
38,908,600
<p>I am trying to merge/join two csv's, based on a unique <code>city</code>/<code>country</code>/<code>state</code> column combination using Pandas. However, when I try to do this using an outer join, I am getting extra columns when instead I would prefer to have the "right" side of my join overwrite the columns in the "left" side of the join. Any suggestions?</p> <p><strong>Here is my attempt, with an example:</strong></p> <p>These are my csv's:</p> <p>My "left" csv file:</p> <pre><code>| city | country | state | pop | lat | long | |--------------+---------+-------+----------+---------+---------| | beijing | cn | 22 | 456 | 456 | 456 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 123 | 123 | 123 | </code></pre> <p>My "right" csv file:</p> <pre><code>| city | country | state | pop | lat | long | |-------------+---------+-------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | | beijing | cn | 22 | 11716620 | 39.907 | 116.397 | | mexico city | mx | 9 | 12294193 | 19.428 | -99.128 | </code></pre> <p>and I want this result:</p> <pre><code>| city | country | state | pop | lat | long | |--------------+---------+-------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | | beijing | cn | 22 | 11716620 | 39.907 | 116.397 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 12294193 | 19.428 | -99.128 | </code></pre> <p>Note that <code>mexico city</code> and <code>beijing</code> are considered matches, based on their <code>city</code>, <code>country</code>, and <code>state</code> columns. Also note that on these matching rows, each column from my "left" csv is overwritten by the matching column from my "right" csv.</p> <p>So here is my attempt using Pandas and dataframes:</p> <pre><code>left = pd.read_csv('left.csv') right = pd.read_csv('right.csv') result = pd.merge(left, right, on=['city', 'country', 'state'], how='outer') </code></pre> <p>Unfortunately, here is my result:</p> <pre><code>| city | country | state | pop_x | lat_x | long_x | pop_y | lat_y | long_y | |--------------+---------+-------+----------+-----------+------------+----------+-----------+------------| | adamsville | us | al | 4400 | 33.60575 | -86.97465 | 4400 | 33.60575 | -86.97465 | | alabaster | us | al | 32707 | 33.219442 | -86.823907 | 32707 | 33.219442 | -86.823907 | | albertville | us | al | | 34.26313 | -86.21066 | | 34.26313 | -86.21066 | | beijing | cn | 22 | 456 | 456 | 456 | 11716620 | 39.907 | 116.397 | | buenos aires | ar | 7 | 13076300 | -34.613 | -58.377 | 13076300 | -34.613 | -58.377 | | mexico city | mx | 9 | 123 | 123 | 123 | 12294193 | 19.428 | -99.128 | | mumbai | in | 16 | 12691836 | 19.073 | 72.883 | 12691836 | 19.073 | 72.883 | | shanghai | cn | 23 | 22315474 | 31.222 | 121.458 | 22315474 | 31.222 | 121.458 | </code></pre> <p>As shown above, the columns that are not being used for the join, and which have the same name, are renamed with a <code>_x</code> suffix for the "left" dataframe and a <code>_y</code> suffix for the "right" dataframe.</p> <p>Is there a simple way to make the columns from the "right" dataframe to overwrite the columns from the "left" dataframe when matched?</p> <hr> <p>Although there seem to be similar questions already out there, I still can't seem to find an answer. For example, I tried implementing the solution based on <a href="http://stackoverflow.com/questions/25145317/pandas-merge-two-dataframes-with-identical-column-names">this question</a>:</p> <pre><code>left = pd.read_csv('left.csv') right = pd.read_csv('right.csv') left = left.set_index(['city','country','state']) right = right.set_index(['city','country','state']) left.update(right) </code></pre> <p>But <code>update</code> only performs left joins, so the resulting dataframe only has the same rows from the left dataframe, so it is missing cities like <code>adamsville</code> and <code>alabaster</code> above.</p>
1
2016-08-12T01:45:43Z
38,910,518
<p>Try this: </p> <pre><code>result = left.append(right).drop_duplicates(['city'], keep='last') </code></pre>
0
2016-08-12T05:24:29Z
[ "python", "csv", "pandas", "join" ]
how to convert a string to unicode/byte string in python3?
38,908,624
<p>I know this works:</p> <pre><code>a = u"\u65b9\u6cd5\uff0c\u5220\u9664\u5b58\u50a8\u5728" print(a) # 方法,删除存储在 </code></pre> <p>but if I got a string from a json file which is not started with "u"(<code>a = "\u65b9\u6cd5\uff0c\u5220\u9664\u5b58\u50a8\u5728"</code>),</p> <p>I have got the way to make it in python2(<code>print unicode(a, encoding='unicode_escape') # Prints 方法,删除存储在</code>),but how to do it with python3?</p> <p>Similarly,if it's a byte string which is load from a file, how to convert it?</p> <pre><code>print("好的".encode("utf-8")) # b'\xe5\xa5\xbd\xe7\x9a\x84' # how to convert this? b = '\xe5\xa5\xbd\xe7\x9a\x84' # 好的 </code></pre>
0
2016-08-12T01:49:15Z
38,908,923
<p>If I understand correctly, the file contains the literal text <code>\u65b9\u6cd5\uff0c\u5220\u9664\u5b58\u50a8\u5728</code> (so it's plain ASCII, but with backslashes and all that describe the Unicode ordinals the same way you would in a Python <code>str</code> literal). If so, there are two ways to handle this:</p> <ol> <li>Read the file in binary mode, then call <code>mystr = mybytes.decode('unicode-escape')</code> to convert from the <code>bytes</code> to <code>str</code> interpreting the escapes</li> <li>Read the file in text mode, and use the <code>codecs</code> module for the "text -> text" conversion (bytes to bytes and text to text codecs are now supported only by the <code>codecs</code> module functions; <code>bytes.decode</code> is purely for bytes to text and <code>str.encode</code> is purely for text to bytes, because usually, in Py2, <code>str.encode</code> and <code>unicode.decode</code> was a mistake, and removing the dangerous methods makes it easier to understand what direction the conversions are supposed to go), e.g. <code>decodedstr = codecs.decode(encodedstr, 'unicode-escape')</code></li> </ol>
2
2016-08-12T02:27:12Z
[ "python", "python-3.x", "unicode", "encode", "codec" ]
Python Multiprocessing - How to pass kwargs to function?
38,908,663
<p>How do I pass a dictionary to a function with Python's Multiprocessing? The Documentation: <a href="https://docs.python.org/3.4/library/multiprocessing.html#reference" rel="nofollow">https://docs.python.org/3.4/library/multiprocessing.html#reference</a> says to pass a dictionary, but I keep getting</p> <pre><code>TypeError: fp() got multiple values for argument 'what' </code></pre> <p>Here's the code:</p> <pre><code>from multiprocessing import Pool, Process, Manager def fp(name, numList=None, what='no'): print ('hello %s %s'% (name, what)) numList.append(name+'44') if __name__ == '__main__': manager = Manager() numList = manager.list() for i in range(10): keywords = {'what':'yes'} p = Process(target=fp, args=('bob'+str(i)), kwargs={'what':'yes'}) p.start() print("Start done") p.join() print("Join done") print (numList) </code></pre>
0
2016-08-12T01:54:32Z
38,908,823
<p>When I ran your code, I got a different error: </p> <pre><code>TypeError: fp() takes at most 3 arguments (5 given) </code></pre> <p>I debugged by printing args and kwargs and changing the method to <code>fp(*args, **kwargs)</code> and noticed that "bob_" was being passed in as an array of letters. It seems that the parentheses used for <code>args</code> were operational and not actually giving you a tuple. Changing it to the list, then also passing in <code>numList</code> as a keyword argument, made the code work for me.</p> <pre><code>from multiprocessing import Pool, Process, Manager def fp(name, numList=None, what='no'): print ('hello %s %s' % (name, what)) numList.append(name+'44') if __name__ == '__main__': manager = Manager() numList = manager.list() for i in range(10): keywords = {'what': 'yes', 'numList': numList} p = Process(target=fp, args=['bob'+str(i)], kwargs=keywords) p.start() print("Start done") p.join() print("Join done") print (numList) </code></pre>
1
2016-08-12T02:13:51Z
[ "python", "multiprocessing", "kwargs" ]
Finding a string in match objects in python
38,908,699
<p>I'd like to find a string in "match objects" in python, but ".find" does not work. Here is my snippet:</p> <pre><code>e_list = [] for file in os.listdir('.'): r = re.compile(r".*\.(aaa|bbb)$") e_found = r.search(file) if e_found is not None: e_list.append(e_found.group(0)) e_length = len(e_list); for num_e in range(e_length): if(e_list[num_e].group(0).find('50M') &gt; 0) print(e_list[num_e].group(0)) </code></pre> <p>... Now <code>e_list</code> is like:</p> <pre><code>[&lt;_sre.SRE_Match object; span=(0, 7), match='30M.aaa'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='40M.bbb'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='50M.aaa'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='50M.bbb'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='50M.ccc'&gt;] </code></pre> <p>I'm expecting to have the result:</p> <pre><code>'50M.aaa' '50M.bbb' </code></pre> <p>While <code>e_list[0].group(0)</code> returns <code>'30M.aaa'</code>, <code>.find</code> cannot be applied because it's a match object. Then, what should I do?</p>
1
2016-08-12T01:58:58Z
38,908,763
<p>To check if the string begins with <code>'50M'</code>, use <code>str.startswith('50M')</code>. This will not detect cases where <code>50M</code> is the suffix (<code>test.50M</code>).</p> <pre><code>if e_list[num_e].startswith('50M'): print(e_list[num_e]) </code></pre> <p>If the suffix is a legitimate place to find the <code>50M</code>, using <code>in</code> is much cleaner than <code>.find('50M') &gt; 0</code>.</p> <pre><code>if '50M' in e_list[num_e]: </code></pre>
2
2016-08-12T02:06:40Z
[ "python", "string", "find", "match" ]
Finding a string in match objects in python
38,908,699
<p>I'd like to find a string in "match objects" in python, but ".find" does not work. Here is my snippet:</p> <pre><code>e_list = [] for file in os.listdir('.'): r = re.compile(r".*\.(aaa|bbb)$") e_found = r.search(file) if e_found is not None: e_list.append(e_found.group(0)) e_length = len(e_list); for num_e in range(e_length): if(e_list[num_e].group(0).find('50M') &gt; 0) print(e_list[num_e].group(0)) </code></pre> <p>... Now <code>e_list</code> is like:</p> <pre><code>[&lt;_sre.SRE_Match object; span=(0, 7), match='30M.aaa'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='40M.bbb'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='50M.aaa'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='50M.bbb'&gt;, &lt;_sre.SRE_Match object; span=(0, 7), match='50M.ccc'&gt;] </code></pre> <p>I'm expecting to have the result:</p> <pre><code>'50M.aaa' '50M.bbb' </code></pre> <p>While <code>e_list[0].group(0)</code> returns <code>'30M.aaa'</code>, <code>.find</code> cannot be applied because it's a match object. Then, what should I do?</p>
1
2016-08-12T01:58:58Z
38,908,820
<p>I think Python is not your first language, your code smell like Java.</p> <p>Please do not use <code>re.compile</code>, because it is unnecessary. Just use <code>re.search</code> or <code>re.findall</code>.</p> <p>And in Python, you can just use:</p> <pre><code>result = re.findall('.*\.(aaa|bbb)$', file) </code></pre> <p>then, <code>result</code> is a list, you can print it or use <code>for... loop</code> to get every item of it.</p> <p>As you can also use:</p> <pre><code>result = re.search('.*\.(aaa|bbb)$', file) </code></pre> <p>the result is a group. </p> <p>Then you should use <strong>result.group(1)</strong> to get the the matched item.</p> <p>SO, your code can be:</p> <pre><code>e_list = [] for file in os.listdir('.'): e_found = re.search(".*\.(aaa|bbb)$", file) if e_found: e_list.append(e_found.group(1)) for item in e_list: if item.find('50M') &gt; 0 print(item) </code></pre>
2
2016-08-12T02:13:43Z
[ "python", "string", "find", "match" ]
Pycharm: different behavior between run and run in Python console?
38,908,845
<p>I'm on Pycharm with python3. I can run the code by shift+control+R (short cut for run, equivalent to press the green triangle run button) Or run the code by shift+alt+E to load the code into Python console suggested by <a href="http://stackoverflow.com/questions/19329601/interactive-shell-debugging-with-pycharm">interactive shell debugging with pycharm</a></p> <p>shift+control+R gives no errors.</p> <p>shift+alt+E throws an exception:</p> <pre><code>TypeError: an integer is required (got type str) </code></pre> <p>The code I run as follows:</p> <pre><code>import sys sys.exit('exist') print('shouldnt print') </code></pre> <p>I want to understand what causes the different behavior and how I can avoid this. The code is inline with <code>sys.exit</code> documentation for python3.</p>
0
2016-08-12T02:16:42Z
38,909,132
<p>When Shift + Alt + E is pressed, it enters the Interactive shell. <code>sys.exit()</code> doesn't work for IDLE applications such as the Interactive shell. For IDLE applications, the built-in <code>os._exit()</code> is used instead.</p> <p>When you closely examine the stack trace, you will notice this behavior:</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 4, in &lt;module&gt; File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevconsole.py", line 260, in DoExit os._exit(args[0]) TypeError: an integer is required </code></pre> <p><code>os._exit()</code> is executed (instead of <code>sys.exit("exist")</code>), and it takes only an integer as an argument. Check the documentation here: <a href="https://docs.python.org/2/library/os.html#os._exit" rel="nofollow">https://docs.python.org/2/library/os.html#os._exit</a></p>
1
2016-08-12T02:56:30Z
[ "python", "pycharm" ]
Python Regex query for substring between the second occurrence of string A and string B
38,908,846
<p>I'm trying to parse some values from a raw output and having difficulties with the regex expression. The raw string contains two or more values with the same 'start' keyword. This is what I have so far, which gives me the first instance:</p> <pre><code>def parser(s, start, end): try: result = re.search('%s(.*)%s' % (start, end), s).group(1).strip() except: result = "" print(result) return result </code></pre> <p>How do I get the second instance between the same 'start' and 'end'? Thanks in advance!</p> <p>Example:</p> <pre><code>s = "verylongstring\n Name Server: IDNS1.NETSOL.COM\n Name Server: IDNS2.NETSOL.COM\n Status: clientTransferProhibited...." start = "Name Server: " end = "\n" </code></pre> <p>Desired output:</p> <pre><code>server1 = IDNS1.NETSOL.COM server2 = IDNS2.NETSOL.COM </code></pre> <p>I can get server1, but not 2.</p> <pre><code>server1 = parser(s, start, end) </code></pre>
0
2016-08-12T02:16:49Z
38,909,097
<pre><code>s = "verylongstring\n Name Server: IDNS1.NETSOL.COM\n Name Server: IDNS2.NETSOL.COM\n Status: clientTransferProhibited...." start = "Name Server: " end = "\n" import re re.findall(start + "(.*?)" + end, s) </code></pre> <p>The output is:</p> <pre><code>['IDNS1.NETSOL.COM', 'IDNS2.NETSOL.COM'] </code></pre> <p>and the function can be like this:</p> <pre><code>def parser(s, start, end): result = [l.strip() for l in re.findall(start + "(.*?)" + end, s)] return result </code></pre> <p>for the same <code>s</code> <code>start</code> <code>end</code>:</p> <pre><code>&gt;&gt;&gt;parser(s, start, end) &gt;&gt;&gt;['IDNS1.NETSOL.COM', 'IDNS2.NETSOL.COM'] </code></pre>
2
2016-08-12T02:51:00Z
[ "python", "regex", "string", "parsing" ]
Python Regex query for substring between the second occurrence of string A and string B
38,908,846
<p>I'm trying to parse some values from a raw output and having difficulties with the regex expression. The raw string contains two or more values with the same 'start' keyword. This is what I have so far, which gives me the first instance:</p> <pre><code>def parser(s, start, end): try: result = re.search('%s(.*)%s' % (start, end), s).group(1).strip() except: result = "" print(result) return result </code></pre> <p>How do I get the second instance between the same 'start' and 'end'? Thanks in advance!</p> <p>Example:</p> <pre><code>s = "verylongstring\n Name Server: IDNS1.NETSOL.COM\n Name Server: IDNS2.NETSOL.COM\n Status: clientTransferProhibited...." start = "Name Server: " end = "\n" </code></pre> <p>Desired output:</p> <pre><code>server1 = IDNS1.NETSOL.COM server2 = IDNS2.NETSOL.COM </code></pre> <p>I can get server1, but not 2.</p> <pre><code>server1 = parser(s, start, end) </code></pre>
0
2016-08-12T02:16:49Z
38,909,117
<p>This works on the given example.</p> <pre><code>def parser(s, start, end): arr = [x.split(start)[1] for x in s.split('\n') if start in x] return arr </code></pre>
1
2016-08-12T02:54:36Z
[ "python", "regex", "string", "parsing" ]
Python Regex query for substring between the second occurrence of string A and string B
38,908,846
<p>I'm trying to parse some values from a raw output and having difficulties with the regex expression. The raw string contains two or more values with the same 'start' keyword. This is what I have so far, which gives me the first instance:</p> <pre><code>def parser(s, start, end): try: result = re.search('%s(.*)%s' % (start, end), s).group(1).strip() except: result = "" print(result) return result </code></pre> <p>How do I get the second instance between the same 'start' and 'end'? Thanks in advance!</p> <p>Example:</p> <pre><code>s = "verylongstring\n Name Server: IDNS1.NETSOL.COM\n Name Server: IDNS2.NETSOL.COM\n Status: clientTransferProhibited...." start = "Name Server: " end = "\n" </code></pre> <p>Desired output:</p> <pre><code>server1 = IDNS1.NETSOL.COM server2 = IDNS2.NETSOL.COM </code></pre> <p>I can get server1, but not 2.</p> <pre><code>server1 = parser(s, start, end) </code></pre>
0
2016-08-12T02:16:49Z
38,909,278
<p>You can also make use of <a href="https://docs.python.org/3/library/re.html#re.finditer" rel="nofollow"><code>re.finditer</code></a> which will create an iterator that will be exhausted until the end of your string:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; pat = re.compile(r'Name Server:(?P&lt;Server_Name&gt;.*?)\n') &gt;&gt;&gt; &gt;&gt;&gt; s 'verylongstring\n Name Server: IDNS1.NETSOL.COM\n Name Server: IDNS2.NETSOL.COM\n Status: clientTransferProhibited....' &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; for match in pat.finditer(s): print(match.group('Server_Name').strip()) IDNS1.NETSOL.COM IDNS2.NETSOL.COM &gt;&gt;&gt; &gt;&gt;&gt; [match.group('Server_Name').strip() for match in pat.finditer(s)] ['IDNS1.NETSOL.COM', 'IDNS2.NETSOL.COM'] </code></pre>
0
2016-08-12T03:13:14Z
[ "python", "regex", "string", "parsing" ]
Rounding up decimals Python
38,908,883
<p>I am new to python pandas and I am having difficulties trying to round up all the values in the column as there is a white space between the decimal point and zero. For example,</p> <pre><code> Hi 21. 0 8. 0 52. 0 45. 0 </code></pre> <p>I tried using my current code below, but it gave me:</p> <blockquote> <p>invalid literal for float(): 21. 0</p> </blockquote> <pre><code> df.Hi.astype(float).round() </code></pre>
-1
2016-08-12T02:20:48Z
38,908,921
<p>Try using <code>replace</code> on the string to replace all whitespace in the string before converting to a float:</p> <pre><code>df.Hi.str.replace(' ', '').astype(float).round() </code></pre>
1
2016-08-12T02:27:02Z
[ "python", "pandas" ]
Rounding up decimals Python
38,908,883
<p>I am new to python pandas and I am having difficulties trying to round up all the values in the column as there is a white space between the decimal point and zero. For example,</p> <pre><code> Hi 21. 0 8. 0 52. 0 45. 0 </code></pre> <p>I tried using my current code below, but it gave me:</p> <blockquote> <p>invalid literal for float(): 21. 0</p> </blockquote> <pre><code> df.Hi.astype(float).round() </code></pre>
-1
2016-08-12T02:20:48Z
38,909,175
<p>If I understand you correctly, you want to convert the values in column <code>Hi</code> to <code>float</code>. </p> <p>You have a white space between the decimal points and zeros, which means your values are strings.</p> <p>You can convert them to <code>float</code> using a <code>lambda</code> function.</p> <pre><code>df['Hi'] = df['Hi'].apply(lambda x: x.replace(" ", "")).astype(float) print(df) Hi 0 21.0 1 8.0 2 52.0 3 45.0 print(df.dtypes) Hi float64 dtype: object </code></pre>
0
2016-08-12T03:02:25Z
[ "python", "pandas" ]
How to install lxml when something went wrong in "gcc" and "libxml2"
38,908,884
<p>OpenSUSE Leap 42.1, python 2.7.9, pip 8.1.2</p> <p>I wanna install Tushare, but the terminal told me there was no lxml. Then I use <code>sudo zypper in libxml2</code> first,but when I want to install "lxml" with lxml-3.6.1.tar.gz downloaded from the official website. It returns:</p> <pre><code> compilation terminated. Compile failed: command 'gcc' failed with exit status 1 cc -I/usr/include/libxml2 -c /tmp/xmlXPathInitVXdVTQ.c -o tmp/xmlXPathInitVXdVTQ.o /tmp/xmlXPathInitVXdVTQ.c:1:26: fatal error: libxml/xpath.h: no such files or directory #include "libxml/xpath.h" ^ compilation terminated. Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed? error: command 'gcc' failed with exit status 1 </code></pre> <p>I've installed 'gcc' before. Then How can I deal with this problem? And How should I find the keys to such problems in the future? Thanks a lot</p>
0
2016-08-12T02:21:01Z
38,926,416
<p>You need to install the development library, most likely called <code>libxml2-dev</code> or <code>libxml2-devel</code> in order to compile against the required header (<code>.h</code>) files.</p>
0
2016-08-12T21:02:34Z
[ "python", "linux", "python-2.7", "pip" ]
Python & Pandas: Find a dict within a list according to a key's value
38,908,903
<p>I have a list which look like this:</p> <pre><code>dict_list = [{'angle': 5.0, 'basic_info': '111', 'x': [1,2,3,4], 'y': [3,2,1,4],}, {'angle': 25.0, 'basic_info': '111', 'x': [1,2,3,4], 'y': [3,1,5,2],}, {'angle': 3.0, 'basic_info': '111', 'x': [1,2,3,4], 'y': [1,1,4,1],},] </code></pre> <p>I want to get the dict angle 25, how can I do it?</p> <hr> <p>UPDATE: </p> <p>After playing a while with Pandas, I find this might be possible </p> <pre><code>df = pd.DataFrame(dict_list) temp = df.query("(angle ==25 )").T.to_dict()[temp.keys()[0]] temp </code></pre> <p>Returns </p> <pre><code>{'angle': 25.0, 'basic_info': '111', 'x': [1, 2, 3, 4], 'y': [3, 1, 5, 2]} </code></pre> <p>But this is a bit hack.</p>
2
2016-08-12T02:24:31Z
38,909,021
<p>Assuming each angle in your dictionary is unique and each dictionary contains the key 'angle':</p> <pre><code>df = None for sub_dict in dict_list: if sub_dict['angle'] == 25: df = pd.DataFrame({'x': sub_dict['x'], 'y': sub_dict['y']}) break # Stops after finding the first matching angle. if df is not None: df.plot(x='x', y='y') </code></pre> <p><a href="http://i.stack.imgur.com/h6TCJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/h6TCJ.png" alt="enter image description here"></a></p>
2
2016-08-12T02:39:52Z
[ "python", "pandas" ]
Python & Pandas: Find a dict within a list according to a key's value
38,908,903
<p>I have a list which look like this:</p> <pre><code>dict_list = [{'angle': 5.0, 'basic_info': '111', 'x': [1,2,3,4], 'y': [3,2,1,4],}, {'angle': 25.0, 'basic_info': '111', 'x': [1,2,3,4], 'y': [3,1,5,2],}, {'angle': 3.0, 'basic_info': '111', 'x': [1,2,3,4], 'y': [1,1,4,1],},] </code></pre> <p>I want to get the dict angle 25, how can I do it?</p> <hr> <p>UPDATE: </p> <p>After playing a while with Pandas, I find this might be possible </p> <pre><code>df = pd.DataFrame(dict_list) temp = df.query("(angle ==25 )").T.to_dict()[temp.keys()[0]] temp </code></pre> <p>Returns </p> <pre><code>{'angle': 25.0, 'basic_info': '111', 'x': [1, 2, 3, 4], 'y': [3, 1, 5, 2]} </code></pre> <p>But this is a bit hack.</p>
2
2016-08-12T02:24:31Z
38,911,580
<p>The built-in <a href="https://docs.python.org/3/library/functions.html#filter" rel="nofollow"><code>filter</code></a> function will do what you want... you just need to feed it a function that determines which objects to keep. That function below is <code>has_angle</code>.</p> <p>I wrapped <code>has_angle</code> in <code>filter_by_angle</code>, so I could use <a href="https://docs.python.org/3/library/functools.html#functools.partial" rel="nofollow"><code>functools.partial</code></a> to avoid hard-coding the angle sought. <code>filter_by_angle</code> is a generator function, so it can <code>yield</code> any number of matching shapes.</p> <pre><code>import functools def has_angle(angle, shape): # get with default None prevents a KeyError on shapes # without angles. return shape.get('angle', None) == angle def filter_by_angle(angle, shapes): filter_key = functools.partial(has_angle, angle) yield from filter(filter_key, shapes) def main(): dict_list = ... # Same as yours. matching_shapes = filter_by_angle(25, dict_list) for shape in matching_shapes: print(shape) return </code></pre> <p>This prints:</p> <pre class="lang-none prettyprint-override"><code>{'y': [3, 1, 5, 2], 'angle': 25.0, 'x': [1, 2, 3, 4], 'basic_info': '111'} </code></pre> <p>Note that the <code>yield from</code> syntax requires Python 3.3 or greater.</p>
0
2016-08-12T06:46:49Z
[ "python", "pandas" ]
Cloud Storage: how to setup service account credentials for python boto library
38,908,956
<p>I'm following this tutorial to upload a file to a bucket I've manually created: <a href="https://cloud.google.com/storage/docs/xml-api/gspythonlibrary" rel="nofollow">https://cloud.google.com/storage/docs/xml-api/gspythonlibrary</a></p> <p>I seem to have trouble with setting up the credentials both as service account or user account. I want to use this in a web server so ideally it should be setup with service account.</p> <p>I created an API using API Manager in Console and downloaded the JSON. Meanwhile my gcloud auth is setup with my OAUTH login. I did try <code>gsutil config -e</code> and got error:</p> <pre><code>CommandException: OAuth2 is the preferred authentication mechanism with the Cloud SDK. Run "gcloud auth login" to configure authentication, unless you want to authenticate with an HMAC access key and secret, in which case run "gsutil config -a". </code></pre> <p>I also tried to authenticate the service account using: <code>gcloud auth activate-service-account --key-file &lt;json file&gt;</code></p> <p>but still no luck with enabling access with python boto. I also copied the ID and Key from <code>~/.config/gcloud/</code> to <code>~/.boto</code> but that didn't work either. I'm not sure how am I supposed to setup the authentication for the python server to access cloud storage. I'm not using App Engine but Cloud Compute to setup the webserver.</p> <p>Here's my source code:</p> <pre><code>import boto import gcs_oauth2_boto_plugin import os import shutil import StringIO import tempfile import time CLIENT_ID = 'my client id from ~/.config/gcloud/credentials' CLIENT_SECRET = 'my client secret from ~/.config/gcloud/credentials' gcs_oauth2_boto_plugin.SetFallbackClientIdAndSecret(CLIENT_ID, CLIENT_SECRET) uri = boto.storage_uri('', 'gs') project_id = 'my-test-project-id' header_values = {"x-test-project-id": project_id} # If the default project is defined, call get_all_buckets() without arguments. for bucket in uri.get_all_buckets(headers=header_values): print bucket.name </code></pre> <p>Most recent error:</p> <pre><code>Traceback (most recent call last): File "upload/uploader.py", line 14, in &lt;module&gt; for bucket in uri.get_all_buckets(headers=header_values): File "/Users/ankitjain/dev/metax/venv/lib/python2.7/site-packages/boto/storage_uri.py", line 574, in get_all_buckets return conn.get_all_buckets(headers) File "/Users/ankitjain/dev/metax/venv/lib/python2.7/site-packages/boto/s3/connection.py", line 444, in get_all_buckets response.status, response.reason, body) boto.exception.GSResponseError: GSResponseError: 403 Forbidden &lt;?xml version='1.0' encoding='UTF-8'?&gt;&lt;Error&gt;&lt;Code&gt;InvalidSecurity&lt;/Code&gt;&lt;Message&gt;The provided security credentials are not valid.&lt;/Message&gt;&lt;Details&gt;Incorrect Authorization header&lt;/Details&gt;&lt;/Error&gt; </code></pre>
1
2016-08-12T02:31:39Z
39,010,445
<p>Okay after some more experiments I gave up on using GCE library for uploading data to Cloud Storage. I actually found using AWS boto to upload to cloud storage works much better. All I had to do was specify Google's host in s3 library:</p> <pre><code>conn = boto.connect_s3(app.config['S3_KEY'], app.config['S3_SECRET'], "c.storage.googleapis.com") bucket = conn.get_bucket(app.config['S3_BUCKET'], validate=False) </code></pre> <p>I used the HMAC credentials generated the way described in the Google Docs. Reference: <a href="https://cloud.google.com/storage/docs/migrating" rel="nofollow">https://cloud.google.com/storage/docs/migrating</a></p>
0
2016-08-18T05:17:05Z
[ "python", "google-cloud-storage", "google-compute-engine" ]
Change all text in file to lowercase
38,908,966
<pre><code>from itertools import chain from glob import glob file = open('FortInventory.txt','w') lines = [line.lower() for line in lines] with open('FortInventory.txt', 'w') as out: out.writelines(sorted(lines)) </code></pre> <p>I am trying to convert all text in a txt file to lowercase how would i go about doing this, here is the code i have so far and i looked at some questions on stack overflow but i couldnt quite figure it out, if anyone could link me to the right article or tell me what is wrong with my code i would greatly appreciate it.</p>
0
2016-08-12T02:33:00Z
38,909,005
<p>Two problems:</p> <ol> <li>Open the file with <code>'r'</code> for read.</li> <li>Change <code>lines</code> to <code>file</code> in your list comprehension.</li> </ol> <p>Here's the fixed code:</p> <pre><code>from itertools import chain from glob import glob file = open('FortInventory.txt', 'r') lines = [line.lower() for line in file] with open('FortInventory.txt', 'w') as out: out.writelines(sorted(lines)) </code></pre>
1
2016-08-12T02:37:44Z
[ "python" ]
npm i -g letsencrypt-cli openshift bronze fedora
38,908,978
<p>I'm trying to emulate <a href="https://community.letsencrypt.org/t/how-to-use-openshift-paas-with-lets-encrypt-solved/9832" rel="nofollow">implementation of letsencrypt on Openshift server</a> initialized/configured for Node.js.</p> <p>After failing to install pip with yum, I looked for a similar client to the one referred in the article and identified <a href="https://github.com/Daplie/letsencrypt-cli" rel="nofollow">the letsencrypt-cli package on npm</a>.</p> <p>Unfortunately, I can't install the client due to or change the permissions:</p> <pre><code>\&gt; npm install -g letsencrypt-cli@2.x npm ERR! tar.unpack untar error /var/lib/openshift/../.npm/letsencrypt-cli/2.1.2/package.tgz npm ERR! Linux 2.6.32-573.12.1.el6.x86_64 npm ERR! argv "node" "/opt/rh/nodejs010/root/usr/bin/npm" "install" "-g" "letsencrypt-cli@2.x" npm ERR! node v0.10.35 npm ERR! npm v2.14.13 npm ERR! path /opt/rh/nodejs010/root/usr/lib/node_modules/letsencrypt-cli npm ERR! code EACCES npm ERR! errno 3 npm ERR! Error: EACCES, mkdir '/opt/rh/nodejs010/root/usr/lib/node_modules/letsencrypt-cli' npm ERR! { [Error: EACCES, mkdir '/opt/rh/nodejs010/root/usr/lib/node_modules/letsencrypt-cli'] npm ERR! errno: 3, npm ERR! code: 'EACCES', npm ERR! path: '/opt/rh/nodejs010/root/usr/lib/node_modules/letsencrypt-cli', npm ERR! fstream_type: 'Directory', npm ERR! fstream_path: '/opt/rh/nodejs010/root/usr/lib/node_modules/letsencrypt-cli', npm ERR! fstream_class: 'DirWriter', npm ERR! fstream_stack: npm ERR! [ '/opt/rh/nodejs010/root/usr/lib/node_modules/fstream/lib/dir-writer.js:36:23', npm ERR! '/opt/rh/nodejs010/root/usr/lib/node_modules/mkdirp/index.js:46:53', npm ERR! 'Object.oncomplete (fs.js:108:15)' ] } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! Linux 2.6.32-573.12.1.el6.x86_64 npm ERR! argv "node" "/opt/rh/nodejs010/root/usr/bin/npm" "install" "-g" "letsencrypt-cli@2.x" npm ERR! node v0.10.35 npm ERR! npm v2.14.13 npm ERR! path npm-debug.log... npm ERR! code EACCES npm ERR! errno 3 npm ERR! Error: EACCES, open 'npm-debug.log...' npm ERR! { [Error: EACCES, open 'npm-debug.log...'] npm ERR! errno: 3, npm ERR! code: 'EACCES', npm ERR! path: 'npm-debug.log...' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! Please include the following file with any support request: npm ERR! /var/lib/openshift/../npm-debug.log </code></pre> <p>Would anyone happen to know if a more appropriate package or workaround to this issue exists ?</p>
0
2016-08-12T02:34:24Z
38,910,821
<p>There's a couple of ways you might be able to fix the permission problems with npm:</p> <p>You can change the permissions to match your user:</p> <pre><code>sudo chown -R $(whoami) ~/node* # ~/node_modules sudo chown -R $(whoami) ~/.node* # .node-gyp sudo chown -R $(whoami) ~/.npm* # .npm .npmrc sudo chown -R $(whoami) /usr/local/*/*node* # node node_modules sudo chown -R $(whoami) /usr/local/*/*npm* # npm </code></pre> <p>You can set the NODE_PATH environment variable for the user and application that you're running:</p> <pre><code>export NODE_PATH=${HOME}/node_modules </code></pre> <p>You can also change your npm settings:</p> <p><a href="https://docs.npmjs.com/getting-started/fixing-npm-permissions" rel="nofollow">https://docs.npmjs.com/getting-started/fixing-npm-permissions</a></p>
1
2016-08-12T05:51:24Z
[ "python", "node.js", "openshift", "lets-encrypt" ]
Pyscopg2 SSL Anaconda Support not compiled in
38,909,000
<p>I am having the following issue with psycopg2. I am connect to a remote postgres server that is running 9.4.5. </p> <p>I get the following error when I use SSLmode:required</p> <blockquote> <p>OperationalError: (psycopg2.OperationalError) sslmode value "require" >invalid when SSL support is not compiled in</p> </blockquote> <p>I am running Anaconda fully updated with psycopg2. I have deleted and reinstall Anaconda, removed and re-installed pip install psycopg2. Followed the brew install / brew uninstall suggested.</p> <p>I have looked into the following threads from stack ==> <a href="http://stackoverflow.com/questions/34684376/psycopg2-python-ssl-support-is-not-compiled-in">Psycopg2 Python SSL Support is not compiled in</a> as well as many other resources on the internet without success. </p> <p>If anyone can help me out that would be fantastic - I feel like I have maxed out on my own abiliti to resolve this - hence I am posting up on Stack! Thanks</p>
0
2016-08-12T02:37:23Z
38,922,827
<p>@cel resolved this for me in the comment thread above. </p> <p>After working through all the different options it looks like using the </p> <blockquote> <p>conda install -c conda-forge psycopg2=2.6.2 solution is the workaround that indeed worked for me. </p> </blockquote> <p>If anyone has other resolutions let me know and I will add them here. I hope noone has the same issues.</p>
0
2016-08-12T16:40:57Z
[ "python", "postgresql", "ssl", "anaconda", "psycopg2" ]
python-django: adding math in my views.py?
38,909,011
<p>Do I need to import some kind of module to do math in my views.py?</p> <pre><code>def calc(request): if 'pv' in request.GET and 'r' in request.GET: pv = request.GET['pv'] r = request.GET['r'] calcPV = pv * r return render(request, 'main/index.html', { 'pv': pv, 'r': r, 'calcPV': calcPV, }) return render(request, 'main/index.html') </code></pre> <p>For example purposes, I'm trying to do a simple multiplication: <code>calcPV = pv * r</code> but its not working. Am I doing this wrong?</p> <p>Thanks</p>
-1
2016-08-12T02:38:31Z
38,909,155
<p>You don't need to import any module to do a multiplication.</p> <p>You might have to cast your parameters first. For example:</p> <p><code>pv = int(request.GET['pv'])</code></p> <p>In the HTML, you can show the results like this:</p> <pre><code>{{ calcPV }} </code></pre>
0
2016-08-12T02:59:23Z
[ "python", "django", "math" ]
core dump from pyinstaller binary
38,909,028
<p>Is there anyway to use gdb to analyse a core dump created by a pyinstaller binary? I am packaging python/C++ files into one binary and gdb cannot read the symbols from python or the binary.</p> <p>I have tried and receive only question marks from gdb.</p> <pre><code>gdb $(which python) -c core gdb my_binary -c core </code></pre>
2
2016-08-12T02:40:18Z
38,933,856
<blockquote> <p>I have tried and receive only question marks from gdb.</p> </blockquote> <p>There could be 2 reasons of this:</p> <ol> <li>You probably mismatched core dump and binary which generated it. Try these commands to find out exact path to binary: <code>file core</code> or <code>gdb -c core</code>. By the way it should be path to python binary.</li> <li>gdb can't find symbols and unable to show meaningful function names in stack trace. Try to install debug symbols for python in your OS with <code>apt-get</code> or <code>yum/dnf</code>.</li> </ol>
0
2016-08-13T14:44:49Z
[ "python", "gdb", "pyinstaller" ]
core dump from pyinstaller binary
38,909,028
<p>Is there anyway to use gdb to analyse a core dump created by a pyinstaller binary? I am packaging python/C++ files into one binary and gdb cannot read the symbols from python or the binary.</p> <p>I have tried and receive only question marks from gdb.</p> <pre><code>gdb $(which python) -c core gdb my_binary -c core </code></pre>
2
2016-08-12T02:40:18Z
39,668,871
<p>Using the python binary with a core file from a binary generated by <code>pyinstaller</code> is incorrect. Output from the <code>file</code> command will confirm this:</p> <pre><code>core: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from './build_id/build/build_id/build_id', </code></pre> <p>(I omitted the end of that output line for brevity).</p> <p>The core file used with that <code>file</code> command came from an attempt to use <code>pyinstaller</code> on <code>build_id.py</code>, hence the occurrence of the name <code>build_id</code> within the pathname.</p> <p>Assuming <code>my_binary</code> represents the result of your attempt to use <code>pyinstaller</code>, it is the correct binary to use with a core file from that attempt. I have compared build IDs from my core file against all of the mapped files, and they all match. Here is output from a verbose invocation of my <code>build_id.py</code> on my core file:</p> <pre><code>0000000000400000 63116679c3030438046175bc610d21cbd50fbac0 /home/eirik/git/pyinstaller/build_id/build/build_id/build_id 00007f042f80d000 377b0152081112c82460680fe99ec01aa090cd81 /lib/x86_64-linux-gnu/libc-2.24.so 00007f042fbab000 adcc4a5e27d5de8f0bc3c6021b50ba2c35ec9a8e /lib/x86_64-linux-gnu/libz.so.1.2.8 00007f042fdc6000 4e43c23036c6bfd2d4dab183e458e29d87234adc /lib/x86_64-linux-gnu/libdl-2.24.so 00007f042ffca000 a731640ef1cd73c1d727c2a9521b10cafec33c15 /lib/x86_64-linux-gnu/ld-2.24.so </code></pre> <p>Output from the <code>file</code> command on any one of those pathnames reports the same build ID seen in the output line for that file. Furthermore, the build ID reported for my <code>build_id</code> binary matches the build ID for the following file, provided by <code>pyinstaller</code>:</p> <pre><code>PyInstaller/bootloader/Linux-64bit/run </code></pre> <p>It appears that <code>pyinstaller</code> uses <code>objcopy</code> to build a binary using that <code>run</code> file as a prefix. In addition to reporting the build ID of that <code>run</code> file, the <code>file</code> command also tells me it's stripped, which is consistent with the backtrace I get from gdb:</p> <pre><code>Core was generated by `./build_id/build/build_id/build_id'. Program terminated with signal SIGSEGV, Segmentation fault. #0 strlen () at ../sysdeps/x86_64/strlen.S:106 106 ../sysdeps/x86_64/strlen.S: No such file or directory. (gdb) backtrace #0 strlen () at ../sysdeps/x86_64/strlen.S:106 #1 0x00007f042f8424d9 in __add_to_environ (name=0x405da8 "LD_LIBRARY_PATH_ORIG", value=0x0, combined=0x0, replace=1) at setenv.c:131 #2 0x0000000000404688 in ?? () #3 0x0000000000402db3 in ?? () #4 0x00007f042f82d2b1 in __libc_start_main (main=0x401950, argc=1, argv=0x7fffc57143c8, init=&lt;optimized out&gt;, fini=&lt;optimized out&gt;, rtld_fini=&lt;optimized out&gt;, stack_end=0x7fffc57143b8) at ../csu/libc-start.c:291 #5 0x000000000040197e in ?? () (gdb) x/i $pc =&gt; 0x7f042f88d496 &lt;strlen+38&gt;: movdqu (%rax),%xmm4 (gdb) i r rax rax 0x0 0 (gdb) </code></pre> <p>Something in the bootloader (that <code>run</code> file) is calling <code>__add_to_environ</code> (perhaps via <code>setenv</code>, which has a <code>jmpq</code> to <code>__add_to_environ</code>), which then passes a null pointer to <code>strlen</code> (presumably that null pointer originated within <code>run</code>). All of the occurrences of <code>??</code> in that backtrace are from the <code>run</code> file (their addresses all begin with <code>0x00000000004</code>).</p> <p>If I run the binary with <code>LD_LIBRARY_PATH=/tmp</code>, I no longer get a core dump, so I'm guessing that null pointer is the return value of <code>getenv("LD_LIBRARY_PATH")</code>. Also, I see this in <code>bootloader/src/pyi_utils.c</code> (in <code>set_dynamic_library_path</code>):</p> <pre><code> orig_path = pyi_getenv(env_var); pyi_setenv(env_var_orig, orig_path); </code></pre> <p>The best hope of making sense of a crash like this, short of relying on debug symbols from <code>libc</code>, might be to build the bootloader (the <code>run</code> file) from source code and set aside its debug symbols and load those into gdb, invoked upon an executable built from that bootloader, and a core file from it. It's important in such a case to use the bootloader built from source rather than the one distributed with <code>pyinstaller</code> (both with gdb, and to build the binary), unless the build ID happens to match (between the distributed <code>run</code> and the one built from source). If using a stripped bootloader is unnecessary, it might be easier to just not strip the <code>run</code> file, but that might be more work than loading the debug symbols separately.</p> <p>It might make sense for <code>pyinstaller</code> to include debug symbols for each included bootloader (for all I know, it does that and I just haven't found them yet, but offhand I doubt that). If you want gdb to use debug symbols for <code>libc</code>, part of that might involve installing a separate package. On my Debian system that package is <code>libc6-dbg</code>. I briefly looked into building the pyinstaller bootloader with debug symbols, but I haven't finished deciphering <code>waf</code> yet.</p>
1
2016-09-23T20:15:34Z
[ "python", "gdb", "pyinstaller" ]
Python Rainfall Calculator
38,909,156
<p>I'm trying to solve a problem but I've been working on it for so long and have tried so many things but I'm really new to python and don't know how to get the input I'm after.</p> <p>The calculator needs to be in a format of a nested loop. First it should ask for the number of weeks for which rainfall should be calculated. The outer loop will iterate once for each week. The inner loop will iterate seven times, once for each day of the week. Each itteration of the inner loop should ask the user to enter number of mm of rain for that day. Followed by calculations for total rainfall, average for each week and average per day. </p> <p>The main trouble I'm having is getting the input of how many weeks there are and the days of the week to iterate in the program eg:</p> <pre><code>Enter the amount of rain (in mm) for Friday of week 1: 5 Enter the amount of rain (in mm) for Saturday of week 1: 6 Enter the amount of rain (in mm) for Sunday of week 1: 7 Enter the amount of rain (in mm) for Monday of week 2: 7 Enter the amount of rain (in mm) for Tuesday of week 2: 6 </code></pre> <p>This is the type out output I want but so far I have no idea how to get it to do what I want. I think I need to use a dictionary but I'm not sure how to do that. This is my code thus far:</p> <pre><code>ALL_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] total_rainfall = 0 total_weeks = 0 rainfall = {} # Get the number of weeks. while True: try: total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: ")) except ValueError: print("Number of weeks must be an integer.") continue if total_weeks &lt; 1: print("Number of weeks must be at least 1") continue else: # age was successfully parsed and we're happy with its value. # we're ready to exit the loop! break for total_rainfall in range(total_weeks): for mm in ALL_DAYS: mm = int(input("Enter the amount of rain (in mm) for ", ALL_DAYS, "of week ", range(total_weeks), ": ")) if mm != int(): print("Amount of rain must be an integer") elif mm &lt; 0 : print("Amount of rain must be non-negative") # Calculate totals. total_rainfall =+ mm average_weekly = total_rainfall / total_weeks average_daily = total_rainfall / (total_weeks*7) # Display results. print ("Total rainfall: ", total_rainfall, " mm ") print("Average rainfall per week: ", average_weekly, " mm ") print("Average rainfall per week: ", average_daily, " mm ") if __name__=="__main__": __main__() </code></pre> <p>If you can steer me in the right direction I will be so appreciative! </p>
0
2016-08-12T02:59:27Z
38,909,948
<p>I use a list to store average rallfall for each week. and my loop is:</p> <p>1.while loop ---> week (using i to count)</p> <p>2.in while loop: initialize week_sum=0, then use for loop to ask rainfall of 7 days.</p> <p>3.Exit for loop ,average the rainfall, and append to the list weekaverage.</p> <p>4.add week_sum to the total rainfall, and i+=1 to next week</p> <pre><code>weekaverage=[] i = 0 #use to count week while i&lt;total_weeks: week_sum = 0. print "---------------------------------------------------------------------" for x in ALL_DAYS: string = "Enter the amount of rain (in mm) for %s of week #%i : " %(x,i+1) mm = float(input(string)) week_sum += mm weekaverage.append(weeksum/7.) total_rainfall+=week_sum print "---------------------------------------------------------------------" i+=1 print "Total rainfall: %.3f" %(total_rainfall) print "Day average is %.3f mm" %(total_rainfall/total_weeks/7.) a = 0 for x in weekaverage: print "Average for week %s is %.3f mm" %(a,x) a+=1 </code></pre>
0
2016-08-12T04:30:42Z
[ "python", "calculator" ]
Python Rainfall Calculator
38,909,156
<p>I'm trying to solve a problem but I've been working on it for so long and have tried so many things but I'm really new to python and don't know how to get the input I'm after.</p> <p>The calculator needs to be in a format of a nested loop. First it should ask for the number of weeks for which rainfall should be calculated. The outer loop will iterate once for each week. The inner loop will iterate seven times, once for each day of the week. Each itteration of the inner loop should ask the user to enter number of mm of rain for that day. Followed by calculations for total rainfall, average for each week and average per day. </p> <p>The main trouble I'm having is getting the input of how many weeks there are and the days of the week to iterate in the program eg:</p> <pre><code>Enter the amount of rain (in mm) for Friday of week 1: 5 Enter the amount of rain (in mm) for Saturday of week 1: 6 Enter the amount of rain (in mm) for Sunday of week 1: 7 Enter the amount of rain (in mm) for Monday of week 2: 7 Enter the amount of rain (in mm) for Tuesday of week 2: 6 </code></pre> <p>This is the type out output I want but so far I have no idea how to get it to do what I want. I think I need to use a dictionary but I'm not sure how to do that. This is my code thus far:</p> <pre><code>ALL_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] total_rainfall = 0 total_weeks = 0 rainfall = {} # Get the number of weeks. while True: try: total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: ")) except ValueError: print("Number of weeks must be an integer.") continue if total_weeks &lt; 1: print("Number of weeks must be at least 1") continue else: # age was successfully parsed and we're happy with its value. # we're ready to exit the loop! break for total_rainfall in range(total_weeks): for mm in ALL_DAYS: mm = int(input("Enter the amount of rain (in mm) for ", ALL_DAYS, "of week ", range(total_weeks), ": ")) if mm != int(): print("Amount of rain must be an integer") elif mm &lt; 0 : print("Amount of rain must be non-negative") # Calculate totals. total_rainfall =+ mm average_weekly = total_rainfall / total_weeks average_daily = total_rainfall / (total_weeks*7) # Display results. print ("Total rainfall: ", total_rainfall, " mm ") print("Average rainfall per week: ", average_weekly, " mm ") print("Average rainfall per week: ", average_daily, " mm ") if __name__=="__main__": __main__() </code></pre> <p>If you can steer me in the right direction I will be so appreciative! </p>
0
2016-08-12T02:59:27Z
38,909,982
<p>Recommendation: Break the problem into smaller pieces. Best way to do that would be with individual functions. </p> <p>For example, getting the number of weeks </p> <pre><code>def get_weeks(): total_weeks = 0 while True: try: total_weeks = int(input("Enter the number of weeks for which rainfall should be calculated: ")) if total_weeks &lt; 1: print("Number of weeks must be at least 1") else: break except ValueError: print("Number of weeks must be an integer.") return total_weeks </code></pre> <p>Then, getting the mm input for a certain week number and day. (Here is where your expected output exists)</p> <pre><code>def get_mm(week_num, day): mm = 0 while True: try: mm = int(input("Enter the amount of rain (in mm) for {0} of week {1}: ".format(day, week_num))) if mm &lt; 0: print("Amount of rain must be non-negative") else: break except ValueError: print("Amount of rain must be an integer") return mm </code></pre> <p>Two functions to calculate the average. First for a list, the second for a list of lists. </p> <pre><code># Accepts one week of rainfall def avg_weekly_rainfall(weekly_rainfall): if len(weekly_rainfall) == 0: return 0 return sum(weekly_rainfall) / len(weekly_rainfall) # Accepts several weeks of rainfall: [[1, 2, 3], [4, 5, 6], ...] def avg_total_rainfall(weeks): avgs = [ avg_weekly_rainfall(w) for w in weeks ] return avg_weekly_rainfall( avgs ) </code></pre> <p>Using those, you can build your weeks of rainfall into their own list. </p> <pre><code># Build several weeks of rainfall def get_weekly_rainfall(): total_weeks = get_weeks() total_rainfall = [] for week_num in range(total_weeks): weekly_rainfall = [0]*7 total_rainfall.append(weekly_rainfall) for i, day in enumerate(ALL_DAYS): weekly_rainfall[i] += get_mm(week_num+1, day) return total_rainfall </code></pre> <p>Then, you can write a function that accepts that "master list", and prints out some results. </p> <pre><code># Print the output of weeks of rainfall def print_results(total_rainfall): total_weeks = len(total_rainfall) print("Weeks of rainfall", total_rainfall) for week_num in range(total_weeks): avg = avg_weekly_rainfall( total_rainfall[week_num] ) print("Average rainfall for week {0}: {1}".format(week_num+1, avg)) print("Total average rainfall:", avg_total_rainfall(total_rainfall)) </code></pre> <p>And, finally, just two lines to run the full script. </p> <pre><code>weekly_rainfall = get_weekly_rainfall() print_results(weekly_rainfall) </code></pre>
0
2016-08-12T04:34:27Z
[ "python", "calculator" ]
Virtual Environment "no module named" error
38,909,173
<p>I have a virtual environment set up running Python 3.5. I ran my source command and ran pip to install beatbox:</p> <pre><code>(venv) Daniels-Air:bin danieldow$ pip list beatbox (32.1) pip (8.1.2) requests (2.11.0) setuptools (25.1.6) six (1.10.0) slack (0.0.2) slackclient (1.0.1) websocket-client (0.37.0) wheel (0.29.0) </code></pre> <p>However, when I try to import I get:</p> <pre><code> (venv) Daniels-Air:bin danieldow$ python3 Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import beatbox Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/danieldow/venv-python3/venv/lib/python3.5/site-packages/beatbox/__init__.py", line 1, in &lt;module&gt; from _beatbox import _tPartnerNS, _tSObjectNS, _tSoapNS, SoapFaultError, SessionTimeoutError ImportError: No module named '_beatbox' </code></pre> <p>In the directory for beatbox in site packages the -beatbox module is there:</p> <pre><code>(venv) Daniels-Air:site-packages danieldow$ pwd /Users/danieldow/venv-python3/venv/lib/python3.5/site-packages (venv) Daniels-Air:site-packages danieldow$ cd beatbox (venv) Daniels-Air:beatbox danieldow$ ls __init__.py _beatbox.py python_client.py __pycache__ marshall.py xmltramp.py </code></pre> <p>Can someone tell mw what I'm doing wrong or anything I can try?</p> <p>Thanks!</p> <p>Dan</p> <p>*PS In Pycharm, under interpreter, it does show the package as being installed.</p>
0
2016-08-12T03:02:16Z
38,909,449
<p>Problem was that beatbox was written for Python 2.x. 'pip instal beatbox3' and it worked.</p>
1
2016-08-12T03:30:11Z
[ "python", "python-3.x", "virtualenv" ]
Virtual Environment "no module named" error
38,909,173
<p>I have a virtual environment set up running Python 3.5. I ran my source command and ran pip to install beatbox:</p> <pre><code>(venv) Daniels-Air:bin danieldow$ pip list beatbox (32.1) pip (8.1.2) requests (2.11.0) setuptools (25.1.6) six (1.10.0) slack (0.0.2) slackclient (1.0.1) websocket-client (0.37.0) wheel (0.29.0) </code></pre> <p>However, when I try to import I get:</p> <pre><code> (venv) Daniels-Air:bin danieldow$ python3 Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import beatbox Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/danieldow/venv-python3/venv/lib/python3.5/site-packages/beatbox/__init__.py", line 1, in &lt;module&gt; from _beatbox import _tPartnerNS, _tSObjectNS, _tSoapNS, SoapFaultError, SessionTimeoutError ImportError: No module named '_beatbox' </code></pre> <p>In the directory for beatbox in site packages the -beatbox module is there:</p> <pre><code>(venv) Daniels-Air:site-packages danieldow$ pwd /Users/danieldow/venv-python3/venv/lib/python3.5/site-packages (venv) Daniels-Air:site-packages danieldow$ cd beatbox (venv) Daniels-Air:beatbox danieldow$ ls __init__.py _beatbox.py python_client.py __pycache__ marshall.py xmltramp.py </code></pre> <p>Can someone tell mw what I'm doing wrong or anything I can try?</p> <p>Thanks!</p> <p>Dan</p> <p>*PS In Pycharm, under interpreter, it does show the package as being installed.</p>
0
2016-08-12T03:02:16Z
38,909,971
<p>You have soluted this problem. But I will tell you some thing more.</p> <p>In Python, please run these code:</p> <pre><code>import sys print(sys.path) </code></pre> <p>this will print the environment variable. If you find these environment variable is your system Python's instead of your venv Python, then the reason must one of these two reasons:</p> <ol> <li>you have writen alias in <code>.zshrc</code>, and point <code>python</code> to system's python path. If so, just delete the alias.</li> <li>the softlink of your python in venv is broken. it can not find the right place of python binary. If so, rebuild the softlink or recreate a venv and use the parameter: --copy <code>virutalenv venv --copy</code></li> </ol>
1
2016-08-12T04:32:54Z
[ "python", "python-3.x", "virtualenv" ]
How to move one dimension of a numpy matrix?
38,909,243
<p>I have a matrix <code>A</code> of shape <code>(480, 640, 3)</code>, and I would like to use the values to populate another matrix <code>B</code>, of shape <code>(3, 480, 640)</code>. I've tried <code>numpy.reshape(A, B.shape)</code>, but I think this is not doing the trick.</p> <p>For some context, the 480 and 640 dimensions are the frame height and width of an image, and the 3 dimension is for the color (RGB) values.</p> <p>(I'm looking for an efficient way of doing this, not a bunch of nested for loops.)</p>
1
2016-08-12T03:09:56Z
38,909,339
<p>I think that you want to swap or roll the axes. Let's start with an 3-D array:</p> <pre><code>&gt;&gt;&gt; mat = np.arange(24).reshape(2, 4, 3) &gt;&gt;&gt; mat.shape (2, 4, 3) </code></pre> <p>Now, let's reorder the axes with swapaxes:</p> <pre><code>&gt;&gt;&gt; mat.swapaxes(0, 2).swapaxes(1, 2).shape (3, 2, 4) </code></pre> <p>Or, let's roll the axes:</p> <pre><code>&gt;&gt;&gt; rolled = np.rollaxis(mat, 2) &gt;&gt;&gt; rolled.shape (3, 2, 4) </code></pre>
1
2016-08-12T03:18:54Z
[ "python", "numpy", "matrix" ]
Salary calc app code wont run
38,909,258
<p>i'm trying to make a calculator application that works out and displays the salary and wage in multiple ways but my functions wont run. i get no error messages and the first 'input' works but after that it seems like my functions don't activate. i have tried to manually activate the functions by removing the "if", and "elif" statements and just putting the name of the function.</p> <pre><code>know = input("Enter the letter for the category you know. if you know how much you earn per hour type '1'. if you know how much you earn per week type '2'. if you know your salary type '3'") def wage(): a = input(int("How much do you earn per Hour?")) b = input(int("How many hours do you work per day?")) c = input(int("How many days do you work per week?")) hour = ("you earn £",a, "per hour") day = ("you earn £",a*b, "per day") week = ("you earn £",day*c, "per Week") year = ("your salary is £",week*52, "per year") print (hours) print (day) print (week) print (year) def week(): a = input(int("How much do you earn per week?")) b = input(int("how many hours do you work per day?")) c = input(int("how many days do you work per week")) hour = ("you earn £",(a/c)/c, "per hour") day = ("you earn £",hour*b, "per day") week = ("you earn £",day*c, "per week") year = ("your salary is £",week*52, "per year") print (hours) print (day) print (week) print (year) def year(): a = input(int("how much do you earn per year?")) b = input(int("how many hours do you work per day?")) c = input(int("how many days do you work per week")) hours = ("you earn £",((a/52)/7)/b, "per hour") day = ("you earn £",hour*b, "per day") week = ("you earn £",day*c, "per week") year = ("your salary is £",week*52, "per year") print (hours) print (day) print (week) print (year) if know == "1": wage elif know == "2": week elif know == "3": year else: print("I'm Confused") </code></pre> <p>if anybody could help me it would be greatly appreciated</p>
0
2016-08-12T03:11:35Z
38,909,406
<p>Change <code>wage</code>, <code>week</code>, and <code>year</code> in your if-else to <code>wage()</code>, <code>week()</code>, and <code>year()</code> to actually execute the functions:</p> <pre><code>if know == "1": wage() elif know == "2": week() elif know == "3": year() else: print("I'm Confused") </code></pre>
0
2016-08-12T03:25:25Z
[ "python", "calculator" ]
Numpy: slice matrix to remove one row and column
38,909,274
<p>Given an n by n matrix (technically an np.array) L, I wish to remove the kth row and kth column. This line of code works as expected (it selects the 1st through 3rd rows and columns):</p> <pre><code>Lt = L[(1,2,3),(1,2,3)] </code></pre> <p>When I try to replace (1,2,3) by a dynamically generated tuple excluding the k, it fails:</p> <pre><code>keep = (i for i in range(n) if i != k) Lt = L[keep,keep] # IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices </code></pre> <p>How can I do this properly?</p>
0
2016-08-12T03:12:41Z
38,909,307
<blockquote> <pre><code>keep = (i for i in range(n) if i != k) </code></pre> </blockquote> <p>This is a generator expression, not a generated tuple itself; instead, try</p> <pre><code>keep = tuple(i for i in range(n) if i != k) </code></pre>
2
2016-08-12T03:16:09Z
[ "python", "numpy", "matrix" ]
Is there a way to find a character's Unicode code point in Python 2.7?
38,909,362
<p>I'm working with International Phonetic Alphabet (IPA) symbols in my Python program, a rather strange set of characters whose UTF-8 codes can range anywhere from 1 to 3 bytes long. <a href="http://stackoverflow.com/questions/7291120/python-and-unicode-code-point-extraction">This thread</a> from several years ago basically asked the reverse question and it seems that <code>ord(character)</code> can retrieve a decimal number that I could convert to hex and thereafter to a code point, but the input for <code>ord()</code> seems to be limited to one byte. If I try <code>ord()</code> on any non-ASCII character, like <code>ɨ</code> for example, it outputs:</p> <pre><code>TypeError: ord() expected a character, but a string of length 2 found </code></pre> <p>With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a <code>unicode</code> type?) I don't mean by just manually looking it up on a Unicode table, either.</p>
1
2016-08-12T03:20:22Z
38,909,377
<pre><code>&gt;&gt;&gt; u'ɨ' u'\u0268' &gt;&gt;&gt; u'i' u'i' &gt;&gt;&gt; 'ɨ'.decode('utf-8') u'\u0268' </code></pre>
1
2016-08-12T03:22:06Z
[ "python", "python-2.7", "unicode" ]
Is there a way to find a character's Unicode code point in Python 2.7?
38,909,362
<p>I'm working with International Phonetic Alphabet (IPA) symbols in my Python program, a rather strange set of characters whose UTF-8 codes can range anywhere from 1 to 3 bytes long. <a href="http://stackoverflow.com/questions/7291120/python-and-unicode-code-point-extraction">This thread</a> from several years ago basically asked the reverse question and it seems that <code>ord(character)</code> can retrieve a decimal number that I could convert to hex and thereafter to a code point, but the input for <code>ord()</code> seems to be limited to one byte. If I try <code>ord()</code> on any non-ASCII character, like <code>ɨ</code> for example, it outputs:</p> <pre><code>TypeError: ord() expected a character, but a string of length 2 found </code></pre> <p>With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a <code>unicode</code> type?) I don't mean by just manually looking it up on a Unicode table, either.</p>
1
2016-08-12T03:20:22Z
38,909,529
<blockquote> <p>With that no longer an option, is there any way in Python 2.7 to find the Unicode code point of a given character? (And does that character then have to be a unicode type?) I don't mean by just manually looking it up on a Unicode table, either.</p> </blockquote> <p>You can only find the unicode code point of a unicode object. To convert your byte string to a unicode object, decode it using <code>mystr.decode(encoding)</code>, where <code>encoding</code> is the encoding of your string. (You know the encoding of your string, right? It's probably UTF-8. :-) Then you can use <code>ord</code> according to the instructions you already found.</p> <pre><code>&gt;&gt;&gt; ord(b"ɨ".decode('utf-8')) 616 </code></pre> <p>As an aside, from your question it sounds like you're working with the strings in their UTF-8 encoded bytes form. That's probably going to be a pain. You should decode the strings to unicode objects as soon as you get them, and only encode them if you need to output them somewhere.</p>
4
2016-08-12T03:40:31Z
[ "python", "python-2.7", "unicode" ]
scaling websocket game application server
38,909,407
<p>I'm developing a realtime multi-player game with websocket (Python3 + autobahn) </p> <p>The game will be played in rooms. Players in a single room should be grouped together to allow messaging, game play, etc. So it's more or less like a chat server.</p> <p>I'm having a hard time scaling this to a multi server scenario. I did some searching but wasn't happy with the result I've found.</p> <p>One way I came up with was with nginx + lua.</p> <p>So the idea is that when a player join a particular room, it'll send the room id in the message. With nginx + lua I plan to decide which of the app server instances it should go to. The result is that all players in the same room will eventually end up in the same instance. </p> <p>A few questions:</p> <ol> <li>Can nginx + lua intercept the websocket message and then pass the connection?</li> <li>This will involve hard-coding logic in the reverse proxy layer. And the backend connection will be hard-coded also. Is there a way to make them dynamic?</li> </ol> <p>Any suggestion to whether this is good idea or not is appreciated as well suggestions for better design.</p>
1
2016-08-12T03:25:40Z
38,914,959
<p>If the room ID is in the URL you can use openresty to parse it and then change the proxy_pass target to the desired backend. To do this you would define a variable in nginx, then set it in access_by_lua, and finally proxy pass to the new variable.</p> <p>You can make the lookup dynamic by storing the room ID -> backend server address mapping in your favourite database and reading it with openresty, and even use openresty's shared dicts to cache the mapping so it doesn't hammer the DB.</p> <p>So in the location block of your nginx.conf you would have something like:</p> <pre><code>set $target ''; access_by_lua ' --[[ - parse the url/headers - lookup the room ID in the database --]] ngx.var.target = host '; proxy_pass http://$target; </code></pre> <p>Another option depending on your game would be to move some of the logic itself to openresty since it can handle the websockets directly.</p>
0
2016-08-12T09:49:25Z
[ "python", "nginx", "websocket", "lua" ]
How to do a Python argparse mutually required argument group
38,909,426
<p>I want to write a script that takes optional <code>--foo</code> and <code>--bar</code> arguments. It is legal to specify neither of them. It is also legal to specify both. However, specifying just <code>--foo</code> or just <code>--bar</code> should raise a command line parser error.</p> <p>After I call <code>parser.parse_args()</code> I can write code to check this condition and raise the appropriate error, but is there a way already built into <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow"><code>argparse</code></a> to do this, a sort of converse of <a href="https://docs.python.org/3/library/argparse.html#mutual-exclusion" rel="nofollow"><code>add_mutually_exclusive_group</code></a>?</p>
1
2016-08-12T03:27:22Z
38,909,575
<p>No there isn't that kind of grouping or builtin test, just this one <code>xor</code> test.</p> <p>But it isn't hard to implement the test after parsing - provided your arguments have reasonable defaults (such as the default default <code>None</code>).</p> <p>Another possibility is to define one argument <code>foobar</code> with <code>nargs=2</code> - it requires 2 values.</p> <p>Yet another is to provide one or both with a good default, such that you don't really care whether the user provides both values or not.</p>
2
2016-08-12T03:46:17Z
[ "python", "command-line-interface", "argparse" ]
python assign variable, test, if true skip else, if not re-assign variable
38,909,480
<p>pulling hair out. (sorry frustrated)</p> <p>ok, so i'm trying to do an if: else in python, only i can't get it to work properly so i'm hoping that someone can help. i'll try and be as specific as possible.</p> <p>what i'm tring to do -> i'm assigning a variable to check if something is true, sometimes it is sometimes it's not.</p> <p>if that variable is true then i want it to skip the else statement and print out the result. (once fully implemented it will return resutlt to script instead of printing)</p> <p>python code:</p> <pre><code>import re os_version = open('/etc/os-release') for line in os_version: OS = re.search(r'\AID_LIKE=\D[A-Za-z]+', line) if OS: print(str(OS.group()).lstrip('ID_LIKE="')) else: OS = re.search(r'\AID=\D[A-Za-z]+', line) print(str(OS.group()).lstrip('ID="')) </code></pre> <p>when i run it like this i get a NoneType object has no group</p> <p>if i have an if OS: statement indented under the else, before the print, then i get both results back, even if i have a 'break' after the first print </p> <p>depending on what platform of linux that i'm running on will depend on what the results should be.</p> <p>example (bash code)</p> <pre><code>#!/bin/bash VAR0=`cat /etc/os-release | grep -w ID_LIKE | cut -f2 -d= |\ tr -d [=\"=] | cut -f1 -d' '` VAR0="${VAR0:=`cat /etc/os-release | grep -w ID | cut -f2 -d= |\ tr -d [=\"=]`}" echo $VAR0 if [ "$VAR0" = 'debian' ]; then echo 'DEBIAN based' elif [ "$VAR0" = 'rhel' ]; then echo 'RHEL based' elif [ "$VAR0" = 'suse' ]; then echo 'SUSE based' else echo 'OTHER based' fi </code></pre> <p>this is the return that comes back from the bash code-></p> <pre><code>bash -o xtrace os-version.sh ++ cat /etc/os-release ++ grep -w ID_LIKE ++ cut -f2 -d= ++ tr -d '[="=]' ++ cut -f1 '-d ' + VAR0=rhel + VAR0=rhel + echo rhel rhel + '[' rhel = debian ']' + '[' rhel = rhel ']' + echo 'RHEL based' RHEL based </code></pre> <p>from a different os-></p> <pre><code>bash -o xtrace test_2.sh ++ tr -d '[="=]' ++ cut -f1 '-d ' ++ cut -f2 -d= ++ grep -w ID_LIKE ++ cat /etc/os-release + VAR0= ++ tr -d '[="=]' ++ grep -w ID ++ cut -f2 -d= ++ cat /etc/os-release + VAR0=debian + echo debian debian + '[' debian = debian ']' + echo 'DEBIAN based' DEBIAN based </code></pre> <p>as you can see the VAR0 on the first run is empty and it then goes to the second.</p> <p>that's what i'm trying to do with python.</p> <p>can someone help? i have a feeling that i'm just overlooking something simple after starting at the screen for so long.</p> <p>thanks</p> <p>em</p> <p>edit for joel:</p> <p>my code now and the results=> code:</p> <pre><code>#!/usr/bin/python3 import re os_version = open('/etc/os-release') for line in os_version: OS = re.search(r'\AID_LIKE=\D[A-Za-z]+', line) if OS: print(str(OS.group()).lstrip('ID_LIKE="')) break else: OS = re.search(r'\AID=\D[A-Za-z]+', line) if OS: print(str(OS.group()).lstrip('ID="')) </code></pre> <p>results from a debian system=></p> <pre><code>python test.os-version_2.py debian </code></pre> <p>results from a debian based system=></p> <pre><code>python test.os-version_2.py raspbian debian </code></pre> <p>results from centos7=></p> <pre><code>python test.os-version_2.py centos rhel </code></pre> <p>results from opensuse=></p> <pre><code>python test.os-version_2.py opensuse suse </code></pre> <p>results from linuxmint(what i'm running now, even though it's ubuntu/debian basied)=></p> <pre><code>python test.os-version_2.py linuxmint </code></pre> <p>so since some things are responding differently and there are so many different distro's based off of a couple, i'm trying to narrow down the results to the fewest possible.</p> <p>each one has a different way that they do things and to try and get a script that is cross platform working as best as it can, i'm trying to narrow things down.</p> <p>if you 'cat /etc/os-release' you will see that different os's display things differently.</p> <p>edit answer:</p> <p>i don't know why this is yet for me putting a variable to the print statements and then printing the variable it's working. maybe someone can answer that for me.</p> <p>answer code:</p> <pre><code>#!/usr/bin/python3 import re os_version = open('/etc/os-release') for line in os_version: OS = re.search(r'\AID_LIKE=\D[A-Za-z]+', line)#.group() if OS is not None: base_distro = (str(OS.group()).lstrip('ID_LIKE="')) else: OS = re.search(r'\AID=\D[A-Za-z]+', line)#.group() if OS is not None: base_distro = (str(OS.group()).lstrip('ID="')) print(base_distro) </code></pre> <p>if you put that into a script and then run it you will see what i'm looking for.</p> <p>thanks everyone for helping</p>
-2
2016-08-12T03:34:26Z
38,909,678
<p>Getting the system platform is easy with Python 2.7 see <a href="http://www.pythonforbeginners.com/systems-programming/how-to-use-the-platform-module-in-python" rel="nofollow">platform import</a></p> <pre><code>import platform print platform.dist()[0],type(platform.dist()[0]) </code></pre> <p>returns</p> <pre><code>debian &lt;type 'str'&gt; </code></pre> <p>On my platform.</p> <p>To clarify - <code>OS = re.search(r'\AID_LIKE=\D[A-Za-z]+', line)</code> returns an object (NoneType)</p> <p>Note "import platform" will be depreciated. Below is method with the new way (just a basic method, might not be suitable to all situations, but it works for what i think you have described - to do your comparisons, just use a <code>dict</code> like in the comments</p> <p>Edit - Super simple way - using subprocess if platform doesn't work</p> <pre><code>import subprocess output = subprocess.check_output(["cat", "etc/os-release"]) with open('text.txt', 'w+') as fd: fd.write(output) with open('text.txt', 'r') as text_output: for os_version in text_output: try: print os_version.split("ID_LIKE=",1)[1] except: continue </code></pre> <p>Here we just call the actual command, take the output as a string, chuck it in a file, and read all the lines, splice the line at the key word we want and bam! Want the OS ID? Then add <code>print os_version.split("ID=",1)[1]</code> </p> <p>Again the output is: debian raspberry pi </p>
1
2016-08-12T04:00:36Z
[ "python" ]
SqlAlchemy can't find record
38,909,523
<p>I have a table called <code>DR</code> with columns <code>dag_id</code>, <code>execution_date</code>, and <code>run_id</code>. I'd like to find a specific record that I know to exist in the table.</p> <p>In my unit tests, I create one entry in the table and then try to find it again. </p> <pre><code>tmp = session.query(DR).filter(DR.dag_id == self.dag_id).first() print(self.dag_id == tmp.dag_id) print(self.execution_date == tmp.execution_date) print(self.run_id == tmp.run_id) </code></pre> <p>All three print statements print true, but then when perform the following query, no records are found:</p> <pre><code>session.query(DR).filter( DR.dag_id == self.dag_id, DR.execution_date == self.execution_date, DR.run_id == self.run_id ).first() </code></pre> <p>Does anyone know why this is happening?</p> <p>Thanks!</p>
0
2016-08-12T03:40:02Z
38,910,190
<p>Have you tried the following query?</p> <pre><code>session.query(DR).filter( DR.dag_id == self.dag_id, DR.run_id == self.run_id ).first() </code></pre> <p>If that works the problem may be python datetime equality is being evaluated differently to your database datetime equality.</p>
1
2016-08-12T04:52:40Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Python3 - How to convert a string to hex
38,909,543
<p>I am trying to convert a string to hex character by character, but I cant figure it out in Python3.</p> <p>In older python versions, what I have below works:</p> <pre><code>test = "This is a test" for c in range(0, len(test) ): print( "0x%s"%string_value[i].encode("hex") ) </code></pre> <p>But with python3 I am getting the following error: </p> <p>LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs.</p> <p>Can anyone help to tell me what the conversion would be in python3.</p> <p>Thanks in advance</p>
1
2016-08-12T03:42:13Z
38,909,568
<p>In python 3x Use <a href="https://docs.python.org/3.1/library/binascii.html" rel="nofollow"><code>binascii</code></a> instead of hex: </p> <pre><code>&gt;&gt;&gt; import binascii &gt;&gt;&gt; binascii.hexlify(b'&lt; character / string&gt;') </code></pre>
2
2016-08-12T03:45:14Z
[ "python", "python-3.x" ]
Python3 - How to convert a string to hex
38,909,543
<p>I am trying to convert a string to hex character by character, but I cant figure it out in Python3.</p> <p>In older python versions, what I have below works:</p> <pre><code>test = "This is a test" for c in range(0, len(test) ): print( "0x%s"%string_value[i].encode("hex") ) </code></pre> <p>But with python3 I am getting the following error: </p> <p>LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs.</p> <p>Can anyone help to tell me what the conversion would be in python3.</p> <p>Thanks in advance</p>
1
2016-08-12T03:42:13Z
38,909,584
<p>How about:</p> <pre><code>&gt;&gt;&gt; test = "This is a test" &gt;&gt;&gt; for c in range(0, len(test) ): ... print( "0x%x"%ord(test[c])) ... 0x54 0x68 0x69 0x73 0x20 0x69 0x73 0x20 0x61 0x20 0x74 0x65 0x73 0x74 </code></pre>
1
2016-08-12T03:47:40Z
[ "python", "python-3.x" ]
Python3 - How to convert a string to hex
38,909,543
<p>I am trying to convert a string to hex character by character, but I cant figure it out in Python3.</p> <p>In older python versions, what I have below works:</p> <pre><code>test = "This is a test" for c in range(0, len(test) ): print( "0x%s"%string_value[i].encode("hex") ) </code></pre> <p>But with python3 I am getting the following error: </p> <p>LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs.</p> <p>Can anyone help to tell me what the conversion would be in python3.</p> <p>Thanks in advance</p>
1
2016-08-12T03:42:13Z
38,909,605
<p>To print:</p> <pre><code>for c in test: print(hex(ord(c))) </code></pre> <p>To convert:</p> <pre><code>output = ''.join(hex(ord(c)) for c in test) </code></pre> <p>or without the '0x' in output:</p> <pre><code>output = ''.join(hex(ord(c))[2:] for c in test) </code></pre>
0
2016-08-12T03:50:23Z
[ "python", "python-3.x" ]
python merge duplicates in a single list and combine the results
38,909,576
<p>ive got a list in python that looks like </p> <pre><code>['Nickey, 20', 'John, 50', 'Nickey, 30'] </code></pre> <p>i simply want it to remove the duplicates however, combine the numbers so the result is </p> <pre><code>['Nickey, 50', 'John, 50'] </code></pre> <p>i've tried the following </p> <pre><code>A = {'a':1, 'b':2, 'c':3} B = {'b':3, 'c':4, 'd':5} c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)} print c </code></pre> <p>but as you can see the list is differently formatted, i pulled mine from a txt file...</p> <p>Is there a way to use get, set, union but with my formatting of a list - and can i do it with one list instead of merging 2</p>
4
2016-08-12T03:46:24Z
38,909,641
<p>One approach is to create a dictionary to store the total count per name:</p> <pre><code>from collections import defaultdict people = ['Nickey, 20', 'John, 50', 'Nickey, 30'] people_map = defaultdict(int) for person in people: name, number_str = person.split(', ') people_map[name] += int(number_str) print ['{}, {}'.format(person, total) for person, total in people_map.iteritems()] </code></pre>
1
2016-08-12T03:55:14Z
[ "python" ]
python merge duplicates in a single list and combine the results
38,909,576
<p>ive got a list in python that looks like </p> <pre><code>['Nickey, 20', 'John, 50', 'Nickey, 30'] </code></pre> <p>i simply want it to remove the duplicates however, combine the numbers so the result is </p> <pre><code>['Nickey, 50', 'John, 50'] </code></pre> <p>i've tried the following </p> <pre><code>A = {'a':1, 'b':2, 'c':3} B = {'b':3, 'c':4, 'd':5} c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)} print c </code></pre> <p>but as you can see the list is differently formatted, i pulled mine from a txt file...</p> <p>Is there a way to use get, set, union but with my formatting of a list - and can i do it with one list instead of merging 2</p>
4
2016-08-12T03:46:24Z
38,909,688
<pre><code>a = [ 'Nickey, 20', 'John, 50', 'Nickey, 30' ] d = dict() t = list() for i in a: t = i.split( ", " ) d[t[0]] = d.get( t[0], 0 ) + int(t[1]) print( [ ", ".join([k,str(v)]) for k,v in d.items() ] ) </code></pre> <p>This will give following result</p> <p><code>['Nickey, 50', 'John, 50']</code></p>
0
2016-08-12T04:01:51Z
[ "python" ]
python merge duplicates in a single list and combine the results
38,909,576
<p>ive got a list in python that looks like </p> <pre><code>['Nickey, 20', 'John, 50', 'Nickey, 30'] </code></pre> <p>i simply want it to remove the duplicates however, combine the numbers so the result is </p> <pre><code>['Nickey, 50', 'John, 50'] </code></pre> <p>i've tried the following </p> <pre><code>A = {'a':1, 'b':2, 'c':3} B = {'b':3, 'c':4, 'd':5} c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)} print c </code></pre> <p>but as you can see the list is differently formatted, i pulled mine from a txt file...</p> <p>Is there a way to use get, set, union but with my formatting of a list - and can i do it with one list instead of merging 2</p>
4
2016-08-12T03:46:24Z
38,910,019
<p>We should use <a href="https://docs.python.org/3/library/functools.html#functools.reduce" rel="nofollow"><code>reduce</code></a> here.</p> <pre><code>from collections import defaultdict # below required for Python 3 # from functools import reduce data = ['Nickey, 20', 'John, 50', 'Nickey, 30'] def accum(sums, p): sums[p[0]] += int(p[1]) return sums cum = reduce(accum, [s.split(', ') for s in data], defaultdict(int)) print(cum) </code></pre> <p>Alternatively, we can use <a href="https://docs.python.org/3/library/collections.html?highlight=counter#collections.Counter" rel="nofollow"><code>collections.Counter</code></a>:</p> <pre><code>from collections import Counter import operator cum = reduce(operator.iadd, (Counter({k: int(v)}) for k, v in (s.split(', ') for s in data)), Counter()) print(cum) </code></pre>
1
2016-08-12T04:37:29Z
[ "python" ]
python merge duplicates in a single list and combine the results
38,909,576
<p>ive got a list in python that looks like </p> <pre><code>['Nickey, 20', 'John, 50', 'Nickey, 30'] </code></pre> <p>i simply want it to remove the duplicates however, combine the numbers so the result is </p> <pre><code>['Nickey, 50', 'John, 50'] </code></pre> <p>i've tried the following </p> <pre><code>A = {'a':1, 'b':2, 'c':3} B = {'b':3, 'c':4, 'd':5} c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)} print c </code></pre> <p>but as you can see the list is differently formatted, i pulled mine from a txt file...</p> <p>Is there a way to use get, set, union but with my formatting of a list - and can i do it with one list instead of merging 2</p>
4
2016-08-12T03:46:24Z
38,910,077
<p>This can be done very simply with a <code>dict</code> and <code>get()</code>:</p> <pre><code>data = ['Nickey, 20', 'John, 50', 'Nickey, 30'] names = {} for value in data: k, v = value.split(', ') names[k] = names.get(k, 0) + int(v) result = ['{}, {}'.format(k, v) for k, v in names.items()] </code></pre>
0
2016-08-12T04:42:28Z
[ "python" ]
counting the number of time a pattern occurs in files
38,909,629
<p>this is my file: </p> <pre><code>$ cat file some pile of text or other &lt;!-- Footer part at bottom of page--&gt; &lt;div id="footer"&gt; &lt;div class="row col-md-2 col-md-offset-5"&gt; &lt;p class="text-muted"&gt;&amp;copy; 2014. Core Team&lt;/p&gt; &lt;/div&gt; &lt;div id="downloadlinks"&gt; &lt;!-- downloadlinks go here--&gt; &lt;/div&gt; &lt;/div&gt; and more maybe. </code></pre> <p>this is the pattern I am trying to match: </p> <pre><code>$ cat old &lt;!-- Footer part at bottom of page--&gt; &lt;div id="footer"&gt; &lt;div class="row col-md-2 col-md-offset-5"&gt; &lt;p class="text-muted"&gt;&amp;copy; 2014. Core Team&lt;/p&gt; &lt;/div&gt; &lt;div id="downloadlinks"&gt; &lt;!-- downloadlinks go here--&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to see how many times a pattern in a file happens in other files(*.html). I am looking to do this using awk and/or python. </p> <p>So for example given this 1 file here the answer would be 1 something like:(I may have to use a for loop and awk on each iteration) </p> <pre><code>awk ... file 1 </code></pre>
0
2016-08-12T03:53:27Z
38,909,750
<pre><code>with open('file.txt', 'r') as myfile: data=myfile.read().replace('\n', '') with open('old.txt', 'r') as myfile: search=myfile.read().replace('\n', '') print data.count(search) </code></pre>
2
2016-08-12T04:07:55Z
[ "python", "awk" ]
counting the number of time a pattern occurs in files
38,909,629
<p>this is my file: </p> <pre><code>$ cat file some pile of text or other &lt;!-- Footer part at bottom of page--&gt; &lt;div id="footer"&gt; &lt;div class="row col-md-2 col-md-offset-5"&gt; &lt;p class="text-muted"&gt;&amp;copy; 2014. Core Team&lt;/p&gt; &lt;/div&gt; &lt;div id="downloadlinks"&gt; &lt;!-- downloadlinks go here--&gt; &lt;/div&gt; &lt;/div&gt; and more maybe. </code></pre> <p>this is the pattern I am trying to match: </p> <pre><code>$ cat old &lt;!-- Footer part at bottom of page--&gt; &lt;div id="footer"&gt; &lt;div class="row col-md-2 col-md-offset-5"&gt; &lt;p class="text-muted"&gt;&amp;copy; 2014. Core Team&lt;/p&gt; &lt;/div&gt; &lt;div id="downloadlinks"&gt; &lt;!-- downloadlinks go here--&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want to see how many times a pattern in a file happens in other files(*.html). I am looking to do this using awk and/or python. </p> <p>So for example given this 1 file here the answer would be 1 something like:(I may have to use a for loop and awk on each iteration) </p> <pre><code>awk ... file 1 </code></pre>
0
2016-08-12T03:53:27Z
38,922,053
<p>With GNU awk for multi-char RS:</p> <pre><code>awk -v RS='^$' 'NR==FNR{RS=$0} END{print (FNR &amp;&amp; (RT=="") ? FNR-1 : FNR)}' old file </code></pre> <p>The above reads the entire contents of <code>old</code> at one time exactly as-is and populates <code>RS</code> with that string before moving onto read <code>file</code>. <code>FNR</code> in the <code>END</code> block represents the number of <code>RS</code>-terminated strings present in <code>file</code>. If the end of <code>file</code> does not end with a <code>RS</code> then there will be one string in the file after the last occurrence of <code>RS</code> and <code>RT</code> will be the null string. In that case if <code>FNR</code> is non-zero you subtract 1 to get the number of <code>RS</code>s that were seen. You need to check for non-zero <code>FNR</code> to avoid printing <code>-1</code> for an empty file.</p> <p>So at the end of the file if FNR != 0 then the file was not empty so then you need to check if the file ended with an RS (in which case RT will be non-null) or not (in which case RT will be null). If it did then the number of RSs seen is FNR, otherwise it's FNR-1. And if FNR == 0 then the file was empty so you want to print a count of zero.</p>
1
2016-08-12T15:55:47Z
[ "python", "awk" ]
Using Curl and Django Rest Framework in Terminal
38,909,652
<p>I have a model</p> <pre><code>class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) otheritemmodel = models.ForeignKey(Model, on_delete=models.CASCADE) uuid = models.CharField(max_length=256, unique=True) floatitem = models.FloatField() relateditem = models.ForeignKey(RelatedItem, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) character = models.CharField(max_length=500, null=True, blank=True) zipcode = models.IntegerField() city = models.CharField(max_length=100) state = models.CharField(max_length=100) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) </code></pre> <p>CreateAPIView</p> <pre><code>class Item_Create_APIView(CreateAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = ItemCreateSerializer queryset = Item.objects.all() </code></pre> <p>And Serializer</p> <p><a href="http://i.stack.imgur.com/Ef4Td.png" rel="nofollow">Create Serializer</a></p> <p>I am trying to test the createView post via curl or http in the terminal but no luck so far. I am using python3.5 and Django==1.8.10 and Django Rest Framework with JWT token authentication. I can login and get a token but I don't know how to format the json data to the baseusrl/create_item endpoint to test the Create Post call via curl to see if the API works.</p> <p>Anyone with guidance on this? Thanks</p> <p>I tried this and it didn't work:</p> <pre><code>curl —X POST H ”Authorization: JWT token” http://localhost:8000/create_item/ ‘{“key”:”val”}’ </code></pre> <p>I have tried this format and got "no url specified" while the url is in the call</p> <pre><code>curl -X POST -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE0NzEwMjc4MjIsImVtYWlsIjoicGF0b3JlQHByb3Rvbm1haWwuY2giLCJ1c2VybmFtZSI6InBhdG9yZUBwcm90b25tYWlsLmNoIn0.seO6ayMayJ8hwGf3Tlqwu95cZOw5VyFGVqsT5LymdJw" -H "Content-Type: application/json" -d “user=37&amp;otheritmemodel=3&amp;uuid=4454353454983543434&amp;floatitem=40.0&amp;relateditem=28&amp;category=1&amp;subcategory=1&amp;character=jim&amp;zipcode=11111&amp;city=City&amp;state=State” http://localhost:8000/user-api/create_item/ </code></pre> <p>any ideas?</p>
0
2016-08-12T03:56:06Z
38,909,821
<p>Did you try the format specified i the official documentation:</p> <pre><code>curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' </code></pre>
0
2016-08-12T04:16:57Z
[ "python", "django", "curl", "terminal", "django-rest-framework" ]
Using Curl and Django Rest Framework in Terminal
38,909,652
<p>I have a model</p> <pre><code>class Item(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) otheritemmodel = models.ForeignKey(Model, on_delete=models.CASCADE) uuid = models.CharField(max_length=256, unique=True) floatitem = models.FloatField() relateditem = models.ForeignKey(RelatedItem, on_delete=models.CASCADE) category = models.ForeignKey(Category, on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE) character = models.CharField(max_length=500, null=True, blank=True) zipcode = models.IntegerField() city = models.CharField(max_length=100) state = models.CharField(max_length=100) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) </code></pre> <p>CreateAPIView</p> <pre><code>class Item_Create_APIView(CreateAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication] permission_classes = [IsAuthenticated] serializer_class = ItemCreateSerializer queryset = Item.objects.all() </code></pre> <p>And Serializer</p> <p><a href="http://i.stack.imgur.com/Ef4Td.png" rel="nofollow">Create Serializer</a></p> <p>I am trying to test the createView post via curl or http in the terminal but no luck so far. I am using python3.5 and Django==1.8.10 and Django Rest Framework with JWT token authentication. I can login and get a token but I don't know how to format the json data to the baseusrl/create_item endpoint to test the Create Post call via curl to see if the API works.</p> <p>Anyone with guidance on this? Thanks</p> <p>I tried this and it didn't work:</p> <pre><code>curl —X POST H ”Authorization: JWT token” http://localhost:8000/create_item/ ‘{“key”:”val”}’ </code></pre> <p>I have tried this format and got "no url specified" while the url is in the call</p> <pre><code>curl -X POST -H "Authorization: JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE0NzEwMjc4MjIsImVtYWlsIjoicGF0b3JlQHByb3Rvbm1haWwuY2giLCJ1c2VybmFtZSI6InBhdG9yZUBwcm90b25tYWlsLmNoIn0.seO6ayMayJ8hwGf3Tlqwu95cZOw5VyFGVqsT5LymdJw" -H "Content-Type: application/json" -d “user=37&amp;otheritmemodel=3&amp;uuid=4454353454983543434&amp;floatitem=40.0&amp;relateditem=28&amp;category=1&amp;subcategory=1&amp;character=jim&amp;zipcode=11111&amp;city=City&amp;state=State” http://localhost:8000/user-api/create_item/ </code></pre> <p>any ideas?</p>
0
2016-08-12T03:56:06Z
38,934,335
<p>After much deliberation, I resulted to a double-dose of coffee and got the proper way to implement the POST calls with JWT authentication. There is one caveat in that I had to put single quotes around the protected url to make a successful POST with the record persisting to the database. I also opted for not passing the data in JSON format as Key Value pairs since the JSON renderer will handle it.</p> <p>For anyone else who encounters the same problem the syntax that worked is:</p> <pre><code>curl -H "Authorization: JWT YourToken" -d "field=value&amp;field=value" 'http://127.0.0.1:8000/protected_url' </code></pre>
0
2016-08-13T15:39:06Z
[ "python", "django", "curl", "terminal", "django-rest-framework" ]
Is there anyway we to get list of processes started by Python?
38,909,675
<p>I wrote an Python code and it as multiple instances of subprocess.Popen and also functions running in different threads. Is there any way I can track all these processes so that at the end of the program I can kill each one.</p>
0
2016-08-12T04:00:19Z
38,909,891
<p>You may want to maintain a list of processes started by your program. Process id of <code>subprocess.Popen(...)</code> can be accessed by <code>Popen.pid</code>. You can refer it here: <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid" rel="nofollow">https://docs.python.org/2/library/subprocess.html#subprocess.Popen.pid</a></p>
0
2016-08-12T04:24:57Z
[ "python" ]
python having trouble iterating through multiple array's
38,909,687
<p>Hey I am pretty new to python and I have been stuck, I am basically trying to make it loop and it gets stuck on just one combination.</p> <pre><code>import random letters = ['jaysasdfr','kileasrs','mdaawe','theuser','super','mrt','charman','allchar','ne ver','swssdord','xmasfan'] numbers = ['111','123','122','143','422','239','213','124','234''093','425','684','858','421','095','555','554','888'] extras = ['!','@','$','*','^','%','&amp;','?','/','.','&gt;','&lt;'] x = random.choice(letters) y = random.choice(numbers) z = random.choice(extras) t = x + y + z while 1 == 1: print(t) </code></pre> <p>Am I going in the right direction with this or am i completely off?</p>
-3
2016-08-12T04:01:48Z
38,909,748
<p>Your problem is that you need to redo the randomization within your <code>while</code> loop. In your version, <code>x</code>, <code>y</code>, and <code>z</code> get set, but are never changed because your loop only includes the <code>print</code> statement.</p> <pre><code>import random letters = ['jaysasdfr','kileasrs','mdaawe','theuser','super','mrt','charman','allchar','ne ver','swssdord','xmasfan'] numbers = ['111','123','122','143','422','239','213','124','234''093','425','684','858','421','095','555','554','888'] extras = ['!','@','$','*','^','%','&amp;','?','/','.','&gt;','&lt;'] while True: x = random.choice(letters) y = random.choice(numbers) z = random.choice(extras) t = x + y + z print(t) </code></pre>
0
2016-08-12T04:07:38Z
[ "python", "arrays", "random", "choice" ]
AttributeError Issue with Python
38,909,690
<p>If I run the file that has this code, I have no problems and everything is smooth. I'm now calling this class in another file and for some reason I get this error:</p> <pre><code>Traceback (most recent call last): File "C:\users\cato\work\reports\runReports.py", line 524, in runAllAdmis self.sortAcctCol() File "C:\users\cato\work\reports\runReports.py", line 553, in sortAcctCol with open(self.inFile, "r") as self.oi, self.temp1: AttributeError: __exit__ </code></pre> <p>I don't understand why it's working in the original file and not when I call it from another. I looked up my error message and I <a href="http://stackoverflow.com/questions/35497373/python-csv-writer-attributeerror-exit-issue">found this question</a> but when I tried configuring my code to match, I couldn't figure out how to apply it in my situation. I think this mostly due to me not understanding the actual error.</p> <p>This is my code:</p> <pre><code>def sortAcctCol(self): with open(self.inFile, "r") as self.oi, self.temp1: r = csv.reader(self.oi) w = csv.writer(self.temp1) self.header = next(r) self.sortedCol = sorted(r, key=operator.itemgetter(self.acct), reverse=False) for row in self.sortedCol: w.writerow(row) self.temp1 = self.temp1.name </code></pre>
0
2016-08-12T04:02:04Z
38,914,591
<p>Your problem is you are passing a string as <em>self.temp1</em>:</p> <pre><code>In [3]: with open("out.log", "r") as read, "foo.txt": ...: pass ...: --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-3-9088e1884eea&gt; in &lt;module&gt;() ----&gt; 1 with open("out.log", "r") as read, "foo.txt": 2 pass 3 AttributeError: __exit__ </code></pre> <p>open <em>self.temp1</em> also:</p> <pre><code>def sort_acct_col(self): with open(self, "r") as read, open(self.temp1, "w") as write: r = csv.reader(read) next(r) sorted_col = sorted(r, key=operator.itemgetter(self.acct), reverse=False) csv.writer(write).writerows(sorted_col) </code></pre> <p>Also I presume <em>self.acct</em> is an integer or your <em>itemgetter</em> logic won't be working.</p>
0
2016-08-12T09:31:04Z
[ "python", "python-3.x", "csv", "with-statement" ]
Syntax error with print()
38,909,730
<p>Our lecturer gave us some code to help us with an assignment and when I try to run it I get a syntax error. I haven't touched the code at all and it's meant to run without us having to change anything. This is half the code that we were given:</p> <pre><code>class Flusher(MessageProc): def main(self): super().main() print('before start message') self.receive( Message( 'start', action=self.flush)) print('after start message') self.receive( Message( ANY, action=lambda data:print('The first thing in the queue after the flush is', data))) def flush(self, *args): self.receive( Message( ANY, action=self.flush), # recursively call the flush method TimeOut( 0, action=lambda: None)) # when no more messages return </code></pre> <p>And the line that throws the exception is:</p> <pre><code>action=lambda data:print('The first thing in the queue after the flush is', data) </code></pre> <p>This is my first time using Python so please can someone explain what's wrong and what I should do to fix it.</p> <p>EDIT: The error trace is:</p> <pre><code>File "./demo_timeout.py", line 18 action=lambda data:print('The first thing in the queue after the flush is' + data))) ^ SyntaxError: invalid syntax </code></pre>
0
2016-08-12T04:06:29Z
38,909,921
<p>That code is Python 3, and you're attempting to run it using Python 2. If you instead run it in Python 3, you should be good. </p> <p>How you go about switching to 3 depends entirely on your execution environment, but there's a decent chance you already have a command available called <code>python3</code>; if so, you should use that instead of <code>python</code> to run the supplied code.</p> <p>If you don't already have a <code>python3</code>, then you need to install it, however you go about installing software on your system.</p>
1
2016-08-12T04:27:24Z
[ "python", "syntax-error" ]
Swig error- Error: Syntax error in input(2)
38,909,890
<p>I have been trying to create a python wrapper for a c++ library. Swig is giving an error for this section of code, and I don't understand what is causing the error. Also I am new to using swig. The error it is giving me is "Syntax error in input(2)", also Here is the section of code. </p> <pre><code>typedef void (__cdecl *TSI_FUNCTION_CAMERA_CONTROL_CALLBACK) (int ctl_event, void*context); typedef void (__cdecl *TSI_FUNCTION_CAMERA_CONTROL_CALLBACK_EX) (int ctl_event, TSI_FUNCTION_CAMERA_CONTROL_INFO *ctl_event_info, void *context); typedef void (__cdecl *TSI_FUNCTION_IMAGE_NOTIFICATION_CALLBACK) (int notification, void *context); typedef void (__cdecl *TSI_FUNCTION_IMAGE_CALLBACK) (TsiImage *tsi_image, void *context); typedef void (__cdecl *TSI_TEXT_CALLBACK_FUNCTION) (char *str, void *context); </code></pre>
0
2016-08-12T04:24:54Z
39,061,953
<p>SWIG does not understand __cdecl. You possibly need to add `%include "windows.i" to your interface file. You may have other symbols, which are undefined, but from the information that you have given I cannot tell.</p> <pre><code>%module example %{ #include "example_if.h" %} ... # Here it must be present %include "windows.i" ... %include "example_if.h" </code></pre>
0
2016-08-21T07:41:08Z
[ "python", "c++", "swig" ]
fastest way to find rectangles in list not contained by other rectangles from list
38,909,912
<p>Given a list of [not rotated] rectangles, what is the fastest way to get a list of the rectangles not contained by any other from that list?</p> <p>For example:</p> <pre><code>[{x1:0, y1:0, x2:10, y2:10}, {x1:0, y1:0, x2:11, y2: 11}, {x1:5, y1:100, x2:5, y2:100}] </code></pre> <p>would return:</p> <pre><code>[{x1:0, y1:0, x2:11, y2: 11}, {x1:5, y1:100, x2:5, y2:100}] </code></pre>
0
2016-08-12T04:27:00Z
38,910,028
<p>I am using Python, the function I used will take the list of rectangles as input. like:</p> <p><code>[[0,0, 10, 10], [0, 0, 11, 11], [5, 100, 5, 100]]</code></p> <pre><code>def non_max_suppression_fast(boxes, overlapThresh=1): # if there are no boxes, return an empty list if len(boxes) == 0: return [] # if the bounding boxes integers, convert them to floats -- # this is important since we'll be doing a bunch of divisions if boxes.dtype.kind == "i": boxes = boxes.astype("float") # # initialize the list of picked indexes pick = [] # grab the coordinates of the bounding boxes x1 = boxes[:,0] y1 = boxes[:,1] x2 = boxes[:,2] y2 = boxes[:,3] # compute the area of the bounding boxes and sort the bounding # boxes by the bottom-right y-coordinate of the bounding box area = (x2 - x1 + 1) * (y2 - y1 + 1) idxs = np.argsort(y2) # keep looping while some indexes still remain in the indexes # list while len(idxs) &gt; 0: # grab the last index in the indexes list and add the # index value to the list of picked indexes last = len(idxs) - 1 i = idxs[last] pick.append(i) # find the largest (x, y) coordinates for the start of # the bounding box and the smallest (x, y) coordinates # for the end of the bounding box xx1 = np.maximum(x1[i], x1[idxs[:last]]) yy1 = np.maximum(y1[i], y1[idxs[:last]]) xx2 = np.minimum(x2[i], x2[idxs[:last]]) yy2 = np.minimum(y2[i], y2[idxs[:last]]) # compute the width and height of the bounding box w = np.maximum(0, xx2 - xx1 + 1) h = np.maximum(0, yy2 - yy1 + 1) # compute the ratio of overlap overlap = (w * h) / area[idxs[:last]] # delete all indexes from the index list that have idxs = np.delete(idxs, np.concatenate(([last], np.where(overlap == 1)[0]))) # return only the bounding boxes that were picked using the # integer data type return boxes[pick].astype("int") </code></pre>
2
2016-08-12T04:38:08Z
[ "javascript", "python", "algorithm", "geometry", "rectangles" ]
Python 3 List array
38,909,976
<p>I run this code in Python 3.5 but i have an error when i run on python 2 not have Error </p> <pre><code>import sys class Array(object): def __init__(self, arr=[]): self.data = arr def salin(self): temp = Array(self.data) return temp def tambah(self, nilai): if self.data.count&gt;0: if type(self.data[0])==type(nilai): self.data.append(nilai) else: print('Nilai yang ditambahkan harus sejenis') sys.exit(1) def ubah(self,indeks,nilai): self.data[indeks]=nilai def hapus(self,nilai): self.data.remove(nilai) def cari(self, nilai): return self.data.index(nilai) def urutkan(self): self.data.sort() def ekstrak(self,awal,akhir): temp = Array(self.data[awal:akhir]) return temp def cetak(self): for nilai in self.data: print(nilai, end=' ') print() def main(): A = Array([10,20,30,40,50]) #menampilkan nilai awal print('Isi A mula-mula: ',end=' ') A.cetak() #mengubah element ketiga A.ubah(2, 63) #menghapus nilai 40 A.hapus(40) #menambah element A.tambah(70) A.tambah(15) #menampilkan isi nilai setelah diubah, #dihapus, dan ditambah print('Isi A setelah dimanipulasi: ',end=' ') A.cetak() B = A.ekstrak(1,4) print('Isi B (hasil Ekstrak): ', end='') B.cetak() C=A.salin() print('Isi C(salinan A): ',end='') C.cetak() C.tambah(45.25) # menabah nilai bertipe float if __name__=='__main__': main() </code></pre>
-2
2016-08-12T04:33:35Z
38,910,021
<p><code>print</code> is not a function in Python 2. Syntactically, this isn't correct </p> <pre><code>print('message', end=' ') </code></pre> <p>If you want to use that <code>print</code> as a function in both Python 2 and 3, just import it</p> <pre><code>from __future__ import print_function </code></pre> <p>And replace <code>self.data.count</code> with <code>len(self.data)</code></p>
2
2016-08-12T04:37:41Z
[ "python", "arrays", "list", "count" ]
Scipy: UnicodeDecodeError while loading image file
38,910,032
<pre><code>def image_to_laplacian(filename): with open(filename, 'r', encoding="latin-1") as f: s = f.read() img = sc.misc.imread(f) image_to_laplacian('images/bw_3x3.png') </code></pre> <p><strong>Produces:</strong></p> <blockquote> <p>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte</p> </blockquote> <p>"images/bw_3x3.png" is a 3x3 image I produced in Pinta. I tried opening a cat.jpg I got from Google Images, but I got the same error.</p> <p>I also tried to use <code>"encoding="latin-1"</code> as an argument to open, based on something I read on SO; I was able to open the file, but I'm read failed with the exception </p> <blockquote> <p>OSError: cannot identify image file &lt;_io.TextIOWrapper name='images/bw_3x3.png' mode='r' encoding='latin-1'></p> </blockquote>
0
2016-08-12T04:38:24Z
38,910,178
<p>The line that is causing the error is</p> <pre><code>s = f.read() </code></pre> <p>In 'r' mode this tries to read the data as a string, but it's a image file, so it will fail. You can use 'rb' instead. Definitely remove the <code>encoding=latin</code> because that's only relevant for text files. </p> <p>Also, note that according to <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imread.html" rel="nofollow">the documentation</a>:</p> <blockquote> <p>name : str or file object <p>The file name or file object to be read.<p></p> </blockquote> <p>So you can dispense with opening a file and just give it a filepath as a string. The following should work:</p> <pre><code>img = sc.misc.imread(filename) </code></pre>
1
2016-08-12T04:51:32Z
[ "python", "numpy", "scipy" ]
How to prevent lxml from adding a default doctype
38,910,227
<p>lxml seems to add a default doctype when one is missing in the html document.</p> <p>See this demo code:</p> <pre><code>import lxml.etree import lxml.html def beautify(html): parser = lxml.etree.HTMLParser( strip_cdata=True, remove_blank_text=True ) d = lxml.html.fromstring(html, parser=parser) docinfo = d.getroottree().docinfo return lxml.etree.tostring( d, pretty_print=True, doctype=docinfo.doctype, encoding='utf8' ) with_doctype = """ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;With Doctype&lt;/title&gt; &lt;/head&gt; &lt;/html&gt; """ # This passes! assert "DOCTYPE" in beautify(with_doctype) no_doctype = """&lt;html&gt; &lt;head&gt; &lt;title&gt;No Doctype&lt;/title&gt; &lt;/head&gt; &lt;/html&gt;""" # This fails! assert "DOCTYPE" not in beautify(no_doctype) # because the returned html contains this line # &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"&gt; # which was not present in the source before </code></pre> <hr> <p>How can I tell lxml to not do this?</p> <p>This issue was originally raised here: <a href="https://github.com/mitmproxy/mitmproxy/issues/845" rel="nofollow">https://github.com/mitmproxy/mitmproxy/issues/845</a></p> <p>Quoting a <a href="https://www.reddit.com/r/Python/comments/42rb90/comparing_execution_time_of_pretty_printing_an/czclx15" rel="nofollow">comment on reddit</a> as it might be helpful:</p> <blockquote> <p>lxml is based on libxml2, which does this by default unless you pass the option <code>HTML_PARSE_NODEFDTD</code>, I believe. Code <a href="https://github.com/GNOME/libxml2/blob/master/HTMLparser.c#L4777" rel="nofollow">here</a>.</p> <p>I don't know if you can tell lxml to pass that option though.. libxml has python bindings that you could perhaps use directly but they seem really hairy.</p> <p>EDIT: did some more digging and that option does appear in the lxml soure <a href="https://github.com/lxml/lxml/blob/master/src/lxml/includes/htmlparser.pxd#L20" rel="nofollow">here</a>. That option does exactly what you want but I'm not sure how to activate it yet, if it's even possible.</p> </blockquote>
0
2016-08-12T04:57:13Z
39,038,017
<p>There is currently no way to do this in lxml, but I've created a <a href="https://github.com/lxml/lxml/issues/203" rel="nofollow">Pull Request on lxml</a> which adds a <code>default_doctype</code> boolean to the <code>HTMLParser</code>.</p> <p>Once the code gets merged in, the parser needs to be created like so:</p> <pre><code>parser = lxml.etree.HTMLParser( strip_cdata=True, remove_blank_text=True, default_doctype=False, ) </code></pre> <p>Everything else stays the same.</p>
1
2016-08-19T11:32:56Z
[ "python", "lxml", "libxml2" ]
python numpy filter two dimentional array by condition
38,910,258
<p>Python newbie here, I have read <a href="http://stackoverflow.com/questions/26154711/filter-rows-of-a-numpy-array">Filter rows of a numpy array?</a> and the doc but still can't figure out how to code it the python way.</p> <p>Example array I have: (the real data is 50000 x 10)</p> <pre><code>a = numpy.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']]) filter = ['a','c'] </code></pre> <p>I need to find all rows in <code>a</code> with <code>a[:, 1] in filter</code>. Expected result:</p> <pre><code>[[2,'a'],[4,'c']] </code></pre> <p>My current code is this:</p> <pre><code>numpy.asarray([x for x in a if x[1] in filter ]) </code></pre> <p>It works okay but I have read somewhere that it is not efficient. What is the proper numpy method for this?</p> <h3>Edit:</h3> <p>Thanks for all the correct answers! Unfortunately I can only mark one as accepted answer. I am surprised that <code>numpy.in1d</code> is not turned up in google searchs for <code>numpy filter 2d array</code>.</p>
1
2016-08-12T05:00:13Z
38,910,472
<p>Try this:</p> <pre><code>&gt;&gt;&gt; a[numpy.in1d(a[:,1], filter)] array([['2', 'a'], ['4', 'c']], dtype='|S21') </code></pre> <p>Also go through <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.in1d.html</a></p>
2
2016-08-12T05:21:23Z
[ "python", "arrays", "python-2.7", "numpy" ]
python numpy filter two dimentional array by condition
38,910,258
<p>Python newbie here, I have read <a href="http://stackoverflow.com/questions/26154711/filter-rows-of-a-numpy-array">Filter rows of a numpy array?</a> and the doc but still can't figure out how to code it the python way.</p> <p>Example array I have: (the real data is 50000 x 10)</p> <pre><code>a = numpy.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']]) filter = ['a','c'] </code></pre> <p>I need to find all rows in <code>a</code> with <code>a[:, 1] in filter</code>. Expected result:</p> <pre><code>[[2,'a'],[4,'c']] </code></pre> <p>My current code is this:</p> <pre><code>numpy.asarray([x for x in a if x[1] in filter ]) </code></pre> <p>It works okay but I have read somewhere that it is not efficient. What is the proper numpy method for this?</p> <h3>Edit:</h3> <p>Thanks for all the correct answers! Unfortunately I can only mark one as accepted answer. I am surprised that <code>numpy.in1d</code> is not turned up in google searchs for <code>numpy filter 2d array</code>.</p>
1
2016-08-12T05:00:13Z
38,910,498
<p>You can use a <code>bool</code> index array that you can produce using <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a>. </p> <p>You can index a <code>np.ndarray</code> along any <a href="http://docs.scipy.org/doc/numpy-1.10.0/glossary.html" rel="nofollow"><code>axis</code></a> you want using for example an array of <code>bool</code>s indicating whether an element should be included. Since you want to index along <code>axis=0</code>, meaning you want to choose from the outest index, you need to have 1D <code>np.array</code> whose length is the number of rows. Each of its elements will indicate whether the row should be included.</p> <p>A fast way to get this is to use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> on the second column of <code>a</code>. You get all elements of that column by <code>a[:, 1]</code>. Now you have a 1D <code>np.array</code> whose elements should be checked against your filter. Thats what <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.in1d.html" rel="nofollow"><code>np.in1d</code></a> is for.</p> <p>So the complete code would look like:</p> <pre><code>import numpy as np a = np.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']]) filter = np.asarray(['a','c']) a[np.in1d(a[:, 1], filter)] </code></pre> <p>or in a longer form:</p> <pre><code>import numpy as np a = np.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']]) filter = np.asarray(['a','c']) mask = np.in1d(a[:, 1], filter) a[mask] </code></pre>
1
2016-08-12T05:23:16Z
[ "python", "arrays", "python-2.7", "numpy" ]
python numpy filter two dimentional array by condition
38,910,258
<p>Python newbie here, I have read <a href="http://stackoverflow.com/questions/26154711/filter-rows-of-a-numpy-array">Filter rows of a numpy array?</a> and the doc but still can't figure out how to code it the python way.</p> <p>Example array I have: (the real data is 50000 x 10)</p> <pre><code>a = numpy.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']]) filter = ['a','c'] </code></pre> <p>I need to find all rows in <code>a</code> with <code>a[:, 1] in filter</code>. Expected result:</p> <pre><code>[[2,'a'],[4,'c']] </code></pre> <p>My current code is this:</p> <pre><code>numpy.asarray([x for x in a if x[1] in filter ]) </code></pre> <p>It works okay but I have read somewhere that it is not efficient. What is the proper numpy method for this?</p> <h3>Edit:</h3> <p>Thanks for all the correct answers! Unfortunately I can only mark one as accepted answer. I am surprised that <code>numpy.in1d</code> is not turned up in google searchs for <code>numpy filter 2d array</code>.</p>
1
2016-08-12T05:00:13Z
38,910,520
<p>A somewhat elaborate pure <code>numpy</code> vectorized solution:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; a = numpy.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']]) &gt;&gt;&gt; filter = numpy.array(['a','c']) &gt;&gt;&gt; a[(a[:,1,None] == filter[None,:]).any(axis=1)] array([['2', 'a'], ['4', 'c']], dtype='|S21') </code></pre> <p><code>None</code> in the index creates a singleton dimension, therefore we can compare the column of <code>a</code> and the row of <code>filter</code>, and then reduce the resulting boolean array</p> <pre><code>&gt;&gt;&gt; a[:,1,None] == filter[None,:] array([[ True, False], [False, False], [False, True], [False, False]], dtype=bool) </code></pre> <p>over the second dimension with <code>any</code>.</p>
2
2016-08-12T05:24:46Z
[ "python", "arrays", "python-2.7", "numpy" ]
python numpy filter two dimentional array by condition
38,910,258
<p>Python newbie here, I have read <a href="http://stackoverflow.com/questions/26154711/filter-rows-of-a-numpy-array">Filter rows of a numpy array?</a> and the doc but still can't figure out how to code it the python way.</p> <p>Example array I have: (the real data is 50000 x 10)</p> <pre><code>a = numpy.asarray([[2,'a'],[3,'b'],[4,'c'],[5,'d']]) filter = ['a','c'] </code></pre> <p>I need to find all rows in <code>a</code> with <code>a[:, 1] in filter</code>. Expected result:</p> <pre><code>[[2,'a'],[4,'c']] </code></pre> <p>My current code is this:</p> <pre><code>numpy.asarray([x for x in a if x[1] in filter ]) </code></pre> <p>It works okay but I have read somewhere that it is not efficient. What is the proper numpy method for this?</p> <h3>Edit:</h3> <p>Thanks for all the correct answers! Unfortunately I can only mark one as accepted answer. I am surprised that <code>numpy.in1d</code> is not turned up in google searchs for <code>numpy filter 2d array</code>.</p>
1
2016-08-12T05:00:13Z
38,924,371
<p>In this case where the <code>len(filter)</code> is sufficiently smaller than <code>a[:,1]</code>, <code>np.in1d</code> does an iterative version of</p> <pre><code>mask = (a[:,1,None] == filter[None,:]).any(axis=1) a[mask,:] </code></pre> <p>It does (adapting the <code>in1d</code> code):</p> <pre><code>In [1301]: arr1=a[:,1];arr2=np.array(filter) In [1302]: mask=np.zeros(len(arr1),dtype=np.bool) In [1303]: for i in arr2: ...: mask |= (arr1==i) In [1304]: mask Out[1304]: array([ True, False, True, False], dtype=bool) </code></pre> <p>With more items in <code>filter</code> is would build its search around <code>unique</code>, <code>concatenate</code> and <code>argsort</code>, looking for duplicates.</p> <p>So it's convenience hides a fair amount of complexity.</p>
0
2016-08-12T18:29:03Z
[ "python", "arrays", "python-2.7", "numpy" ]
accessing the tokenized words in python
38,910,318
<p>Suppose we have values in query column of a panda data frame which are tokenized using the split() function like </p> <pre><code>query[4] = "['rain', 'shower', 'head']". </code></pre> <p>Now I want to perform some operations on individual words. So, I converted it into list and iterated through it using for loop like like :</p> <pre><code>l=list(query[4]) for word in l : word=func(word) </code></pre> <p>But it is storing each alphabets on the list like - <code>['[', "'", 'r', 'a', 'i', 'n', "'", ','</code> and so on.</p> <p>I have even tried to use join function i.e. - <code>''.join(word)</code> and <code>''.join(l)</code></p> <p>But still nothing is working for me. Can you suggest something here. Any help will be appreciated. </p>
2
2016-08-12T05:06:14Z
38,910,385
<p>You are seeing the correct output. The line </p> <pre><code>query[4] = "['rain', 'shower', 'head']" </code></pre> <p>means that query[4] is of type string. To be treatable as array, it should be <code>['rain', 'shower', 'head']</code>.</p> <p>Check this output from python REPL with what you have:</p> <pre><code>&gt;&gt;&gt; query = "['rain', 'shower', 'head']" &gt;&gt;&gt; list(query) &gt;&gt;&gt; ['[', "'", 'r', 'a', 'i', 'n', "'", ',', ' ', "'", 's', 'h', 'o', 'w', 'e', 'r', "'", ',', ' ', "'", 'h', 'e', 'a', 'd', "'", ']'] </code></pre> <p>After changing the assignment to an array, here is the new output in REPL:</p> <pre><code>&gt;&gt;&gt; query = ['rain', 'shower', 'head'] &gt;&gt;&gt; list(query) &gt;&gt;&gt; ['rain', 'shower', 'head'] </code></pre>
0
2016-08-12T05:14:19Z
[ "python", "pandas" ]