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
findAll doesn't work, nested tags
39,017,243
<p>I'm parsing through <a href="https://www.wired.com/2016/08/live-debate-whats-right-kind-intersection" rel="nofollow">this</a> page. I need to get text content - which is located in <code>p</code> tags. The general structure of the page is the following:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;artic...
-1
2016-08-18T11:38:04Z
39,018,304
<p>This should get you started: </p> <pre><code>from bs4 import BeautifulSoup import mechanize url = "https://www.wired.com/2016/08/live-debate-whats-right-kind-intersection" br = mechanize.Browser() response = br.open(url) soup = BeautifulSoup(response, 'html.parser') media = [] for x in soup.findAll("script",{"t...
0
2016-08-18T12:31:10Z
[ "python", "web-scraping", "beautifulsoup" ]
DoxyPy - Member (variable) of namespace is not documented
39,017,317
<p>I get the error message <code>warning: Member constant1 (variable) of namespace &lt;file_name&gt; is not documented.</code> for my doxygen (doxypy) documentation. I have documented the file and all functions and classes. But I also have some additional constants in this file which I don't know how to document and I ...
0
2016-08-18T11:41:47Z
39,018,888
<p>@albert was right. It works when putting a <code>##</code> in front of the variables. I didn't find a solution using the <code>"""</code> syntax.</p> <pre><code>"""\file \brief &lt;this is what the file contains&gt; \author &lt;author&gt; """ import numpy as np ## Doxygen documentation for constant1 constant1 = 2...
0
2016-08-18T12:57:30Z
[ "python", "doxygen" ]
DoxyPy - Member (variable) of namespace is not documented
39,017,317
<p>I get the error message <code>warning: Member constant1 (variable) of namespace &lt;file_name&gt; is not documented.</code> for my doxygen (doxypy) documentation. I have documented the file and all functions and classes. But I also have some additional constants in this file which I don't know how to document and I ...
0
2016-08-18T11:41:47Z
39,019,321
<p>If you need (because of any reason) to have more documentation for those members, you can also split the text into several lines. It will be treated as <code>"""</code> block.</p> <pre><code>## Doxygen documentation for constant1. The way which you already found. constant1 = 24 ## Doxygen documentation for constant...
0
2016-08-18T13:18:56Z
[ "python", "doxygen" ]
array slices (checkio) , python 3
39,017,342
<pre><code>array =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] def checkio(array): if len(array)&gt;0: (sum (array[0:len(array):2])) * array [-1] else : return 0 </code></pre> <p>The result is 0 always. What`s the problem?</p>
-2
2016-08-18T11:43:14Z
39,017,836
<pre><code>array =[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19] def checkio(array): if len(array)&gt;0: return (sum (array[0:len(array):2])) * array[-1] else : return 0 </code></pre> <p>You're missing a return statement for your <code>if</code> block. </p>
0
2016-08-18T12:07:44Z
[ "python" ]
to_csv append mode is not appending to next new line
39,017,406
<p>I have a csv called <code>test.csv</code> that looks like:</p> <pre><code>accuracy threshold trainingLabels abc 0.506 15000 eew 18.12 15000 </code></pre> <p>And then a dataframe called <code>summaryDF</code> that looks like:</p> <pre><code>accuracy threshold trainingLabels de...
0
2016-08-18T11:46:08Z
39,017,897
<p>Are you using the pandas package? You do not mention that anywhere.</p> <p>Pandas does not automatically append a new line, and I am not sure how to force it. But you can just do:</p> <pre><code>f.write('\n') summaryDF.to_csv(path_or_buf=f, mode='a', ...) </code></pre> <hr> <p>An unrelated bug in your code:</p> ...
1
2016-08-18T12:11:27Z
[ "python", "csv", "append", "export-to-csv" ]
common exit status to python,bash,tcl scripts
39,017,466
<p>"""i have a framework that calls python,bash,tcl modules ,each module should end with some common exit status SUCCESS=0,FAILURE=1.the framework has to catch it and interpret it ,how can i do that. i thought of declaring a class and importing this class in all the modules but how can i import into tcl and bash modul...
0
2016-08-18T11:49:24Z
39,048,730
<p>Every language describes things differently. It's effectively a non-starter to use the same file as source code for more than one language at once (it can be done, but it's hard work and not worth it). You <em>don't</em> import things from one language into another without really complicated inter-lingual shims, and...
2
2016-08-19T22:56:56Z
[ "python", "bash", "tcl" ]
Python grouping JSON object using multiple keys
39,017,487
<p>I have this JSON object which has structure as follows (the json object was extracted from pandas dataframe using <code>to_json(orient="records")</code>)</p> <pre><code>data = [{'month': 'Jan','date': '18','activity': 'cycling','duration': 3}, {'month': 'Jan', 'date': '18','activity': 'reading', 'duration':...
0
2016-08-18T11:51:02Z
39,018,346
<p>This seems to work:</p> <h1>Code</h1> <pre><code>data = [{'month': 'Jan','date': '18','activity': 'cycling','duration': 3}, {'month': 'Jan', 'date': '18','activity': 'reading', 'duration': 3.0}, {'month': 'Jan', 'date': '19', 'activity': 'scripting', 'duration': 19.5}, {'month': 'Feb','date...
1
2016-08-18T12:32:50Z
[ "javascript", "python", "json" ]
Extract files from folder according to timestamp given in their title using python
39,017,665
<p>I have a folder containing various files which are named using timestamps like this:</p> <pre><code>2016.08.06_09.31.53_test 2016.08.06_09.36.23_test1 2016.08.04_10.41.23_test 2016.08.04_10.46.20_test1 </code></pre> <p>I am trying to write a program that can pull out only files from this folder which have a tim...
-1
2016-08-18T11:58:57Z
39,018,157
<p>With the above naming system, it is incredibly simple... Get your files into a list</p> <pre><code>list_of_files = [file1, file2 , ... ] list_of_files.sort() print list_of_files </code></pre> <p>That will sort it for you incredibly quickly - the .sort() changes the original list, and puts it into alphabetical orde...
0
2016-08-18T12:24:07Z
[ "python" ]
Python for loops has index for counter
39,017,671
<p>Hello I'm beginner in Python and trying to read a part of a code with for loop but can't understand it, does any body knows how there is index over loop counter? Thanks</p> <pre><code>updateNodeNbrs = [] for a in nodeData: updateNodeNbrs.append(a[0]) </code></pre>
-4
2016-08-18T11:59:11Z
39,017,707
<p>You're iterating <a href="http://www.diveintopython.net/file_handling/for_loops.html" rel="nofollow">directly over the elements</a> of <code>nodeData</code>, so there is no need for an index. The current element is designated by <code>a</code>.</p> <p>This is equivalent to:</p> <pre><code>updateNodeNbrs = [] for i...
1
2016-08-18T12:01:05Z
[ "python", "for-loop" ]
Python for loops has index for counter
39,017,671
<p>Hello I'm beginner in Python and trying to read a part of a code with for loop but can't understand it, does any body knows how there is index over loop counter? Thanks</p> <pre><code>updateNodeNbrs = [] for a in nodeData: updateNodeNbrs.append(a[0]) </code></pre>
-4
2016-08-18T11:59:11Z
39,017,724
<p>See same question <a href="http://stackoverflow.com/questions/9524209/count-indexes-using-for-in-python">here</a></p> <p>If you have an existing list and you want to loop over it and keep track of the indices you can use the <code>enumerate</code> function. For example</p> <pre><code>l = ["apple", "pear", "banana"...
0
2016-08-18T12:02:00Z
[ "python", "for-loop" ]
Django and celery on different servers and celery being able to send a callback to django once a task gets completed
39,017,678
<p>I have a django project where I am using celery with rabbitmq to perform a set of async. tasks. So the setup i have planned goes like this.</p> <ol> <li>Django app running on one server.</li> <li>Celery workers and rabbitmq running from another server.</li> </ol> <p>My initial issue being, how to do i access djang...
2
2016-08-18T11:59:32Z
39,018,282
<p>Concerning your first question, accessing django models from the workers' server:</p> <p>Your django app must be available on both <strong>Server A</strong> (serving users) and <strong>Server B</strong> (hosting the celery workers)</p> <p>Concerning your second question, updating the database based on the values. ...
3
2016-08-18T12:30:28Z
[ "python", "django", "asynchronous", "rabbitmq", "celery" ]
Django and celery on different servers and celery being able to send a callback to django once a task gets completed
39,017,678
<p>I have a django project where I am using celery with rabbitmq to perform a set of async. tasks. So the setup i have planned goes like this.</p> <ol> <li>Django app running on one server.</li> <li>Celery workers and rabbitmq running from another server.</li> </ol> <p>My initial issue being, how to do i access djang...
2
2016-08-18T11:59:32Z
39,065,804
<p>I've used the following set up on my application:</p> <ol> <li>Task is initiated from Django - information is extracted from the model instance and passed to the task as a dictionary. NB - this will be more future proof as Celery 4 will default to JSON encoding</li> <li>Remote server runs task and creates a diction...
0
2016-08-21T15:21:11Z
[ "python", "django", "asynchronous", "rabbitmq", "celery" ]
Better way to change pandas date format to remove leading zeros?
39,017,748
<p>DataFrame look like:</p> <pre><code> OPENED 0 2004-07-28 1 2010-03-02 2 2005-10-26 3 2006-06-30 4 2012-09-21 </code></pre> <p>I converted them to my desired format successfully but it seems very inefficient.</p> <pre><code> OPENED 0 40728 1 100302 2 51026 3 60630 4 120921 </code></pre> <p>Th...
1
2016-08-18T12:02:59Z
39,017,803
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a>, then remove first 2 chars by <code>str[2:]</code> and last remove leading <code>0</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Ser...
2
2016-08-18T12:05:42Z
[ "python", "datetime", "pandas", "dataframe", "leading-zero" ]
Number of values lying in a specified range
39,017,766
<p>I have a data frame like the one below:</p> <pre><code>NC_011163.1:1 NC_011163.1:22 NC_011163.1:44 NC_011163.1:65 NC_011163.1:73 NC_011163.1:87 NC_011163.1:104 NC_011163.1:130 NC_011163.1:151 NC_011163.1:172 NC_011163.1:194 NC_011163.1:210 NC_011163.1:235 NC_011163.1:255 NC_011163.1:295 NC_011163.1:320 NC_011163.1:...
0
2016-08-18T12:03:50Z
39,018,033
<p>If you use python and <a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a>, you can do:</p> <p>with your data in a dataframe <code>df</code>:</p> <pre><code> NC N 0 NC_011163.1 1 1 NC_011163.1 22 2 NC_011163.1 44 3 NC_011163.1 65 4 NC_011163.1 73 5 NC_011163.1 87 6 ...
2
2016-08-18T12:18:27Z
[ "python", "unix", "pandas", "awk" ]
Number of values lying in a specified range
39,017,766
<p>I have a data frame like the one below:</p> <pre><code>NC_011163.1:1 NC_011163.1:22 NC_011163.1:44 NC_011163.1:65 NC_011163.1:73 NC_011163.1:87 NC_011163.1:104 NC_011163.1:130 NC_011163.1:151 NC_011163.1:172 NC_011163.1:194 NC_011163.1:210 NC_011163.1:235 NC_011163.1:255 NC_011163.1:295 NC_011163.1:320 NC_011163.1:...
0
2016-08-18T12:03:50Z
39,018,535
<pre><code>awk -v t=210 'BEGIN{FS=":";t++}{++a[int($2/t)]} END{for(x in a){printf "%s:%s\t%d\n",$1,t*x"-"(x+1)*t,a[x]}}' file </code></pre> <p>will give this output:</p> <pre><code>NC_011163.1:0-211 12 NC_011163.1:211-422 4 NC_011163.1:422-633 2 </code></pre> <ul> <li><p>You don't need to find out w...
0
2016-08-18T12:41:30Z
[ "python", "unix", "pandas", "awk" ]
Number of values lying in a specified range
39,017,766
<p>I have a data frame like the one below:</p> <pre><code>NC_011163.1:1 NC_011163.1:22 NC_011163.1:44 NC_011163.1:65 NC_011163.1:73 NC_011163.1:87 NC_011163.1:104 NC_011163.1:130 NC_011163.1:151 NC_011163.1:172 NC_011163.1:194 NC_011163.1:210 NC_011163.1:235 NC_011163.1:255 NC_011163.1:295 NC_011163.1:320 NC_011163.1:...
0
2016-08-18T12:03:50Z
39,021,734
<pre><code>$ cat tst.awk BEGIN { FS=":"; OFS="\t"; endOfRange=210 } { key = $1 bucket = int((($2-1)/endOfRange)+1) cnt[bucket]++ maxBucket = (bucket &gt; maxBucket ? bucket : maxBucket) } END { for (bucket=1; bucket&lt;=maxBucket; bucket++) { print key ":" ((bucket-1)*endOfRange)+1 "-" bucke...
1
2016-08-18T15:10:04Z
[ "python", "unix", "pandas", "awk" ]
Espeak on windows 7 and python 2.7
39,017,808
<p>On the begin I'll say that there is a similar post here: <a href="http://stackoverflow.com/questions/17547531/how-to-use-espeak-with-python">How to use espeak with python</a> and I was using answers from this post, but still i'm getting errors, so maybe u'll be able to help me fix it.</p> <pre><code>import subproce...
0
2016-08-18T12:06:01Z
39,017,848
<pre><code>import subprocess subprocess.call(['ping', '127.0.0.1'], shell=True) </code></pre>
0
2016-08-18T12:08:37Z
[ "python", "python-2.7", "text-to-speech", "espeak" ]
ase.visualize.view misses pygtk
39,017,925
<p>On Ubuntu 16.04 machinge w/ XFCE desktop i have installed <code>python3</code> and <code>pip</code> with the command <code>sudo apt install python3-pip</code>. I then installed <code>numpy</code> and <code>ase</code> (atomic Simulation Environment) using <code>sudo -H python3 -m pip install --upgrade numpy ase</code...
0
2016-08-18T12:12:44Z
39,723,931
<p>Unfortunately, none of the ASE gui functions will work with Python3. PyGTK is only for Python2 and it has been moved to <a href="https://wiki.gnome.org/action/show/Projects/PyGObject?action=show&amp;redirect=PyGObject" rel="nofollow">PyGObject</a> for Python3. This is an <a href="https://gitlab.com/ase/ase/issues/13...
0
2016-09-27T11:51:20Z
[ "python", "python-3.x", "numpy", "python-3.5" ]
Deploy caffe regression model
39,017,998
<p>I have trained a regression network with <code>caffe</code>. I use <code>"EuclideanLoss"</code> layer in both the train and test phase. I have plotted these and the results look promising. </p> <p>Now I want to deploy the model and use it. I know that if <code>SoftmaxLoss</code> is used, the final layer must be <c...
2
2016-08-18T12:15:53Z
39,018,076
<p>For deploy you only need to discard the loss layer, in your case the <code>"EuclideanLoss"</code> layer. The output of your net is the <code>"bottom"</code> you fed the loss layer.</p> <p>For <code>"SoftmaxWithLoss"</code> layer (and <code>"SigmoidCrossEntropy"</code>) you need to <strong>replace</strong> the loss ...
1
2016-08-18T12:20:16Z
[ "python", "neural-network", "deep-learning", "caffe", "conv-neural-network" ]
My Django form data won't save to my database
39,018,024
<p>I'm trying to get a simple form to save to my MariaDB database but I can't get it to save when I use the form. If I use the Django Admin interface, I can make changes to the database however.</p> <p><strong>addstudent.html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;titl...
0
2016-08-18T12:17:44Z
39,018,207
<p>Your form action is set to what I assume is the index page also which means its probably not calling that view whatsoever</p> <pre><code>&lt;form id="studentform" method="post" action="/add-student/index/"&gt; </code></pre> <p>The action here should point to the url that links to that particular view (preferably u...
2
2016-08-18T12:26:54Z
[ "python", "django", "django-forms", "mariadb" ]
How to add Google places autocomplete to flask?
39,018,026
<p>I would like to add the Google places autocomplete library to an input field but am not able to in my flask app (it doesn't give the dropdown suggestions), although it works fine in a standalone HTML file.</p>
0
2016-08-18T12:17:48Z
39,018,224
<p>Have you consider using <a href="https://ubilabs.github.io/geocomplete/" rel="nofollow">Geocomplete</a>? The example code they provide is pretty easy to implement</p>
0
2016-08-18T12:27:27Z
[ "javascript", "jquery", "python", "flask", "autocomplete" ]
BFS, trying to find the longest way between nodes
39,018,055
<p>Currently I'm working with an assignment (BFS), where I am supposed to find the longest way between two nodes. Notice that I'm working with both a queue-class and a node-class, the node-class is called <code>Word</code> in my assignment. The words are 3-letter words, and I currently have a method (longestway) that r...
0
2016-08-18T12:19:35Z
39,018,781
<p>A good start would be to stop removing elements from the head of the list, since all you do is print, and introduce an offset variable. Also, you're calling <code>printpath1</code> twice with the same argument, making twice as much as necessary calculations.</p> <pre><code>offset = 0 for elem in lista: pp1 = pr...
0
2016-08-18T12:52:27Z
[ "python", "bfs" ]
How do the arguments are being passed to test functions in tox/py.test?
39,018,056
<p>I'm learning to write tests with tox. How do the arguments are being passed to test functions in tox/py.test? For example in <code>test_simple_backup_generation</code> from <code>tests/test_backup_cmd.py</code> of <code>django-backup</code> <a href="https://github.com/django-backup/django-backup" rel="nofollow">exte...
0
2016-08-18T12:19:38Z
39,018,666
<p>These are <a href="http://docs.pytest.org/en/latest/fixture.html" rel="nofollow">pytest fixtures</a> provided by <a href="http://pytest-django.readthedocs.io/en/latest/helpers.html#fixtures" rel="nofollow">pytest-django</a> and <a href="http://doc.pytest.org/en/latest/tmpdir.html" rel="nofollow">pytest itself</a>.</...
1
2016-08-18T12:47:35Z
[ "python", "automated-tests", "py.test", "tox" ]
iterating replacing string in a text
39,018,138
<p>I’m writing a program that has to replace the string “+” by “!”, and strings “*+” by “!!” in a particular text. As an example, I need to go from:</p> <pre><code> some_text = ‘here is +some*+ text and also +some more*+ text here’ </code></pre> <p>to</p> <pre><code> some_text_new = ‘here i...
0
2016-08-18T12:23:24Z
39,018,214
<pre><code>&gt;&gt;&gt; x = 'here is +some*+ text and also +some more*+ text here' &gt;&gt;&gt; x = x.replace('*+','!!') &gt;&gt;&gt; x 'here is +some!! text and also +some more!! text here' &gt;&gt;&gt; x = x.replace('+','!') &gt;&gt;&gt; x 'here is !some!! text and also !some more!! text here' </code></pre> <p>The f...
0
2016-08-18T12:27:15Z
[ "python", "str-replace" ]
iterating replacing string in a text
39,018,138
<p>I’m writing a program that has to replace the string “+” by “!”, and strings “*+” by “!!” in a particular text. As an example, I need to go from:</p> <pre><code> some_text = ‘here is +some*+ text and also +some more*+ text here’ </code></pre> <p>to</p> <pre><code> some_text_new = ‘here i...
0
2016-08-18T12:23:24Z
39,018,621
<p>It can be done using regex groups</p> <pre><code>import re def replacer(matchObj): if matchObj.group(1) == '*+': return '!!' elif matchObj.group(2) == '+' return '!' text = 'here is +some*+ text and also +some more*+ text here' replaced = re.sub(r'(\*\+)|(\+)', replacer, text) </code></pre...
-1
2016-08-18T12:45:27Z
[ "python", "str-replace" ]
python - lists are being read in from csv as strings
39,018,150
<p>I have a dictionary that uses an strings(edit) as keys and stores lists of lists as values.</p> <pre><code>dict = {key1: [[data1],[data2],[data3]], key2: [[data4],[data5]],...etc} </code></pre> <p>EDIT: where the data variables are rows containing different data types from a converted pandas DataFrame</p> <p>Ex.<...
2
2016-08-18T12:23:52Z
39,018,399
<p>your code must be like :</p> <pre><code>import csv import ast #dict = {1: [[1],[2],[3]], 2: [[4],[5]]} reader = csv.reader(open("storage.csv", 'r')) dict = {} for key,val in reader: dict[int(key)] = ast.literal_eval(val) print dict </code></pre>
1
2016-08-18T12:34:39Z
[ "python", "csv", "pandas", "read-write" ]
python - lists are being read in from csv as strings
39,018,150
<p>I have a dictionary that uses an strings(edit) as keys and stores lists of lists as values.</p> <pre><code>dict = {key1: [[data1],[data2],[data3]], key2: [[data4],[data5]],...etc} </code></pre> <p>EDIT: where the data variables are rows containing different data types from a converted pandas DataFrame</p> <p>Ex.<...
2
2016-08-18T12:23:52Z
39,018,494
<p><strong>Edit:</strong> Since you are using a <code>pandas.DataFrame</code> don't use the <code>csv</code> module or <code>json</code> module. Instead, use <a href="http://pandas.pydata.org/pandas-docs/stable/io.html" rel="nofollow"><code>pandas.io</code></a> for both reading and writing.</p> <hr> <p><strong>Origi...
3
2016-08-18T12:39:33Z
[ "python", "csv", "pandas", "read-write" ]
Python: how to find elements in array x which have values close to elements in array y?
39,018,232
<p>Elements in arrays <em>x</em> and <em>y</em> are floats. I would like to find elements in array <em>x</em> which have values as close as possible to the ones in array <em>y</em> (for each value in array <em>y</em> - one element in array <em>x</em>). Also array <em>x</em> contains >10^6 elements and array <em>y</em> ...
1
2016-08-18T12:27:50Z
39,018,271
<p>maybe sort the larger array, then binary search the smaller array's values from it, if found that is the closest value and the nearby values are next to it in nearby indexes, if not found, then the closest values are next to the point of failure. </p>
0
2016-08-18T12:30:03Z
[ "python", "arrays", "elements" ]
Python: how to find elements in array x which have values close to elements in array y?
39,018,232
<p>Elements in arrays <em>x</em> and <em>y</em> are floats. I would like to find elements in array <em>x</em> which have values as close as possible to the ones in array <em>y</em> (for each value in array <em>y</em> - one element in array <em>x</em>). Also array <em>x</em> contains >10^6 elements and array <em>y</em> ...
1
2016-08-18T12:27:50Z
39,019,151
<p>The following gives the desired result.</p> <pre><code>x[abs((np.tile(x, (len(y), 1)).T - y).T).argmin(axis=1)] </code></pre> <p>It <code>tile</code>s <code>x</code> for each element in <code>y</code> (<code>len(y)</code>), transposes (<code>.T</code>) this tiled array, subtracts <code>y</code>, re-transposes it, ...
0
2016-08-18T13:10:28Z
[ "python", "arrays", "elements" ]
Python: how to find elements in array x which have values close to elements in array y?
39,018,232
<p>Elements in arrays <em>x</em> and <em>y</em> are floats. I would like to find elements in array <em>x</em> which have values as close as possible to the ones in array <em>y</em> (for each value in array <em>y</em> - one element in array <em>x</em>). Also array <em>x</em> contains >10^6 elements and array <em>y</em> ...
1
2016-08-18T12:27:50Z
39,019,247
<p>It come at the cost of the order of x and y, but is that code answer your needs of performance? Rem: the same value from x could be used for more than one value of y.</p> <pre><code>import numpy as np # x = np.array([0, 0.2, 1, 2.4, 3, 5]); # y = np.array([0, 1, 2]); x = np.random.rand(10**6)*5000000 y = (np.rand...
2
2016-08-18T13:15:46Z
[ "python", "arrays", "elements" ]
Python list filter performance
39,018,238
<p>I'm trying to do</p> <pre><code>In [21]: l1 = range(1,1000000) In [22]: l2 = range(100,90000) In [23]: l1.append(101) In [24]: print(set([x for x in l1 if l1.count(x) - l2.count(x) == 1])) </code></pre> <p>in my python shell this takes ages. Generally my goal is to substract a list from a second one while takin...
2
2016-08-18T12:28:13Z
39,018,440
<p><strong>Non order preserving</strong> using <code>collections.Counter</code>:</p> <pre><code>from collections import Counter a = Counter([1, 2, 2, 3]) b = Counter([2, 3]) res = list(a - b ) # [1, 2] </code></pre> <p>This works because the <code>-</code> method of a <code>Counter</code> removes any elements from t...
5
2016-08-18T12:36:30Z
[ "python", "performance" ]
Python list filter performance
39,018,238
<p>I'm trying to do</p> <pre><code>In [21]: l1 = range(1,1000000) In [22]: l2 = range(100,90000) In [23]: l1.append(101) In [24]: print(set([x for x in l1 if l1.count(x) - l2.count(x) == 1])) </code></pre> <p>in my python shell this takes ages. Generally my goal is to substract a list from a second one while takin...
2
2016-08-18T12:28:13Z
39,018,453
<p>I think that I would use <code>Counter</code>, then convert the result of subtracting the two counters to a sorted list:</p> <pre><code>from collections import Counter l1 = [1, 2, 2, 3] l2 = [2, 3] counter_l1 = Counter(l1) counter_l2 = Counter(l2) res = counter_l1 - counter_l2 print(sorted(res)) &gt;&gt; [1, 2]...
0
2016-08-18T12:37:06Z
[ "python", "performance" ]
Python list filter performance
39,018,238
<p>I'm trying to do</p> <pre><code>In [21]: l1 = range(1,1000000) In [22]: l2 = range(100,90000) In [23]: l1.append(101) In [24]: print(set([x for x in l1 if l1.count(x) - l2.count(x) == 1])) </code></pre> <p>in my python shell this takes ages. Generally my goal is to substract a list from a second one while takin...
2
2016-08-18T12:28:13Z
39,018,482
<p>Count the elements first:</p> <pre><code>from collections import defaultdict count1 = defaultdict(int) count2 = defaultdict(int) for x in l1: count1[x] += 1 for x in l2: count2[x] += 1 print([x for x, count in count1.iteritems() if count - count2[x] == 1]) </code></pre> <p>(don't forget to convert <code...
0
2016-08-18T12:38:50Z
[ "python", "performance" ]
Python list filter performance
39,018,238
<p>I'm trying to do</p> <pre><code>In [21]: l1 = range(1,1000000) In [22]: l2 = range(100,90000) In [23]: l1.append(101) In [24]: print(set([x for x in l1 if l1.count(x) - l2.count(x) == 1])) </code></pre> <p>in my python shell this takes ages. Generally my goal is to substract a list from a second one while takin...
2
2016-08-18T12:28:13Z
39,018,904
<p>execute time:</p> <pre><code>import time from functools import wraps from collections import defaultdict from collections import Counter, OrderedDict class OrderedCounter(Counter, OrderedDict):pass def tefn(fn): t = time.time() set(fn()) return t - time.time() def efn(fn): t = time.time() fn()...
0
2016-08-18T12:58:23Z
[ "python", "performance" ]
Python list filter performance
39,018,238
<p>I'm trying to do</p> <pre><code>In [21]: l1 = range(1,1000000) In [22]: l2 = range(100,90000) In [23]: l1.append(101) In [24]: print(set([x for x in l1 if l1.count(x) - l2.count(x) == 1])) </code></pre> <p>in my python shell this takes ages. Generally my goal is to substract a list from a second one while takin...
2
2016-08-18T12:28:13Z
39,076,830
<p>I learned that the merge pattern is even faster (read <a href="http://openbookproject.net/thinkcs/python/english3e/list_algorithms.html#alice-in-wonderland-again" rel="nofollow">http://openbookproject.net/thinkcs/python/english3e/list_algorithms.html#alice-in-wonderland-again</a>):</p> <pre><code> 6 def substract_...
0
2016-08-22T10:12:53Z
[ "python", "performance" ]
Python/Tkinter - delete all objects in enclosed area
39,018,279
<p>I am trying to make a program where on click the program would delete all objects in enclosed area.</p> <p>Here is my example code:</p> <pre><code>import tkinter as tk root = tk.Tk() cv = tk.Canvas(root, height=400, width=400) cv.pack() cv.create_rectangle(50, 50, 100, 100) cv.create_line(60, 60, 80, 80) cv.c...
0
2016-08-18T12:30:23Z
39,018,409
<p>You have to apply <code>delete</code> to all items of the list</p> <pre><code>for d in todel: cv.delete(d) </code></pre> <p>or</p> <pre><code>any(map(cv.delete,todel)) </code></pre>
2
2016-08-18T12:35:01Z
[ "python", "canvas", "tkinter" ]
How to improve my coding style for assigning a new value?
39,018,292
<p>Is there a better way to write the third line of following code ?</p> <pre><code>from datetime import date d = date.today() d = d.replace(day=1) </code></pre>
-1
2016-08-18T12:30:46Z
39,018,598
<p>How about</p> <pre><code>d = date.today().replace(day=1) </code></pre>
1
2016-08-18T12:44:34Z
[ "python", "pep8" ]
How to improve my coding style for assigning a new value?
39,018,292
<p>Is there a better way to write the third line of following code ?</p> <pre><code>from datetime import date d = date.today() d = d.replace(day=1) </code></pre>
-1
2016-08-18T12:30:46Z
39,018,895
<p>you did it right.</p> <p>another suggestion:</p> <pre><code>current_date=date.today() fixed_date=date(current_date.year, current_date.month, 1) </code></pre>
0
2016-08-18T12:58:01Z
[ "python", "pep8" ]
super() gives an error in Python 2
39,018,313
<p>I just started learning Python and I don't quite understand where the problem in this code is. I have a base class Proband with two methods and I want to create a subclass Gesunder and I want to override the attributes idn,artefakte. </p> <pre><code>import scipy.io class Proband: def __init__(self,idn,artefakte):...
-1
2016-08-18T12:31:25Z
39,018,362
<p>In Python 2, <code>super()</code> on its own is invalid. Instead, you must use <code>super(ClassName, self)</code>.</p> <pre><code>super(Gesunder, self).__init__(self, idn, artefakte) </code></pre>
0
2016-08-18T12:33:19Z
[ "python", "subclass", "super" ]
super() gives an error in Python 2
39,018,313
<p>I just started learning Python and I don't quite understand where the problem in this code is. I have a base class Proband with two methods and I want to create a subclass Gesunder and I want to override the attributes idn,artefakte. </p> <pre><code>import scipy.io class Proband: def __init__(self,idn,artefakte):...
-1
2016-08-18T12:31:25Z
39,018,371
<p>The <code>super()</code> call should be modified to :</p> <pre><code>super(Gesunder, self).__init__(self, idn, artefakte) </code></pre>
0
2016-08-18T12:33:42Z
[ "python", "subclass", "super" ]
super() gives an error in Python 2
39,018,313
<p>I just started learning Python and I don't quite understand where the problem in this code is. I have a base class Proband with two methods and I want to create a subclass Gesunder and I want to override the attributes idn,artefakte. </p> <pre><code>import scipy.io class Proband: def __init__(self,idn,artefakte):...
-1
2016-08-18T12:31:25Z
39,018,545
<p>You have 2 problems in your code. In python 2:</p> <ol> <li><code>super()</code> takes 2 arguments: the class name, and the instance</li> <li>in order to use <code>super()</code>, the base class must inherit from <code>object</code></li> </ol> <p>So your code becomes:</p> <pre><code>import scipy.io class Proband...
2
2016-08-18T12:42:14Z
[ "python", "subclass", "super" ]
django test RequestFactory cannot get route parameter to work
39,018,431
<p>I have a problem that I don't know how to make it work. </p> <p>urls.py:</p> <pre><code>urlpatterns = [ url(r'athletes/search$', SearchAthletes.as_view()), url(r'athletes/([0-9]+)$', ViewAthlete.as_view()) ] </code></pre> <p>views.py:</p> <pre><code>class ViewAthlete(APIView): def get(self, request,...
0
2016-08-18T12:36:10Z
39,018,687
<p>AFAIK <code>urlpatterns</code> are considered when testing through the full django request stack, e.g.: through <code>django.test.Client</code>, using it's <code>get</code>/<code>post</code> methods</p> <p>When testing your view directly (<code>MyView.as_view()(request)</code>) the whole url resolver logic is bypas...
2
2016-08-18T12:48:23Z
[ "python", "django" ]
django test RequestFactory cannot get route parameter to work
39,018,431
<p>I have a problem that I don't know how to make it work. </p> <p>urls.py:</p> <pre><code>urlpatterns = [ url(r'athletes/search$', SearchAthletes.as_view()), url(r'athletes/([0-9]+)$', ViewAthlete.as_view()) ] </code></pre> <p>views.py:</p> <pre><code>class ViewAthlete(APIView): def get(self, request,...
0
2016-08-18T12:36:10Z
39,018,854
<p>As zsepi says, your URLs aren't used here. To avoid repeating the arguments, rather than calling the view directly you could use the test client to "call" the URL: another advantage of doing this is that the middleware runs, so you don't need to assign the user attribute separately.</p> <pre><code>response = self.c...
0
2016-08-18T12:56:03Z
[ "python", "django" ]
Padding elements of a numpy array
39,018,476
<p>Lets say that I have the following <code>numpy array</code>:</p> <pre><code>[[1,1,1] [1,1,1] [1,1,1]] </code></pre> <p>And I need to pad each element in the array with a zero on either side (rather then <code>numpy.pad()</code> which pads rows and columns). This ends up as follows:</p> <pre><code>[ [0,1,0,0,1,0...
3
2016-08-18T12:38:35Z
39,018,798
<p>Flatten the array, convert each 1 to [0, 1, 0], then reshape again to 3 rows. In the following code the ones array is in var a:</p> <pre><code>a = np.ones([3,3]) b = [[0, x, 0] for x in a.ravel()] c = np.reshape(b, (a.shape[0], -1)) print(c) </code></pre> <p>Output:</p> <pre><code>[[0 1 0 0 1 0 0 1 0] [0 1 0 0...
1
2016-08-18T12:53:10Z
[ "python", "arrays", "numpy" ]
Padding elements of a numpy array
39,018,476
<p>Lets say that I have the following <code>numpy array</code>:</p> <pre><code>[[1,1,1] [1,1,1] [1,1,1]] </code></pre> <p>And I need to pad each element in the array with a zero on either side (rather then <code>numpy.pad()</code> which pads rows and columns). This ends up as follows:</p> <pre><code>[ [0,1,0,0,1,0...
3
2016-08-18T12:38:35Z
39,018,893
<p>You can create the related indices with <code>np.repeat</code> based on array's shape, then insert the 0 in that indices.</p> <pre><code>&gt;&gt;&gt; def padder(arr, n): ... x, y = arr.shape ... indices = np.repeat(np.arange(y+1), n*2)[n:-n] ... return np.insert(arr, indices, 0, axis=1) ... &gt;&gt;&gt...
1
2016-08-18T12:57:56Z
[ "python", "arrays", "numpy" ]
Padding elements of a numpy array
39,018,476
<p>Lets say that I have the following <code>numpy array</code>:</p> <pre><code>[[1,1,1] [1,1,1] [1,1,1]] </code></pre> <p>And I need to pad each element in the array with a zero on either side (rather then <code>numpy.pad()</code> which pads rows and columns). This ends up as follows:</p> <pre><code>[ [0,1,0,0,1,0...
3
2016-08-18T12:38:35Z
39,018,913
<p>Here's an approach using <code>zeros-initialization</code> -</p> <pre><code>def padcols(arr,padlen): N = 1+2*padlen m,n = arr.shape out = np.zeros((m,N*n),dtype=arr.dtype) out[:,padlen+np.arange(n)*N] = arr return out </code></pre> <p>Sample run -</p> <pre><code>In [118]: arr Out[118]: array(...
6
2016-08-18T12:58:55Z
[ "python", "arrays", "numpy" ]
Padding elements of a numpy array
39,018,476
<p>Lets say that I have the following <code>numpy array</code>:</p> <pre><code>[[1,1,1] [1,1,1] [1,1,1]] </code></pre> <p>And I need to pad each element in the array with a zero on either side (rather then <code>numpy.pad()</code> which pads rows and columns). This ends up as follows:</p> <pre><code>[ [0,1,0,0,1,0...
3
2016-08-18T12:38:35Z
39,028,460
<p>A problem with time and memory comparison of these methods is that it treats <code>insert</code> as a blackbox. But that function is Python code that can be read and replicated. While it can handle various kinds of inputs, in this case I think it</p> <ul> <li>generates a <code>new</code> target array of the right...
0
2016-08-18T22:28:21Z
[ "python", "arrays", "numpy" ]
How to build Side Bar Menu which shows on mouse hover on pyqt?
39,018,549
<p>I have been trying to build an app which has a dynamic side bar. I am using qtdesigner and pyqt5. I tryed in two ways:</p> <p>1) Using stylesheet whith hover. But the sidebar (frame) has buttons on it. It happens that when I see the bar I just can see the button which has the mouse on.</p> <p>stylesheetcode:</p> ...
1
2016-08-18T12:42:22Z
39,079,379
<p>I spent a little time reading the docs. The simplest way I found was this:</p> <p>in the class <strong>init</strong> I installed a filter, then I overide the eventFilter method.</p> <pre><code>class MainScreen(QMainWindow, QDialog, Ui_TelaPrincipal): def __init__(self, parent=None): super(MainScreen, ...
0
2016-08-22T12:19:07Z
[ "python", "qt", "pyqt", "qt-designer" ]
Django: passing variable to simple_tag other than id fails
39,018,599
<p>Situation is simple: I want to show a specific object (model Block) in a template like this: <code>{% block_by_name editorial as b %} {{ b.title }}</code> or, preferably with a filter like this <code>{{ block.title|get_by_name:editorial }}</code>.</p> <p>I succeeded with a simple_tag.</p> <h3>Getting items by id w...
0
2016-08-18T12:44:37Z
39,018,711
<p>But you didn't pass <code>"editorial"</code>, you passed <code>editorial</code>. That's a variable, which does not exist. Use the string.</p>
0
2016-08-18T12:49:14Z
[ "python", "django", "django-templates", "django-custom-tags" ]
Sorting separately over different attributes in django
39,018,728
<p>I have a mongodb collection of ~80,000 documents. I want to display the top 200 documents per attribute on a webpage, where the user can sort by different attributes by using a dropdown menu on the webpage.</p> <p>At the moment I'm returning a queryset per attribute and then combining them, but this is super slow: ...
1
2016-08-18T12:50:04Z
39,019,056
<p>I think(haven't tested) you can use the initial query set object and sort it by different attributes with python's sorted </p> <pre><code>all_people = People.objects().all()[:200] tall_people = sorted(all_people, key=lambda person: person.height) heavy_people = sorted(all_people, key=lambda person: person.weight) ...
0
2016-08-18T13:06:07Z
[ "python", "django", "mongodb", "mongoengine" ]
Sorting separately over different attributes in django
39,018,728
<p>I have a mongodb collection of ~80,000 documents. I want to display the top 200 documents per attribute on a webpage, where the user can sort by different attributes by using a dropdown menu on the webpage.</p> <p>At the moment I'm returning a queryset per attribute and then combining them, but this is super slow: ...
1
2016-08-18T12:50:04Z
39,019,167
<p>A <em>slightly</em> more efficient way is to fetch only the IDs for each group, and then do a final query to get the objects:</p> <pre><code>tall_people = People.objects().values_list('pk', flat=True).order_by('-height')[:200] heavy_people = People.objects().values_list('pk', flat=True).order_by('-weight')[:200] o...
0
2016-08-18T13:11:04Z
[ "python", "django", "mongodb", "mongoengine" ]
Creating a hierarchy of methods in a class?
39,018,742
<p>I have class with hundreds of methods I want create a hierarchy of them that will let easy find method. </p> <p>For example</p> <pre><code>class MyClass: def SpectrumFrequencyStart()... def SpectrumFrequencyStop()... def SpectrumFrequencyCenter()... def SignalAmplitudedBm()... </code></pre> <p>Tha...
-5
2016-08-18T12:50:48Z
39,019,015
<p>Consider using a dictionary to map your methods to keys (either hierarchical dictionaries, or simply '.' separated keys).</p> <p>Another option which may be more elegant is <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="nofollow">namedtuples</a>. Something like:</p> <pre><...
0
2016-08-18T13:03:52Z
[ "python" ]
Creating a hierarchy of methods in a class?
39,018,742
<p>I have class with hundreds of methods I want create a hierarchy of them that will let easy find method. </p> <p>For example</p> <pre><code>class MyClass: def SpectrumFrequencyStart()... def SpectrumFrequencyStop()... def SpectrumFrequencyCenter()... def SignalAmplitudedBm()... </code></pre> <p>Tha...
-5
2016-08-18T12:50:48Z
39,019,488
<p>This is just a very bad design.<br> It's clear that <code>Spectrum</code>, <code>Signal</code>, <code>Frequency</code> (and so on) should be all separate classes with much less than "hundreds of methods".<br> I'm not sure if MyClassObject actually represents something or is effectively just a namespace.<br> Objects ...
0
2016-08-18T13:28:22Z
[ "python" ]
Exception handler to check if inline script for variable worked
39,018,875
<p>I need to add exception handling that considers if line 7 fails because there is no intersection between the query and array brands. I'm new to using exception handlers and would appreciate any advice or solutions. </p> <p>I have written an example structure for exception handling, but I am not certain whether it w...
-1
2016-08-18T12:56:55Z
39,018,999
<p>This is not the best way to do it, but it is <strong>a</strong> way.</p> <pre><code>def brandSelector(query): try: brand = set(brands).intersection(query.split()) brand = ', '.join(brand) return brand except ValueError: print("Brand does not exist") query = input("Ent...
2
2016-08-18T13:03:01Z
[ "python", "arrays", "function", "error-handling", "exception-handling" ]
Exception handler to check if inline script for variable worked
39,018,875
<p>I need to add exception handling that considers if line 7 fails because there is no intersection between the query and array brands. I'm new to using exception handlers and would appreciate any advice or solutions. </p> <p>I have written an example structure for exception handling, but I am not certain whether it w...
-1
2016-08-18T12:56:55Z
39,019,092
<p>When querying input from user, especially when you expect user to input bad data, I tend to put the querying function inside an infinite loop and break out when input data makes sense. As Ev. Kounis points out, there are many ways to do this. Here's a way I would do (untested code):</p> <pre><code>brands = ["apple"...
2
2016-08-18T13:07:38Z
[ "python", "arrays", "function", "error-handling", "exception-handling" ]
Plotting Coordinate Lines Using Matplotlib
39,018,945
<p>I want to plot the co-ordinate lines of a co-ordinate system (e.g. Cartesian co-ords) using matplotlib. </p> <p>Then I want to transform them using some linear transform (skew, scale, rotate, etc.), and I want to plot this transformed version of the system as well. </p> <p>I am quite new to matplotlib and I have n...
0
2016-08-18T13:00:34Z
39,019,448
<p>This should get you started on the right track</p> <pre><code>import matplotlib import matplotlib.pyplot as plt xx = range(10) yy = range(10) [plt.plot([x,x],[min(yy),max(yy)],color='k') for x in xx] [plt.plot([min(xx),max(xx)],[y,y],color='k') for y in yy] </code></pre>
1
2016-08-18T13:26:09Z
[ "python", "matlab", "matplotlib", "plot" ]
Plotting Coordinate Lines Using Matplotlib
39,018,945
<p>I want to plot the co-ordinate lines of a co-ordinate system (e.g. Cartesian co-ords) using matplotlib. </p> <p>Then I want to transform them using some linear transform (skew, scale, rotate, etc.), and I want to plot this transformed version of the system as well. </p> <p>I am quite new to matplotlib and I have n...
0
2016-08-18T13:00:34Z
39,020,767
<p><a href="http://stackoverflow.com/a/39019448/812786">user2539738's answer</a> demonstrates how to draw a grid in a plot. The next step is applying a transform. This is a mathematical operation which can be described as a function of the x and y coordinates. For example, a shear transform like your example images -<...
1
2016-08-18T14:25:36Z
[ "python", "matlab", "matplotlib", "plot" ]
ctypes using HRESULT(python)
39,018,998
<p>I'm writing a DLL which is being called using a python script as below:</p> <pre><code> //sample.h #include&lt;stdio.h&gt; typedef struct _data { char * name; }data,*xdata; __declspec(dllexport) void getinfo(data xdata,HRESULT *error); //sample.c #include&lt;stdio.h&gt; #include"sample.h" void get(data xdata,H...
0
2016-08-18T13:02:59Z
39,068,518
<p>Per my comments, I suspect the error with <code>fgets()</code> is in code not shown, but there are problems in the Python and C code shown as well. Here's the DLL source I used, making sure to pass a pointer to the data structure:</p> <pre><code>typedef long HRESULT; typedef struct _data { char * name; } data...
0
2016-08-21T20:22:26Z
[ "python", "c++", "dll", "ctypes" ]
In Python3, is `urllib.request` thread-safe?
39,019,045
<p>It's not found if <code>urllib.request</code> is <strong>thread-safe</strong> or not in Pyhton 3 <a href="https://docs.python.org/3/library/urllib.request.html" rel="nofollow">document</a>. Is there anything special that I have to look for when using it in multi-threading scripts?</p>
0
2016-08-18T13:05:43Z
39,019,876
<p>According to <code>urllib.request</code>'s source <a href="https://hg.python.org/cpython/file/3.5/Lib/urllib/request.py#l1642" rel="nofollow">here</a>, <a href="https://hg.python.org/cpython/file/3.5/Lib/urllib/request.py#l1978" rel="nofollow">here</a> and <a href="https://hg.python.org/cpython/file/3.5/Lib/urllib/r...
0
2016-08-18T13:46:03Z
[ "python", "python-3.x", "thread-safety", "urllib", "python-multithreading" ]
How to parse certain text data?
39,019,060
<p>I have a text file with such a format: </p> <p><code>B2100 Door Driver Key Cylinder Switch Failure B2101 Head Rest Switch Circuit Failure B2102 Antenna Circuit Short to Ground`, plus 1000 lines more. </code></p> <p>This is how I want it to be:</p> <p><code>B2100*Door Driver Key Cylinder Switch Failure B210...
1
2016-08-18T13:06:21Z
39,019,395
<p>First, your regex is wrong '\^B[0-9][0-9][0-9][0-9]$\gi</p> <ol> <li>The modifiers don't work this way on Python</li> <li>The ^ and $ means beginning and end of the line, which wouldn't match anything on your text</li> <li>The multiples [0-9] can be replaced with a '[0-9]{4}'</li> <li>If you want ignore case use th...
0
2016-08-18T13:23:17Z
[ "python", "text-processing" ]
How to parse certain text data?
39,019,060
<p>I have a text file with such a format: </p> <p><code>B2100 Door Driver Key Cylinder Switch Failure B2101 Head Rest Switch Circuit Failure B2102 Antenna Circuit Short to Ground`, plus 1000 lines more. </code></p> <p>This is how I want it to be:</p> <p><code>B2100*Door Driver Key Cylinder Switch Failure B210...
1
2016-08-18T13:06:21Z
39,019,521
<pre><code>import re text = """B2100 Door Driver Key Cylinder Switch Failure B2101 Head Rest Switch Circuit Failure B2102 Antenna Circuit Short to Ground B2103 Antenna Not Connected B2104 Door Passenger Key Cylinder Switch Failure B2105 Throttle Position Input Out of Range Low B2106 Throttle Position Input Out...
0
2016-08-18T13:29:44Z
[ "python", "text-processing" ]
How to parse certain text data?
39,019,060
<p>I have a text file with such a format: </p> <p><code>B2100 Door Driver Key Cylinder Switch Failure B2101 Head Rest Switch Circuit Failure B2102 Antenna Circuit Short to Ground`, plus 1000 lines more. </code></p> <p>This is how I want it to be:</p> <p><code>B2100*Door Driver Key Cylinder Switch Failure B210...
1
2016-08-18T13:06:21Z
39,019,530
<p>Basically, you want to:</p> <ul> <li>Find any Bxxxx strings in the input.</li> <li>Replace any whitespace before them with a newline.</li> <li>Replace any whitespace after them with a <code>*</code>.</li> </ul> <p>This can all be done with a single <code>re.sub()</code>:</p> <pre><code>re.sub(r'\s*(B\d{4})\s*', r...
5
2016-08-18T13:30:01Z
[ "python", "text-processing" ]
How to parse certain text data?
39,019,060
<p>I have a text file with such a format: </p> <p><code>B2100 Door Driver Key Cylinder Switch Failure B2101 Head Rest Switch Circuit Failure B2102 Antenna Circuit Short to Ground`, plus 1000 lines more. </code></p> <p>This is how I want it to be:</p> <p><code>B2100*Door Driver Key Cylinder Switch Failure B210...
1
2016-08-18T13:06:21Z
39,020,006
<p>import re</p> <p>import pandas as pd</p> <p>pat= r"(B\d+)"</p> <p>zzz=[i for i in re.split(pat,kkk) if i!='']</p> <p>pd.DataFrame({'Col1': zzz[::2],'Col2':[i.strip() for i in zzz if re.match(pat,i) is None] })</p> <p>Col1 Col2</p> <p>0 B2100 Door Driver Key Cylinder Switch Failure</p> <p>1 B2101 ...
0
2016-08-18T13:50:59Z
[ "python", "text-processing" ]
Delete pandas group based on condition
39,019,252
<p>I have a pandas dataframe in with several groups and I would like to exclude groups where some conditions (in a specific column) are not met. E.g. delete here group B because they have a non-number value in column "crit1".</p> <p>I could delete specific columns based on the condition <code>df.loc[:, (df &gt;&lt; 0)...
2
2016-08-18T13:16:02Z
39,019,380
<p>You can use <code>groupby</code> and <code>filter</code>, for the example you give you can check if <code>np.inf</code> exists in a group and <code>filter</code> on the condition:</p> <pre><code>import pandas as pd import numpy as np df.groupby('name').filter(lambda g: (g != np.inf).all().all()) # name crit1 ...
1
2016-08-18T13:22:38Z
[ "python", "pandas", "filter" ]
Handling keyboard interrupt in async zmq
39,019,354
<p>I'm making a ZeroMQ server in <code>pyzmq</code> using <code>asyncio</code>. I'm trying to gracefully handle stopping the server, but there's very little documentation on the async module and there doesn't seem to be a simple way to handle stopping the current poll/await. Stopping the loop in the <code>.stop</code> ...
0
2016-08-18T13:20:39Z
39,403,026
<p>It ended up being a bug in the implementation of <code>pyzmq</code>. The bug was fixed and now calling <code>loop.stop()</code> works as intended.</p>
0
2016-09-09T02:40:52Z
[ "python", "zeromq", "python-asyncio", "pyzmq" ]
Inserting a file name to Postgres table
39,019,516
<p>I have the following code to insert the file name to Postgres table called 'logs'</p> <pre><code>c = engine.connect() conn = c.connection cur = conn.cursor() cur.execute("SELECT filename from logs" ) rows1 = cur.fetchall() rows1 = [x[0] for x in rows1] for root, directories, filenames in os.walk(path): for fi...
0
2016-08-18T13:29:34Z
39,019,631
<p>You haven't passed any parameters to the query, so no replacement will be made; the adapter will pass the literal string <code>(%(fname)s)</code> to Postgres.</p> <pre><code>cur.execute("""INSERT INTO logs(filename) VALUES (%(fname)s)""", {'fname': fname'}) </code></pre>
0
2016-08-18T13:33:52Z
[ "python", "postgresql", "for-loop" ]
How to calculate variables from worksheet columns using xlrd?
39,019,564
<p>I am attempting to calculate all variables of a specific value in a given column from an Excel document. I want to be able to iterate over the column and calculate the total of each instance... e.g. how many students received a grade "A".</p> <p>Here is what I have so far...</p> <p>test.xls:</p> <blockquote> <p...
1
2016-08-18T13:31:04Z
39,019,706
<pre><code>for rownum in range(sh.nrows): grades = str(sh.cell(rownum, 2).value) # Grab all variables in column 2. print Counter(grades.split('\n')) # Count grades </code></pre> <p>You are creating a list in every iteration.</p> <p>You can use list comprehension to a create a single list with all the grades:...
0
2016-08-18T13:37:20Z
[ "python", "xlrd", "python-collections" ]
How to calculate variables from worksheet columns using xlrd?
39,019,564
<p>I am attempting to calculate all variables of a specific value in a given column from an Excel document. I want to be able to iterate over the column and calculate the total of each instance... e.g. how many students received a grade "A".</p> <p>Here is what I have so far...</p> <p>test.xls:</p> <blockquote> <p...
1
2016-08-18T13:31:04Z
39,019,931
<p>You can start by instantiating a <code>Counter</code> and then add grades to it while you iterate:</p> <pre><code>grades_counter = Counter() mysheet = xlrd.open_workbook('grades.xls').sheet_by_index(0) for i in range(1,mysheet.nrows): grades_counter += Counter(str(mysheet.row_values(i)[2])) print grades_count...
0
2016-08-18T13:48:21Z
[ "python", "xlrd", "python-collections" ]
Duplicated rows when merging dataframes in python
39,019,591
<p>I am currently merging 2 dataframes with an outer join, but after merging, I see all the rows are duplicated even when the columns I did the merge upon contain the same values. In detail:</p> <pre><code>list_1 = pd.read_csv('list_1.csv') list_2 = pd.read_csv('list_2.csv') merged_list = pd.merge(list_1 , list_2 , o...
2
2016-08-18T13:32:00Z
39,019,766
<pre><code>list_2_nodups = list_2.drop_duplicates() pd.merge(list_1 , list_2_nodups , on=['email_address']) </code></pre> <h2><a href="http://i.stack.imgur.com/MXtAP.png" rel="nofollow"><img src="http://i.stack.imgur.com/MXtAP.png" alt="enter image description here"></a></h2> <p>The duplicate rows are expected. Each...
1
2016-08-18T13:40:45Z
[ "python", "python-2.7", "python-3.x", "pandas", "merge" ]
Different grid behavior from inherited Tkinter Text element
39,019,667
<p><a href="http://stackoverflow.com/a/21565476/3884408" title="In another answer here">In another answer here</a>, a user created an inherited TextWithVar class that provides instances of the Tkinter.Text element but with textvariable functionality like Tkinter.Entry has. However, in testing, this new class behaves di...
0
2016-08-18T13:35:33Z
39,022,345
<p>It's a bug in <code>TextWithVar</code>, in this line of code:</p> <pre><code>tk.Text.__init__(self, *args, **kwargs) </code></pre> <p>The code needs to include the <code>parent</code> parameter:</p> <pre><code>tk.Text.__init__(self, parent, *args, **kwargs) </code></pre>
0
2016-08-18T15:39:26Z
[ "python", "tkinter" ]
How to execute twitter.Api.PostUpdate in loop?
39,019,773
<p>This code executes with error:</p> <pre><code> # some constants and auth before, looks not important topPosts = reddit.get_subreddit('funny').get_top(limit=3) for post in topPosts: twitter.PostUpdate(status = post.title, media = post.url) </code></pre> <p>Console log:</p> <pre><code>Traceback (most r...
0
2016-08-18T13:40:58Z
39,027,335
<p>This is a bug in <code>python-twitter</code> library and it's fixed in this <a href="https://github.com/bear/python-twitter/pull/347/files#diff-ca47863eef03007ed84692b07b74eda6L1132" rel="nofollow">PR</a>. The problem is that <code>bytes</code> in python2 equals to <code>str</code> and accepts only one argument whil...
1
2016-08-18T20:54:24Z
[ "python", "twitter", "praw" ]
Get attributes from an XML tag using Python
39,019,779
<p>I am trying to grab the attributes from an XML tag so I can get the correct data and place it in a CSV file</p> <p>I have attempted to find some answers, but have found nothing definitive other than how to grab that tag itself, or get the attributes using another language. </p> <p>Here is what a line from the XML ...
0
2016-08-18T13:41:08Z
39,020,032
<p>An <a href="https://docs.python.org/2/library/xml.etree.elementtree.html?highlight=elementtree#xml.etree.ElementTree.Element" rel="nofollow">xml.etree.ElementTree.Element</a> also has an <code>attrib</code> property, which is a dictionary containing the element’s attributes</p> <pre><code>&gt;&gt;&gt; item.attrib...
2
2016-08-18T13:52:17Z
[ "python", "xml", "csv" ]
Issue with Selenium,Python
39,019,917
<p>I have written the following. </p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys bot = webdriver.Firefox() bot.find_element_by_name("username").send_keys(config['username']) </code></pre> <p>When I am using send_keys and happen to be typing at the same instant, then wh...
1
2016-08-18T13:47:55Z
39,020,817
<p>I see 2 options:</p> <ol> <li><p>Create hidden input send keys to it than perform copy/paste from hidden to visible input, after remove hidden input. </p></li> <li><p>Hide input, than send_keys to it and after show it back. </p></li> </ol> <p>Usefull links:</p> <p><a href="http://stackoverflow.com/questions/11750...
0
2016-08-18T14:27:48Z
[ "python", "selenium" ]
Issue with Selenium,Python
39,019,917
<p>I have written the following. </p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys bot = webdriver.Firefox() bot.find_element_by_name("username").send_keys(config['username']) </code></pre> <p>When I am using send_keys and happen to be typing at the same instant, then wh...
1
2016-08-18T13:47:55Z
39,020,920
<p>You can use executeScript method:</p> <pre><code>webdriver.execute_script("document.getElementById('username').setAttribute('value', 'Sandeep')") </code></pre> <p><code>JavaScript</code> will do text insertion as single operation. </p>
1
2016-08-18T14:32:14Z
[ "python", "selenium" ]
Count occurrences of certain values in dask.dataframe
39,019,918
<p>I have a dataframe like this:</p> <pre><code>df.head() day time resource_record 0 27 00:00:00 AAAA 1 27 00:00:00 A 2 27 00:00:00 AAAA 3 27 00:00:01 A 4 27 00:00:02 A </code></pre> <p>and want to find out how ma...
0
2016-08-18T13:47:55Z
39,023,088
<p>One quite nice method I found is this:</p> <pre><code>counts = df.resource_record.mask(df.resource_record.isin(['AAAA'])).dropna().value_counts() </code></pre> <p>First we mask all entries we'd like to get removed, which replaces the value with NaN. Then we drop all rows with NaN and last count the occurrences of ...
0
2016-08-18T16:18:27Z
[ "python", "dask" ]
Count occurrences of certain values in dask.dataframe
39,019,918
<p>I have a dataframe like this:</p> <pre><code>df.head() day time resource_record 0 27 00:00:00 AAAA 1 27 00:00:00 A 2 27 00:00:00 AAAA 3 27 00:00:01 A 4 27 00:00:02 A </code></pre> <p>and want to find out how ma...
0
2016-08-18T13:47:55Z
39,048,119
<p>In most cases pandas syntax will work as well with dask, with the necessary addition of <code>.compute()</code> (or <code>dask.compute</code>) to actually perform the action. Until the compute, you are merely constructing the graph which defined the action.</p> <p>I believe the simplest solution to your question is...
0
2016-08-19T21:47:27Z
[ "python", "dask" ]
Working with checkboxes in tkinter (pygubu)
39,019,935
<p>I created a window with the GUI maker pygubu. This window contains checkboxes. But my script is not able to recognize if the checkboxes are marked or not. How do I have to check if the checkboxes are marked or not? Do Ihave to use the command or the variable? What is the right syntax?</p> <p>Below you can see what ...
-1
2016-08-18T13:48:24Z
39,020,843
<p>As per the example from here <a href="http://www.python-course.eu/tkinter_checkboxes.php" rel="nofollow">http://www.python-course.eu/tkinter_checkboxes.php</a></p> <pre><code>from tkinter import * master = Tk() var1 = IntVar() Checkbutton(master, text="male", variable=var1).grid(row=0, sticky=W) var2 = IntVar() Che...
0
2016-08-18T14:28:41Z
[ "python", "checkbox", "tkinter" ]
Working with checkboxes in tkinter (pygubu)
39,019,935
<p>I created a window with the GUI maker pygubu. This window contains checkboxes. But my script is not able to recognize if the checkboxes are marked or not. How do I have to check if the checkboxes are marked or not? Do Ihave to use the command or the variable? What is the right syntax?</p> <p>Below you can see what ...
-1
2016-08-18T13:48:24Z
39,020,877
<p>Thanks for clarifying your question. Now that I know you're using Pygubu to build your GUI, I could look into it a little more. I found the following doc page that could help with your issue: <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Checkbutton.html" rel="nofollow">http://infohost.nmt.edu/tcc/h...
0
2016-08-18T14:30:05Z
[ "python", "checkbox", "tkinter" ]
Working with checkboxes in tkinter (pygubu)
39,019,935
<p>I created a window with the GUI maker pygubu. This window contains checkboxes. But my script is not able to recognize if the checkboxes are marked or not. How do I have to check if the checkboxes are marked or not? Do Ihave to use the command or the variable? What is the right syntax?</p> <p>Below you can see what ...
-1
2016-08-18T13:48:24Z
39,081,698
<p>Finally I found an inelegant way to do it. It's not very "pretty", but it works:</p> <pre><code>self.xxx1 = 0 def checker13(self): if self.xxx1 == 0: self.xxx1 = self.xxx1+1 else: self.xxx1 = 0 </code></pre> <p>Normally the checkbox is not marked and the value is <code>0</code>. If the ch...
0
2016-08-22T14:07:47Z
[ "python", "checkbox", "tkinter" ]
How do I access Python code programmatically? For example, getting a list of classes, its docstrings, etc?
39,019,962
<p>I'm trying to read python code (specifically, unit tests) as structured objects.</p> <p>For example.</p> <pre><code>class ProjectA(unittest.TestCase): def testB(self): """ hello world B """ assert False def testA(self): """ hello world """ a...
2
2016-08-18T13:49:19Z
39,020,263
<p>You can explore the class using <a href="https://docs.python.org/2/library/inspect.html" rel="nofollow">inspect</a></p>
0
2016-08-18T14:02:23Z
[ "python" ]
How do I access Python code programmatically? For example, getting a list of classes, its docstrings, etc?
39,019,962
<p>I'm trying to read python code (specifically, unit tests) as structured objects.</p> <p>For example.</p> <pre><code>class ProjectA(unittest.TestCase): def testB(self): """ hello world B """ assert False def testA(self): """ hello world """ a...
2
2016-08-18T13:49:19Z
39,020,330
<p>This is what the <a href="https://docs.python.org/2/library/ast.html" rel="nofollow">ast</a> module is for -- generate abstract syntax trees of Python source:</p> <pre><code>&gt;&gt;&gt; import ast &gt;&gt;&gt; source = '''import unittest ... ... ... class ProjectA(unittest.TestCase): ... ... def testB(self): ....
2
2016-08-18T14:05:55Z
[ "python" ]
Using Python's requests lib throwing ProxyError
39,020,011
<p>I am still new to python and can't figure out how to handle this error and what to do with it to avoid it.</p> <p>When I use <code>requests.get('http://www.baidu.com')</code></p> <pre><code> import requests header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Ch...
0
2016-08-18T13:51:10Z
39,022,206
<p>your code seems to work and the issue is a network connection error as others have stated. </p> <p>One way to verify the issue via cli (the connection should open ...) </p> <p>$ telnet baidu.com 80 Trying 220.181.57.217... Connected to baidu.com. Escape character is '^]'.</p>
-1
2016-08-18T15:32:51Z
[ "python", "python-requests" ]
Using Python's requests lib throwing ProxyError
39,020,011
<p>I am still new to python and can't figure out how to handle this error and what to do with it to avoid it.</p> <p>When I use <code>requests.get('http://www.baidu.com')</code></p> <pre><code> import requests header = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Ch...
0
2016-08-18T13:51:10Z
39,033,251
<p>I deal with the problem.</p> <p>just add proxies={'http':'','https':''}</p> <p>for example:</p> <pre><code>h=requests.get('http://www.baidu.com', proxies={'http':'','https':''}) </code></pre>
0
2016-08-19T07:20:23Z
[ "python", "python-requests" ]
Python I/O: Mixing The Datatypes
39,020,080
<p>I'm writing a small script which merges a host of JSON files in one directory into a single file. Trouble is, I'm not entirely sure when my data is in which state. TypeErrors abound. Here's the script;</p> <pre><code>import glob import json import codecs reader = codecs.getreader("utf-8") for file in glob.glob("/...
0
2016-08-18T13:54:42Z
39,020,642
<p>If this is Python 3, removing the <code>b</code> (binary mode) to open the file in <em>text mode</em> should work just fine. You probably want to specify the encoding explicitly:</p> <pre><code>with open("test.json", "w", encoding='utf8') as outfile: json.dump(data, outfile, sort_keys = True, indent = 2, ensure...
1
2016-08-18T14:20:12Z
[ "python", "json", "file-io", "types" ]
How to use joblib.Memory of cache the output of a member function of a Python Class
39,020,217
<p>I would like to cache the output of a member function of a class using <code>joblib.Memory</code> library. Here is a sample code:</p> <pre><code>import joblib import numpy as np mem = joblib.Memory(cachedir='/tmp', verbose=1) @mem.cache def my_sum(x): return np.sum(x) class TestClass(object): def __ini...
0
2016-08-18T14:00:38Z
39,515,143
<p>the following excerpt is taken from <a href="https://pythonhosted.org/joblib/memory.html#gotchas" rel="nofollow">https://pythonhosted.org/joblib/memory.html#gotchas</a></p> <blockquote> <p>caching methods: you cannot decorate a method at class definition, because when the class is instantiated, the first argume...
1
2016-09-15T15:38:24Z
[ "python", "caching", "memory", "decorator", "joblib" ]
Python & Scipy: How to fit a von mises distribution?
39,020,222
<p>I'm trying to fit a von Mises distribution, from scipy (<a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.vonmises.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.vonmises.html</a>)</p> <p>So I tried </p> <pre><code>from scipy.stats import vonmises kappa...
0
2016-08-18T14:00:44Z
39,020,834
<p>The returned values are kappa, loc and scale. Unfortunately, the von Mises pdf does not seem to yield itself to fitting. It does fit correctly if you fix the scale:</p> <pre><code>&gt;&gt;&gt; vonmises.fit(r, fscale=1) (2.994517240859579, -0.0080482378119089287, 1) </code></pre>
3
2016-08-18T14:28:11Z
[ "python", "numpy", "scipy" ]
Why does my Python code skips a while loop?
39,020,230
<p>I'm building a guessing program for user's input in range 1 - 100.</p> <p>Why does it skips the second while loop where I check user input and forward it. It goes straight with number 1</p> <pre><code>import random nums_lasted = [] a = 0 while a &lt; 101: nums_lasted.append(a) a += 1 secret_num = 1 while ...
0
2016-08-18T14:00:55Z
39,020,295
<p>Because the condition <code>secret_num &lt; 0 or secret_num &gt; 100</code> is false for <code>secret_num == 1</code>. 1 is definitely between 0 and 100. You should set <code>secret_number</code> to something larger than 100 for this to work as expected.</p>
1
2016-08-18T14:04:09Z
[ "python", "while-loop" ]
Why does my Python code skips a while loop?
39,020,230
<p>I'm building a guessing program for user's input in range 1 - 100.</p> <p>Why does it skips the second while loop where I check user input and forward it. It goes straight with number 1</p> <pre><code>import random nums_lasted = [] a = 0 while a &lt; 101: nums_lasted.append(a) a += 1 secret_num = 1 while ...
0
2016-08-18T14:00:55Z
39,020,298
<pre><code>secret_num = 1 while secret_num &lt; 0 or secret_num &gt; 100: </code></pre> <p>You set <code>secret_num</code> to <code>1</code>. The <code>while</code> will only run when <code>secret_num</code> is less than 0 or grater than 100, so it will never be executed.</p>
3
2016-08-18T14:04:12Z
[ "python", "while-loop" ]
Python web crawler (NameError: name 'spider' is not defined)
39,020,253
<p>I'm trying to run an example I found online at <a href="http://www.netinstructions.com/how-to-make-a-web-crawler-in-under-50-lines-of-python-code/" rel="nofollow">http://www.netinstructions.com/how-to-make-a-web-crawler-in-under-50-lines-of-python-code/</a></p> <p>However, I'm running into issues when running it vi...
0
2016-08-18T14:02:00Z
39,021,079
<p>Yourno,</p> <p>You have indentation problem in your code buddy. After defining class, there are no indentation before method <code>handle_starttag</code> and <code>getLinks</code>. Also in function <code>spider</code>, there are indetation missing in <code>if-else</code> section. Kindly check your code against the ...
0
2016-08-18T14:38:37Z
[ "python", "web-crawler" ]
How to run Python 3 Pyinstaller when I have Pyinstaller installed for both python 2 and 3?
39,020,353
<p>I am on a windows machine. I wrote my application in python 3. I have Pyinstaller installed for both python 2 and 3. How do I call python 3 pyinstaller?</p>
1
2016-08-18T14:06:55Z
39,025,222
<p>I believe all you'd need to do is set the path for your python environment to point to the python3 install location. You'd then just use the <code>pip3 install pyinstaller</code> command and it should run. You can use the command <code>pyinstaller --version</code> to confirm.</p>
0
2016-08-18T18:32:47Z
[ "python", "pyinstaller" ]
Python scipy module import error due to missing ._ufuncs dll
39,020,361
<p>I have some troubles with sub-module integrate from scipy in python. I have a 64 bits architecture, and it seems, according to the first lines of the python interpreter (see below) that I am also using a 64 bit build of Python together with Anaconda.</p> <p>Below is the problem (I just wrote the minimal code to sho...
0
2016-08-18T14:07:14Z
39,021,044
<p>It appears the DLL load failed because the module specified is irretrievable? </p> <p>Please see: </p> <p><a href="http://stackoverflow.com/questions/19019720/importerror-dll-load-failed-1-is-not-a-valid-win32-application-but-the-dlls">ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL&...
0
2016-08-18T14:37:19Z
[ "python", "dll", "import", "scipy" ]
Which Python pattern to use for dynamically selecting and ordering a filtered list of functions?
39,020,362
<p>I have a growing list of general purpose re-usable validation checks, similar to this list below:</p> <pre><code> 1. check_product_name() 2. check_product_price_within_range() 3. check_product_expiration_date() 4. check_product_sizes() 5. check_foo() 6. check_bar() 7. ... </code></pre> <p>I also have a growi...
0
2016-08-18T14:07:14Z
39,021,143
<p>As I understand Django can be a good example. Django have two entities - form field and validator and one field can have multiple validators.</p> <pre><code>from django import forms class MyForm(forms.Form): even_field = forms.IntegerField(validators=[validate_even, max_value]) </code></pre> <p>So it's simila...
1
2016-08-18T14:41:06Z
[ "python", "design-patterns" ]
Python: define a string variable pattern
39,020,470
<p>I'm new to python.</p> <p>I have a program that reads from <code>str(sys.argv[1])</code>:</p> <pre><code>myprogram.py "some date" # I'd like this in YYYYMMDD format. I.e: myprogram.py 20160806 if __name__ == '__main__': if str(sys.argv[1]): CTRL = str(sys.argv[1]) print "some stuff" s...
0
2016-08-18T14:11:54Z
39,020,712
<p>If I understand what you said right, you want to pass an argument in a YYYYMMDD format.</p> <p>There is nothing stopping you from doing this with your script.</p> <p>You can run: <code>python yourscript.py YYYYMMDD</code> and a string "YYYYMMDD" will be stored in your CTRL variable.</p> <hr> <p>UPDATE:</p> <p>T...
0
2016-08-18T14:23:36Z
[ "python" ]
Python: define a string variable pattern
39,020,470
<p>I'm new to python.</p> <p>I have a program that reads from <code>str(sys.argv[1])</code>:</p> <pre><code>myprogram.py "some date" # I'd like this in YYYYMMDD format. I.e: myprogram.py 20160806 if __name__ == '__main__': if str(sys.argv[1]): CTRL = str(sys.argv[1]) print "some stuff" s...
0
2016-08-18T14:11:54Z
39,020,726
<p>you need function <strong>datetime.strptime</strong> with mask <strong>%Y%m%d</strong> </p> <pre><code>import sys from datetime import datetime if __name__ == '__main__': if str(sys.argv[1]): CTRL = str(sys.argv[1]) try: print datetime.strptime(CTRL, "%Y%m%d") except ValueEr...
2
2016-08-18T14:24:03Z
[ "python" ]
Triple nested dictionary comprehension?
39,020,492
<p>Suppose I have a <code>pandas</code> <code>Series</code>, like this:</p> <pre><code>import pandas as pd s = pd.Series(["hello go home bye bye", "you can't always get", "what you waaaaaaant", "apple banana carrot munch 123"]) </code></pre> <p>I want to create a dictionary with individual characters as keys, and the...
3
2016-08-18T14:12:43Z
39,020,558
<p>I think you can use</p> <pre><code>Counter([j for i in s for j in i]) Counter({'a': 16, ' ': 13, 'e': 6, 'o': 6, 'n': 5, 't': 5, 'y': 5, 'h': 4, 'l': 4, 'c': 3, 'b': 3, 'u': 3, 'w': 3, 'g': 2, 'm': 2, 'p': 2, 'r': 2, "'": 1, '1': 1, '3': 1, '2': 1, 's': 1}) </code></pre> <p>to get the individual character count.</...
2
2016-08-18T14:16:27Z
[ "python", "dictionary", "list-comprehension" ]
Triple nested dictionary comprehension?
39,020,492
<p>Suppose I have a <code>pandas</code> <code>Series</code>, like this:</p> <pre><code>import pandas as pd s = pd.Series(["hello go home bye bye", "you can't always get", "what you waaaaaaant", "apple banana carrot munch 123"]) </code></pre> <p>I want to create a dictionary with individual characters as keys, and the...
3
2016-08-18T14:12:43Z
39,020,598
<p>Just pass each word calling <em>.lower()</em> flattening the list of lists:</p> <pre><code>import pandas as pd s = pd.Series(["hello go home bye bye", "you can't always get", "what you waaaaaaant", "apple banana carrot munch 123"]) from collections import Counter print(Counter(word.lower() for row in s for word i...
2
2016-08-18T14:18:23Z
[ "python", "dictionary", "list-comprehension" ]
Triple nested dictionary comprehension?
39,020,492
<p>Suppose I have a <code>pandas</code> <code>Series</code>, like this:</p> <pre><code>import pandas as pd s = pd.Series(["hello go home bye bye", "you can't always get", "what you waaaaaaant", "apple banana carrot munch 123"]) </code></pre> <p>I want to create a dictionary with individual characters as keys, and the...
3
2016-08-18T14:12:43Z
39,020,638
<p>Using pandas:</p> <pre><code>n [6]: pd.Series(list(''.join(s))).value_counts() Out[6]: a 16 13 e 6 o 6 n 5 t 5 y 5 h 4 l 4 u 3 b 3 c 3 w 3 p 2 m 2 r 2 g 2 1 1 s 1 ' 1 2 1 3 1 dtype: int64 In [7]: dict(pd.Series(list(''.join(s)...
2
2016-08-18T14:20:04Z
[ "python", "dictionary", "list-comprehension" ]
Triple nested dictionary comprehension?
39,020,492
<p>Suppose I have a <code>pandas</code> <code>Series</code>, like this:</p> <pre><code>import pandas as pd s = pd.Series(["hello go home bye bye", "you can't always get", "what you waaaaaaant", "apple banana carrot munch 123"]) </code></pre> <p>I want to create a dictionary with individual characters as keys, and the...
3
2016-08-18T14:12:43Z
39,020,989
<p>You want this :</p> <pre><code>dict(zip([letter for row in s for word in row.lower().split() for letter in word], range(len([letter for row in s for word in row.lower().split() for letter in word])))) </code></pre>
1
2016-08-18T14:34:56Z
[ "python", "dictionary", "list-comprehension" ]
Heroku R10 error in Python app
39,020,501
<p>I'm having a problem running my Python app in Heroku. My app scrapes a website for weather data and performs a few calculations on it. Pulling the data doesn't take more than a few seconds. When I open my app, my logs show the output of my app, but my app page continues loading until I get an R10 error, then the app...
0
2016-08-18T14:13:03Z
39,022,423
<p>Heroku expects the <code>web</code> process to bind to <code>$PORT</code> within 60 seconds. You need to use a different kind of process (e.g., <code>bot</code>) in your Procfile and scale the different processes (similar to <a href="http://stackoverflow.com/questions/35541027/python-twitter-bot-w-heroku-error-r10-b...
0
2016-08-18T15:43:07Z
[ "python", "python-2.7", "heroku" ]
How do Luigi parameters work?
39,020,591
<p>So I have two tasks (let's say TaskA and TaskB). I want both tasks to run hourly, but TaskB requires TaskA. TaskB does not have any parameters, but TaskA has two parameters for the day and the hour. If I run TaskB on the command line, would I need to pass it arguments?</p>
0
2016-08-18T14:18:01Z
39,028,831
<p>In general, you would not need to pass the parameters for Task A to Task B, but Task B would then need to generate the values of those parameters for Task A. If Task B can not generate those parameters, you would have to setup Task B to take those parameters in from the command line, and then pass them through to th...
1
2016-08-18T23:09:31Z
[ "python", "luigi" ]