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> <pr...
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 ...
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: Canno...
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>...
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 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>...
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 advan...
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>...
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 compres...
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 ju...
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 ...
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><...
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><...
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><...
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_...
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 ...
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 th...
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 se...
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 lo...
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]:...
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...
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...
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 se...
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__...
-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 ...
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 wa...
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 =...
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...
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...
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 a...
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...
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...
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> <...
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], ...
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], ...
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...
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 ...
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. Pe...
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;modu...
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 baid...
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 ...
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.ad...
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 ...
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>, a...
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"))...
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 d...
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></...
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>...
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...
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 averag...
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 = d...
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 averag...
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.CSVTool...
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 ...
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: # "...
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 t...
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 'pr...
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'...
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 i...
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>...
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> ...
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...
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...
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 a...
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...
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><c...
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...
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...
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 mak...
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>...
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>T...
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 th...
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...
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...
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...
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><...
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">in...
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>...
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(...
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>...
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(...
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(...
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...
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 ...
-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 ...
-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>...
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 ter...
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],}, {'a...
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 ...
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],}, {'a...
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> i...
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 accou...
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_SECRE...
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 do...
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.l...
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 ...
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* ...
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>...
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 l...
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', { ...
-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 c...
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 ...
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 c...
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...
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 cal...
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_su...
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 cal...
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 ...
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
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
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 rea...
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 ...
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...
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", a...
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...
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 th...
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 bas...
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 bas...
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 ...
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 sce...
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 -> ba...
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>parse...
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>foob...
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 somet...
-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><c...
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.q...
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 a...
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 a...
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 a...
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'...
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...
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'...
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'...
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):...
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'...
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; ...
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; ...
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>...
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.ForeignKe...
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.ForeignKe...
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...
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/su...
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','...
-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','kile...
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() F...
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) &l...
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): ...
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, y...
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...
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 ...
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>[{x...
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 [] ...
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...
-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 ...
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...
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, not...
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, par...
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...
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,...
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.in1...
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,...
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...
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,...
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']],...
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,...
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]: ...
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 l...
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>...
0
2016-08-12T05:14:19Z
[ "python", "pandas" ]