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
Reading in file block by block using specified delimiter in python
38,655,176
<p>I have an input_file.fa file like this (<a href="https://en.wikipedia.org/wiki/FASTA_format" rel="nofollow">FASTA</a> format):</p> <pre><code>&gt; header1 description data data data &gt;header2 description more data data data </code></pre> <p>I want to read in the file one chunk at a time, so that each chunk conta...
1
2016-07-29T09:25:00Z
38,656,892
<p>A general solution here will be write a generator function for this that yields one group at a time. This was you will be storing only one group at a time in memory.</p> <pre><code>def get_groups(seq, group_by): data = [] for line in seq: # Here the `startswith()` logic can be replaced with other ...
1
2016-07-29T10:46:50Z
[ "python", "file", "python-3.x" ]
Reading in file block by block using specified delimiter in python
38,655,176
<p>I have an input_file.fa file like this (<a href="https://en.wikipedia.org/wiki/FASTA_format" rel="nofollow">FASTA</a> format):</p> <pre><code>&gt; header1 description data data data &gt;header2 description more data data data </code></pre> <p>I want to read in the file one chunk at a time, so that each chunk conta...
1
2016-07-29T09:25:00Z
38,657,002
<pre><code>def read_blocks(file): block = '' for line in file: if line.startswith('&gt;') and len(block)&gt;0: yield block block = '' block += line yield block with open('input_file.fa') as f: for block in read_blocks(f): print(block) </code></pre> <p>T...
0
2016-07-29T10:52:46Z
[ "python", "file", "python-3.x" ]
Reading in file block by block using specified delimiter in python
38,655,176
<p>I have an input_file.fa file like this (<a href="https://en.wikipedia.org/wiki/FASTA_format" rel="nofollow">FASTA</a> format):</p> <pre><code>&gt; header1 description data data data &gt;header2 description more data data data </code></pre> <p>I want to read in the file one chunk at a time, so that each chunk conta...
1
2016-07-29T09:25:00Z
38,663,342
<p>One approach that I like is to use <a href="https://docs.python.org/3.5/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> together with a simple <code>key</code> fuction:</p> <pre><code>from itertools import groupby def make_grouper(): counter = 0 def key(line): ...
1
2016-07-29T16:18:02Z
[ "python", "file", "python-3.x" ]
Adding widgets to form produced by model
38,655,241
<p>Hey i am working on calendarium and it is layed out differently to what i normally work with so i'm having a little bit if trouble adding widgets to the form.</p> <p>There is nothing in the EventCreatView so i dont understnad why there is a form on the page fully im guessing its the args that are passed.which is th...
0
2016-07-29T09:28:07Z
38,658,547
<p>There are at least two issues here.</p> <p>Firstly, <code>widgets</code> is an attribute on a form, not on a view. Like all editing views, UpdateView automatically creates a ModelForm for you based on the model if you don't specify one; but since you want to customise it, you need to define your ModelForm explicitl...
0
2016-07-29T12:12:31Z
[ "python", "django" ]
AttributeError: 'list' object has no attribute 'items' in a scrapy
38,655,329
<p>I was doing a scrapy with python3.5 then this happened:</p> <pre><code>Traceback (most recent call last): File "F:/PyCharm/xiaozhou/main.py", line 6, in &lt;module&gt; cmdline.execute("scrapy crawl nvospider".split()) File "F:\Python3.5\lib\site-packages\scrapy\cmdline.py", line 108, in execute settings =...
1
2016-07-29T09:32:17Z
38,656,785
<p>According to the docs <code>ITEM_PIPELINES</code> setting <a href="http://doc.scrapy.org/en/latest/topics/settings.html#item-pipelines" rel="nofollow">should be dict</a>, and you got list instead <code>ITEM_PIPELINES = ['xiaozhou.pipelines.XiaozhouPipeline']</code></p>
2
2016-07-29T10:40:54Z
[ "python", "mongodb", "scrapy" ]
Convert regex string from Java to Python
38,655,341
<p>I have the following function in Java to replace occurrences of a regex with a blank space:</p> <pre><code>string.replaceAll("\r?\n[\\s&amp;&amp;[^\r\n]]*", " ") </code></pre> <p>In Python, the equivalent would be:</p> <pre><code>re.sub("\r?\n[\\s&amp;&amp;[^\r\n]]*", " ", string) </code></pre> <p>But I just rea...
3
2016-07-29T09:33:14Z
38,655,421
<p>In python, it would be</p> <pre><code>re.sub(r'\r?\n(?:(?![\r\n])\s)*', " ", stri) </code></pre> <p>You may use the same regex in java also.</p>
1
2016-07-29T09:36:39Z
[ "java", "python", "regex", "python-2.7", "python-3.x" ]
Routing from Django to Angular route
38,655,403
<p>I have a Django backend and an Angular frontend. I am using a package called django-invitations. When a user receives an invitation in an email they click on it and are taken to the app. django-invitations requires this line in settings.py</p> <pre><code>INVITATIONS_SIGNUP_REDIRECT = 'register' </code></pre> <p>Th...
0
2016-07-29T09:35:45Z
38,656,293
<p>Got it!</p> <p>Changed the line in urls.py to</p> <pre><code>url(r'^register/', views.redirect_to_register, name='register'), </code></pre> <p>Added a views.py </p> <pre><code>from django.shortcuts import render from django.shortcuts import redirect def redirect_to_register(request): return redirect('/#/reg...
0
2016-07-29T10:16:06Z
[ "python", "angularjs", "django", "routes", "angular-ui-router" ]
Sum alternate columns of a dataframe
38,655,464
<p>I have a dataframe which looks like</p> <pre><code> A 00:00 00:30 01:00 01:30 02:00 .....22:30 23:00 23:30 1 2 3 3 4 3 1 6 4 2 5 6 2 6 5 2 1 2 </code></pre> <p>I am trying to get, </p> <pre><code> A 00:00 01:00 02:00 ..... 23:00 1 ...
2
2016-07-29T09:38:47Z
38,655,559
<p>I think this should work:</p> <pre><code>In [261]: df = pd.DataFrame(np.random.randn(5,6), columns=['00:00','00:30','01:00','01:30','02:00','02:30']) df Out[261]: 00:00 00:30 01:00 01:30 02:00 02:30 0 0.176952 1.161850 0.894800 -0.246474 1.252235 -0.816835 1 0.817057 -1.338584 -0.983...
2
2016-07-29T09:43:41Z
[ "python", "numpy", "pandas" ]
Add a dynamically generated matplotlib picture in Django home
38,655,635
<p>I would like to add a dynamically generated picture in my home. I do not want to save the figure, but just show it directly in my home page, after some text. My <code>views.py</code> looks like:</p> <pre><code>from django.shortcuts import render def index(request): import random import datetime import d...
0
2016-07-29T09:47:13Z
38,657,308
<p>In my experience, <a href="http://frontend.co.il/articles/avoid-data-uris-english" rel="nofollow">using data URIs is usually a bad idea</a>.</p> <p>In this case, there is no real need for them anyway. Just create a separate view that returns the image. I am using <code>gnuplot</code> here for simplicity. The comman...
1
2016-07-29T11:08:07Z
[ "python", "django", "matplotlib" ]
how to add columns label on a Pandas DataFrame
38,655,701
<p>I can't understand how can I add column names on a pandas dataframe, an easy example will clarify my issue:</p> <pre><code>dic = {'a': [4, 1, 3, 1], 'b': [4, 2, 1, 4], 'c': [5, 7, 9, 1]} df = pd.DataFrame(dic) </code></pre> <p>now if I type df than I get</p> <pre><code> a b c 0 4 4 5 1 1 2 7 2 3 1 9 ...
0
2016-07-29T09:49:44Z
38,655,847
<p>The method <code>DataFrame.sum()</code> does an aggregation and therefore returns a <code>Series</code>, not a <code>DataFrame</code>. And a Series has no columns, only an index. If you want to create a DataFrame out of your sum you can change <code>a = df.sum()</code> by:</p> <pre><code>a = pandas.DataFrame(df.sum...
1
2016-07-29T09:56:09Z
[ "python", "pandas" ]
Optimal method to find the max of sublist items within list
38,655,727
<p>I have a multidimensional list in the format:</p> <pre><code>list = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] </code></pre> <p>How do I obtain the maximum value of the third value of all the sublists. In pseudo code:</p> <pre><code>max(list[0][2], list[1][2], list[2][2]) </code></pre> <p>I know this can be done via iter...
3
2016-07-29T09:51:08Z
38,655,758
<p>Use <code>zip</code> function to get the list of columns then use a simple indexing in order to get the expected column:</p> <pre><code>&gt;&gt;&gt; lst = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] &gt;&gt;&gt; &gt;&gt;&gt; max(zip(*lst)[-1]) # in python 3.x max(list(zip(*lst))[-1]) 3 </code></pre> <p>One another alternat...
3
2016-07-29T09:52:44Z
[ "python", "arrays", "list", "list-comprehension" ]
Optimal method to find the max of sublist items within list
38,655,727
<p>I have a multidimensional list in the format:</p> <pre><code>list = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] </code></pre> <p>How do I obtain the maximum value of the third value of all the sublists. In pseudo code:</p> <pre><code>max(list[0][2], list[1][2], list[2][2]) </code></pre> <p>I know this can be done via iter...
3
2016-07-29T09:51:08Z
38,655,781
<p>Just use <code>max</code> with a generator expression:</p> <pre><code>&gt;&gt;&gt; lst = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] &gt;&gt;&gt; max(l[2] for l in lst) 3 </code></pre> <p>Also, don't name your variables <code>list</code>, you are shadowing the type.</p>
3
2016-07-29T09:53:37Z
[ "python", "arrays", "list", "list-comprehension" ]
Optimal method to find the max of sublist items within list
38,655,727
<p>I have a multidimensional list in the format:</p> <pre><code>list = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] </code></pre> <p>How do I obtain the maximum value of the third value of all the sublists. In pseudo code:</p> <pre><code>max(list[0][2], list[1][2], list[2][2]) </code></pre> <p>I know this can be done via iter...
3
2016-07-29T09:51:08Z
38,655,794
<p>applying <code>max</code> on the list will return the maximum list, which isn't what you want. You could indeed use a list comprehension to extract the third element, and then apply <code>max</code> on that comprehension:</p> <pre><code>&gt;&gt;&gt; lst = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] &gt;&gt;&gt; max([x[2] for...
1
2016-07-29T09:54:10Z
[ "python", "arrays", "list", "list-comprehension" ]
Optimal method to find the max of sublist items within list
38,655,727
<p>I have a multidimensional list in the format:</p> <pre><code>list = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] </code></pre> <p>How do I obtain the maximum value of the third value of all the sublists. In pseudo code:</p> <pre><code>max(list[0][2], list[1][2], list[2][2]) </code></pre> <p>I know this can be done via iter...
3
2016-07-29T09:51:08Z
38,655,959
<p>This is exactly why <a href="https://docs.python.org/3/library/functions.html#max" rel="nofollow"><code>max</code></a> has a <code>key</code> argument, it allows to use a custom function to select the "maximum" element:</p> <pre><code>&gt;&gt;&gt; L = [[1, 2, 3], [2, 4, 2], [0, 1, 1]] &gt;&gt;&gt; L2 = max(L, key=l...
3
2016-07-29T10:01:31Z
[ "python", "arrays", "list", "list-comprehension" ]
How to access class attributes of a derived class in the base class in Python3?
38,655,738
<p>I want to do something in a base class (<code>FooBase</code>) with the <strong>class attribues</strong> of the derived classes (<code>Foo</code>). I want to do this with Python<strong>3</strong>.</p> <pre><code>class BaseFoo: #felder = [] doesn't work def test(): print(__class__.felder) class Foo(Base...
0
2016-07-29T09:51:35Z
38,656,262
<p>You need to make <code>test</code> a <a href="https://docs.python.org/3/library/functions.html#classmethod" rel="nofollow">class method</a>, and give it an argument that it can use to access the class; conventionally this arg is named <code>cls</code>.</p> <pre><code>class BaseFoo: @classmethod def test(cls...
1
2016-07-29T10:15:01Z
[ "python", "python-3.x", "class-attributes" ]
Python: add to a dictionary in a list
38,655,798
<p>I have the following dictionary (It is for creating json), </p> <pre><code>temp = {'logs':[]} </code></pre> <p>I want to append dictionaries, but i only got 1 key:val at a time.</p> <p>what I tried:</p> <pre><code>temp['logs'].append({key:val}) </code></pre> <p>This does as expected and appends the dict to the ...
1
2016-07-29T09:54:19Z
38,655,866
<blockquote> <p>But now I want to add a key/val pair to this dictionary</p> </blockquote> <p>You can <em>index</em> the list and <em>update</em> that dictionary:</p> <pre><code>temp['logs'][0].update({'new_key': 'new_value'}) </code></pre>
1
2016-07-29T09:56:45Z
[ "python", "json", "list", "dictionary" ]
Python: add to a dictionary in a list
38,655,798
<p>I have the following dictionary (It is for creating json), </p> <pre><code>temp = {'logs':[]} </code></pre> <p>I want to append dictionaries, but i only got 1 key:val at a time.</p> <p>what I tried:</p> <pre><code>temp['logs'].append({key:val}) </code></pre> <p>This does as expected and appends the dict to the ...
1
2016-07-29T09:54:19Z
38,655,975
<p>You can use this command to change your dict values :</p> <pre><code>&gt;&gt;&gt; temp['logs'][0]={'no':'val'} &gt;&gt;&gt; temp {'logs': [{'no': 'val'}]} </code></pre> <p>And this one to add values : </p> <pre><code>&gt;&gt;&gt; temp['logs'][0].update({'yes':'val'}) &gt;&gt;&gt; temp {'logs': [{'key': 'val', 'ye...
0
2016-07-29T10:02:06Z
[ "python", "json", "list", "dictionary" ]
Python: add to a dictionary in a list
38,655,798
<p>I have the following dictionary (It is for creating json), </p> <pre><code>temp = {'logs':[]} </code></pre> <p>I want to append dictionaries, but i only got 1 key:val at a time.</p> <p>what I tried:</p> <pre><code>temp['logs'].append({key:val}) </code></pre> <p>This does as expected and appends the dict to the ...
1
2016-07-29T09:54:19Z
38,656,040
<p>There must be unique "key" every time you append it. (If it is for json)</p> <p>Also making "=" will update your old dictionary</p> <p>What I have done when I was stuck once is </p> <pre><code>user = {} name,password,id1 = [],[],[] user1=session.query(User).all() for i in user1: name=i.name password=i.pas...
0
2016-07-29T10:05:12Z
[ "python", "json", "list", "dictionary" ]
Python: add to a dictionary in a list
38,655,798
<p>I have the following dictionary (It is for creating json), </p> <pre><code>temp = {'logs':[]} </code></pre> <p>I want to append dictionaries, but i only got 1 key:val at a time.</p> <p>what I tried:</p> <pre><code>temp['logs'].append({key:val}) </code></pre> <p>This does as expected and appends the dict to the ...
1
2016-07-29T09:54:19Z
38,656,062
<p>Note that adding a dictionary (or any object) to a list only stores a reference, not a copy.</p> <p>You can therefor do this:</p> <pre><code>&gt;&gt;&gt; temp = {'logs': []} &gt;&gt;&gt; log_entry = {'key1': 'val1'} &gt;&gt;&gt; temp['logs'].append(log_entry) &gt;&gt;&gt; temp {'logs': [{'key1': 'val1'}]} &gt;&gt;...
0
2016-07-29T10:06:16Z
[ "python", "json", "list", "dictionary" ]
How to find a node from a file-like xml object in Python3?
38,655,843
<p>These is the content of a file-like object <code>toc</code>:</p> <pre><code>&lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="eng"&gt; &lt;head&gt; ... &lt;/head&gt; &lt;docTitle&gt; &lt;text&gt;THE_TEXT_I_WANT&lt;/te...
0
2016-07-29T09:55:59Z
38,656,086
<p>Because there is a (default) namespace in your XML, searching for elements called <code>docTitle</code> will find nothing, as it is searching for un-namespaced elements called <code>docTitle</code>. Instead, you need to use clark notation with the full namespace URI:</p> <pre><code>toc_tree.find('{http://www.daisy....
0
2016-07-29T10:07:12Z
[ "python", "xml", "elementtree" ]
How is __mro__ different from other double underscore names?
38,655,863
<p>I stumbled upon this behavior for double underscore name that I don't understand:</p> <pre><code>class A: pass class B: pass class C(A,B): __id__ = 'c' c = C() print(C.__mro__) # print the method resolution order of class C #print(c.__mro__) # AttributeError: 'C' object has no attribute '__mro__' pr...
4
2016-07-29T09:56:36Z
38,656,156
<p>This has to do with the lookup order.</p> <p>Letting <a href="https://docs.python.org/3/reference/datamodel.html#implementing-descriptors" rel="nofollow">descriptors</a> aside, python first checks the objects <code>__dict__</code> to find an attribute. If it cannot find it, it will look at the class of the object...
4
2016-07-29T10:10:42Z
[ "python", "python-3.4", "double-underscore" ]
Search part of string matching in python
38,655,972
<p>I have two files one is "error_dict" file and other is "jbosslogfile" error dict file contains known error messages in each line like error_dict</p> <pre><code>"0500 ERROR [org.picketlink.identity.federation]" "-0500 ERROR [com.gravitant.cloud.appsportfolio.jsf.architecture.beans.StorageAccountBean]" "Invalid Cont...
0
2016-07-29T10:02:02Z
38,727,204
<p>Here is code which loop through my error repo files and in final error log file if there is match with line it will yank(delete) that line from log file and before performing this operation it will create backup file.</p> <pre><code>#This function will be matching error lines from error repo files and if matched it...
0
2016-08-02T17:45:49Z
[ "python", "regex", "python-2.7" ]
Reading text file with numpy.loadtxt
38,655,983
<p>I am getting an error when trying to read a text file. </p> <pre><code>import numpy as np fnam = 'file.txt' test_fnames = np.loadtxt(fnam, dtype=None, delimiter=',') test_fnames </code></pre> <p>I now get this error:</p> <pre><code>ValueError: could not convert string to float: </code></pre> <p>The file conten...
0
2016-07-29T10:02:45Z
38,658,893
<p>You could use <code>np.genfromtxt()</code> instead of <code>np.loadtxt</code>. Because the first one let handles missing values :</p> <pre><code>import numpy as np fnam = 'file.txt' test_fnames = np.genfromtxt(fnam, dtype=None, delimiter=',') </code></pre> <p>You could also try :</p> <pre><code>import numpy as n...
0
2016-07-29T12:30:34Z
[ "python", "numpy", "file-io" ]
lxml eTree iterparse depth
38,656,008
<p>I am trying to parse some xml which is in the following format:</p> <pre><code>&lt;label&gt; &lt;name&gt;&lt;/name&gt; &lt;sometag&gt;&lt;/sometag&gt; &lt;sublabels&gt; &lt;label&gt;&lt;/label&gt; &lt;label&gt;&lt;/label&gt; &lt;/sublabel&gt; &lt;/label&gt; </...
4
2016-07-29T10:03:48Z
38,717,524
<p>The first thing that came to mind</p> <pre><code>path = [] for event, element in etree.iterparse(gzip.GzipFile(f), events=('start', 'end')): if event == 'start': path.append(element.tag) elif event == 'end': if element.tag == 'label': if not 'sublabels' in path: n...
0
2016-08-02T10:08:27Z
[ "python", "lxml" ]
lxml eTree iterparse depth
38,656,008
<p>I am trying to parse some xml which is in the following format:</p> <pre><code>&lt;label&gt; &lt;name&gt;&lt;/name&gt; &lt;sometag&gt;&lt;/sometag&gt; &lt;sublabels&gt; &lt;label&gt;&lt;/label&gt; &lt;label&gt;&lt;/label&gt; &lt;/sublabel&gt; &lt;/label&gt; </...
4
2016-07-29T10:03:48Z
38,740,507
<p>This works for me and is inspired by the previous answer:</p> <pre><code>name = None level = 0 for event, element in etree.iterparse(gzip.GzipFile(f), events=('end', 'start' ), tag='label'): # Update current level if event == 'start': level += 1; elif event == 'end': level -= 1; # Get name for top l...
2
2016-08-03T10:06:13Z
[ "python", "lxml" ]
Access JSON data in Python
38,656,081
<pre><code>header = {'Content-type': 'application/json','Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' } url = 'https://sandbox-authservice.priaid.ch/login' response = requests.post(url, headers = header, verify=False).json() token = json.dumps(response) print token['ValidThrough'] </code></pre> <p>I want to prin...
0
2016-07-29T10:07:02Z
38,656,191
<p>Since the response already seems to be in json, there is no need to use <code>json.dumps</code>.</p> <p><code>json.dumps</code> on a dictionary will return a string which cannot be indexed obviously and hence that error.</p>
2
2016-07-29T10:11:57Z
[ "python", "json", "hook.io" ]
Access JSON data in Python
38,656,081
<pre><code>header = {'Content-type': 'application/json','Authorization': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' } url = 'https://sandbox-authservice.priaid.ch/login' response = requests.post(url, headers = header, verify=False).json() token = json.dumps(response) print token['ValidThrough'] </code></pre> <p>I want to prin...
0
2016-07-29T10:07:02Z
38,656,606
<p>a requests response <code>.json()</code> method already loads the content of the string to json.</p> <p>You should use that, but your code later serializes it back to a string, and hence the error (<code>token</code> is a string representation of the dict you are expecting, not the dict). You should just omit the <...
0
2016-07-29T10:32:01Z
[ "python", "json", "hook.io" ]
Tweepy script affecting MongoDB service shutting down
38,656,126
<p>I have the following Python script that uses <a href="http://docs.tweepy.org" rel="nofollow">Tweepy</a> to get tweets and store them into MongoDB using <a href="https://api.mongodb.com/python/current/" rel="nofollow">PyMongo</a>. What's happening is whenever I run this script, my MongoDB instance gets shut down, and...
0
2016-07-29T10:09:21Z
39,656,533
<p>Not exactly sure yet why, but the following answer to a question about permission problems on the MongoDB lock helped solve this problem: <a href="http://stackoverflow.com/a/15982017/863923">http://stackoverflow.com/a/15982017/863923</a></p>
0
2016-09-23T08:48:29Z
[ "python", "mongodb", "pymongo", "tweepy" ]
Using a dynamic array python multi-threads
38,656,201
<p>In python, I have a thread to add elements to an array. And I have another thread that uses the first element of that array then deletes it. The problem is that the second thread is faster than the first one, so I need that it waits for the first one to add other elements and then process instead of going into an er...
0
2016-07-29T10:12:28Z
38,656,365
<p>You should be using the <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">Synchronised Queue</a> class or similar.</p> <p>The Queue class handles overlength and underlength with blocking and optional timeouts. It's also threadsafe.</p> <pre><code>import threading import Queue import time import...
3
2016-07-29T10:19:24Z
[ "python" ]
Visible deprecation warning using boolean operation on numpy array
38,656,284
<p>I'm having an issue where I keep receiving a warning stating:</p> <pre><code>VisibleDeprecationWarning: boolean index did not match indexed array along dimension 0; dimension is 744 but corresponding boolean dimension is 1 </code></pre> <p>When I try to use this:</p> <pre><code>x_low = xcontacts[(xcontacts[5:6]...
2
2016-07-29T10:15:44Z
38,656,991
<p>Thanks to @Syrtis Major for this:</p> <pre><code>x_low = xcontacts[(xcontacts[:,5] &lt;= 2000)] x_med = xcontacts[(xcontacts[:,5] &lt;= 4000)] x_med = xcontacts[(xcontacts[:,5] &gt; 2000)] x_hi = xcontacts[(xcontacts[:,5] &gt; 4000)] </code></pre>
0
2016-07-29T10:51:57Z
[ "python", "arrays", "numpy", "boolean-operations" ]
get_pdf api.v8 Odoo. What parameter should I send as "records"
38,656,347
<p>In the source code of record.py I found</p> <pre><code>@api.v8 def get_pdf(self, records, report_name, html=None, data=None): return Report.get_pdf(self._model, self._cr, self._uid, records.ids, report_name, html=html, data=data, context=self._context) </code></pre> <p>I inher...
0
2016-07-29T10:18:28Z
38,660,614
<p>Records are database entries in object form. For example <code>account.invoice</code>: when you press the print button on an invoice, it will be the record for the report. In your example, <code>self</code> will be the record of the model <code>cust_report</code> model you pressed the button on.</p> <p>Every Odoo r...
1
2016-07-29T13:51:53Z
[ "python", "openerp" ]
Python looping through multiple lists
38,656,370
<p>I've this code:</p> <pre><code>for i in range(0, len(codiceCassExcel)): count1step += 1 for j in range(0, len(vwLinesToList)): if data_reg[i] == vwLinesToList[j][1]: if codiceCassExcel[i] == vwLinesToList[j][0]: #Gestione movimento diverso da 601 e non bolle nostre if tipo_mov[i...
0
2016-07-29T10:19:35Z
38,656,461
<p>Use <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><strong>zip</strong></a> method to iterate over your lists. See <a href="http://stackoverflow.com/questions/13704860/zip-lists-in-python">zip lists in python</a> for code samples.</p> <p>Also consider using of <a href="https://docs.py...
1
2016-07-29T10:24:20Z
[ "python", "list", "for-loop", "nested-lists" ]
Python:Selecting a range of lines from one file and copying it to another file
38,656,396
<p>I have a file and i want to select certain lines in the file and copy it to another file.</p> <p>In the first file the line where i want to copy has the word "XYZ" and from here i want to select the next 200 lines(including the match line) and copy it to another file.</p> <p>The below is my code</p> <pre><code>ma...
1
2016-07-29T10:21:07Z
38,656,610
<p>You can use <code>itertools.islice</code> on the file object once the match is found:</p> <pre><code>from itertools import islice # some code before matching line is found chunk = line + ''.join(islice(f1, 200)) </code></pre> <p>This will consume the iterator <code>f1</code> to the next 200 lines, and so the <cod...
1
2016-07-29T10:32:09Z
[ "python", "python-2.7", "file" ]
Python:Selecting a range of lines from one file and copying it to another file
38,656,396
<p>I have a file and i want to select certain lines in the file and copy it to another file.</p> <p>In the first file the line where i want to copy has the word "XYZ" and from here i want to select the next 200 lines(including the match line) and copy it to another file.</p> <p>The below is my code</p> <pre><code>ma...
1
2016-07-29T10:21:07Z
38,657,797
<p>How about something like</p> <pre><code>&gt;&gt;&gt; with open("pokemonhunt", "r") as f: ... Lines = [] ... numlines = 5 ... count = -1 ... for line in f: ... if "pokemon" in line: % gotta catch 'em all!!! ... count = 0 ... if -1 &lt; count &lt; numlines: ... Lines.append(line)...
0
2016-07-29T11:33:46Z
[ "python", "python-2.7", "file" ]
Conditionally override python module on import: Design issues
38,656,563
<p>in my setup/design, requesting a module of a subpackage automatically loads all other modules from that package. I seek a way to circumvent this.</p> <h2>Disclaimer</h2> <p><em>A few months ago, I asked a question which is related. However, since this issue is new and different, I created this as a new question.</...
0
2016-07-29T10:30:15Z
38,656,772
<p>Just make local configuration <em>explicit</em>.</p> <p>Have people that want to override configuration create a <code>local_config.py</code> file. You can add that to <code>.gitignore</code>. Have users import <strong>that</strong> module in their own code.</p> <p>At the top of the <code>local_config.py</code> mo...
1
2016-07-29T10:40:34Z
[ "python", "python-2.7", "import", "module" ]
input dimensions to a one dimensional convolutional network in keras
38,656,566
<p>really finding it hard to understand the input dimensions to the convolutional 1d <a href="http://keras.io/layers/convolutional/#convolution1d" rel="nofollow">layer</a> in keras:</p> <p>Input shape</p> <p>3D tensor with shape: (samples, steps, input_dim).</p> <p>Output shape</p> <p>3D tensor with shape: (samples...
1
2016-07-29T10:30:23Z
38,673,493
<p>The reason why it look like this is that Keras designer intended to make 1-dimensional convolutional framework to be interpreted as a framework to deal with sequences. To fully understand the difference - try to imagine that you have a sequence of a multiple feature vectors. Then your output will be at least two dim...
2
2016-07-30T11:34:47Z
[ "python", "neural-network", "theano", "conv-neural-network", "keras" ]
'Gui' object has no attribute 'after'
38,656,585
<p>I took my working tkinter code (which only drew window/buttons and so on) and tried to add some code from the approved answer here: <a href="http://stackoverflow.com/questions/16938647/python-code-for-serial-data-to-print-on-window">python code for serial data to print on window.</a></p> <p>The approved answer work...
0
2016-07-29T10:31:17Z
38,656,720
<p>The the method <code>after</code> was a inherited from <code>Tkinter.Tk</code>. <a href="http://stackoverflow.com/questions/16938647/python-code-for-serial-data-to-print-on-window">Check mentioned question</a></p> <p>You probably should subclass Tkinter.Tk</p> <pre><code>... import Tkinter class Gui(Tkinter.Tk) ...
1
2016-07-29T10:37:48Z
[ "python", "multithreading", "tkinter", "pyserial" ]
'Gui' object has no attribute 'after'
38,656,585
<p>I took my working tkinter code (which only drew window/buttons and so on) and tried to add some code from the approved answer here: <a href="http://stackoverflow.com/questions/16938647/python-code-for-serial-data-to-print-on-window">python code for serial data to print on window.</a></p> <p>The approved answer work...
0
2016-07-29T10:31:17Z
38,656,773
<p>The culprit is in this line in the process_serial function:</p> <pre><code>self.after(100, self.process_serial) </code></pre> <p>The self variable that is in here refers to the Gui object, not to a tkinter object that has the 'after' function.</p> <p>There is a mismatch between your code and the code from the lin...
4
2016-07-29T10:40:35Z
[ "python", "multithreading", "tkinter", "pyserial" ]
How to compute percentiles from frequency table?
38,656,609
<p>I have CSV file:</p> <pre><code>fr id 1 10000152 1 10000212 1 10000847 1 10001018 2 10001052 2 10001246 14 10001908 ........... </code></pre> <p>This is a frequency table, where <code>id</code> is integer variable and <code>fr</code> is number of occurrences given value. File is sorted ascending by value. I ...
0
2016-07-29T10:32:09Z
38,657,471
<p>Seems like you want cumulative sum of <code>fr</code>. You can do</p> <pre><code>cumfr = [sum(fr(:i+1)) for i in range(len(fr))] </code></pre> <p>Then the percentiles are</p> <pre><code>percentile = [100*i/cumfr[-1] for i in cumfr] </code></pre>
0
2016-07-29T11:16:51Z
[ "python", "numpy", "pandas", "statistics" ]
Building MultiIndex in Pandas DataFrame
38,656,625
<p>I am reading in two files into Python, both with the form:</p> <pre><code> 0.00902317 0.0270695 0.0451159 0.0631622 \ 0000010 6.962980e-05 7.063750e-05 7.165970e-05 7.269680e-05 1000010 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 2000010 0.000000e+00 0.000000e+00 0...
2
2016-07-29T10:33:02Z
38,657,256
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a>:</p> <pre><code>print (pd.concat([df1, df2], axis=1, keys=['File 1','File 2'])) File 1 File 2 0.00902317 0.0...
2
2016-07-29T11:05:07Z
[ "python", "pandas", "indexing", "dataframe", "multi-index" ]
Alias in list comprehension and iterators
38,656,729
<p>Suppose I have something like:</p> <pre><code>for e in some_list: fct(e.my_first_property, e. e.my_second_property) fct2(e.my_first_property) </code></pre> <p>That's a bit repetitive to write, so I could use</p> <pre><code>for e in some_list: p1 = e.my_first_property p2 = e.my_second_property ...
0
2016-07-29T10:38:05Z
38,656,774
<p>You can use <a href="https://docs.python.org/2/library/operator.html#operator.attrgetter" rel="nofollow"><code>operator.attrgetter</code></a> with <code>map</code>:</p> <pre><code>from operator import attrgetter for p1, p2 in map(attrgetter(my_first_property, my_second_property), some_list): fct(p1, p2) fc...
2
2016-07-29T10:40:38Z
[ "python" ]
Formatting calculated fields in Django to have spaces as decimal thousand separator
38,656,910
<p>I've come across a strange behaviour of Django formatting. Best described by an example:</p> <p>Model:</p> <pre><code>class MyModel(models.Model): value= models.DecimalField(max_digits=8, decimal_places=2) </code></pre> <p>my_template.html:</p> <pre><code>{% load humanize %} {{calculated_sum|floatformat|intco...
1
2016-07-29T10:47:45Z
38,661,017
<p>did you try changing <code>return order_sum</code> to <code>return int(order_sum)</code> or doing the logic to add a space in your get_latest_orders_sum func. ie </p> <pre><code>return str(order_sum).replace("," " ") </code></pre>
0
2016-07-29T14:12:57Z
[ "python", "django" ]
In Pandas, when selecting with "where", delete columns where condition is not met rather than filling with NaN
38,656,930
<p>In Numpy, using <code>where</code> will give you a subset of the original array. For example,</p> <pre><code>import numpy as np np.where(np.arange(5)&gt;2)[0] </code></pre> <p>will return <code>array([3, 4])</code>. I'd like to do something similar with Pandas. However, if I define a similar DataFrame like so:</p>...
2
2016-07-29T10:48:25Z
38,657,145
<p>IIUC you can call <code>dropna</code> passing <code>axis=1</code> to drop columns containing any <code>NaN</code> values:</p> <pre><code>In [272]: df[df &gt; 2].dropna(axis=1) Out[272]: 3 4 0 3 4 </code></pre>
3
2016-07-29T10:59:26Z
[ "python", "pandas" ]
In Pandas, when selecting with "where", delete columns where condition is not met rather than filling with NaN
38,656,930
<p>In Numpy, using <code>where</code> will give you a subset of the original array. For example,</p> <pre><code>import numpy as np np.where(np.arange(5)&gt;2)[0] </code></pre> <p>will return <code>array([3, 4])</code>. I'd like to do something similar with Pandas. However, if I define a similar DataFrame like so:</p>...
2
2016-07-29T10:48:25Z
38,657,605
<p>You can drop the columns where the column names are smaller than 3, <em>provided the column names are integers</em>, if the column values are higher than 2.</p> <pre><code>print(df.drop(df[df.columns[df.columns &lt; 3]] &gt; 2, 1)) </code></pre> <p>output:</p> <pre><code> 3 4 0 3 4 </code></pre>
0
2016-07-29T11:23:43Z
[ "python", "pandas" ]
Write non-Unicode using csv module
38,656,958
<p>While migrating to Python 3, I noticed some files we generate using the built-in <code>csv</code> now have <code>b'</code> prefix around each strings...</p> <p>Here's the code, that should generate a .csv for a list of <code>dogs</code>, according to some parameters defined by <code>export_fields</code> (thus alway...
0
2016-07-29T10:50:01Z
38,657,058
<p>The <code>csv</code> module deals with <em>text</em>, and converts anything that is not a string to a string using <code>str()</code>. </p> <p>Don't pass in <code>bytes</code> objects. Pass in <code>str</code> objects or types that cleanly convert to strings with <code>str()</code>. That means you <em>should not en...
1
2016-07-29T10:55:29Z
[ "python", "python-3.x", "csv", "encoding", "stringio" ]
Python: create a dictionary from data in excel
38,656,975
<p>I have data </p> <pre><code> sign number result Qjobstatus 1 Работаю полный рабочий день Qjobstatus 2 Работаю неполный рабочий день Qjobstatus 3 Не работаю Qcountry 1 Россия Qcountry 2 Украина Qcountry 3 БелаÑ...
1
2016-07-29T10:50:49Z
38,657,231
<p>IIUC then you can just call <code>dict</code> on the np array:</p> <pre><code>In [284]: dict(df.loc[df['sign']=='Qcountry','number':].values) Out[284]: {1: 'Россия', 2: 'Украина', 3: 'Беларусь', 4: 'Азербайджан', 5: 'Армения', 6: 'Грузия', 7: 'Казахстан',...
2
2016-07-29T11:03:49Z
[ "python", "pandas", "dictionary" ]
Python: create a dictionary from data in excel
38,656,975
<p>I have data </p> <pre><code> sign number result Qjobstatus 1 Работаю полный рабочий день Qjobstatus 2 Работаю неполный рабочий день Qjobstatus 3 Не работаю Qcountry 1 Россия Qcountry 2 Украина Qcountry 3 БелаÑ...
1
2016-07-29T10:50:49Z
38,657,281
<p>A bit of a roundabout method but try:</p> <pre><code>df = df[df['sign'] == 'Qcountry'] transposed = df.T.to_dict() result = {transposed[item]['number']: transposed[item]['result'] for item in transposed} </code></pre>
1
2016-07-29T11:06:26Z
[ "python", "pandas", "dictionary" ]
Python: create a dictionary from data in excel
38,656,975
<p>I have data </p> <pre><code> sign number result Qjobstatus 1 Работаю полный рабочий день Qjobstatus 2 Работаю неполный рабочий день Qjobstatus 3 Не работаю Qcountry 1 Россия Qcountry 2 Украина Qcountry 3 БелаÑ...
1
2016-07-29T10:50:49Z
38,657,494
<p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html" rel="nofollow"><code>to_dict</code></a>:</p> <pre><code>print (df[df['sign']=='Qcountry'].set_index('number')['result'].to_dict()) {1: 'Россия', 2: 'Украина', 3: 'Беларусь', 4: 'Азе...
1
2016-07-29T11:17:59Z
[ "python", "pandas", "dictionary" ]
How to call a Python script with arguments from Java class
38,657,109
<p>I am using <em>Python 3.4</em>.</p> <p>I have a Python script <code>myscript.py</code> :</p> <pre><code>import sys def returnvalue(str) : if str == "hi" : return "yes" else : return "no" print("calling python function with parameters:") print(sys.argv[1]) str = sys.argv[1] res = returnvalue...
1
2016-07-29T10:57:57Z
38,657,448
<p>Have you looked at these? They suggest different ways of doing this:</p> <p><a href="http://stackoverflow.com/questions/27235286/call-python-code-from-java-by-passing-parameters-and-results">Call Python code from Java by passing parameters and results</a></p> <p><a href="http://stackoverflow.com/questions/9381906/...
0
2016-07-29T11:15:46Z
[ "java", "python", "python-3.4" ]
scikits learn SVM - 1-dimensional Separating Hyperplane
38,657,138
<p>How to plot the separating "hyperplane" for 1-dimensional data using scikit svm ?</p> <p>I follow this guide for 2-dimensional data : <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_svm_margin.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/svm/plot_svm_margin.html</a>, but don't kn...
0
2016-07-29T10:59:07Z
38,661,632
<p>the <code>.coef_</code> member of <code>clf</code> will return the "hyperplane," which, in one dimension, is just a point. Check out <a href="http://stackoverflow.com/questions/23186804/graph-point-on-straight-line-number-line-in-python">this post</a> for info on how to plot points on a numberline.</p>
0
2016-07-29T14:44:28Z
[ "python", "numpy", "matplotlib", "scikit-learn", "svm" ]
scikits learn SVM - 1-dimensional Separating Hyperplane
38,657,138
<p>How to plot the separating "hyperplane" for 1-dimensional data using scikit svm ?</p> <p>I follow this guide for 2-dimensional data : <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_svm_margin.html" rel="nofollow">http://scikit-learn.org/stable/auto_examples/svm/plot_svm_margin.html</a>, but don't kn...
0
2016-07-29T10:59:07Z
38,666,962
<p>The separating hyperplane for two-dimensional data is a line, whereas for one-dimensional data the hyperplane boils down to a point. The easiest way to plot the separating hyperplane for one-dimensional data is a bit of a hack: the <strong>data are made two-dimensional</strong> by adding a second feature which takes...
0
2016-07-29T20:26:09Z
[ "python", "numpy", "matplotlib", "scikit-learn", "svm" ]
Openstack IP address Filter
38,657,243
<p>The command : <code>neutron.list_ports()["ports"]</code> (Python) gives me all the IP addresses that I have on my machine.</p> <p>For example:</p> <pre><code>[{u'status': u'ACTIVE', u'name': u'', u'allowed_address_pairs': [], u'admin_state_up': True, u'network_id': u'7da####81c2##79e2', u'dns_name': u'', u'e...
0
2016-07-29T11:04:27Z
38,657,877
<p>list -> num -> dict</p> <pre><code>a = [{'name': 'one'}, {'name': 'two'}] a[0]['name'] </code></pre> <p>access to elements</p> <pre><code>network = neutron.list_ports()["ports"] for elem in network: print a['status'] print a['network_id'] print a['ip_address'] print a['dns_assignment'][0]['ip_addr...
0
2016-07-29T11:38:02Z
[ "python", "django", "ip-address", "openstack", "keystone" ]
Skimage: how to combine RGB channels?
38,657,282
<p>I have three grey channels of one image, each channel is a 2-dim array with values from 0 to 255. I need to combine this three images to one RGB and get something like this: [[234, 45, 67], ...], ... [[34, 7, 162], ...]! I use skimage, numpy to solve this problem. I can't find in documentation appropriate function(<...
0
2016-07-29T11:06:28Z
38,657,655
<p>Use numpy's dstack (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.dstack.html</a>)</p> <pre><code>import numpy as np r = np.random.rand(10) g = np.random.rand(10) b = np.random.rand(10) zipped = np.dstack((r,...
1
2016-07-29T11:26:10Z
[ "python", "skimage" ]
Return value from python script via CGI
38,657,311
<p>I work on a raspberry Pi. I did a small html page with 2 buttons calling executables via CGI and doing things. I would like to add a temperature display on the same page.</p> <p>I have a small python script that reads the temperature of a sensor and I can successfully display it on console or via direct CGI (typing...
0
2016-07-29T11:08:26Z
38,657,536
<p>You can write out a complete html page with CGI</p> <p>A simple CGI script would be</p> <pre><code>temp=100 print("Content-Type: text/html") # HTML is following print() # blank line, end of headers print("&lt;!doctype html&gt;") print("&lt;html&gt;&lt;head&gt;&lt;title&gt;Example&lt;...
0
2016-07-29T11:19:56Z
[ "python", "cgi", "raspberry-pi2" ]
How can I get the type of a class without instantiating it in Python?
38,657,337
<p>Given an object it is easy to get the object type in python:</p> <pre><code>obj = SomeClass() t = type(obj) </code></pre> <p>How can I do this without first creating an instance of the class?</p> <p>Background: Once you have the type you easily can create instances of that type. Using this mechanism I want to pas...
0
2016-07-29T11:09:16Z
38,657,719
<p>See this example code:</p> <pre><code>class MyClass(object): pass if __name__ == '__main__': o1 = MyClass() c = MyClass o2 = c() print(type(o1), type(o2), MyClass) </code></pre> <p>Defining a class binds it to its name (here: <code>MyClass</code>), which is nothing else but a reference to tha...
1
2016-07-29T11:28:58Z
[ "python", "python-3.x", "oop" ]
Pandas: groupby by date and transform nunique returning too many entries
38,657,341
<p>I am trying to do a simple group-by in Pandas and it is not working as it should:</p> <pre><code>url='https://raw.githubusercontent.com/108michael/ms_thesis/master/raw_bills' bills=pd.read_csv(url) bills.date.nunique() 11 bills.dtypes date float64 bills object id.thomas int64 dtype: object ...
0
2016-07-29T11:09:29Z
38,657,514
<p>I'm not sure what you're asking, but don't you want to use:</p> <pre><code>bills[['date', 'bills']].groupby('date').bills.nunique() date 2005.0 6820 2006.0 3738 2007.0 7454 2008.0 3627 2009.0 7324 2010.0 3297 2011.0 5787 2012.0 4647 2013.0 5694 2014.0 3211 2015.0 5 Name: bills, ...
1
2016-07-29T11:18:45Z
[ "python", "pandas", "group-by" ]
C# returning tuple - like Python
38,657,476
<p>I'm new to OOP and C#. I have a strong Python background and I was wondering is there an equivalent in C# for this</p> <pre><code>#Python def outputSmth(): num1 = 3 num2 = 3 str1 = "Hi" return (num1, num2, str1) #Returning a tuple that can later be accessed # by ind...
0
2016-07-29T11:17:15Z
38,657,527
<p>You could simply return a <code>string[]</code> or <code>List&lt;string&gt;</code>:</p> <pre><code>static string[] PrintUserCreationMnu() { // ... return new[]{ usrID, f_Name, l_Name, l_Date}; } </code></pre> <p>But in general it would be better to create a custom type <code>User</code> with meaningful ...
1
2016-07-29T11:19:15Z
[ "c#", "python", "return", "tuples" ]
C# returning tuple - like Python
38,657,476
<p>I'm new to OOP and C#. I have a strong Python background and I was wondering is there an equivalent in C# for this</p> <pre><code>#Python def outputSmth(): num1 = 3 num2 = 3 str1 = "Hi" return (num1, num2, str1) #Returning a tuple that can later be accessed # by ind...
0
2016-07-29T11:17:15Z
38,657,543
<p>Tuples are coming in C# 7 (current is 6.0). So, unfortunately not yet. </p> <p>I cant wait for them, especially when dealing with methods that return more that one parameter (without having to set up structures to deal with them). </p> <p>For now you need to return something like a <code>List</code>, <code>Diction...
0
2016-07-29T11:20:21Z
[ "c#", "python", "return", "tuples" ]
python ravel vs. transpose when used in reshape
38,657,496
<p>I have a 2D array <code>v</code>, <code>v.shape=(M_1,M_2)</code>, which I want to reshape into a 3D array with <code>v.shape=(M_2,N_1,N_2)</code>, and <code>M_1=N_1*N_2</code>. </p> <p>I came up with the following lines which produce the same result:</p> <pre><code>np.reshape(v.T, reshape_tuple) </code></pre> <p>...
3
2016-07-29T11:18:04Z
38,663,695
<p>The order in which they do things - reshape, change strides, and make a copy - differs, but they end up doing the same thing.</p> <p>I like to use <code>__array_interface__</code> to see where the data buffer is located, and other changes. I suppose I should add the <code>flags</code> to see the <code>order</code>...
1
2016-07-29T16:40:57Z
[ "python", "numpy", "reshape" ]
Detect whether to fetch from psycopg2 cursor or not?
38,657,566
<p>Let's say if I execute the following command.</p> <pre><code>insert into hello (username) values ('me') </code></pre> <p>and I ran like</p> <pre><code>cursor.fetchall() </code></pre> <p>I get the following error</p> <pre><code>psycopg2.ProgrammingError: no results to fetch </code></pre> <p>How can I detect whe...
0
2016-07-29T11:21:59Z
38,657,798
<p>So what you <em>appear</em> to be asking is:</p> <p>Is there any way, given a PostgreSQL cursor, to fetch the data from that cursor if there is any?</p> <p>My own personal preference would simply be to attempt to run the <code>fetchall()</code> and then catch the inevitable exception.</p> <pre><code>try: data...
1
2016-07-29T11:33:51Z
[ "python", "psycopg2" ]
Add headers from csv to dictionary keys and the columns below them as a list of values
38,657,578
<p>I have the following csv file:</p> <pre><code>h1 h2 h3 h4 10 11 12 13 14 15 16 17 18 19 20 21 </code></pre> <p>And the output that I'd like to obtain is a dictionary:</p> <pre><code>dict = {'h1': ['10','14','18'], 'h2': ['11','15','19'], 'h3': ['12','16','20'], 'h4': ['13','17','21']} </code>...
0
2016-07-29T11:22:28Z
38,657,775
<p>You just have to add the <code>delimiter='\t'</code> argument and you'll get what you want:</p> <pre><code>import csv from collections import defaultdict def get_columns_from_source_file(): source_file_reader = csv.DictReader(open('test.csv'), delimiter='\t') columns_storage = defaultdict(list) for so...
3
2016-07-29T11:32:26Z
[ "python", "python-3.x", "csv" ]
Generating models for Flask-AppBuilder using flask-sqlqcodegen
38,657,634
<p>I'm a beginner in Python and Flask ecosystems, trying to create a small proof-of-concept Web application for a research project. I'm using Debian Linux 7.9, PostgreSQL 9.5, SQLAlchemy (latest) and Flask-AppBuilder (latest). Since creating models manually is tedious and error-prone, I searched the mighty Internet and...
1
2016-07-29T11:25:16Z
38,680,067
<p>Upon some Internet searching, I ran across an issue on GitHub, which described exactly the same problem. However, the most recent recommendation at the time produced another error instead of the original one. In the <a href="https://github.com/ksindi/flask-sqlacodegen/issues/8" rel="nofollow">discussion</a> with the...
1
2016-07-31T01:53:47Z
[ "python", "postgresql", "flask", "flask-sqlalchemy" ]
Adding pandas dataframe iteratively in a memory efficient way
38,657,712
<p>I am trying to iteratively add some pandas dataframe that I read from a set of csv files, and after the 16th file or so I get a memory error. The new files are pandas of around 300k rows.</p> <p>Is there a way to do this in the hard drive (for example with hdf5) or in a more memory efficient way?</p> <p>See code b...
2
2016-07-29T11:28:46Z
38,657,807
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a>:</p> <pre><code>files = glob.glob('files/*.csv') d...
1
2016-07-29T11:34:18Z
[ "python", "pandas", "memory-management", "dataframe" ]
Adding pandas dataframe iteratively in a memory efficient way
38,657,712
<p>I am trying to iteratively add some pandas dataframe that I read from a set of csv files, and after the 16th file or so I get a memory error. The new files are pandas of around 300k rows.</p> <p>Is there a way to do this in the hard drive (for example with hdf5) or in a more memory efficient way?</p> <p>See code b...
2
2016-07-29T11:28:46Z
38,657,939
<p><strong>UPDATE:</strong> i would simply add reading all CSVs in chunks to your solution. I think you are already doing it very well in terms of memory saving...</p> <pre><code>sum_of_all_files = pd.DataFrame() for file_name in list_of_files: for file_df in pd.read_csv(file_name, index_col=0, header=None, chunks...
1
2016-07-29T11:41:52Z
[ "python", "pandas", "memory-management", "dataframe" ]
Docker Apache Proxy point to running Python Script
38,657,735
<p>Hoping that someone can help me understand what I have done wrong in my setup. I have a Ubuntu Server set up with Docker. I have an Apache container(running on port 80) set up to run as a Proxy and use Virtual Hosts to point to a port dependent on domain name.</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName m...
1
2016-07-29T11:30:13Z
38,657,805
<p>I assume this is running on localhost? so you want to collect on the domain but route to localhost?</p> <p>I also assume that the python script is running on port 8080? And that apache is running on port 80?</p> <p>Try this </p> <pre><code>&lt;VirtualHost *:80&gt; ServerName myDomain.com ServerAlias www.myD...
0
2016-07-29T11:34:16Z
[ "python", "apache", "docker", "proxy", "virtualhost" ]
Docker Apache Proxy point to running Python Script
38,657,735
<p>Hoping that someone can help me understand what I have done wrong in my setup. I have a Ubuntu Server set up with Docker. I have an Apache container(running on port 80) set up to run as a Proxy and use Virtual Hosts to point to a port dependent on domain name.</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName m...
1
2016-07-29T11:30:13Z
38,658,319
<p>OMG! I am sorry to waste your time, stupid me didn't run <code>a2ensite domain.com.conf</code> before I reloaded apache2 service... I apologise... That has fixed the issue!</p>
0
2016-07-29T12:00:51Z
[ "python", "apache", "docker", "proxy", "virtualhost" ]
how to remove duplicate values in a dataset : python
38,657,741
<p>I want to remove duplicate items in a dataset by keeping the ones with highest value. Now I am using pandas :</p> <pre><code>c_maxes = hospProfiling.groupby(['Hospital_ID', 'District_ID'], group_keys=False)\ .apply(lambda x: x.ix[x['Hospital_employees'].idxmax()]) print c_maxes c_maxes.to_csv('data...
1
2016-07-29T11:30:22Z
38,658,251
<p>I think you need:</p> <pre><code>hospProfiling.loc[hospProfiling.groupby(['Hospital_ID', 'District_ID'])['Hospital_employees'] .idxmax()] </code></pre> <p>I was very surprised with another answer and I do some research, if function <a href="http://pandas.pydata.org/pandas-docs/stable...
1
2016-07-29T11:57:13Z
[ "python", "pandas" ]
how to remove duplicate values in a dataset : python
38,657,741
<p>I want to remove duplicate items in a dataset by keeping the ones with highest value. Now I am using pandas :</p> <pre><code>c_maxes = hospProfiling.groupby(['Hospital_ID', 'District_ID'], group_keys=False)\ .apply(lambda x: x.ix[x['Hospital_employees'].idxmax()]) print c_maxes c_maxes.to_csv('data...
1
2016-07-29T11:30:22Z
38,658,258
<p>Why not using groupby <code>max</code> method? </p> <pre><code>hopsProfiling.groupby(['Hospital_ID','District_ID'],as_index = False).max() </code></pre> <p>And if you happen to have more than three columns, replace max by agg:</p> <pre><code>hopsProfiling.groupby(['Hospital_ID','District_ID'],as_index = False).ag...
3
2016-07-29T11:57:25Z
[ "python", "pandas" ]
Download docxtpl generated file with cherrypy
38,657,787
<p>I am using docxtpl to generate a word document, and wondering how a user can download this file once generated using cherrypy, please see my code below.</p> <p>the only solution i could come up with is to save it to the www folder and create a link to the location, but i am sure this can be simplified.</p> <p>code...
0
2016-07-29T11:33:14Z
38,665,815
<p>The short answer is that basically you need to write some in-memory stream (e.g. <code>BytesIO</code>), pre-set some HTTP headers and return a <a href="http://docs.cherrypy.org/en/latest/pkg/cherrypy.lib.html?highlight=file_generator#cherrypy.lib.file_generator" rel="nofollow"><code>file_generator</code></a>. Your q...
1
2016-07-29T18:59:07Z
[ "python", "cherrypy" ]
Python Tkinter label refresh
38,657,868
<p>I'm trying to build a gui that creates a password and i've got as far as generating the password and making it appear in a label. However when the button is clicked multiple times it appears the old password doesnt dissapear, it just overlays on top. I'm also getting an error that i cant seem to rectify, although it...
0
2016-07-29T11:37:19Z
38,658,132
<p>Try this example.</p> <pre><code>from tkinter import * import random myGui = Tk() myGui.geometry('300x200+700+250') myGui.title('Password Generator') def passwordgen(): password = '' for i in range(8): ##----runs the for loop 8 times if (i == 0) or (i == 4): password = passwor...
2
2016-07-29T11:51:26Z
[ "python", "user-interface", "tkinter" ]
Does enumerate over slice perform sublist materialization?
38,657,870
<p>Does this:</p> <pre><code>for i,v in enumerate(lst[from:to]): </code></pre> <p>or this:</p> <pre><code>for i,v in enumerate(itertools.islice(lst,from,to)): </code></pre> <p>...make a copy of iterated sublist?</p>
2
2016-07-29T11:37:23Z
38,658,522
<p>Assuming that <code>lst</code> is a regular Python list, and not a Numpy array, Pandas dataframe, or some custom class supporting slice indexing, then the slice <code>[...:...]</code> will create a new list, whereas <a href="https://docs.python.org/3/library/itertools.html#itertools.islice" rel="nofollow"><code>iter...
2
2016-07-29T12:11:13Z
[ "python", "python-3.x" ]
Grep and replace fuzzy pattern of string
38,658,041
<p>I have a few files with python code and decorators like this:</p> <pre><code>@trace('api.module.function_name', info=None, custom_args=False) </code></pre> <p>The only difference between these decorators is the string 'api.module.function_name' - func name and module are different. And depending on the this param ...
0
2016-07-29T11:47:09Z
38,658,501
<p>Something like this should work:</p> <pre class="lang-none prettyprint-override"><code>(\n|^)\s*@trace\(\s*'[^']*',\s*info=None,\s*custom_args=False\s*\)\s*(\r|\n|$) </code></pre> <p>See the <a href="https://regex101.com/r/wU7zK5/2" rel="nofollow">demo</a></p>
1
2016-07-29T12:10:10Z
[ "python", "regex" ]
Grep and replace fuzzy pattern of string
38,658,041
<p>I have a few files with python code and decorators like this:</p> <pre><code>@trace('api.module.function_name', info=None, custom_args=False) </code></pre> <p>The only difference between these decorators is the string 'api.module.function_name' - func name and module are different. And depending on the this param ...
0
2016-07-29T11:47:09Z
38,658,571
<p>Use <code>^@trace\('api\.(.+)\.(.+)', info=None, custom_args=False\)$</code> with a multiline flag.</p> <p>You may want to use <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow">re.sub</a> :</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; pattern = re.compile('^@trace\('api\.(.+)\.(.+)', ...
1
2016-07-29T12:13:56Z
[ "python", "regex" ]
How can i find all ydl_opts
38,658,046
<pre><code>ydl_opts = { 'verbose': True, #like this 'format': '{}'.format(int(comboget)), #format,vebrose,ottmpl 'outtmpl': '%(title)s-%(id)s.%(ext)s', #how can i find 'noplaylist': mt, #all dictionary 'logger': MyLogger(), #options 'p...
0
2016-07-29T11:47:22Z
38,659,184
<p>All options for the Python Module are listed in <a href="https://github.com/rg3/youtube-dl/blob/master/youtube_dl/YoutubeDL.py#L128-L278" rel="nofollow">YoutubeDL.py</a></p> <p>Here is a small excerpt</p> <blockquote> <pre><code>username: Username for authentication purposes. password: Password f...
1
2016-07-29T12:42:39Z
[ "python", "python-3.x", "youtube-dl" ]
Python Selenium Webdriver - Grab div after specified one
38,658,052
<p>I am trying to use Python Selenium Firefox Webdriver to grab the h2 content 'My Data Title' from this HTML</p> <pre><code>&lt;div class="box"&gt; &lt;ul class="navigation"&gt; &lt;li class="live"&gt; &lt;span&gt; Section Details &lt;/span&gt; &lt;/li&gt; ...
2
2016-07-29T11:47:39Z
38,658,352
<p>yeah, you need to do some complicated xpath searching:</p> <pre><code>referenceElementList = driver.find_elements_by_xpath("//span") for eachElement in referenceElementList: if eachElement.get_attribute("innerHTML") == 'Section Details': elementYouWant = eachElement.find_element_by_xpath("../../../follo...
1
2016-07-29T12:02:19Z
[ "python", "selenium", "selenium-webdriver" ]
Python Selenium Webdriver - Grab div after specified one
38,658,052
<p>I am trying to use Python Selenium Firefox Webdriver to grab the h2 content 'My Data Title' from this HTML</p> <pre><code>&lt;div class="box"&gt; &lt;ul class="navigation"&gt; &lt;li class="live"&gt; &lt;span&gt; Section Details &lt;/span&gt; &lt;/li&gt; ...
2
2016-07-29T11:47:39Z
38,658,446
<p>Here is an XPath to select the title following the text "Section Details":</p> <pre><code>//div[@class='box'][normalize-space(.)='Section Details']/following::h2 </code></pre>
2
2016-07-29T12:06:53Z
[ "python", "selenium", "selenium-webdriver" ]
Python Selenium Webdriver - Grab div after specified one
38,658,052
<p>I am trying to use Python Selenium Firefox Webdriver to grab the h2 content 'My Data Title' from this HTML</p> <pre><code>&lt;div class="box"&gt; &lt;ul class="navigation"&gt; &lt;li class="live"&gt; &lt;span&gt; Section Details &lt;/span&gt; &lt;/li&gt; ...
2
2016-07-29T11:47:39Z
38,658,548
<p>If you want grab the <code>h2</code> in the box class that comes after the one that has the span with text <code>Section Details</code> try below <code>xpath</code> using <code>preceding</code> :-</p> <pre><code>(//h2[preceding::span[normalize-space(text()) = 'Section Details']])[1] </code></pre> <p>or using <code...
2
2016-07-29T12:12:36Z
[ "python", "selenium", "selenium-webdriver" ]
How to remove .com from an url in python?
38,658,085
<p>I want to remove the domain in an url For e.g. User entered www.google.com But I only need www.google</p> <p>How to do this in python? Thanks </p>
0
2016-07-29T11:48:56Z
38,658,108
<p>If you want to remove 4 characters at the end, <a class='doc-link' href="http://stackoverflow.com/documentation/python/289/indexing-and-slicing#t=201607291151112404835">slice it</a></p> <pre><code>url = 'www.google.com' cut_url = str[:-4] # output : 'www.google' </code></pre> <hr> <p><em>More advanced answer</em>...
0
2016-07-29T11:50:10Z
[ "python", "urlparse" ]
How to remove .com from an url in python?
38,658,085
<p>I want to remove the domain in an url For e.g. User entered www.google.com But I only need www.google</p> <p>How to do this in python? Thanks </p>
0
2016-07-29T11:48:56Z
38,658,143
<p>This is a very general question. But the narrowest answer would be as follows (assuming <code>url</code> holds the URL in question):</p> <pre><code>if url.endswith(".com"): url = url[:-4] </code></pre> <p>If you want to remove the last period and everything to the right of it the code would be a little more co...
3
2016-07-29T11:52:01Z
[ "python", "urlparse" ]
How to remove .com from an url in python?
38,658,085
<p>I want to remove the domain in an url For e.g. User entered www.google.com But I only need www.google</p> <p>How to do this in python? Thanks </p>
0
2016-07-29T11:48:56Z
38,658,372
<p>To solve this without having the problem of dealing with domain name, you can look for the dots from left hand side and stop at the second dot.</p> <pre><code>t = 'www.google.com' a = t.split('.')[1] pos = t.find(a) t = t[:pos+len(a)] &gt;&gt;&gt; 'www.google' </code></pre>
0
2016-07-29T12:03:11Z
[ "python", "urlparse" ]
How to remove .com from an url in python?
38,658,085
<p>I want to remove the domain in an url For e.g. User entered www.google.com But I only need www.google</p> <p>How to do this in python? Thanks </p>
0
2016-07-29T11:48:56Z
38,658,634
<p>What you need here is <code>rstrip</code> function.</p> <p>Try this code:</p> <pre><code>url = 'www.google.com' url2 = 'www.google' new_url = url.rstrip('.com') print (new_url) new_url2 = url2.rstrip('.com') print (new_url2) </code></pre> <p><code>rstrip</code> will only strip if the string is present, in this ...
-1
2016-07-29T12:16:26Z
[ "python", "urlparse" ]
how to fix "list indices must be integers, not list"
38,658,135
<p>Hi i would like to know what is wrong with this code</p> <pre><code>f = open('test.txt', 'a+') yourResult = [line.split(',') for line in f.readlines()] for answer in yourResult: print (yourResult[answer]) a = raw_input('What Was That') Format = (answer + ' : ' + a + ', ') f.write(Format) print (Format) File = ...
0
2016-07-29T11:51:32Z
38,658,219
<p>When you use a for this way, <code>answer</code> is one of the elements of yourResult, not the index of such an element.<br> To do what you want with indexes, do :</p> <pre><code>for answer in range(len(yourResult)): print(yourResult[answer]) </code></pre> <p>In this case, you'll look inside yourResult by usin...
0
2016-07-29T11:55:47Z
[ "python", "typeerror" ]
how to fix "list indices must be integers, not list"
38,658,135
<p>Hi i would like to know what is wrong with this code</p> <pre><code>f = open('test.txt', 'a+') yourResult = [line.split(',') for line in f.readlines()] for answer in yourResult: print (yourResult[answer]) a = raw_input('What Was That') Format = (answer + ' : ' + a + ', ') f.write(Format) print (Format) File = ...
0
2016-07-29T11:51:32Z
38,658,234
<p><code>yourResult[answer]</code> can't work, the <code>[]</code> are expecting integer. when you do:</p> <p><code>for answer in yourResult:</code>, <code>answer</code> is a <strong>list</strong>(thanks bruno desthuilliers).</p> <p>You should do: </p> <pre><code>for answer in yourResult: print (answer) </code><...
1
2016-07-29T11:56:42Z
[ "python", "typeerror" ]
how to fix "list indices must be integers, not list"
38,658,135
<p>Hi i would like to know what is wrong with this code</p> <pre><code>f = open('test.txt', 'a+') yourResult = [line.split(',') for line in f.readlines()] for answer in yourResult: print (yourResult[answer]) a = raw_input('What Was That') Format = (answer + ' : ' + a + ', ') f.write(Format) print (Format) File = ...
0
2016-07-29T11:51:32Z
38,658,301
<p>Python's <code>for</code> loop doesn't yield indices but the item in the sequence itself, so here, inside the loop, <code>answer</code> is already an element of <code>yourResult</code>. IOW, you want:</p> <pre><code>for answer in yourResult: print (answer) </code></pre> <p>As a side note:</p> <p>1/ a <code>fi...
1
2016-07-29T11:59:39Z
[ "python", "typeerror" ]
how to fix "list indices must be integers, not list"
38,658,135
<p>Hi i would like to know what is wrong with this code</p> <pre><code>f = open('test.txt', 'a+') yourResult = [line.split(',') for line in f.readlines()] for answer in yourResult: print (yourResult[answer]) a = raw_input('What Was That') Format = (answer + ' : ' + a + ', ') f.write(Format) print (Format) File = ...
0
2016-07-29T11:51:32Z
38,658,374
<p>You don't need to use </p> <pre><code>print(yourResult[answer]) </code></pre> <p>using</p> <pre><code>print(answer) </code></pre> <p>will do what I expect you want. Since you have created yourResult as a list, yourResult[x] expects x to be a number from 0 to len(yourResult)-1. By doing</p> <pre><code>for answ...
0
2016-07-29T12:03:20Z
[ "python", "typeerror" ]
Python Scrapy 301 redirects
38,658,247
<p>I have a little problem, printing the redirected urls (new URLs after 301 redirection) when scraping a given website. My idea is to only print them and not scrape them. My current peace of code is:</p> <pre><code>import scrapy import os from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import ...
0
2016-07-29T11:57:07Z
38,659,886
<p>To parse any responses that are not 200 you need to add <code>handle_httpstatus_list</code> parameter to your spider. In your case something like: </p> <pre><code>class MySpider(scrapy.Spider): handle_httpstatus_list = [301] ... # rest of the spider </code></pre>
3
2016-07-29T13:15:26Z
[ "python", "scrapy" ]
Django CMS – Show different content for users and guests in same template
38,658,253
<p>I would like to have different content for users and guests in my home page's template using <strong>Django 1.9</strong> and <strong>Django CMS 3.3.1</strong>.</p> <p>It could be acomplished by making subpages and showing the corresponding content in the ancestor based on authentication conditional, but that makes ...
0
2016-07-29T11:57:16Z
38,659,327
<p><strong>Try this:</strong></p> <pre><code>{% block content %} {% if request.toolbar.build_mode or request.toolbar.edit_mode %} {% placeholder "guests" %} {% placeholder "authenticated" %} {% else %} {% if not user.is_authenticated %} {% placeholder "guests" %} ...
3
2016-07-29T12:48:46Z
[ "python", "django", "django-templates", "django-cms" ]
Write to file from different functions(python)
38,658,376
<p>is it possible to write to a single file from different function python.</p> <pre><code>from __future__ import print_function f = open("txt.txt", "wb") def f1(): ...write to txt.txt def f2(): ...write to txt.txt </code></pre> <p>is it possible?</p>
0
2016-07-29T12:03:24Z
38,658,680
<p>Just taking the previous suggestions and putting it into code. Thanks all.</p> <p><strong>functions.py:</strong></p> <pre><code>def f1(file): file.write("Function one.") def f2(file): file.write("Function two.") </code></pre> <p><strong>main.py:</strong></p> <pre><code>from functions import f1, f2 wit...
1
2016-07-29T12:19:09Z
[ "python" ]
Create blob from URL in gae using python
38,658,417
<p>I'm trying to create a blob from an image URL but I can't figure out how to do that. </p> <p>I've already read the documentation from google about creating blob, but it talks only about creating blob from a form and using <code>blobstore.create_upload_url('/upload_photo').</code> I read some question over there but...
0
2016-07-29T12:05:28Z
38,658,773
<p>The <a href="https://cloud.google.com/appengine/docs/python/googlecloudstorageclient/functions#open" rel="nofollow"><code>cloudstorage.open()</code></a> clearly exists, so the error likely indicates some library/naming conflict in your environment.</p> <p>A method for debugging such conflict is described in this po...
0
2016-07-29T12:23:35Z
[ "python", "python-2.7", "google-app-engine", "blobstore", "google-cloud-datastore" ]
recursively collect string blocks in python
38,658,470
<p>I have a custom data file formatted like this:</p> <pre><code>{ data = { friends = { max = 0 0, min = 0 0, }, family = { cars = { van = "honda", car = "ford", bike = "trek", }, pre...
1
2016-07-29T12:08:29Z
38,659,444
<p>You can create a <code>to_block</code> function that takes the lines from your file as an iterator and recursively creates a nested dictionary from those. (Of course you could also use a custom <code>Block</code> class, but I don't really see the benefit in doing so.)</p> <pre><code>def to_block(lines): block =...
1
2016-07-29T12:54:37Z
[ "python" ]
recursively collect string blocks in python
38,658,470
<p>I have a custom data file formatted like this:</p> <pre><code>{ data = { friends = { max = 0 0, min = 0 0, }, family = { cars = { van = "honda", car = "ford", bike = "trek", }, pre...
1
2016-07-29T12:08:29Z
38,659,653
<p>You can also do with ast or json with the help of regex substitutions.</p> <pre><code>import re a = """{ data = { friends = { max = 0 0, min = 0 0, }, family = { cars = { van = "honda", car = "ford", bik...
1
2016-07-29T13:03:36Z
[ "python" ]
Indexing many JSON objects into Elasticsearch - the canonical way
38,658,471
<p>Here's a scenario I keep facing, and I am in doubt whether the solution I take is the canonical/smart one. Assume you a file where each line is a valid JSON. Furthermore, each object contains a field <code>type</code> and <code>id</code> and the pairs of are unique. My goal is to index all the objects into an index ...
2
2016-07-29T12:08:30Z
38,658,606
<p>Definitely the <code>bulk</code> approach. But you need to put a bit more work into this, as it's not as easy as creating one file, sending it to ES and expect it to deal with it.</p> <p>If the file is too big, of course it will struggle. Do please read this section of the documentation, especially the last part wh...
0
2016-07-29T12:15:25Z
[ "python", "json", "elasticsearch", "jq" ]
Calculating circular motion in a tuple array
38,658,472
<p>I got a project to deliver for school. The project is about random movement based systems, me and my mate chose to research a double pendulum set(movement is not random but chaotic). Our research question wants to investigate if the system can get to a state of periodic motion in any point and in how much time will ...
0
2016-07-29T12:08:33Z
38,660,237
<p><strong>EDIT:</strong> OP clarified the question and stated that he is searching for periodical movement, not <code>m1</code> or <code>m2</code> <em>flipping over</em>.</p> <p>The approach below refers to <em>flip detection</em> for one of the two masses at the double pendulum.</p> <h2>Flip detection</h2> <p>Dete...
2
2016-07-29T13:33:04Z
[ "python", "arrays", "physics" ]
Changing iterable variable during loop
38,658,490
<p>Let <code>it</code> be an iterable element in python. In what cases is a change of <code>it</code> inside a loop over <code>it</code> reflected? Or more straightforward: When does something like this work?</p> <pre><code>it = range(6) for i in it: it.remove(i+1) print i </code></pre> <p>Leads to 0,2,4 bein...
6
2016-07-29T12:09:32Z
38,658,791
<p>When you iterate over a <code>list</code> you actually call <code>list.__iter__()</code>, which returns a <code>listiterator</code> object bound to the <code>list</code>, and then actually iterate over this <code>listiterator</code>. Technically, this:</p> <pre><code>itt = [1, 2, 3] for i in itt: print i </code...
6
2016-07-29T12:24:36Z
[ "python", "for-loop" ]
Changing iterable variable during loop
38,658,490
<p>Let <code>it</code> be an iterable element in python. In what cases is a change of <code>it</code> inside a loop over <code>it</code> reflected? Or more straightforward: When does something like this work?</p> <pre><code>it = range(6) for i in it: it.remove(i+1) print i </code></pre> <p>Leads to 0,2,4 bein...
6
2016-07-29T12:09:32Z
38,658,815
<p>In the first loop you are changing the <code>it</code> object (inner state of the object), however, in the second loop you are reassigning the <code>it</code> to another object, leaving initial object unchanged.</p> <p>Let's take a look at the generated bytecode:</p> <pre><code>In [2]: def f1(): ...: it = r...
4
2016-07-29T12:25:58Z
[ "python", "for-loop" ]
Changing iterable variable during loop
38,658,490
<p>Let <code>it</code> be an iterable element in python. In what cases is a change of <code>it</code> inside a loop over <code>it</code> reflected? Or more straightforward: When does something like this work?</p> <pre><code>it = range(6) for i in it: it.remove(i+1) print i </code></pre> <p>Leads to 0,2,4 bein...
6
2016-07-29T12:09:32Z
38,658,829
<p>First, it is essential to understand what happens under the hood when you run a simple for-loop, like:</p> <pre><code>for i in it: pass </code></pre> <p>At the beginning of the loop, an <em>iterator</em> is created. That iterator is the result of an implicit call to <code>iter(it)</code>. This is the <em>only</em...
4
2016-07-29T12:26:33Z
[ "python", "for-loop" ]
Calculate with date, without import dateutil
38,658,521
<pre><code>from datetime import datetime from dateutil import relativedelta date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S') date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d') r = relativedelta.relativedelta(date2, date1) r.months </code></pre> <p>The code above does the trick for me bu...
1
2016-07-29T12:11:04Z
38,658,756
<p>Seems this post helps: <a href="http://stackoverflow.com/questions/1345827/how-do-i-find-the-time-difference-between-two-datetime-objects-in-python">How do I find the time difference between two datetime objects in python?</a></p> <p>simply do a substraction on two datetime obj, then you can get what detail you wan...
1
2016-07-29T12:23:08Z
[ "python", "python-2.7" ]
Calculate with date, without import dateutil
38,658,521
<pre><code>from datetime import datetime from dateutil import relativedelta date1 = datetime.strptime(str('2011-08-15 12:00:00'), '%Y-%m-%d %H:%M:%S') date2 = datetime.strptime(str('2012-02-15'), '%Y-%m-%d') r = relativedelta.relativedelta(date2, date1) r.months </code></pre> <p>The code above does the trick for me bu...
1
2016-07-29T12:11:04Z
38,659,029
<p>Interestingly enough, your code outputs to: <code>5</code> which means, as suggested in the comments, that you are probably interested in the duration of each month and you do not want to round your results. Unfortunately the <code>timedelta</code> object will not work for you in this case because by definition, a t...
0
2016-07-29T12:35:46Z
[ "python", "python-2.7" ]
Scrapy iterating over selector yields n duplicated items for number of selectors found on page
38,658,552
<p>I have a working scraper that I have built to collect information from a review site. The problem I'm having is that when I crawl a business page with several reviews and try to yield the items, I only get the first item n times (where n is the number of reviews the selector found).</p> <p>I've read up a lot on gen...
0
2016-07-29T12:12:45Z
38,659,276
<p>Once you have your "sub-selector" <code>reviewSelector</code> you need to use <code>.</code> before your xpath to indicate sub-selector level.</p> <p>i.e. this:</p> <pre><code>reviewSelector.xpath('//*[@itemprop="author"]/@content').extract_first() </code></pre> <p>should be:</p> <pre><code>reviewSelector.xpath(...
0
2016-07-29T12:46:38Z
[ "python", "scrapy", "generator" ]
add() argument after * must be a sequence, not Settings
38,658,684
<p>I'm trying to build a game that moves a ship left and right with the arrow keys and fires bullets when the spacebar is pressed. When I press the spacebar my game crashes and this error is shown: Traceback (most recent call last):</p> <pre><code>TypeError: add() argument after * must be a sequence, not Settings </co...
2
2016-07-29T12:19:23Z
38,660,821
<p>You are missing an underscore <code>_</code> in your <code>Bullet.__init__</code> method. You currently have <code>_init__</code> when it should be <code>__init__</code>.</p> <p>This results in Python calling the <code>Sprite.__init__</code> method with <code>ai_settings</code> as the first argument, since it canno...
2
2016-07-29T14:02:52Z
[ "python", "pygame", "sprite", "add" ]