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
Simplify database (psycopg2) usage by creating a module
37,488,175
<p>Let me preface this by saying that I am fairly new to Python and I apologize if this is not the appropriate place for this question.</p> <p>I am using the <strong>psycopg2</strong> module to manipulate a PostgreSQL database. The general usage would look something like this:</p> <pre><code># Example 1 import psyco...
1
2016-05-27T16:17:55Z
37,488,907
<p>You could do it the way you want to - although I would consider using <code>sqlalchemy</code> or other module to handle those parts for you.</p> <p>The code you pasted doesn't work because <code>cursor</code> is not defined in your other methods.</p> <p>Consider doing it in one call - for example:</p> <pre><code>...
0
2016-05-27T17:04:17Z
[ "python", "sql", "postgresql", "module", "psycopg2" ]
python none value return
37,488,229
<pre><code>class MyWindow(): class Filter(QtCore.QObject) : def eventFilter(self, widget, event): return event.type() == QtCore.QEvent.FocusOut def __init__(self, ui) : self.ui = ui def mycode (self) : myvalue = float(self.ui.myvalueEdit.text(...
0
2016-05-27T16:20:52Z
37,488,507
<p>The method installEventFilter doesn't return anything, which is why you are getting None. Your eventFilter method is a callback that will be called when an event happens. </p> <p>The return value of eventFilter is suppose to indicate whether or not you have handled the event. That is, you return True if you don't w...
1
2016-05-27T16:38:28Z
[ "python", "qt", "focus" ]
Chain repetitions of same generator in python
37,488,346
<p>Consider the following simple generator:</p> <pre><code>def simple_gen(): for number in range(5): yield number ** 2 </code></pre> <p>I'm willing to user <code>itertools.repeat</code> and <code>itertools.chain</code> to chain n times the generator to itself. For clarity consider the following (non-gener...
2
2016-05-27T16:28:23Z
37,488,383
<p>You could convert the generator output to a list first:</p> <pre><code>repeat(list(simple_gen()), 2) </code></pre> <p>You <em>can't</em> otherwise repeat a generator output. At most you could <em>recreate</em> the generator <em>count</em> number of times:</p> <pre><code>from itertools import repeat def recreate(...
4
2016-05-27T16:31:22Z
[ "python", "functional-programming", "generator" ]
Chain repetitions of same generator in python
37,488,346
<p>Consider the following simple generator:</p> <pre><code>def simple_gen(): for number in range(5): yield number ** 2 </code></pre> <p>I'm willing to user <code>itertools.repeat</code> and <code>itertools.chain</code> to chain n times the generator to itself. For clarity consider the following (non-gener...
2
2016-05-27T16:28:23Z
37,488,432
<p>How about a decorator:</p> <pre><code>from itertools import repeat class repeat_gen: def __init__(self, count): self.count = count def __call__(self, gen): for it in repeat(gen, self.count): yield from it() @repeat_gen(3) def simple_gen(): for number in range(5): y...
2
2016-05-27T16:34:34Z
[ "python", "functional-programming", "generator" ]
Matplotlib 3DPlot Extra Lines when Dimensions not Equal
37,488,379
<p>Consider this MWE: </p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np from matplotlib import cm n = 15 m = 12 x = np.linspace(-5, 5, n) y = np.linspace(-5, 5, m) Z = np.zeros((m, n)) for i in xrange(m): for j in xrange(n): Z[i, j] = x[j]**2 + y[...
2
2016-05-27T16:31:08Z
37,489,040
<p>Unlike 2D, 3D plots in matplotlib have a lot of <a href="http://matplotlib.org/mpl_toolkits/mplot3d/faq.html" rel="nofollow">shortcomings</a>. Let me quote one of the answers in matplotlib FAQ:</p> <blockquote> <p>This is probably the most commonly reported issue with mplot3d. The problem is that – from some ...
2
2016-05-27T17:13:57Z
[ "python", "matplotlib" ]
Python IRC ChatBot hangs on socket.recv after seemingly random time even though socket.settimeout is 8
37,488,380
<p>Hey so I decided to create an IRC ChatBot whose sole purpose it is to read incoming messages from Twitch Chat and if a giveaway is recognized by a keyword it's supposed to enter the giveaway by sending !enter in Chat.</p> <p>I build the Bot upon this source: <a href="https://github.com/BadNidalee/ChatBot" rel="nofo...
1
2016-05-27T16:31:10Z
37,488,622
<p>I think you've missunderstood how timeout work on the socket.</p> <pre><code>s.settimeout(8.0) </code></pre> <p>Will only set <code>s.connect(...)</code> to timeout if it can't reach the destination host.<br> Further more, usually what you want to use instead if <code>s.setblocking(0)</code> however this alone won...
0
2016-05-27T16:45:13Z
[ "python", "sockets", "chat", "irc", "receiver" ]
Can you tell me why this web scraper isn't able to log in correctly?
37,488,390
<p>I'm trying to make a web scraper to get some information from the site Colloquy.com, on which I have an account. I am having trouble getting my scraper to log in to the site though. I'm using Python 2.7 with BeautifulSoup and Requests.</p> <p><a href="http://i.stack.imgur.com/hyFNE.png" rel="nofollow">Here is a scr...
0
2016-05-27T16:31:50Z
37,489,180
<p>Instead of attempting to scrape the login page where the javascript is, it appears they <code>post</code> the information to <code>https://colloquy.com/app/account/login</code>, so you could do something like the following to try and login.</p> <pre><code>import requests resp = requests.post("https://colloquy.com/a...
2
2016-05-27T17:22:58Z
[ "javascript", "python", "beautifulsoup", "web-crawler", "screen-scraping" ]
brew install python for scrapy - symlink & permission issues
37,488,439
<p>I'm following the Scrapy installation guide to install a fresh copy of python (2.7.11) despite I already have 2.6, 2.7.10 and 3.4.0. The installation was going fine until the final step with these errors</p> <pre><code>==&gt; Pouring python-2.7.11.el_capitan.bottle.2.tar.gz Error: The `brew link` step did not compl...
1
2016-05-27T16:34:54Z
37,494,988
<p>Based on numerous posts from various fora, the most recommended best practice is to have homebrew install all versions of python you need, leave the OSX bundled python alone (&amp; unused) and remove all other versions because homebrew does not necessarily play nice with them.</p> <p>According to <a href="http://st...
1
2016-05-28T03:45:08Z
[ "python", "scrapy", "symlink", "2to3" ]
How to use an existing Environment variable in subprocess.Popen()
37,488,480
<p><strong>Scenario</strong></p> <p>In my python script I need to run an executable file as a subprocess with x number of command line parameters which the executable is expecting.</p> <p>Example:</p> <ul> <li>EG 1: myexec.sh param1 param2 </li> <li>EG 2: myexec.sh param1 $MYPARAMVAL</li> </ul> <p>The executable an...
2
2016-05-27T16:36:45Z
37,488,554
<p>You can not access the environment variable using <code>$VAR</code>. You'd use <code>os.environ[..]</code> instead:</p> <pre><code>cmdlst = ['echo','param1',os.environ['PARAM']] </code></pre>
0
2016-05-27T16:41:34Z
[ "python", "subprocess" ]
How to use an existing Environment variable in subprocess.Popen()
37,488,480
<p><strong>Scenario</strong></p> <p>In my python script I need to run an executable file as a subprocess with x number of command line parameters which the executable is expecting.</p> <p>Example:</p> <ul> <li>EG 1: myexec.sh param1 param2 </li> <li>EG 2: myexec.sh param1 $MYPARAMVAL</li> </ul> <p>The executable an...
2
2016-05-27T16:36:45Z
37,488,607
<p>You could do:</p> <pre><code>cmdlist = ['echo','param',os.environ["PARAM"] </code></pre> <p>Or:</p> <pre><code>cmdlist = ['echo','param1','$PARAM'] proc = subprocess.Popen(cmdlist,stdout=subprocess.PIPE, env={'PARAM':os.environ['PARAM']) </code></pre>
1
2016-05-27T16:44:18Z
[ "python", "subprocess" ]
How to use an existing Environment variable in subprocess.Popen()
37,488,480
<p><strong>Scenario</strong></p> <p>In my python script I need to run an executable file as a subprocess with x number of command line parameters which the executable is expecting.</p> <p>Example:</p> <ul> <li>EG 1: myexec.sh param1 param2 </li> <li>EG 2: myexec.sh param1 $MYPARAMVAL</li> </ul> <p>The executable an...
2
2016-05-27T16:36:45Z
37,488,623
<p>If you want to have the shell expand environment variables, you have to set <code>shell=True</code></p> <pre><code>subprocess.Popen('echo param1 $PARAM', shell=True, stdout=subprocess.PIPE) </code></pre> <p>Alternatively, you could just query the environment variable yourself when constructing the command, and the...
2
2016-05-27T16:45:36Z
[ "python", "subprocess" ]
How to form proper query list acording to selected category in Django Solr
37,488,560
<p>Can someone explain me if thats an right approach, im trying to form a list of query field in a filter form, depend on what category were selected.</p> <p>As for now if i select category weapons, in the filter all other fields from other categories, are being shown too like that <a href="http://i.imgur.com/92UwAS8....
0
2016-05-27T16:41:53Z
37,509,259
<p>fixed, thx to solr Irc - <code>self.conn.search(query_string, facet = 'on' ,** {'facet.pivot': 'category_exact,product_class_exact'})</code></p>
0
2016-05-29T11:19:56Z
[ "python", "django", "solr", "oscar" ]
python - PyQt detect when worker is finished and do something in main thread
37,488,667
<p>i have an issue, I am newbie to PyQt and I can't figure out how to detect when my worker(thread got finished) using main thread(the UI thread).. so basically what I want to says : I have a class which create UI and a bunch of widget and when i click a button my <strong>Qthread</strong> run with success the <strong>...
-1
2016-05-27T16:48:16Z
37,488,902
<p>You can't define signals dynamically on instances, they have to be declared as class attributes. Also, <code>SIGNAL</code> is only used with the old-style syntax, which nobody uses anymore, for the new-style signal/slot syntax use <code>pyqtSignal</code> and <code>pyqtSlot</code>. Also, the arguments to the <code>...
1
2016-05-27T17:03:43Z
[ "python", "selenium-webdriver", "pyqt" ]
python - PyQt detect when worker is finished and do something in main thread
37,488,667
<p>i have an issue, I am newbie to PyQt and I can't figure out how to detect when my worker(thread got finished) using main thread(the UI thread).. so basically what I want to says : I have a class which create UI and a bunch of widget and when i click a button my <strong>Qthread</strong> run with success the <strong>...
-1
2016-05-27T16:48:16Z
37,498,907
<p>O Thanks Brendan Abel for you answer it did worked when i run your code in simple UI .. </p> <pre><code>from PyQt4 import QtGui, QtCore import time, sys class Worker(QtCore.QThread): signal = QtCore.pyqtSignal(str) def run(self): self.signal.emit(':) Oh I did it the string is final sent over the ...
0
2016-05-28T12:20:16Z
[ "python", "selenium-webdriver", "pyqt" ]
Recursion and Binary Trees
37,488,710
<pre><code>#Get length of the longest path through recursion def max_height(node): if not node: return 0 left = max_height(node.left) #Base Case based on my understanding right = max_height(node.right) #Base Case based on my understanding return max_height(left, right) + 1 </code></pre> <p>I ke...
1
2016-05-27T16:51:16Z
37,488,828
<ol> <li><p>The base case is where the recursion stops and you have one: <code>not node</code> (<code>node == None</code>)</p></li> <li><p>I don't see an issue with the spacing... Make sure you use only tabs or only spaces</p></li> <li><p>This does produce the height: the number of nodes from root to leaf along the lon...
2
2016-05-27T17:00:06Z
[ "python", "recursion" ]
Recursion and Binary Trees
37,488,710
<pre><code>#Get length of the longest path through recursion def max_height(node): if not node: return 0 left = max_height(node.left) #Base Case based on my understanding right = max_height(node.right) #Base Case based on my understanding return max_height(left, right) + 1 </code></pre> <p>I ke...
1
2016-05-27T16:51:16Z
37,799,528
<p>All answered were right but, I faced little problem while writing inside the class;</p> <p>So, the code goes like this, I hope this helps.</p> <pre><code> class Tree(object): def height(self, root): if root == None: #root == None return 0 else: ret...
0
2016-06-13T21:35:26Z
[ "python", "recursion" ]
Python 3 not reading a JSON file right
37,488,748
<p>I have some json files created by powershell using the <code>ConvertTo-Json</code> command. The content of the json file looks like</p> <pre><code>{ "Key1": "Value1", "Key2": "Value2" } </code></pre> <p>I ran the python interpreter to see if I could read the file but I get this weird output</p> <pre><co...
0
2016-05-27T16:54:37Z
37,488,908
<p>It seems that you have a <a href="https://en.wikipedia.org/wiki/Byte_order_mark#UTF-16" rel="nofollow">BOM</a> at the start of your file. You can verify it in a hex editor or with a good text editor (Notepad++ shows if BOM is present).</p>
3
2016-05-27T17:04:23Z
[ "python", "json", "file", "python-3.x", "parsing" ]
Python 3 not reading a JSON file right
37,488,748
<p>I have some json files created by powershell using the <code>ConvertTo-Json</code> command. The content of the json file looks like</p> <pre><code>{ "Key1": "Value1", "Key2": "Value2" } </code></pre> <p>I ran the python interpreter to see if I could read the file but I get this weird output</p> <pre><co...
0
2016-05-27T16:54:37Z
37,489,050
<p>If you want to load text files with Unicode BOM headers, like yours you should better use to codecs.open functions instead of open as the default open is not able to interpret the BOM.</p> <p>Or you can have a look at <a href="http://tendo.readthedocs.io/en/latest/_modules/tendo/unicode.html" rel="nofollow">tendo.u...
1
2016-05-27T17:14:16Z
[ "python", "json", "file", "python-3.x", "parsing" ]
Python 3 not reading a JSON file right
37,488,748
<p>I have some json files created by powershell using the <code>ConvertTo-Json</code> command. The content of the json file looks like</p> <pre><code>{ "Key1": "Value1", "Key2": "Value2" } </code></pre> <p>I ran the python interpreter to see if I could read the file but I get this weird output</p> <pre><co...
0
2016-05-27T16:54:37Z
37,489,223
<p>As pointed out by jwodder, PowerShell has encoded your json using UTF-16LE. To get this data into json correctly, you need to open the file using the correct encoding. eg.</p> <pre><code>with open("test.json", "r", encoding="utf16") as f: json_string = f.read() my_dict = json.loads(json_string) </code></pre> <...
2
2016-05-27T17:25:29Z
[ "python", "json", "file", "python-3.x", "parsing" ]
Stripping Out Characters
37,488,765
<p>I have this code writing to a file;</p> <pre><code>rline = quantity," x ",product, productcost </code></pre> <p>When I read the file, I get this <code>(8, ' x ', '98456390,Paper Tray,6\r\n', 48)</code> I am trying to strip out the characters - brackets, speech marks and\r\n</p> <p>I am trying to use rline.strip, ...
0
2016-05-27T16:55:47Z
37,488,875
<p>Technically, there aren't any brackets or quotes.</p> <p>The following line of code creates a tuple consisting of <code>quantity</code>, the string <code>" x "</code> (i.e an x surrounded by a space on each side), <code>product</code>, and <code>productcost</code>.</p> <pre><code>rline = quantity," x ",product, pr...
1
2016-05-27T17:02:04Z
[ "python" ]
How to make QTreeWIdgetItems editable selectively
37,488,831
<p><a href="http://i.stack.imgur.com/HAmuo.png" rel="nofollow"><img src="http://i.stack.imgur.com/HAmuo.png" alt="enter image description here"></a></p> <p>All the cells are currently editable (editable on double-click). I only need the column 0 to be editable and all others not. How to achieve this?</p> <pre><code>f...
0
2016-05-27T17:00:09Z
37,493,155
<p>To keep it simple I am using treeWidget's <code>doubleClick</code> signal that is processed before things get to QTreeWidgetItem's <code>setData</code> method. Since the <code>onDoubleClick</code> method gets an index we can set the item as editable or not as editable ahead of time. The working solution is posted be...
0
2016-05-27T22:29:23Z
[ "python", "qt", "pyqt", "qtreewidget", "qtreewidgetitem" ]
How to make QTreeWIdgetItems editable selectively
37,488,831
<p><a href="http://i.stack.imgur.com/HAmuo.png" rel="nofollow"><img src="http://i.stack.imgur.com/HAmuo.png" alt="enter image description here"></a></p> <p>All the cells are currently editable (editable on double-click). I only need the column 0 to be editable and all others not. How to achieve this?</p> <pre><code>f...
0
2016-05-27T17:00:09Z
37,497,836
<p>Generally, you would do this with the use of a <code>QItemDelegate</code>. Delegates give you control over how data from the model is displayed in the view and how data from the controller/view is edited and inserted back into the model. They allow you to do things like custom painting and custom editors. In this...
0
2016-05-28T10:23:08Z
[ "python", "qt", "pyqt", "qtreewidget", "qtreewidgetitem" ]
Python Unicode and ASCII issues when parsing HTML
37,488,901
<p>I am trying to write a Python script which acts similar to Ctrl + S on a Chrome web browser, it saves the HTML page, downloads any links on the webpage and finally, replaces the URIs of the links with the local path on disk.</p> <p>The code posted below attempts to replace the URIs in for CSS files with local path...
0
2016-05-27T17:03:41Z
37,491,499
<h1>THIS WILL SOLVE YOUR ISSUE</h1> <p>use <code>webContent.decode('utf-8', errors='ignore')</code> or <code>webContent.decode('latin-1')</code></p> <p><code>webContent[13801:13850]</code> has some weird characters. Just ignore them.</p> <h1>IGNORE EVERYTHING BELOW HERE</h1> <hr> <p>This is kind of a shot at the ...
1
2016-05-27T20:07:37Z
[ "python", "html", "unicode", "encoding", "utf-8" ]
pythonic way to index list of objects
37,488,912
<p>I have a list of objects. Each object has two fields</p> <pre><code>obj1.status = 2 obj1.timestamp = 19211 obj2.status = 3 obj2.timestamp = 14211 obj_list = [obj1, obj2] </code></pre> <p>I will keep adding / deleting objects in the list and also changing attributes of objects, for example I may change ob1.status...
6
2016-05-27T17:04:35Z
37,489,536
<p>One approach here would be to create a class level <code>dict</code> for <code>MyObj</code> and define updating behavior using <code>property</code> decorator. Every time an object is changed or added, it is reflected in the respected dictionaries associated with the class.</p> <p>Edit: as @BrendanAbel points out, ...
2
2016-05-27T17:47:52Z
[ "python", "dictionary", "indexing" ]
pythonic way to index list of objects
37,488,912
<p>I have a list of objects. Each object has two fields</p> <pre><code>obj1.status = 2 obj1.timestamp = 19211 obj2.status = 3 obj2.timestamp = 14211 obj_list = [obj1, obj2] </code></pre> <p>I will keep adding / deleting objects in the list and also changing attributes of objects, for example I may change ob1.status...
6
2016-05-27T17:04:35Z
37,489,540
<p>For a collection to be aware of mutation of its elements, there must be some connection between the elements and that collection which can communicate when changes happen. For this reason, we either must bind an instance to a collection or proxy the elements of the collection so that change-communication doesn't lea...
1
2016-05-27T17:48:10Z
[ "python", "dictionary", "indexing" ]
pythonic way to index list of objects
37,488,912
<p>I have a list of objects. Each object has two fields</p> <pre><code>obj1.status = 2 obj1.timestamp = 19211 obj2.status = 3 obj2.timestamp = 14211 obj_list = [obj1, obj2] </code></pre> <p>I will keep adding / deleting objects in the list and also changing attributes of objects, for example I may change ob1.status...
6
2016-05-27T17:04:35Z
37,489,727
<p>You could override the <code>__setattr__</code> on the objects to update the indexes whenever you set the values. You can use a <code>weakref</code> dictionary for the indexes so that when you delete objects and are no longer using them, they are automatically removed from the indexes.</p> <pre><code>import weakre...
2
2016-05-27T18:00:05Z
[ "python", "dictionary", "indexing" ]
pythonic way to index list of objects
37,488,912
<p>I have a list of objects. Each object has two fields</p> <pre><code>obj1.status = 2 obj1.timestamp = 19211 obj2.status = 3 obj2.timestamp = 14211 obj_list = [obj1, obj2] </code></pre> <p>I will keep adding / deleting objects in the list and also changing attributes of objects, for example I may change ob1.status...
6
2016-05-27T17:04:35Z
37,490,350
<p>I am not sure if this is what you are asking for but ...</p> <p>Objects:</p> <pre><code>import operator class Foo(object): def __init__(self): self.one = 1 self.two = 2 f = Foo() f.name = 'f' g = Foo() g.name = 'g' h = Foo() h.name = 'h' name = operator.attrgetter('name') </code></pre> <p>li...
-1
2016-05-27T18:41:42Z
[ "python", "dictionary", "indexing" ]
Python spawned child process ID
37,488,971
<p>I need to get the <em>real</em> process ID <em>IN the spawned child</em> as seen by the parent in my example. Right now os.getpgid(0) just returns the parents process ID because its inherited which is correct. But in the parent the child process ID is different. This is just a simple example but I will implement ...
0
2016-05-27T17:08:30Z
37,489,320
<p>Duh. The answer is use os.getpid() I was just confused. Thx for the nudge @Jasper.</p>
1
2016-05-27T17:32:48Z
[ "python", "linux" ]
Map Python list element to multiple elements, avoiding nested lists
37,489,013
<p>This way I can build a new list by mapping every element in another list:</p> <pre><code># turn [0,5,10,15] into [1,6,11,16] [ x+1 for x in range(0,20,5) ] </code></pre> <p>But I want every element to yield two elements in my new lists. How can I do that? Here are my attempts:</p> <pre><code># turn [0,5,10,16] in...
0
2016-05-27T17:11:40Z
37,489,076
<p>You need to use two loop:</p> <pre><code>&gt;&gt;&gt; [t for x in range(0,20,5) for t in [-x,x+1] ] [0, 1, -5, 6, -10, 11, -15, 16] </code></pre> <p>Or if you are dealing with larger data sets you can use <code>itertools.chain()</code></p> <pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; &gt;&gt;...
4
2016-05-27T17:15:29Z
[ "python", "list" ]
Map Python list element to multiple elements, avoiding nested lists
37,489,013
<p>This way I can build a new list by mapping every element in another list:</p> <pre><code># turn [0,5,10,15] into [1,6,11,16] [ x+1 for x in range(0,20,5) ] </code></pre> <p>But I want every element to yield two elements in my new lists. How can I do that? Here are my attempts:</p> <pre><code># turn [0,5,10,16] in...
0
2016-05-27T17:11:40Z
37,489,082
<p>To my knowledge, a list comprehension (with one <code>for</code>) can not do more than one element at a time. You can either:</p> <ul> <li>flatten it (<code>from itertools import chain</code>)</li> <li><p>Use a function like below and use that as a generator:</p> <pre><code>def myFunc(elements): for elem in el...
2
2016-05-27T17:15:38Z
[ "python", "list" ]
Map Python list element to multiple elements, avoiding nested lists
37,489,013
<p>This way I can build a new list by mapping every element in another list:</p> <pre><code># turn [0,5,10,15] into [1,6,11,16] [ x+1 for x in range(0,20,5) ] </code></pre> <p>But I want every element to yield two elements in my new lists. How can I do that? Here are my attempts:</p> <pre><code># turn [0,5,10,16] in...
0
2016-05-27T17:11:40Z
37,489,106
<p>You could use <code>functools.reduce</code> (no need to import it if you are in Python 2.x):</p> <pre><code>from functools import reduce flat_list = reduce(lambda x, y: x + y, [[-x, x+1] for x in range(0, 20, 5)], []) </code></pre> <p>Or, even better, as @Thrustmaster pointed out:</p> <pre><code>flat_list = sum(...
0
2016-05-27T17:17:26Z
[ "python", "list" ]
Map Python list element to multiple elements, avoiding nested lists
37,489,013
<p>This way I can build a new list by mapping every element in another list:</p> <pre><code># turn [0,5,10,15] into [1,6,11,16] [ x+1 for x in range(0,20,5) ] </code></pre> <p>But I want every element to yield two elements in my new lists. How can I do that? Here are my attempts:</p> <pre><code># turn [0,5,10,16] in...
0
2016-05-27T17:11:40Z
37,489,267
<p>Note that the exact notation you are wanting <a href="https://www.python.org/dev/peps/pep-0448/#variations" rel="nofollow">was proposed but rejected</a> to add to python:</p> <blockquote> <p>Earlier iterations of this PEP allowed unpacking operators inside list, set, and dictionary comprehensions as a flattening ...
0
2016-05-27T17:29:22Z
[ "python", "list" ]
Retrieving data in Python from two MySQL tables?
37,489,052
<p>I'm using Python and I'm trying to retrieve data from two mySQL tables(name = deal_info and profile) in the same database (name = begin). The two tables are not linked or do NOT have the same primary key, but I get the error</p> <pre><code> raise errors.InternalError("Unread result found.") mysql.connector.errors....
0
2016-05-27T17:14:28Z
37,505,055
<p>Per the MySQL.connector <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursorbuffered.html" rel="nofollow">docs</a>, you need to fetch results before executing any other statement:</p> <blockquote> <p>In this case, you must be sure to fetch all rows of the result set before exe...
0
2016-05-29T00:38:40Z
[ "python", "mysql" ]
I have 2 very similar C functions being called from python and Java. How can I combine the 2 libraries into 1 that can be called from both languages?
37,489,128
<p>Basically I have 2 implementations of a C function "encrypt" which I call from python using ctypes and java using JNI. I've been told to take the two dynamic libraries that were used for java and python, and combine them into a static library that can be called from both. To clarify, here's the C function implementa...
0
2016-05-27T17:19:04Z
37,845,317
<p>You can call the python version from the java one. This avoids the duplicate code. You’ll still have to do the to/from JNI marshalling though:</p> <pre><code>void encrypt(int size, unsigned char *buffer){ for(int i=0; i &lt; size; i++){ buffer[i]+=1; printf("%c", buffer[i]); } } JNIEXPOR...
0
2016-06-15T20:37:28Z
[ "java", "python", "c", "jni", "static-libraries" ]
How do I retrieve mean value for each height level?
37,489,148
<p>For each height level in the data, I need to print the mean value of this height data. The data is listed here:</p> <pre><code>array([[[[ 0. , 0. , 0. , ..., 0. , 0. , 0. ], [ 0. , 0. , 0. , ..., 0....
0
2016-05-27T17:20:39Z
37,489,423
<p>Use the <code>np.mean(array,axis=1)</code> to get means within the array.</p> <p>I'm not sure I understand the dimensionality of the data, but I think you are trying to maintain the top 99 categories and take the mean of the 99 x 6 observations within.</p> <p>if your array is named array, this will get you 99 resu...
1
2016-05-27T17:40:09Z
[ "python", "numpy" ]
Fastest way to compute a subset of columns of the pseudoinverse of a scipy.sparse matrix
37,489,191
<p>I am looking for the best way to compute a subset of the columns of the pseudoinverse of a sparse matrix <code>A</code>. Here are some relevant facts:</p> <ol> <li><p><code>A</code> is a sparse <code>NxN</code> matrix that has a single zero eigenvalue with known eigenvector</p></li> <li><p>I only need <code>M &lt;...
1
2016-05-27T17:23:58Z
38,356,533
<p>You are looking for <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.svds.html" rel="nofollow"><code>scipy.sparse.linalg.svds</code></a> which will “Compute the largest <code>k</code> singular values/vectors for a sparse matrix” (though that’s a bit misleading since it’ll do t...
0
2016-07-13T15:58:12Z
[ "python", "matrix", "scipy", "linear-algebra", "sparse-matrix" ]
how to randomize results from two querysets in django template
37,489,336
<p>Friends, I want to know how we can present results from two different querysets in django template.</p> <p>My views.py is as follows:</p> <pre><code>def index(request): answers = Answer.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) return render(request,"welco...
1
2016-05-27T17:33:40Z
37,489,412
<p>Using the <a href="https://docs.python.org/2/library/random.html#random.shuffle" rel="nofollow"><code>shuffle</code></a> function?</p> <pre><code>import random def index(request): answers = Answer.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) mixed = list(ans...
2
2016-05-27T17:39:07Z
[ "python", "django" ]
Problems with Pygame on MAC OS X
37,489,348
<p>I am having trouble setting up Pygame on my MAC. Here are my specifications: OS X El Capitan 10.11.4. Whenever I run a file with import pygame I get the following error message in terminal: </p> <pre><code>ImportError: No module named 'pygame' </code></pre> <p>If I try to install pygame from bitbucket that the di...
0
2016-05-27T17:34:29Z
37,490,432
<p>Note, I'm not currently on a mac so I'm doing kind of from memory and what I assume should work so some of this might be different for you.</p> <p>open terminal and type:</p> <pre><code>which python3 </code></pre> <p>Copy the value of what the which command returns. Open up your ~/.bash_profile using a text edito...
0
2016-05-27T18:47:50Z
[ "python", "bash", "osx", "python-2.7" ]
Problems with Pygame on MAC OS X
37,489,348
<p>I am having trouble setting up Pygame on my MAC. Here are my specifications: OS X El Capitan 10.11.4. Whenever I run a file with import pygame I get the following error message in terminal: </p> <pre><code>ImportError: No module named 'pygame' </code></pre> <p>If I try to install pygame from bitbucket that the di...
0
2016-05-27T17:34:29Z
37,491,769
<p>I found that the information at this site worked: <a href="https://bitbucket.org/pygame/pygame/issues/82/homebrew-on-leopard-fails-to-install" rel="nofollow">https://bitbucket.org/pygame/pygame/issues/82/homebrew-on-leopard-fails-to-install</a></p>
0
2016-05-27T20:29:35Z
[ "python", "bash", "osx", "python-2.7" ]
Selenium Hub, Launches 2 browser only runs test in 1 of them (selenium python)
37,489,369
<p>TL/DR: Right now it launches 2 browsers but only runs the test in 1. What am I missing?</p> <p>So I'm trying to get selenium hub working on a mac (OS X 10.11.5). I installed with <a href="https://www.npmjs.com/package/selenium-standalone" rel="nofollow">this</a>, then launch hub in a terminal tab with:</p> <pre><c...
0
2016-05-27T17:36:03Z
37,531,984
<p>You need to use <a href="http://stackoverflow.com/questions/15067107/difference-between-webdriver-dispose-close-and-quit"><code>self.driver.quit()</code></a> because otherwise the browser will not quit and will only close the current window.</p> <p>You will soon end-up with multiple browser running, and you will ha...
1
2016-05-30T18:45:08Z
[ "python", "selenium", "automated-tests", "selenium-grid", "qa" ]
Selenium Hub, Launches 2 browser only runs test in 1 of them (selenium python)
37,489,369
<p>TL/DR: Right now it launches 2 browsers but only runs the test in 1. What am I missing?</p> <p>So I'm trying to get selenium hub working on a mac (OS X 10.11.5). I installed with <a href="https://www.npmjs.com/package/selenium-standalone" rel="nofollow">this</a>, then launch hub in a terminal tab with:</p> <pre><c...
0
2016-05-27T17:36:03Z
37,554,458
<p>Forgive me if I am way off as I haven't actually worked with selenium, this answer is purely based on the issue related to only keeping the reference to the last created driver in <code>setUp</code></p> <p>Instead of keeping one <code>self.driver</code> you need to have a list of all drivers, lets say <code>self.dr...
2
2016-05-31T19:49:59Z
[ "python", "selenium", "automated-tests", "selenium-grid", "qa" ]
Remove occluded scatter plot points
37,489,469
<p>With vector backends (pdf, eps), it's wasteful in terms of file size and rendering time to have points that are completely occluded by other points. How can these be removed?</p>
2
2016-05-27T17:43:26Z
37,493,188
<p>That is an almost unfair question since that will depend on the marker size vs real coordinates which is <a href="http://stackoverflow.com/questions/14827650/pyplot-scatter-plot-marker-size">difficult to calculate</a>.</p> <p>In any case perhaps an half solution will do for you. I'm thinking that if you calculate t...
2
2016-05-27T22:33:47Z
[ "python", "matplotlib" ]
How to use Google Cloud Client Library for Python to configure the gcloud project
37,489,477
<p>Hi I am trying to use the Google Cloud Client Library for Python to convert a shell script using the gcloud CLI to launch a container to python. In searching through the documentation (<a href="https://googlecloudplatform.github.io/gcloud-python/" rel="nofollow">https://googlecloudplatform.github.io/gcloud-python/<...
0
2016-05-27T17:43:49Z
37,491,187
<p>Actually I didn't get your question right.</p> <p>It is possible, let me just take the example of gcloud storage. When creating a Client instance you can provide a project name:</p> <pre><code>class gcloud.storage.client.Client(project=None, credentials=None, http=None) </code></pre> <p><a href="http://googleclou...
0
2016-05-27T19:46:03Z
[ "python", "gcloud", "google-client", "gcloud-python", "google-cloud-python" ]
How to use Google Cloud Client Library for Python to configure the gcloud project
37,489,477
<p>Hi I am trying to use the Google Cloud Client Library for Python to convert a shell script using the gcloud CLI to launch a container to python. In searching through the documentation (<a href="https://googlecloudplatform.github.io/gcloud-python/" rel="nofollow">https://googlecloudplatform.github.io/gcloud-python/<...
0
2016-05-27T17:43:49Z
37,493,850
<p>Note that <a href="https://github.com/GoogleCloudPlatform/gcloud-python" rel="nofollow">gcloud-python</a> library and <a href="https://cloud.google.com/sdk/" rel="nofollow">gcloud cli tool</a> are not related. It is possible for gcloud-python library (or many other libraries) to use <a href="https://cloud.google.com...
0
2016-05-27T23:54:14Z
[ "python", "gcloud", "google-client", "gcloud-python", "google-cloud-python" ]
Django_comments: What's the proper way to override post_comment()?
37,489,507
<p>I'm trying to customize <code>django_comments</code> app (<a href="https://github.com/django/django-contrib-comments" rel="nofollow" title="github repo">github repo</a>, <a href="https://django-contrib-comments.readthedocs.io/en/latest/" rel="nofollow">docs</a>).</p> <p>The default <code>get_form_target()</code> re...
0
2016-05-27T17:46:37Z
37,490,132
<p>It depends on where your logic happens relative to what is happening in the current <code>post_comment()</code>. If you simply want to do something <em>before</em> <code>post_comment()</code>, then just copy a pointer to the existing func, create your func, and call the original at the end. Finally, you can MonkeyPa...
0
2016-05-27T18:27:37Z
[ "python", "django", "django-forms", "django-views", "django-comments" ]
How do I put a circle with annotation in matplotlib?
37,489,874
<p>I plot a graph created by networkx with matplotlib. Now, I'd like to add annotation to a specific node with a circle around. For instance,</p> <p><a href="http://i.stack.imgur.com/mJaRq.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJaRq.png" alt="enter image description here"></a></p> <p>I use <a href="h...
2
2016-05-27T18:09:39Z
37,491,859
<blockquote> <p>how do I draw a circle around the node 6 as shown in first figure.</p> </blockquote> <p>You get a center of node #6 (tuple <code>pos</code>). Use this data to set the blue circle position.</p> <blockquote> <p>to get a nice looking figure, I need manually set the value of xytext many times. Is ther...
2
2016-05-27T20:36:03Z
[ "python", "matplotlib", "annotations", "networkx" ]
How do I put a circle with annotation in matplotlib?
37,489,874
<p>I plot a graph created by networkx with matplotlib. Now, I'd like to add annotation to a specific node with a circle around. For instance,</p> <p><a href="http://i.stack.imgur.com/mJaRq.png" rel="nofollow"><img src="http://i.stack.imgur.com/mJaRq.png" alt="enter image description here"></a></p> <p>I use <a href="h...
2
2016-05-27T18:09:39Z
37,494,127
<p>If you use the <a href="http://matplotlib.org/examples/pylab_examples/fancyarrow_demo.html" rel="nofollow">fancyarrow</a> <code>arrowprops</code> syntax as demonstrated in <a href="http://matplotlib.org/examples/pylab_examples/annotation_demo2.html" rel="nofollow">annotation_demo2</a>, there is a <code>shrinkA</code...
3
2016-05-28T00:39:19Z
[ "python", "matplotlib", "annotations", "networkx" ]
What would be the quickest/most pythonic way of removing all rows in a dataframe that are also in another dataframe?
37,489,960
<p>For now I've got it this way:</p> <pre><code>dfA = dfA[dfA.names.isin(dfB.names) == False] </code></pre> <p>Edit: I'm checking to see if the value of a specific column - "names", is the same in dfA &amp; dfB. If yes, I would like to remove that entire row from dfA.</p> <p>Is there something quicker than this? I'm...
1
2016-05-27T18:16:03Z
37,490,037
<p>Maybe try add <code>~</code> for inverting mask instead <code>== False</code>:</p> <pre><code>dfA = dfA[~dfA.columns.isin(dfB)] </code></pre>
3
2016-05-27T18:21:06Z
[ "python", "pandas", "dataframe" ]
Turtle.goto error
37,490,057
<p>When I try to run this python code:</p> <pre><code>import turtle coordiantes = ['(100, 100)', '(90, 20)', '(50, 45)'] turtle.goto(coordiantes[0]) </code></pre> <p>I get this error message: </p> <blockquote> <p>TypeError: <strong>new</strong>() takes 3 positional arguments but 9 were given</p> </blockquote> <p>...
2
2016-05-27T18:22:05Z
37,490,125
<p><code>goto</code> is a method on a Turtle instance so you need to first instantiate a Turtle instance and then pass in two numbers (X, Y) to the <code>goto</code> method. </p> <pre><code>from turtle import Turtle t = Turtle() coordiantes = [(100, 100), (90, 20), (50, 45)] t.goto(*coordiantes[0]) </code></pre> <p>...
1
2016-05-27T18:27:21Z
[ "python", "typeerror", "turtle-graphics" ]
Turtle.goto error
37,490,057
<p>When I try to run this python code:</p> <pre><code>import turtle coordiantes = ['(100, 100)', '(90, 20)', '(50, 45)'] turtle.goto(coordiantes[0]) </code></pre> <p>I get this error message: </p> <blockquote> <p>TypeError: <strong>new</strong>() takes 3 positional arguments but 9 were given</p> </blockquote> <p>...
2
2016-05-27T18:22:05Z
37,490,152
<p>You need to instantiate your <code>turtle</code> as well:</p> <pre><code>bob = turtle.Turtle() </code></pre> <p>Then you may use the <code>goto</code> but without strings (documentation is <a href="https://docs.python.org/2/library/turtle.html#turtle.goto" rel="nofollow">here</a>):</p> <pre><code>coordiantes = [(...
3
2016-05-27T18:29:03Z
[ "python", "typeerror", "turtle-graphics" ]
How to use 2to3 to edit files in-place?
37,490,069
<p>I am able to load the <code>2to3</code> file in Terminal. It does a lot of printing, with output like the following:</p> <pre><code>- print str + print(str) ... </code></pre> <p>But the file is left without changes. And I don’t have any instructions after “run <code>2to3</code>”. Please help.</p>
-1
2016-05-27T08:59:15Z
37,505,498
<p>If you <a href="https://www.google.com/search?q=2to3" rel="nofollow">search for “2to3”</a> the first result is the <a href="https://docs.python.org/2/library/2to3.html" rel="nofollow">documentation for 2to3</a>. As the documentation says, to overwrite the file instead of printing a diff, you just need to add the...
0
2016-05-29T02:08:30Z
[ "python", "2to3" ]
How to find the raw header of a website using python?
37,490,100
<p>I'm learning something about the website by myself. and I'm trying to fetch the raw header followed by the 3-digit HTTP return code from a website. Here is what I did so far:</p> <pre><code>import urllib.request with urllib.request.urlopen('https://www.youtube.com/results?search_query=clippers+vs+lakers') as respo...
1
2016-05-27T18:25:25Z
37,490,148
<p>Try <code>response.info()</code> method to get the headers.</p>
0
2016-05-27T18:28:38Z
[ "python", "python-3.x", "http-headers", "urllib" ]
How to find the raw header of a website using python?
37,490,100
<p>I'm learning something about the website by myself. and I'm trying to fetch the raw header followed by the 3-digit HTTP return code from a website. Here is what I did so far:</p> <pre><code>import urllib.request with urllib.request.urlopen('https://www.youtube.com/results?search_query=clippers+vs+lakers') as respo...
1
2016-05-27T18:25:25Z
37,490,704
<p>Simplest and more elegant way is to use requests library</p> <pre><code>import requests as req url = 'https://www.youtube.com/results?search_query=clippers+vs+lakers' response = req.get(url) headers = response.headers html = response.text </code></pre>
0
2016-05-27T19:08:21Z
[ "python", "python-3.x", "http-headers", "urllib" ]
Machine learning Curse of dimensionality
37,490,185
<p>I have word vectors from a word2vec model in 500 dim and 1000dim. I am computing the euclidean distance between some example vectors in 500 and 1000 dim. My problem is that I have read papers about the curse of dimensionality: Euclidean distance does not work in high dimension space. But here the results are quite s...
0
2016-05-27T18:30:46Z
37,492,515
<p>It seems it's not something to do with sparsity. It's more like an attribute or text representation problem. Just check that with 500 dim you're getting almost 100% similarity when calculating cosine between 'neither' and 'either' vectors but a 35% similarity when using 1000 dim. While other data comparations are do...
1
2016-05-27T21:31:00Z
[ "python", "python-2.7", "machine-learning", "word2vec" ]
Machine learning Curse of dimensionality
37,490,185
<p>I have word vectors from a word2vec model in 500 dim and 1000dim. I am computing the euclidean distance between some example vectors in 500 and 1000 dim. My problem is that I have read papers about the curse of dimensionality: Euclidean distance does not work in high dimension space. But here the results are quite s...
0
2016-05-27T18:30:46Z
37,493,694
<p>There is the effect that the difference between minimum and maximum distance of points distributed in high-dimensional space vanishes as the dimensionality goes to infinity. However this effect assumes that vector dimensions are independently and identically distributed. In your case you are still far from infinity,...
0
2016-05-27T23:32:21Z
[ "python", "python-2.7", "machine-learning", "word2vec" ]
Machine learning Curse of dimensionality
37,490,185
<p>I have word vectors from a word2vec model in 500 dim and 1000dim. I am computing the euclidean distance between some example vectors in 500 and 1000 dim. My problem is that I have read papers about the curse of dimensionality: Euclidean distance does not work in high dimension space. But here the results are quite s...
0
2016-05-27T18:30:46Z
37,496,533
<p>Based on your original question, I believe you are comparing the distance between word vectors. The curse of dimension simply states that as the dimension increases, we also need more data to compensate the increasing spaces. If you happened to train word2vec with sufficient large enough data, the semantic property ...
0
2016-05-28T07:42:29Z
[ "python", "python-2.7", "machine-learning", "word2vec" ]
Unicode special characters not working on Mac OSX 10.11.5 bash terminal
37,490,332
<p>So I have been used for a very long time to typing special characters such as accented vowels and the quite common <code>ñ</code> in Spanish language when using bash on my Mac. Specifically, I used to write commit messages in Spanish via bash using these characters, no problem. </p> <p>After upgrading my Mac to OS...
1
2016-05-27T18:40:46Z
37,502,201
<p>I finally got it sorted out. I compared my terminal profile settings on both my macs bit by bit. The only option in which they were different, was in fact under Preferences>Profiles>Advanced. The 'International' section has a checkbox for setting locale variables on startup. This was not checked on my non-working Ma...
1
2016-05-28T17:57:16Z
[ "python", "unicode", "terminal", "special-characters" ]
mailjet send email with attachments in txt form
37,490,401
<p>Another program send to my script already finished letter:</p> <p><a href="http://pastebin.com/XvnMrKzE" rel="nofollow">http://pastebin.com/XvnMrKzE</a></p> <p>So, i parse <code>from_email</code> and <code>to_email</code>, do some changes in text and send it with <a href="https://pypi.python.org/pypi/mailjet/" rel...
0
2016-05-27T18:45:45Z
37,568,194
<p>You should be using the official Mailjet wrapper which is a Mailjet-maintained API client. As specified in the documentation, here is the way to send your attachment: <a href="http://dev.mailjet.com/guides/?python#sending-with-attached-files" rel="nofollow">http://dev.mailjet.com/guides/?python#sending-with-attached...
1
2016-06-01T12:07:12Z
[ "python", "email", "mailjet" ]
UnicodeEncodeError with csv.writer
37,490,428
<p>Pardon my ugly newb code, I'm learning. I'm pulling movie data from OMDB API, but when I move it to CSV I get UnicodeEncodeError for many films. Likely because actor names have accents, for instance. I want to 1.) Identify which films are problematic, 2.) skip them, and/or 3.) preferably correct the error. What I ha...
1
2016-05-27T18:47:38Z
37,490,558
<p>Python 2.x:Instead of <code>with open("Films.csv", 'w') as g:</code> you could try to use <a href="https://docs.python.org/2.7/library/codecs.html" rel="nofollow">codecs</a> in order to open the csv output as <code>UTF-8</code> encoding.</p> <pre><code>import codecs with codecs.open('Films.csv', 'w', encoding='UTF-...
1
2016-05-27T18:57:54Z
[ "python", "unicode", "error-handling" ]
UnicodeEncodeError with csv.writer
37,490,428
<p>Pardon my ugly newb code, I'm learning. I'm pulling movie data from OMDB API, but when I move it to CSV I get UnicodeEncodeError for many films. Likely because actor names have accents, for instance. I want to 1.) Identify which films are problematic, 2.) skip them, and/or 3.) preferably correct the error. What I ha...
1
2016-05-27T18:47:38Z
37,490,647
<p>try out <code>smart_str</code> </p> <pre><code>from django.utils.encoding import smart_str data_list.append(map(smart_str, [z['element1'], z['element2']])) a.write_row(map(smart_str, ["Title", "Year", "Actors", "Awards", "Director", "Genre", "Metascore", "Plot", "Rated", "Runtime", "Writer", "imdbID", "imdbRating",...
0
2016-05-27T19:04:09Z
[ "python", "unicode", "error-handling" ]
UnicodeEncodeError with csv.writer
37,490,428
<p>Pardon my ugly newb code, I'm learning. I'm pulling movie data from OMDB API, but when I move it to CSV I get UnicodeEncodeError for many films. Likely because actor names have accents, for instance. I want to 1.) Identify which films are problematic, 2.) skip them, and/or 3.) preferably correct the error. What I ha...
1
2016-05-27T18:47:38Z
37,505,389
<p>If using Python 2, <code>csvwriter</code> doesn't really support Unicode, but there is an example in the <code>csv</code> documentation to work around it. An example is in <a href="http://stackoverflow.com/a/17245651/235698">this answer</a>.</p> <p>If using Python 3, then make the following changes:</p> <pre><cod...
0
2016-05-29T01:45:28Z
[ "python", "unicode", "error-handling" ]
Alembic downgrade doesn't seem to understand the meta data
37,490,575
<p>The <strong>model.py</strong> looks like this:</p> <pre><code>import datetime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, Numeric, ForeignKey, DateTime, Boolean from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, relationship fr...
2
2016-05-27T18:58:45Z
37,490,838
<p>Are you using sqlite? Sqlite does not allow you to drop a column from the scheme. I had a similar problem when I tried to downgrade a local sqlite database I was testing.</p> <blockquote> <p>SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or ...
0
2016-05-27T19:18:24Z
[ "python", "sqlalchemy", "python-3.5", "alembic", "sqlalchemy-migrate" ]
android.py installsdk error
37,490,599
<p>I am trying to make an android app with python's pygame and pgs4a. I am following <a href="http://possiblywrong.wordpress.com/2012/06/16/python-on-android/" rel="nofollow">this</a> tutorial and using windows.</p> <p>When I try to run android.py installsdk I get the following error:</p> <pre><code>usage: android.py...
0
2016-05-27T19:00:38Z
37,551,870
<p>On Windows, you need to call Python explicitly. Change</p> <pre><code>android.py installsdk </code></pre> <p>to</p> <pre><code>python android.py installsdk </code></pre>
0
2016-05-31T17:15:08Z
[ "android", "python", "pygame" ]
Where and how to calculate total price depending on date range user selected?
37,490,609
<p>i'm working on site for renting rooms. User picks 2 dates(UserStartDate &amp; UserEndDate).</p> <p>with this python code i gonna get number of days in his date range:</p> <pre><code>user_date_range = [endUser - timedelta(i) for i in range((endUser - startUser).days+1)] user_range_num_days = len(user_date_range) <...
0
2016-05-27T19:01:00Z
37,490,685
<p>It doesn't have anything to do with django but rather python. I assume <code>user_start_date</code> and <code>user_end_date</code> are both python <code>datetime.date</code> or <code>datetime.datetime</code> objects, then you could do:</p> <pre><code>num_days = (user_end_date - user_start_date).days total_price = n...
1
2016-05-27T19:07:16Z
[ "python", "ajax", "django" ]
Where and how to calculate total price depending on date range user selected?
37,490,609
<p>i'm working on site for renting rooms. User picks 2 dates(UserStartDate &amp; UserEndDate).</p> <p>with this python code i gonna get number of days in his date range:</p> <pre><code>user_date_range = [endUser - timedelta(i) for i in range((endUser - startUser).days+1)] user_range_num_days = len(user_date_range) <...
0
2016-05-27T19:01:00Z
37,490,820
<p><a href="https://docs.python.org/2/library/calendar.html" rel="nofollow">https://docs.python.org/2/library/calendar.html</a></p> <p>A calendar is necessary as you should be aware that not all months have the same amount of days in them. itermonthdates(year, month) returns an iterator for all days in the month. Run ...
0
2016-05-27T19:16:48Z
[ "python", "ajax", "django" ]
regex: match everything until `:` or `(`
37,490,619
<p>I would like a regex to get everything until the first occurrence of the char <code>:</code> OR the char <code>(</code>, with an optional space before.</p> <p>Take this text:</p> <pre><code>foo : bar foo bar: baz foo (bar): baz </code></pre> <p>expected:</p> <pre><code>&lt;foo&gt;: bar &lt;foo bar&gt;: baz &lt;f...
1
2016-05-27T19:01:43Z
37,490,696
<p>You can use</p> <pre><code>^([^:(]+?)(\s*[:(]) </code></pre> <p>and replace with <code>&lt;\1&gt;\2</code>. See the <a href="https://regex101.com/r/uU7vV6/1" rel="nofollow">regex demo</a>.</p> <p>The pattern matches:</p> <ul> <li><code>^</code> - start of string </li> <li><code>([^:(]+?)</code> - Group 1 matchin...
4
2016-05-27T19:07:55Z
[ "python", "regex", "python-3.x" ]
regex: match everything until `:` or `(`
37,490,619
<p>I would like a regex to get everything until the first occurrence of the char <code>:</code> OR the char <code>(</code>, with an optional space before.</p> <p>Take this text:</p> <pre><code>foo : bar foo bar: baz foo (bar): baz </code></pre> <p>expected:</p> <pre><code>&lt;foo&gt;: bar &lt;foo bar&gt;: baz &lt;f...
1
2016-05-27T19:01:43Z
37,491,256
<p><code>^[^(:]*[^(:\s]</code></p> <p><a href="http://i.stack.imgur.com/6uJSr.png" rel="nofollow"><img src="http://i.stack.imgur.com/6uJSr.png" alt="enter image description here"></a></p> <p>This version does not grab the trailing ':' or '\s'</p>
1
2016-05-27T19:50:21Z
[ "python", "regex", "python-3.x" ]
python-requests cookies export to selenium
37,490,665
<p>I want to login to website whit requests library and after export cookies to selenium, I'm write this code :</p> <pre><code>import requests from selenium import webdriver session=requests.Session() MyHeaderss = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.32 (KHTML, like Gecko) Chrome/48.0.2564.10...
0
2016-05-27T19:05:45Z
37,493,768
<p>You first need to navigate to the page to set the domain, then add each cookie by iterating the cookie jar:</p> <pre class="lang-py prettyprint-override"><code>driver.get("https://www.cartetitolari.mps.it/portaleTitolari/titolari.html") for c in session.cookies : driver.add_cookie({'name': c.name, 'value': c.v...
0
2016-05-27T23:45:30Z
[ "python", "selenium", "cookies", "python-requests" ]
Pandas: apply operation to repetitive columns in MultiIndex
37,490,717
<p>I have MultiColumns: the second level repetitively contains <code>Job Openings</code> and <code>Hires</code>. I would like to subtract one from another for each of the top-level columns - but all I try gets me into index-errors or slice errors. How can I compute it?</p> <p>Sample data:</p> <pre><code>&gt;&gt;&gt; ...
3
2016-05-27T19:08:50Z
37,490,799
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/advanced.html#using-slicers" rel="nofollow">IndexSlice</a>:</p> <pre><code>idx = pd.IndexSlice df[('Total private','difference')] = (df.loc[:, idx[('Total nonfarm', 'Hires')]] - df.loc[:, idx[('Total priv...
2
2016-05-27T19:14:50Z
[ "python", "pandas" ]
Pandas: apply operation to repetitive columns in MultiIndex
37,490,717
<p>I have MultiColumns: the second level repetitively contains <code>Job Openings</code> and <code>Hires</code>. I would like to subtract one from another for each of the top-level columns - but all I try gets me into index-errors or slice errors. How can I compute it?</p> <p>Sample data:</p> <pre><code>&gt;&gt;&gt; ...
3
2016-05-27T19:08:50Z
37,490,808
<h3>Setup</h3> <pre><code>import pandas as pd df = pd.DataFrame( [ [5777, 5385, 5419, 4887], [4849, 3759, 4539, 3381], [4971, 3824, 4645, 3424], [4827, 3459, 4552, 3153], [5207, 3670, 4876, 3358], ], index=pd.to_datetime(['2001-01-01', '200...
3
2016-05-27T19:15:55Z
[ "python", "pandas" ]
Pandas: apply operation to repetitive columns in MultiIndex
37,490,717
<p>I have MultiColumns: the second level repetitively contains <code>Job Openings</code> and <code>Hires</code>. I would like to subtract one from another for each of the top-level columns - but all I try gets me into index-errors or slice errors. How can I compute it?</p> <p>Sample data:</p> <pre><code>&gt;&gt;&gt; ...
3
2016-05-27T19:08:50Z
37,491,345
<p>Let's keep it simple.</p> <pre><code>In [19]: df['Total nonfarm'] - df['Total private'] Out[19]: Hires Job Openings 2001-01-01 358 498 2002-01-01 310 378 2003-01-01 326 400 2004-01-01 275 306 2005-01-01 331 312 </code></pre>
1
2016-05-27T19:56:59Z
[ "python", "pandas" ]
Pandas: apply operation to repetitive columns in MultiIndex
37,490,717
<p>I have MultiColumns: the second level repetitively contains <code>Job Openings</code> and <code>Hires</code>. I would like to subtract one from another for each of the top-level columns - but all I try gets me into index-errors or slice errors. How can I compute it?</p> <p>Sample data:</p> <pre><code>&gt;&gt;&gt; ...
3
2016-05-27T19:08:50Z
37,500,479
<p>Another way to go about this is to swap the column levels and use the column accessors.</p> <h3>Setup</h3> <pre><code>import pandas as pd df = pd.DataFrame( [ [5777, 5385, 5419, 4887], [4849, 3759, 4539, 3381], [4971, 3824, 4645, 3424], [4827, 3459, 4552, 3153], [5207, ...
1
2016-05-28T14:57:11Z
[ "python", "pandas" ]
Pandas: apply operation to repetitive columns in MultiIndex
37,490,717
<p>I have MultiColumns: the second level repetitively contains <code>Job Openings</code> and <code>Hires</code>. I would like to subtract one from another for each of the top-level columns - but all I try gets me into index-errors or slice errors. How can I compute it?</p> <p>Sample data:</p> <pre><code>&gt;&gt;&gt; ...
3
2016-05-27T19:08:50Z
37,500,840
<p>Use <code>groupby</code> and <code>apply</code></p> <h3>Setup</h3> <pre><code>import pandas as pd df = pd.DataFrame( [ [5777, 5385, 5419, 4887], [4849, 3759, 4539, 3381], [4971, 3824, 4645, 3424], [4827, 3459, 4552, 3153], [5207, 3670, 4876, 3358], ], index=pd.t...
1
2016-05-28T15:30:55Z
[ "python", "pandas" ]
Mpmath hypergeometric function shows different behaviour for high & low precision
37,490,749
<p>For one of my projects, I need to repeatedly evaluate an expression involving the general hypergeometric function. While SciPy does not support the general HypGeo function, MPMath does. However, using <code>mp.hyper(..)</code> is very time consuming. So instead I decided to use their fast precision library function ...
-1
2016-05-27T19:11:29Z
37,490,814
<p>The <a href="http://mpmath.org/doc/0.19/contexts.html#fast-low-precision-arithmetic-fp" rel="nofollow">documentation</a> for <code>fp</code> says (emphasis added):</p> <blockquote> <p>Due to intermediate rounding and cancellation errors, results computed with fp arithmetic may be much less accurate than those com...
1
2016-05-27T19:16:16Z
[ "python", "python-3.x", "mpmath" ]
Seaborn categorical plot with hue from DataFrame rows
37,490,771
<p>I have this pandas DataFrame:</p> <pre><code>&gt;&gt;&gt; print(df) Channel 0 1 2 3 4 5 6 7 Sample 7d 3.82 4.10 3.86 3.86 3.95 3.65 3.43 3.63 12d 2.97 4.32 3.50 3.58 3.22 3.37 3.58 3.78 17d 4.01 4.04 4.1...
1
2016-05-27T19:13:12Z
37,491,268
<p>You've basically answered your question in the edit, but you may want to look at <code>pd.melt</code> or <code>pd.stack</code> as an easier way of creating your new tidy DataFrame.</p> <p>e.g.</p> <pre><code>s=df.stack() s.name='values' df_tidy=s.reset_index() sns.stripplot(data=df_tidy,hue='sample',x='Channel',y=...
2
2016-05-27T19:51:17Z
[ "python", "pandas", "seaborn" ]
Strange scroll behaviour in Kivy
37,490,827
<p>I have a <code>ScrollView</code> and a <code>Bubble</code>, that partially overlaps it and contains a <code>GridLayout</code><br> Questions: </p> <ul> <li>How can I hide the widget without removing it?</li> </ul> <p>I've read answers to a <a href="http://stackoverflow.com/questions/23211142/how-to-hide-an-actionb...
0
2016-05-27T19:17:27Z
37,493,656
<p>If you don't want opacity&amp;disabled trick (nice one) or something like <code>y = 5000</code> that doesn't work well in e.g. BoxLayout - and clearly using that would result in stretching your <code>ScrollView</code>, I see "two" simple options though not really without removing - yet with preserving!</p> <p>First...
1
2016-05-27T23:27:09Z
[ "python", "python-3.x", "kivy" ]
python 3.4 , django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
37,490,832
<p>I am new at learning Django, I am using django-1.9.6. By default I was using python 2.7 and for this django app I have installed 3.4 and run the terminal typing </p> <pre><code>manage.py shell </code></pre> <p>When ever I tried to import something from my models in terminal , it throughs this error.</p> <pre><cod...
0
2016-05-27T19:18:05Z
37,490,992
<p>If you're just opening the Python shell, you won't have access to anything in Django. Try <code>manage.py shell</code> to load the Django environment.</p>
1
2016-05-27T19:29:13Z
[ "python", "django" ]
Getting File Metadata from Google API V3 in Python
37,490,899
<p>I am trying to retrieve file metadata from Google drive API V3 in Python. I did it in API V2, but failed in V3. I tried to get metadata by this line:</p> <pre><code>data = DRIVE.files().get(fileId=file['id']).execute() </code></pre> <p>but all I got was a dict of <code>'id'</code>, <code>'kind'</code>, <code>'name...
1
2016-05-27T19:22:50Z
37,497,692
<p>Suppose you want to get the md5 hash of a file given its <code>fileId</code>, you can do it like this: </p> <pre><code>DRIVE = build('drive','v3', http=creds.authorize(Http())) file_service = DRIVE.files() remote_file_hash = file_service.get(fileId=fileId, fields="md5Checksum").execute()['md5Checksum'] </code></pr...
2
2016-05-28T10:08:01Z
[ "python", "api", "python-3.x", "google-api", "drive" ]
recalling the positions of EVERY word in a list (or even a dictionary)
37,490,934
<p>i'm having trouble with something at the moment. i need my code to recall the positions of every word in a list and print it and i have no idea where to start.</p> <p>so say i input: "i like cheese because its cheese" i would need it to print the positions of all the words so it would print something like "0, 1, 2,...
-1
2016-05-27T19:25:22Z
37,490,988
<p>Your question is a little unclear but it seems like you're looking for something like this:</p> <pre><code>sentence = input("Sentence here:") words = sentence.split() for i in words: print(i + ": " + str(sentence.find(i))) </code></pre> <p>Or if you want to print out the numbers separated by commas like you sh...
0
2016-05-27T19:28:53Z
[ "python" ]
recalling the positions of EVERY word in a list (or even a dictionary)
37,490,934
<p>i'm having trouble with something at the moment. i need my code to recall the positions of every word in a list and print it and i have no idea where to start.</p> <p>so say i input: "i like cheese because its cheese" i would need it to print the positions of all the words so it would print something like "0, 1, 2,...
-1
2016-05-27T19:25:22Z
37,491,038
<p>Try this to store the first position of all the distinct words. </p> <pre><code> words = input("Sentence here:") allwords = words.split(" "); mydict = dict() for i in range(len(allwords)): if allwords[i] not in mydict.keys(): mydict[allwords[i]] = i; </code></pre>
0
2016-05-27T19:33:46Z
[ "python" ]
recalling the positions of EVERY word in a list (or even a dictionary)
37,490,934
<p>i'm having trouble with something at the moment. i need my code to recall the positions of every word in a list and print it and i have no idea where to start.</p> <p>so say i input: "i like cheese because its cheese" i would need it to print the positions of all the words so it would print something like "0, 1, 2,...
-1
2016-05-27T19:25:22Z
37,491,095
<pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; s = 'i like cheese because its cheese' &gt;&gt;&gt; words = s.split() &gt;&gt;&gt; list(map(words.index, words)) [0, 1, 2, 3, 4, 2] </code></pre>
0
2016-05-27T19:39:31Z
[ "python" ]
recalling the positions of EVERY word in a list (or even a dictionary)
37,490,934
<p>i'm having trouble with something at the moment. i need my code to recall the positions of every word in a list and print it and i have no idea where to start.</p> <p>so say i input: "i like cheese because its cheese" i would need it to print the positions of all the words so it would print something like "0, 1, 2,...
-1
2016-05-27T19:25:22Z
37,491,409
<p>I have written the code in C# which i prefer. You may use the logic in your language. Logic : a) Store the individual words in a dictionary. This dictionary stores the key as a word from the sentence and its index as its value. </p> <pre><code>Dictionary&lt;string,int&gt; _indexes = new Dictionary&lt;string,int&g...
-1
2016-05-27T20:00:37Z
[ "python" ]
How do I get an installed script to ignore PYTHONPATH
37,490,935
<p>I know I can get Python to ignore <code>PYTHONPATH</code> if I start it with the <code>-E</code> flag.</p> <p>But how do I get a script installed by <code>pip</code> to have this flag?</p> <p>I tried both the "scripts" and the "console_scripts" section of the code and <code>pip</code> strips the -E if I put it on ...
0
2016-05-27T19:25:32Z
37,491,863
<p>I generally recommend against this sort of trickery. The target system puts paths in place for a reason. If you want to break out of a virtualenv you should simply recommend not installing in a virtualenv in your documentation.</p> <p>However you can remove the entry from <code>sys.path</code>.</p> <pre><code>impo...
1
2016-05-27T20:36:32Z
[ "python", "pip" ]
How do I get an installed script to ignore PYTHONPATH
37,490,935
<p>I know I can get Python to ignore <code>PYTHONPATH</code> if I start it with the <code>-E</code> flag.</p> <p>But how do I get a script installed by <code>pip</code> to have this flag?</p> <p>I tried both the "scripts" and the "console_scripts" section of the code and <code>pip</code> strips the -E if I put it on ...
0
2016-05-27T19:25:32Z
37,618,417
<p>The easiest way right now seems to be to put write a scripts that restarts Python if the flag is not included:</p> <pre><code>#!/bin/env python import sys if not sys.flags.ignore_environment: import os os.execv(sys.executable, [sys.executable, '-E'] + sys.argv) # Run your actual script here </code></pre...
0
2016-06-03T15:37:01Z
[ "python", "pip" ]
What's the time complexity of this method to find the number of inversions in an array (python)?
37,490,946
<pre><code>inv=0 for j in range(n): inv=inv+ sum((x&lt;arr[j]) for x in arr[j:] ) </code></pre> <p>For every element I am checking the number of elements smaller than it occurring after it in the array.(<strong>arr[j : ]</strong>)</p>
1
2016-05-27T19:26:14Z
37,491,073
<p>It is <strong>O(n<sup>2</sup>)</strong>. Here is how you can compute this:</p> <ul> <li>for the 1<sup>st</sup> element, you need to compare with the next n-1 elements.</li> <li><p>for the 2<sup>nd</sup> element, you need to compare with the next n-2 elements.</p> <p>...</p></li> <li>for the n<sup>th</sup> element,...
1
2016-05-27T19:37:33Z
[ "python", "arrays", "python-3.x", "time-complexity" ]
What's the time complexity of this method to find the number of inversions in an array (python)?
37,490,946
<pre><code>inv=0 for j in range(n): inv=inv+ sum((x&lt;arr[j]) for x in arr[j:] ) </code></pre> <p>For every element I am checking the number of elements smaller than it occurring after it in the array.(<strong>arr[j : ]</strong>)</p>
1
2016-05-27T19:26:14Z
37,491,264
<pre><code>inv=0 for j in range(n): inv=inv+ sum((x&lt;arr[j]) for x in arr[j:] ) </code></pre> <p>Let's break this code into three parts</p> <p><strong>1:</strong> <code>inv = 0</code> This will take contant time operation sat <code>T1</code></p> <p><strong>2:</strong> <code>for j in range(n):</code> here we ar...
1
2016-05-27T19:50:59Z
[ "python", "arrays", "python-3.x", "time-complexity" ]
Trello always adding 1 hour to my Date
37,491,076
<p>I have a script that sets some Trello cards for me. Everything is working but <a href="https://developers.trello.com/advanced-reference/card#put-1-cards-card-id-or-shortlink-due" rel="nofollow">card due date</a>. Let's say I have the following dates that I got from my SQLite DB:</p> <pre><code>2016-03-30 23:55:00 2...
0
2016-05-27T19:37:49Z
37,492,157
<p>I found a fix, I needed to set <code>settings={'TIMEZONE': 'America/Sao_Paulo'}</code> on my <code>parse()</code>. Working now!</p>
0
2016-05-27T20:58:36Z
[ "python", "python-3.x", "trello" ]
How to make statement `import datetime` bind the datetime type instead of the datetime module?
37,491,110
<p>After one too many times having accidentally typed <code>import datetime</code> when what was really needed was <code>from datetime import datetime</code>, I wondered whether it was possible to hack around and make the former do the latter. </p> <p>That is, to recreate this behaviour (in a freshly opened interpret...
4
2016-05-27T19:40:21Z
37,491,209
<p>Here we go:</p> <p><code>datetime.py</code>:</p> <pre><code>import sys import imp import os path = [p for p in sys.path if p != os.path.dirname(__file__)] f, pathname, desc = imp.find_module('datetime', path) std_datetime = imp.load_module('datetime', f, pathname, desc) # if this^ is renamed to datetime, everythi...
7
2016-05-27T19:47:23Z
[ "python", "python-import", "python-module" ]
How to make statement `import datetime` bind the datetime type instead of the datetime module?
37,491,110
<p>After one too many times having accidentally typed <code>import datetime</code> when what was really needed was <code>from datetime import datetime</code>, I wondered whether it was possible to hack around and make the former do the latter. </p> <p>That is, to recreate this behaviour (in a freshly opened interpret...
4
2016-05-27T19:40:21Z
37,492,498
<p>With a small modification of the original idea, this actually works on python3:</p> <pre><code># datetime.py import sys, _datetime sys.modules['datetime'] = _datetime.datetime </code></pre>
2
2016-05-27T21:29:24Z
[ "python", "python-import", "python-module" ]
Error: " Undefined Reference to" - Compile C extension for Python using Anaconda
37,491,158
<p>I have the following problem on a 64-bit Windows server:</p> <p>I have a .c file that declares a Python extension. The .c file compiles to a .o file, using the following command</p> <pre><code>gcc -c chr.c -IC:\Anaconda\include -o chr.o </code></pre> <p>Now, the .o file is created and all is well. But when I try ...
0
2016-05-27T19:44:06Z
37,561,209
<p>I was able to fix this problem. The issue was that the functions mentioned above were forward declared in my header files, but the body of the function was declared in a separate source file that used these same header files. I copied the function body into my source file and everything worked</p>
1
2016-06-01T06:40:10Z
[ "python", "c", "gcc", "anaconda" ]
Python object method not reading full list
37,491,216
<p>I've written a program to parse info about an object from a file, but it consistently won't read the last item in the file list and I'm not sure why.</p> <p>The object's compute method (the one that's having issues) depends on the following dictionary (abridged for minimality):</p> <pre><code>S_dict = {'Advanced S...
0
2016-05-27T19:47:46Z
37,491,434
<p>The problem is that the last string (from the split) has a newline character, which causes the key lookup error. Try doing this instead:</p> <pre><code>perms = text.rstrip().split(', ') </code></pre> <p>Yielded this skills output for me:</p> <pre><code>[4, 8, 10, 8, 9, 6] </code></pre>
2
2016-05-27T20:02:22Z
[ "python" ]
How do you add a controllable graphic with an image overtop in kivy?
37,491,228
<p>I am new to python and have messed around with Kivy a little. This is the first app of my own design I've been tying to make. The goal is for it to be a game where there is a character that moves in all directions around the screen. My problem right now is that I can't get the character widget to display and I don't...
0
2016-05-27T19:48:30Z
37,496,763
<p>The problem is <code>self.add_widget(self.character)</code> i.e. adding widget in <code>__init__</code> method. Try to run <code>python main.py -m inspector</code>, Ctrl+E and get to <code>GUI()</code>. No children, nothing. Add children after <code>__init__</code>.</p> <p>About the structure:</p> <ul> <li>use <a ...
0
2016-05-28T08:12:26Z
[ "python", "kivy" ]
Output that looks like something else in Python
37,491,242
<p>Today I had some free time and I started to play a little bit with Python. I tried running an apparently simple piece of code which looks like this:</p> <pre><code>a = [] for i in range(10): a.append(i * ++i) for a[i] in a: print(a[i]) </code></pre> <p>Now, as you probably may expect, the <em>obvious</em> ...
0
2016-05-27T19:49:16Z
37,491,309
<pre><code>for i in range(10): a.append(i * ++i) </code></pre> <p>Python doesn't have a <code>++</code> operator. <code>++i</code> is just the unary <code>+</code> operator twice, which is a no-op.</p> <pre><code>for a[i] in a: print(a[i]) </code></pre> <p>That is a really bizarre loop. It's mixing up <code>...
7
2016-05-27T19:54:21Z
[ "python" ]
Output that looks like something else in Python
37,491,242
<p>Today I had some free time and I started to play a little bit with Python. I tried running an apparently simple piece of code which looks like this:</p> <pre><code>a = [] for i in range(10): a.append(i * ++i) for a[i] in a: print(a[i]) </code></pre> <p>Now, as you probably may expect, the <em>obvious</em> ...
0
2016-05-27T19:49:16Z
37,491,332
<p>When you want to print out <code>a</code> you should do:</p> <pre><code>for element in a: print(element) </code></pre> <p>The problem with your code is that </p> <pre><code>for a[i] in a </code></pre> <p>overwrites <code>a[i]</code> every time the loop runs. <code>i = 9</code> in this case because it comes f...
1
2016-05-27T19:55:44Z
[ "python" ]
Output that looks like something else in Python
37,491,242
<p>Today I had some free time and I started to play a little bit with Python. I tried running an apparently simple piece of code which looks like this:</p> <pre><code>a = [] for i in range(10): a.append(i * ++i) for a[i] in a: print(a[i]) </code></pre> <p>Now, as you probably may expect, the <em>obvious</em> ...
0
2016-05-27T19:49:16Z
37,491,575
<p>Let's break it down to pieces.</p> <pre><code>a = [] </code></pre> <p>Empty list initialized, so far, so good.</p> <pre><code>for i in range(10): a.append(i * ++i) </code></pre> <p>Two mistakes here. First of all, <code>++i</code> is <code>+(+i)</code> which essentially is no op. Secondly, any changes done i...
1
2016-05-27T20:13:18Z
[ "python" ]
Using Multiple Modules Python
37,491,287
<p>I am currently making a game which uses multiple modules to run. However when I try to run the program the modules do not seem to work. And example of this is when the program doesn't recognise functions from modules in main.</p> <p><a href="https://gyazo.com/9d303b12707f5829e084125b76d8cdf9" rel="nofollow">https:/...
2
2016-05-27T19:52:52Z
37,491,494
<p>You need to import the class in a correct way. For example:</p> <p>from package.module import class</p> <p>in your case <code>from jedi import Jedi</code></p>
1
2016-05-27T20:07:11Z
[ "python", "module", "pygame" ]
convert distance matrix to phylogenetic tree in newick string format
37,491,346
<p>I have created a distance matrix by reading a FASTA file, now I'm asked to write a function that will produce a phylogenetic tree in newick string format. the function will take one argument a distance matrix. Can you please help me with some code to start with. </p> <p>format example:</p> <p>print(upgma(edwards))...
1
2016-05-27T19:57:01Z
37,491,557
<p>BioPython's <code>Seq</code> type doesn't have an <code>iter_kmer</code> method. Perhaps you're looking for the equivalent class from <code>skbio</code>? <a href="http://scikit-bio.org/docs/0.4.2/generated/skbio.sequence.GrammaredSequence.iter_kmers.html" rel="nofollow">http://scikit-bio.org/docs/0.4.2/generated/skb...
1
2016-05-27T20:12:03Z
[ "python", "bioinformatics", "biopython", "distance-matrix" ]
NameError in Python - not sure if the class or the function is causing the error
37,491,389
<p>I have a text file describing resumes where each line looks like:</p> <pre><code>name university sex filename </code></pre> <p>So one line would say something like</p> <pre><code>John Texas M resume1.doc </code></pre> <p>The file has standard formatting and does not contain any errors. There are four possible na...
2
2016-05-27T19:59:15Z
37,493,286
<p>Your code is throwing a <a href="https://docs.python.org/2/library/exceptions.html#exceptions.NameError" rel="nofollow"><code>NameError</code></a> because at some point in the iteration of your file, some <code>word</code> variable doesn't fulfill any of the conditionals in this line of your function: <code>if word ...
1
2016-05-27T22:44:33Z
[ "python", "python-2.7", "nameerror" ]
NameError in Python - not sure if the class or the function is causing the error
37,491,389
<p>I have a text file describing resumes where each line looks like:</p> <pre><code>name university sex filename </code></pre> <p>So one line would say something like</p> <pre><code>John Texas M resume1.doc </code></pre> <p>The file has standard formatting and does not contain any errors. There are four possible na...
2
2016-05-27T19:59:15Z
37,493,816
<p>The <code>NameError</code> is caused by undefined variables in cases where no values are found in the text file. Define them <em>within</em> the function before you try to assign values from the text file to them:</p> <pre><code>def resumes(): f = open("resumes.txt",'r') for line in f: name = "" ...
1
2016-05-27T23:51:04Z
[ "python", "python-2.7", "nameerror" ]
Python regex is having problems finding a special unicode character
37,491,414
<p>I am currently parsing through some old exams to determine the frequency of the questions (because many questions would resurface at this years exam). I am using pyperclip to get the input for the re.findall.</p> <p>This is the regex I am using: <code>pattern = re.compile(ur'\d.[a-zA-Z .,\']+\?', re.UNICODE)</code>...
1
2016-05-27T20:00:55Z
37,491,595
<p>Your python file has declared a file encoding of utf8 but the file itself is saved in another encoding.</p> <p>You should give the correct encoding in the first line:</p> <pre><code># -*- coding: &lt;correct encoding&gt; -*- </code></pre>
0
2016-05-27T20:15:09Z
[ "python", "regex", "python-2.7", "python-unicode" ]