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 |
|---|---|---|---|---|---|---|---|---|---|
python *args and **kwargs | 39,596,753 | <p>I have seen the previous stack overflow posts on this topic, but I am still unable to create use these two commands when I try to run my function. I have coded a demo example of a simple moving average that I would like to run through the args,kwargs command.</p>
<pre><code>import numpy as np
def moving_average(dat... | -4 | 2016-09-20T14:27:21Z | 39,596,847 | <p>Pass the <code>*args</code> and <code>**kwargs</code> to your function not the argument(s) and named argument(s):</p>
<pre><code>def test1(*args,**kwargs):
return moving_average(*args, **kwargs)
</code></pre>
| 1 | 2016-09-20T14:31:25Z | [
"python",
"args",
"kwargs"
] |
python *args and **kwargs | 39,596,753 | <p>I have seen the previous stack overflow posts on this topic, but I am still unable to create use these two commands when I try to run my function. I have coded a demo example of a simple moving average that I would like to run through the args,kwargs command.</p>
<pre><code>import numpy as np
def moving_average(dat... | -4 | 2016-09-20T14:27:21Z | 39,596,866 | <p>In your example using *args and **kwargs:</p>
<pre><code>def test1(*args,**kwargs):
return moving_average(data,lookback,SMA)
</code></pre>
<p><code>data</code>, <code>lookback</code> and <code>SMA</code> are no longer defined. It could be:</p>
<pre><code>def test1(*args, **kwargs):
return moving_average(a... | 1 | 2016-09-20T14:32:04Z | [
"python",
"args",
"kwargs"
] |
python *args and **kwargs | 39,596,753 | <p>I have seen the previous stack overflow posts on this topic, but I am still unable to create use these two commands when I try to run my function. I have coded a demo example of a simple moving average that I would like to run through the args,kwargs command.</p>
<pre><code>import numpy as np
def moving_average(dat... | -4 | 2016-09-20T14:27:21Z | 39,596,904 | <pre><code>def test1(*args,**kwargs):
</code></pre>
<p>Your function now has two local variables, <code>args</code> and <code>kwargs</code>. One holds the positional arguments that were passed in (as a tuple), the other the keyword arguments (as a dictionary).</p>
<pre><code>return moving_average(data,lookback,SMA)
<... | 1 | 2016-09-20T14:33:39Z | [
"python",
"args",
"kwargs"
] |
Intercepting python interpreter code before it executes | 39,596,768 | <p>Is it possible to intercept interpreter's code before it executes?</p>
<p>Let's say I want to handle a case like:</p>
<pre><code>>>> for f in glob.glob('*.*'): # I'd like to intercept this code before it executes
... something_to_do(f) # and play with it in some dangerous fashion :)
...
ERROR: Us... | 0 | 2016-09-20T14:27:49Z | 39,636,924 | <p>Ok, solved it by creating new module which starts new interpreter instance and do whatever.</p>
<p>I just put the code below in the module and import it.</p>
<pre><code>import code
class GlobeFilterConsole(code.InteractiveConsole):
def push(self, line):
self.buffer.append(line)
source = "\n".j... | 0 | 2016-09-22T10:45:13Z | [
"python",
"interpreter"
] |
logging - merging multiple configuration files | 39,596,802 | <p>I am working on a project where we have a core application that loads multiple plugins.
Each plugin has its own configuration file, and the core application has one as well.</p>
<p>We are using the excellent logging module from python's standard library.
The logging module includes the ability to load the logging c... | 0 | 2016-09-20T14:29:10Z | 39,699,279 | <p>I couldn't find a way to do what I wanted, so I ended up rolling a class to do it.</p>
<p>Here it is as a convenient <a href="https://gist.github.com/Ippo343/c2ab9d4ec03cc89b66211caf81b34545" rel="nofollow">github gist</a>.</p>
| 0 | 2016-09-26T09:33:23Z | [
"python",
"python-2.7"
] |
What kind of algorithm would I need to compute a name that equals a number? | 39,596,808 | <p>For instance A =1, B = 2 ... Z = 26
The name is auto generated and must equal lets say 200 with the sum of the letters.
e.g.</p>
<pre><code> A = 1
AB = 3 etc
</code></pre>
<p>What steps would be taken in creating a function to create an array of auto generated strings that has a value of 200?</p>
<p>How would th... | -4 | 2016-09-20T14:29:39Z | 39,597,036 | <p>You want to generate a string under some constraints.
And this is kind of optimisation problem. However we don't need to hire any machine learning here.</p>
<p>One possible solution might look like this (sorry, no python, just pseudo code)</p>
<ol>
<li><code>name = ""</code> #initialize name variable</li>
<li><cod... | 2 | 2016-09-20T14:39:08Z | [
"python"
] |
Change if conditon dynamic ? (python) | 39,596,834 | <p>Hey guys i want to change the if condition in a function dynamic.</p>
<pre><code>def func(<):
if y<x:
return x
def func(=):
if y=x:
return x
</code></pre>
<p>i want just the condition changed, any ideas?</p>
| -3 | 2016-09-20T14:30:43Z | 39,597,192 | <p>You can not use the operators like <code>=</code> and <code><</code> directly. But you can import them from <code>operator</code>:</p>
<pre><code>from operator import le, eq
def func(op):
if op(x, y):
return x
func(le) # â x < y
func(eq) # â x == y
</code></pre>
<p>BTW the compa... | 0 | 2016-09-20T14:46:31Z | [
"python",
"function",
"python-3.x",
"if-statement"
] |
PyQt: How to set window size to match widget size? | 39,596,868 | <p>I am writing a pyqt application with a menu and central widget (a table widget with rows and columns that looks like a spread sheet). I want to set the size of the enclosing window to be the size of the widget. I do not want to fix it to some size and waste space around the border for aesthetic reasons. How do I ext... | 0 | 2016-09-20T14:32:08Z | 39,600,345 | <p>I'm not sure if there is a simple way to get the size of the table, but how about something like this?</p>
<pre><code>from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, table_rows, table_cols, **kwargs):
super(MainWindow, self).__init__(**kwargs)
self.table ... | 1 | 2016-09-20T17:29:50Z | [
"python",
"pyqt",
"pyqt4"
] |
How to put sequential numbers into lists from a list | 39,596,936 | <p>I have a list numbers say,</p>
<p><code>[1,2,3,6,8,9,10,11]</code></p>
<p>First, I want to get the sum of the differences (step size) between the numbers <code>(n, n+1)</code> in the list.</p>
<p>Second, if a set of consecutive numbers having a difference of 1 between them, put them in a list, i.e. there are two ... | 0 | 2016-09-20T14:34:55Z | 39,597,210 | <p>I wonder if you've already got the answer to this (given the missing 4 from your answers) as the first thing I naively tried produced that answer. (That and/or it reads like a homework question)</p>
<pre><code>>>> a=[1,2,3,4,6,8,9,10,11]
>>> sum([a[x+1] - a[x] for x in range(len(a)-1)])
10
>>... | 1 | 2016-09-20T14:47:31Z | [
"python",
"list"
] |
How to put sequential numbers into lists from a list | 39,596,936 | <p>I have a list numbers say,</p>
<p><code>[1,2,3,6,8,9,10,11]</code></p>
<p>First, I want to get the sum of the differences (step size) between the numbers <code>(n, n+1)</code> in the list.</p>
<p>Second, if a set of consecutive numbers having a difference of 1 between them, put them in a list, i.e. there are two ... | 0 | 2016-09-20T14:34:55Z | 39,597,329 | <blockquote>
<p>First, I want to get the sum of the differences (step size) between
the numbers <code>(n, n+1)</code> in the list.</p>
</blockquote>
<p>Use <code>sum</code> on the successive differences of elements in the list:</p>
<pre><code>>>> sum(lst[i] - x for i, x in enumerate(lst[:-1], start=1))
1... | 4 | 2016-09-20T14:52:36Z | [
"python",
"list"
] |
Python - PARAMIKO SSH close session | 39,596,978 | <p>I need help terminating my SSH session after my sendShell object runs through list commandfactory[].</p>
<p>I have a python script where I use paramiko to connect to a cisco lab router via ssh; execute commands in commandfactory[]; and output the results to the standard out. Everything seems to work except, I can'... | 0 | 2016-09-20T14:36:31Z | 39,601,845 | <p>End the sendShell function with self.transport.close(), see <a href="http://docs.paramiko.org/en/2.0/api/transport.html" rel="nofollow">http://docs.paramiko.org/en/2.0/api/transport.html</a></p>
| 0 | 2016-09-20T18:58:38Z | [
"python",
"networking",
"ssh",
"cisco"
] |
Python - PARAMIKO SSH close session | 39,596,978 | <p>I need help terminating my SSH session after my sendShell object runs through list commandfactory[].</p>
<p>I have a python script where I use paramiko to connect to a cisco lab router via ssh; execute commands in commandfactory[]; and output the results to the standard out. Everything seems to work except, I can'... | 0 | 2016-09-20T14:36:31Z | 39,606,491 | <p>Was able to solve by adding self.shell.transport.close() after my iterator.</p>
<pre><code>def sendShell(self):
self.commandfactory = []
print("\nWelcome to Command Factory. Enter Commands you want to execute.\nType \"done\" when you are finished:")
while not re.search(r"done.*", str(self.commandfactory... | 0 | 2016-09-21T02:16:32Z | [
"python",
"networking",
"ssh",
"cisco"
] |
download specific columns of csv using requests.get | 39,596,979 | <p>I am using <code>requests.get</code> to download a csv file. I only need two columns from this csv file and the rest of the column are useless for me. Currently I am using </p>
<pre><code>r = requests.get(finalurl, verify=False,stream=True)
shutil.copyfileobj(r.raw, csvfile)
</code></pre>
<p>to get the complete c... | 0 | 2016-09-20T14:36:33Z | 39,597,113 | <p>Not used requests.get before but I'd be surprised if you can request specific columns from within a file from a remote server.</p>
<p>Take a look at this post
<a href="http://stackoverflow.com/questions/26063231/read-specific-columns-with-pandas-or-other-python-module">Read specific columns with pandas or other pyt... | -1 | 2016-09-20T14:42:24Z | [
"python",
"csv",
"download",
"python-requests"
] |
download specific columns of csv using requests.get | 39,596,979 | <p>I am using <code>requests.get</code> to download a csv file. I only need two columns from this csv file and the rest of the column are useless for me. Currently I am using </p>
<pre><code>r = requests.get(finalurl, verify=False,stream=True)
shutil.copyfileobj(r.raw, csvfile)
</code></pre>
<p>to get the complete c... | 0 | 2016-09-20T14:36:33Z | 39,597,229 | <p>You could use Numpy and Loadtext:</p>
<pre><code>import numpy as np
b=np.loadtxt(r'name.csv',dtype=str,delimiter=',',skiprows=1,usecols=(0,1,2))
</code></pre>
<p>This creates an array with data for only the columns you choose.</p>
| 1 | 2016-09-20T14:48:14Z | [
"python",
"csv",
"download",
"python-requests"
] |
download specific columns of csv using requests.get | 39,596,979 | <p>I am using <code>requests.get</code> to download a csv file. I only need two columns from this csv file and the rest of the column are useless for me. Currently I am using </p>
<pre><code>r = requests.get(finalurl, verify=False,stream=True)
shutil.copyfileobj(r.raw, csvfile)
</code></pre>
<p>to get the complete c... | 0 | 2016-09-20T14:36:33Z | 39,597,236 | <p>Try <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>, in your situation, pandas is more convenient.</p>
<pre><code>In [2]: import pandas.io.data as web
...: aapl = web.DataReader("AAPL", 'yahoo','2016-7-20','2016-8-20')
...: aapl['Adj Close']
...:
...:
Out[2]:
Date
2016-07-20 99.421412
... | 2 | 2016-09-20T14:48:29Z | [
"python",
"csv",
"download",
"python-requests"
] |
download specific columns of csv using requests.get | 39,596,979 | <p>I am using <code>requests.get</code> to download a csv file. I only need two columns from this csv file and the rest of the column are useless for me. Currently I am using </p>
<pre><code>r = requests.get(finalurl, verify=False,stream=True)
shutil.copyfileobj(r.raw, csvfile)
</code></pre>
<p>to get the complete c... | 0 | 2016-09-20T14:36:33Z | 39,600,295 | <p>You cannot download certain columns only, you can with the regular finance api. You don't have to download all the data in one go either though and then replace after, you can parse as you go:</p>
<pre><code>import csv
final_url = "http://chart.finance.yahoo.com/table.csv?s=AAPL&a=7&b=20&c=2016&d=8... | -1 | 2016-09-20T17:27:05Z | [
"python",
"csv",
"download",
"python-requests"
] |
How to update metadata of an existing object in AWS S3 using python boto3? | 39,596,987 | <p>boto3 documentation does not clearly specify how to update the user metadata of an already existing S3 Object.</p>
| 0 | 2016-09-20T14:36:51Z | 39,596,988 | <p>It can be done using the copy_from() method -</p>
<pre><code>import boto3
s3 = boto3.resource('s3')
s3_object = s3.Object('bucket-name', 'key')
s3_object.metadata.update({'id':'value'})
s3_object.copy_from(CopySource={'Bucket':'bucket-name', 'Key':'key'}, Metadata=s3_object.metadata, MetadataDirective='REPLACE')
<... | 0 | 2016-09-20T14:36:51Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto3"
] |
Format string in python list | 39,597,006 | <p>I have a list which should contain string with a particular format or character i.e. <code>{{str(x), str(y)},{str(x), str(y)}}</code>. I tried to do string concat like: <code>"{{"+str(x), str(y)+"},{"+str(x), str(y)+"}}"</code> and append to list, but it gets surrounded by brackets: [<code>({{str(x), str(y)}),({str(... | 0 | 2016-09-20T14:37:47Z | 39,597,543 | <p>The parentheses are because you're creating a tuple of three items:</p>
<ul>
<li><code>"{{"+str(x)</code></li>
<li><code>str(y)+"},{"+str(x)</code></li>
<li><code>str(y)+"}}"</code></li>
</ul>
<p>Try replacing those bare commas between <code>str(x)</code> and <code>str(y)</code> with <code>+","+</code>:</p>
<pre>... | 1 | 2016-09-20T15:02:08Z | [
"python"
] |
What is the difference between these two python methods? | 39,597,015 | <p>I am a python newbie. </p>
<p>I have one python method which returns the list recursively (previous is the dictionary of string and s is just a string that is included in the previous dictionary)</p>
<pre><code>def path(previous, s):
"Return a list of states that lead to state s, according to the previous dict... | 0 | 2016-09-20T14:38:11Z | 39,597,078 | <p>You're missing a <code>return</code> statement in the <em>else</em> branch of the second method:</p>
<pre><code>def path(previous, s):
"Return a list of states that lead to state s, according to the previous dict."
if s is None:
return []
else:
return path(previous, previous[s]) + [s]
</... | 4 | 2016-09-20T14:40:52Z | [
"python",
"breadth-first-search"
] |
Scrapy SgmlLinkExtractor how go get number inside span tag | 39,597,065 | <p>How can I get the integer number highlighted at this specific location:</p>
<p><a href="http://i.stack.imgur.com/YDsY4.png" rel="nofollow"><img src="http://i.stack.imgur.com/YDsY4.png" alt="number inside span tag"></a></p>
<p>I got the follwing XPath from Google Chrome:</p>
<pre><code>//*[@id="page"]/main/div[4]/... | 0 | 2016-09-20T14:40:12Z | 39,597,624 | <p>As a rule, to avoid later debugging to have a stable run you need to avoid using absolute xpath's or any xpath that is not flexible on minor changes of the page structure.</p>
<p>From the information available in the picture, your xpath should be:</p>
<pre><code>//*[@class='nr']/span
</code></pre>
<p>For basic ov... | 1 | 2016-09-20T15:05:56Z | [
"python",
"regex",
"xpath",
"scrapy"
] |
How to suppress all the print info from the Python Script? | 39,597,102 | <p>Is there an easy way to suppress all the print info from the python script globally ?</p>
<p>Have a scenario where I had put lot of print info in the script for debug purpose, but when the user runs I don't want the script to print all the infos.</p>
<p>So only when I pass a command line argument like debug=1 or s... | 1 | 2016-09-20T14:41:56Z | 39,597,147 | <p>This is why you should use the built-in <a href="https://docs.python.org/3/library/logging.html" rel="nofollow"><code>logging</code></a> library rather than writing print statements everywhere.</p>
<p>With that, you can call <code>logger.debug()</code> wherever you need to, and configure at application level whethe... | 4 | 2016-09-20T14:43:59Z | [
"python",
"python-2.7"
] |
How to suppress all the print info from the Python Script? | 39,597,102 | <p>Is there an easy way to suppress all the print info from the python script globally ?</p>
<p>Have a scenario where I had put lot of print info in the script for debug purpose, but when the user runs I don't want the script to print all the infos.</p>
<p>So only when I pass a command line argument like debug=1 or s... | 1 | 2016-09-20T14:41:56Z | 39,597,191 | <p>You will have to redirect stdout to /dev/null.
Below is the OS agnostic way of doing it.</p>
<pre><code>import os
import sys
f = open(os.devnull, 'w')
sys.stdout = f
</code></pre>
| 5 | 2016-09-20T14:46:25Z | [
"python",
"python-2.7"
] |
Distinct values with Q objects | 39,597,172 | <p>I have this query on my Django project 1.10.1 on Py3:</p>
<pre><code>Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id))
</code></pre>
<p>How can I prevent to get two identical <code>Event</code> records? </p>
<p>Thank you in advance.</p>
| 0 | 2016-09-20T14:45:28Z | 39,597,305 | <p>Use the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.distinct" rel="nofollow">distinct</a> operator:</p>
<pre><code>Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id)).distinct()
</code></pre>
<p>From the documentation:</p>
<b... | 2 | 2016-09-20T14:51:50Z | [
"python",
"django"
] |
Distinct values with Q objects | 39,597,172 | <p>I have this query on my Django project 1.10.1 on Py3:</p>
<pre><code>Event.objects.filter(Q(subject=topic.id) | Q(object=topic.id) | Q(place=topic.id))
</code></pre>
<p>How can I prevent to get two identical <code>Event</code> records? </p>
<p>Thank you in advance.</p>
| 0 | 2016-09-20T14:45:28Z | 39,597,396 | <p>I don't think that query can ever give duplicate results.</p>
<p>I just tried a similar query on my similar setup, it will convert to an SQL query which looks roughly like this:</p>
<pre><code>SELECT *
FROM event
WHERE (subject=x OR object=x OR place=x)
</code></pre>
<p>This will not duplicate any rows, so you ... | 0 | 2016-09-20T14:55:47Z | [
"python",
"django"
] |
maya kBeforeSave callback | 39,597,364 | <p>I need to register to some maya's MSceneMessage callback, and query the scene paths. I need to get both before and after's maya path. (open , save file)</p>
<p>Here's what I have so far.</p>
<pre><code>def before(*args, **kwargs):
print 'BEFORE: ' + cmds.file(query = True)
def after(*args, **kwargs):
prin... | 2 | 2016-09-20T14:54:16Z | 39,698,282 | <h1>get the <a href="http://download.autodesk.com/us/maya/2011help/CommandsPython/file.html" rel="nofollow">scenename</a></h1>
<pre><code>def scene_id(*args):
return cmds.file(query=True, scenename=True)
def before(*args, **kwargs):
print 'BEFORE: {0}'.format(scene_id())
def after(*args, **kwargs):
print... | 0 | 2016-09-26T08:44:50Z | [
"python",
"api",
"maya"
] |
Install virtualenvwrapper on mac- OSError: [Errno 1] Operation not permitted: | 39,597,368 | <p>I try to install virtualenvwrapper on Mac and get the classic python catch 22:</p>
<pre><code>C02QPBHWFVH3MBP:~ ckc3153$ pip install virtualenvwrapper
Collecting virtualenvwrapper
Using cached virtualenvwrapper-4.7.2.tar.gz
Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Python/2.... | 0 | 2016-09-20T14:54:26Z | 39,597,448 | <ol>
<li>use <code>sudo pip install virtualenvwrapper</code> command.</li>
<li>type the password of current user.</li>
</ol>
| 1 | 2016-09-20T14:58:29Z | [
"python",
"osx",
"python-2.7",
"virtualenv",
"virtualenvwrapper"
] |
Python Multiplicative Array Concatenating | 39,597,377 | <p>If I have a array of an inconsistent size, <code>lists</code> that consists of an (inconsistent) amount of lists:</p>
<pre><code> lists = [List1, List2, List3,...ListN]
</code></pre>
<p>where each contained list is of inconsistent size.</p>
<p>How can I concatenate the contents multiplicatively of each contained ... | 1 | 2016-09-20T14:55:00Z | 39,597,856 | <p><a href="https://docs.python.org/2/library/itertools.html#itertools.product" rel="nofollow">itertools.product</a> Is what you are looking for, I think:</p>
<pre><code>>>> import itertools
>>> A = ["A","B"]
>>> B = ["1","2","3","4"]
>>> C = [A,B]
>>> [''.join(i) for i in ... | 0 | 2016-09-20T15:17:44Z | [
"python",
"arrays",
"list"
] |
Python Multiplicative Array Concatenating | 39,597,377 | <p>If I have a array of an inconsistent size, <code>lists</code> that consists of an (inconsistent) amount of lists:</p>
<pre><code> lists = [List1, List2, List3,...ListN]
</code></pre>
<p>where each contained list is of inconsistent size.</p>
<p>How can I concatenate the contents multiplicatively of each contained ... | 1 | 2016-09-20T14:55:00Z | 39,597,944 | <pre><code>import itertools
A = ["A","B"]
B = ["1","2","3","4"]
list(itertools.product(A, B))
</code></pre>
<p>Generic</p>
<pre><code>lists_var = [List1, List2, List3,...ListN]
list(itertools.product(*lists_var))
</code></pre>
| 1 | 2016-09-20T15:21:47Z | [
"python",
"arrays",
"list"
] |
Python Multiplicative Array Concatenating | 39,597,377 | <p>If I have a array of an inconsistent size, <code>lists</code> that consists of an (inconsistent) amount of lists:</p>
<pre><code> lists = [List1, List2, List3,...ListN]
</code></pre>
<p>where each contained list is of inconsistent size.</p>
<p>How can I concatenate the contents multiplicatively of each contained ... | 1 | 2016-09-20T14:55:00Z | 39,598,047 | <p>Use <code>itertools</code> to get the results, and then format as you want:</p>
<pre><code>import itertools
A = ["A","B","C","D"]
B = ["1","2","3","4"]
C = ["D","E","F","G"]
lists = [A, B, C]
results = [''.join(t) for t initertools.product(*lists)]
print(results)
</code></pre>
<p>prints:</p>
<pre><code>['A1D'... | 1 | 2016-09-20T15:25:14Z | [
"python",
"arrays",
"list"
] |
Numpy log slow for numbers close to 1? | 39,597,405 | <p>Look at the following piece of code:</p>
<pre><code>import numpy as np
import timeit
print('close', timeit.Timer(lambda: np.log(0.99999999999999978)).timeit())
print('not close', timeit.Timer(lambda: np.log(0.99)).timeit()))
</code></pre>
<p>The output is:</p>
<pre><code>close 4.462684076999722
not close 0.63192... | 3 | 2016-09-20T14:56:09Z | 39,597,509 | <p>At the time of writing, most chipsets evaluate <code>log</code> using a Taylor series coupled with a table of specific pre-computed values.</p>
<p>With the Taylor series, a number closer to 1 is slower to <em>converge</em> than a number further away from 1. That could go some way to explaining the difference in exe... | 1 | 2016-09-20T15:01:07Z | [
"python",
"numpy",
"runtime"
] |
Is this a correct way to implement bubble sort? | 39,597,479 | <p>Is this a correct way to implement bubble sort?
I get a sorted list, but I have a doubt that the method is correct.</p>
<pre><code># Input unsorted list
size_lis = int(input("enter the size of the list"))
size = 0
list1 = list()
while (size < size_lis):
element = int(input("enter the element"))
list1.ap... | 0 | 2016-09-20T15:00:02Z | 39,598,372 | <p>This is the <em>correct implementation</em> of the bubble sort algorithm. But you can prevent extra loops using this kind of implementation:</p>
<pre><code>def bubble_sort(arr):
for i in range(len(arr))[::-1]:
for j in range(1, i + 1):
if arr[j - 1] > arr[j]:
arr[j], arr[j... | 1 | 2016-09-20T15:40:02Z | [
"python",
"bubble-sort"
] |
Is this a correct way to implement bubble sort? | 39,597,479 | <p>Is this a correct way to implement bubble sort?
I get a sorted list, but I have a doubt that the method is correct.</p>
<pre><code># Input unsorted list
size_lis = int(input("enter the size of the list"))
size = 0
list1 = list()
while (size < size_lis):
element = int(input("enter the element"))
list1.ap... | 0 | 2016-09-20T15:00:02Z | 39,599,162 | <p>In bubble sort the largest element is moved step by step to the end of list. Thus after first pass there is this one element in its final position. The second pass should sort only N-1 remaining elements, etc.</p>
<p>In the posted code, just adjust the inner circle like this. That'll save almost 50% of CPU time.</p... | 1 | 2016-09-20T16:18:20Z | [
"python",
"bubble-sort"
] |
How can I know the location of a python function that imported from a library | 39,597,486 | <pre><code>from cs231n.fast_layers import conv_forward_fast, conv_backward_fast
out_fast, cache_fast = conv_forward_fast(x, w, b, conv_param)
</code></pre>
<p>How can I find the location of the <code>conv_forward_fast</code> function with a command? </p>
| 1 | 2016-09-20T15:00:21Z | 39,597,572 | <p>You can just </p>
<pre><code>import cs231n.fast_layers as path
print(path)
</code></pre>
<p>and it will show you the path of the library.</p>
| 2 | 2016-09-20T15:03:51Z | [
"python"
] |
How can I know the location of a python function that imported from a library | 39,597,486 | <pre><code>from cs231n.fast_layers import conv_forward_fast, conv_backward_fast
out_fast, cache_fast = conv_forward_fast(x, w, b, conv_param)
</code></pre>
<p>How can I find the location of the <code>conv_forward_fast</code> function with a command? </p>
| 1 | 2016-09-20T15:00:21Z | 39,598,234 | <p>In Python 2.x:</p>
<pre><code>from os.path import join
path_to_module = __import__(join.__module__).__file__
</code></pre>
| 0 | 2016-09-20T15:33:34Z | [
"python"
] |
Python's fuzzywuzzy returns unpredictable results | 39,597,550 | <p>I'm working with fuzzy wuzzy in python and while it claims it works with a levenshtein distance, I find that many strings with a single character different produce different results. For example.</p>
<pre><code>>>>fuzz.ratio("vendedor","vendedora")
94
>>>fuzz.ratio("estagiário","estagiária")
90
... | 1 | 2016-09-20T15:02:36Z | 39,598,074 | <p>You are correct about how fuzzywuzzy works in general. A larger output number from the <code>fuzz.ratio</code> function means that the strings are closer to one another (with a 100 being a perfect match). I preformed a couple of additional test cases to check out how it worked. Here they are:</p>
<pre><code>fuzz.ra... | 2 | 2016-09-20T15:26:04Z | [
"python",
"string-matching",
"fuzzywuzzy"
] |
From DatetimeIndex to list of times | 39,597,553 | <p>My objectif is to have a lists of times (in seconds), already packaged in lists of times in 5 minutes for a whole day.
This is my code to package the whole day of "2016-07-08" by 5 minutes :</p>
<pre><code>pd.date_range('2016-07-08 00:00:00', '2016-07-08 23:59:00', freq='5Min')
</code></pre>
<p>The result :</p>
<... | 2 | 2016-09-20T15:02:47Z | 39,597,704 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.strftime.html" rel="nofollow"><code>DatetimeIndex.strftime</code></a>:</p>
<p><em>I try remove some code (in sample is not necessary, maybe in real code is important)</em></p>
<pre><code>for time in pd.date_rang... | 2 | 2016-09-20T15:09:44Z | [
"python",
"list",
"datetime",
"pandas",
"datetimeindex"
] |
Adding an element to the key's value in ordered dictionary | 39,597,574 | <p>I have an ordered dictionary:</p>
<pre><code>{'20140106': '82.1000000',
'20140217': '77.0300000',
'20140224': '69.6200000',
'20140310': '46.3300000',
'20140414': '49.3800000',
</code></pre>
<p>Keys are dates: yyyy-mm-dd and i want to store all values of one month in one key:</p>
<pre><code>{'20140106': '82.10... | 1 | 2016-09-20T15:03:53Z | 39,597,642 | <p>I think the issue lies in the last line of your code. You do assign a string to the variable <code>var</code> there.</p>
<p><strong>EDIT : Here is a suggestion which stays close to your original code.</strong></p>
<pre><code>new_collection = {}
for key in collection:
month = key[:6]
if new_collection.get(m... | 1 | 2016-09-20T15:06:48Z | [
"python",
"list",
"dictionary"
] |
Adding an element to the key's value in ordered dictionary | 39,597,574 | <p>I have an ordered dictionary:</p>
<pre><code>{'20140106': '82.1000000',
'20140217': '77.0300000',
'20140224': '69.6200000',
'20140310': '46.3300000',
'20140414': '49.3800000',
</code></pre>
<p>Keys are dates: yyyy-mm-dd and i want to store all values of one month in one key:</p>
<pre><code>{'20140106': '82.10... | 1 | 2016-09-20T15:03:53Z | 39,597,951 | <p>Here is a better approach. Given a dict of type {str:str}, we can turn the value into a list on inserts while retaining all the functionality of dict by extending the builtin <code>dict</code> class.</p>
<p>Here is a demonstration.</p>
<pre><code>>>> class CustomDict(dict):
... def insert(self, key, v... | 1 | 2016-09-20T15:21:53Z | [
"python",
"list",
"dictionary"
] |
Adding an element to the key's value in ordered dictionary | 39,597,574 | <p>I have an ordered dictionary:</p>
<pre><code>{'20140106': '82.1000000',
'20140217': '77.0300000',
'20140224': '69.6200000',
'20140310': '46.3300000',
'20140414': '49.3800000',
</code></pre>
<p>Keys are dates: yyyy-mm-dd and i want to store all values of one month in one key:</p>
<pre><code>{'20140106': '82.10... | 1 | 2016-09-20T15:03:53Z | 39,598,089 | <p>I don't see any advantage of using strings here as keys to represent the <em>date.</em> This is my solution, but I hope it won't break your current code. </p>
<p>Well, your code shows you're doing so much nesting there: </p>
<pre><code> val.append(list(collection.pop(key)))
</code></pre>
<p>And: </p>
<blockquote... | 1 | 2016-09-20T15:26:51Z | [
"python",
"list",
"dictionary"
] |
Adding an element to the key's value in ordered dictionary | 39,597,574 | <p>I have an ordered dictionary:</p>
<pre><code>{'20140106': '82.1000000',
'20140217': '77.0300000',
'20140224': '69.6200000',
'20140310': '46.3300000',
'20140414': '49.3800000',
</code></pre>
<p>Keys are dates: yyyy-mm-dd and i want to store all values of one month in one key:</p>
<pre><code>{'20140106': '82.10... | 1 | 2016-09-20T15:03:53Z | 39,598,403 | <p>Why not make use of <code>reduce</code> and <code>filter</code> function. <code>reduce</code> will apply a function to every item in the iterated object, and you can also specify the initial value for <code>reduce</code> </p>
<pre><code>from collections import OrderedDict
a = {'20140106': '82.1000000', '20140217':... | 1 | 2016-09-20T15:41:27Z | [
"python",
"list",
"dictionary"
] |
Mathematical algorithm failing but seems correct | 39,597,580 | <p>I've been given a problem in which a function is fed in A and B. These are target numbers from 1, 1, whereby B may only increase by A and A may only increase by B (Ex, 1 1 -> 2 1 or 1 2. 2 1 -> 3 1 or 2 3. 2 3 -> 5 3 or 2 5). This creates a binary tree. In the problem, given the target numbers, I need to find the "m... | 1 | 2016-09-20T15:03:57Z | 39,598,146 | <p>Your solution was too complicated for what it is in my honest opinion. Take a look at this:</p>
<pre><code>def answer(M, F):
my_bombs = [int(M), int(F)]
my_bombs.sort()
generations = 0
while my_bombs != [1, 1]:
if my_bombs[0] == 1:
return str(generations + my_bombs[1] - 1)
... | 1 | 2016-09-20T15:29:15Z | [
"python",
"algorithm",
"math",
"binary-tree",
"primes"
] |
Mathematical algorithm failing but seems correct | 39,597,580 | <p>I've been given a problem in which a function is fed in A and B. These are target numbers from 1, 1, whereby B may only increase by A and A may only increase by B (Ex, 1 1 -> 2 1 or 1 2. 2 1 -> 3 1 or 2 3. 2 3 -> 5 3 or 2 5). This creates a binary tree. In the problem, given the target numbers, I need to find the "m... | 1 | 2016-09-20T15:03:57Z | 39,598,911 | <p>You didn't say whether you're using Python 2 or Python 3, but the <code>math.floor( m / f )</code> only makes sense in Python 3. There the <code>m / f</code> is a float, which is imprecise. You'd better simply use integer division: <code>numgen += m // f</code>. An example where it matters is <code>M, F = str(10**30... | 2 | 2016-09-20T16:05:39Z | [
"python",
"algorithm",
"math",
"binary-tree",
"primes"
] |
How to set the server timeout in python Klein? | 39,597,585 | <p>I am using python Klein <a href="http://klein.readthedocs.io/en/latest/" rel="nofollow">http://klein.readthedocs.io/en/latest/</a> for setting up a web service. I had checked the documentation but I still don't know how to set the timeout of the service. Can anyone who is more familiar with tool shows how to set the... | 0 | 2016-09-20T15:04:09Z | 39,753,400 | <p>You could call <code>Request.loseConnection()</code> to drop the request connection to the client after an set timeout interval. Here is a quick example:</p>
<pre><code>from twisted.internet import reactor, task, defer
from klein import Klein
app = Klein()
request_timeout = 10 # seconds
@app.route('/delayed/<i... | 1 | 2016-09-28T16:51:09Z | [
"python",
"web-services",
"klein-mvc"
] |
Python empty csr_matrix throws ValueError: cannot infer dimensions from zero sized index arrays | 39,597,638 | <p>Here's the python SSCCE: </p>
<pre><code>import scipy.sparse
data = []
row = []
col = []
csr = scipy.sparse.csr_matrix((data, (row, col))) #error happens here
print(type(csr))
print(csr)
</code></pre>
<p>I'm running it with python2.7 I get an error:</p>
<pre><code>raise ValueError('cannot infer dimensions from z... | 0 | 2016-09-20T15:06:45Z | 39,598,951 | <p>Scipy sparse matrices have a definite shape, e.g. (m, n) where m is the number of rows and n is the number of columns. When you write, for example, <code>csr_matrix(([1, 2], ([0, 3], [1, 4])))</code>, <code>csr_matrix</code> infers the shape from the maximum values of the row and column indices. But when you write... | 1 | 2016-09-20T16:07:27Z | [
"python",
"scipy",
"sparse-matrix"
] |
Python empty csr_matrix throws ValueError: cannot infer dimensions from zero sized index arrays | 39,597,638 | <p>Here's the python SSCCE: </p>
<pre><code>import scipy.sparse
data = []
row = []
col = []
csr = scipy.sparse.csr_matrix((data, (row, col))) #error happens here
print(type(csr))
print(csr)
</code></pre>
<p>I'm running it with python2.7 I get an error:</p>
<pre><code>raise ValueError('cannot infer dimensions from z... | 0 | 2016-09-20T15:06:45Z | 39,599,555 | <p>You can make an empty sparse matrix - from an empty dense one or by giving the shape parameter:</p>
<pre><code>In [477]: from scipy import sparse
In [478]: sparse.csr_matrix([])
Out[478]:
<1x0 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>
In... | 0 | 2016-09-20T16:40:54Z | [
"python",
"scipy",
"sparse-matrix"
] |
Create sparse circulant matrix in python | 39,597,649 | <p>I want to create a large (say 10^5 x 10^5) sparse circulant matrix in Python. It has 4 elements per row at positions <code>[i,i+1], [i,i+2], [i,i+N-2], [i,i+N-1]</code>, where I have assumed periodic boundary conditions for the indices (i.e. <code>[10^5,10^5]=[0,0], [10^5+1,10^5+1]=[1,1]</code> and so on). I looked ... | 1 | 2016-09-20T15:07:07Z | 39,598,506 | <p>To create a <em>dense</em> circulant matrix, you can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.circulant.html" rel="nofollow"><code>scipy.linalg.circulant</code></a>. For example,</p>
<pre><code>In [210]: from scipy.linalg import circulant
In [211]: N = 7
In [212]: vals = np.a... | 2 | 2016-09-20T15:46:29Z | [
"python",
"numpy",
"matrix",
"scipy",
"sparse-matrix"
] |
python import MySQLdb | 39,597,771 | <p>in python, import MySQLdb</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/MySQL_python-1.2.4b4-py2.7-macosx-10.10-intel.egg/MySQLdb/__init__.py", line 19, in <module>
import _mysql
ImportError: dlopen(/Library/Py... | 0 | 2016-09-20T15:13:09Z | 40,107,011 | <p>I'm using ubuntu 16.04 and I don't have that lib in the same place as you specified. </p>
<p>The best solution for me was installing the mysql pip package with the <code>--no-binary</code> option as shown in this <a href="http://stackoverflow.com/a/36835229/3086572">post reply</a></p>
| 0 | 2016-10-18T11:27:32Z | [
"python",
"mysql",
"django"
] |
Pandas Multicolumn Groupby Plotting | 39,597,785 | <p>Problem:<br>
I have a pandas dataframe of data that I would like to group-by year-months and rule_name. Once grouped by I want to be able to get the counts of each of the rules during that period and the % of all the rules for that group. So far I am able to get each of the periods counts but not the percentage. </... | 1 | 2016-09-20T15:13:58Z | 39,599,650 | <p>I was able to resolve this. The following code provides the necessary plots and data processing. I am putting it up in case this helps someone else. It feels kind of janky but it gets the trick done. Any suggestion to improve this would be appreciated.</p>
<p>Thanks SO.</p>
<pre><code>import seaborn as sns
df... | 0 | 2016-09-20T16:47:17Z | [
"python",
"pandas",
"plot",
"group-by",
"filtering"
] |
Display objects related current user django admin | 39,597,836 | <p>I'm trying to display only objects related to the current user. Users can upload a file and then they can only see their files in the admin. Here is my models :</p>
<pre><code>class Share(models.Model):
owner = models.ForeignKey(User, default='')
title = models.CharField("File's title", max_length=100, uniq... | 0 | 2016-09-20T15:16:34Z | 39,597,964 | <p>You've confused the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter" rel="nofollow"><code>queryset</code></a> method (used with <code>list_filter</code>) with the <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.M... | 1 | 2016-09-20T15:22:19Z | [
"python",
"django",
"django-queryset"
] |
Django Aggregation: Sum of Multiplication of two fields that are not in same model | 39,597,886 | <p>I have three models (Django 1.6.5):</p>
<pre><code>class Vote(models.Model):
voter = models.ForeignKey(UserSettings)
answer = models.ForeignKey(Answer)
rating = models.IntegerField()
class Answer(models.Model):
content = models.CharField(max_length=255)
class UserSettings(models.Model):
user... | 0 | 2016-09-20T15:18:53Z | 39,604,972 | <p>The problem is that we need the join with another table (in this case UserSettings), so we need "force" the join.</p>
<pre><code>q = Vote.objects.all().filter(voter__settings__weight__gt=0).values("answer").annotate(Sum('id', field='rating*weight'))
</code></pre>
<p>To force the join I used the filter clause (In f... | 0 | 2016-09-20T22:57:07Z | [
"python",
"django",
"aggregate",
"django-queryset"
] |
How do I Hangup up call in Asterisk Event | 39,598,018 | <p>I am connecting to Asterisk server using Python Asterisk manager. How do I hangup calls from the AMI.</p>
<pre><code>def hangup_event(event, manager):
with ctx:
if event.name == 'Hangup':
data = {
"channel":event.message['Channel'],
"unique_id":event.message['Uniqueid'],
... | 0 | 2016-09-20T15:24:04Z | 39,605,548 | <p>Use ami action COMMAND. Issue command </p>
<pre><code>channel request hangup channel_name_here
</code></pre>
| 0 | 2016-09-21T00:05:22Z | [
"python",
"asterisk"
] |
Implementing a single thread server/daemon (Python) | 39,598,038 | <p>I am developing a server (daemon).</p>
<p>The server has one "worker thread". The worker thread runs a queue of commands. When the queue is empty, the worker thread is paused (but does not exit, because it should preserve certain state in memory). To have exactly one copy of the state in memory, I need to run all t... | -1 | 2016-09-20T15:24:46Z | 39,599,631 | <p>This is a sample code with internet sockets, easily replaced with unix domain sockets. It takes whatever you write to the socket, passes it as a "command" to worker, responds OK as soon as it has queued the command. The single worker simulates a lengthy task with sleep(30). You can queue as many tasks as you want, ... | 1 | 2016-09-20T16:45:47Z | [
"python",
"sockets",
"server",
"daemon"
] |
Django 1.10 AppRegistryNotReady: Apps aren't loaded yet. I can't use django.setup | 39,598,151 | <p>I'm facing an issue since I upgraded my django from <code>1.7.10</code> to <code>1.10.1</code>.
Indeed, I had the
<code>django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.</code>
Error and in order to solve that I figured out that I had to remove django.setup() in order to solve t... | 0 | 2016-09-20T15:29:22Z | 39,598,825 | <p>You are hitting <a href="https://code.djangoproject.com/ticket/27033" rel="nofollow">this issue</a>. The answer appears to be to upgrade your version of <code>easy_select2</code>.</p>
<p>The issue <a href="https://github.com/asyncee/django-easy-select2/commit/8b9a4f050166" rel="nofollow">is fixed</a> in <code>easy_... | 0 | 2016-09-20T16:01:42Z | [
"python",
"django"
] |
Code debugging, Raspberry pi relays and if statements | 39,598,252 | <p>I've a problem with Raspberry Pi relays. Earlier I wrote about LED's and the problem was similar, but this time these methods don't work. </p>
<pre><code>#!/usr/bin/env python
import sys
import time
import datetime
import RPi.GPIO as GPIO
import SDL_DS1307
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
Rele1 = 17... | 0 | 2016-09-20T15:34:21Z | 39,602,724 | <p>You need to do some work on your logic. Think about what happens when the the time is between the values on the third line of data.txt. As your code reads the first line, the result is false so the outputs are set correspondingly, then on the second line the result is false and the outputs are set for false again, ... | 0 | 2016-09-20T19:53:53Z | [
"python",
"raspberry-pi"
] |
Recursive if-statement python | 39,598,319 | <p>Hi I am new to python and trying to implement a recursive function which fills up a table, but when running by program I get the following exception</p>
<blockquote>
<p>unsupported operand type(s) for +: 'NoneType' and 'int'.</p>
</blockquote>
<pre><code>def cost(i, j):
if table[i][j] == None:
v1 = v... | -1 | 2016-09-20T15:37:25Z | 39,598,596 | <p>Apparently, your <code>cost()</code> function returns <code>None</code> for some cases. If I understand right, then this can only happen if i or j are negative. As this only occurs in cases 2 or 3, it seems to me, that your i or j are indeed floats which can be larger than 0 but smaller than 1. Could this be the cas... | 0 | 2016-09-20T15:50:12Z | [
"python",
"if-statement",
"recursion"
] |
Calculate mean of array with specific value from another array | 39,598,371 | <p>I have these numpy arrays:</p>
<pre><code>array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2])
array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56])
</code></pre>
<p>Now I want to return a 2d array in which there is the mean for each distinctive value from array1 so my output would look something like thi... | 2 | 2016-09-20T15:39:58Z | 39,598,529 | <p>Here's an approach using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>np.unique</code></a> and <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>np.bincount</code></a> -</p>
<pre><code># Get unique array1 e... | 1 | 2016-09-20T15:47:32Z | [
"python",
"arrays",
"performance",
"numpy"
] |
Calculate mean of array with specific value from another array | 39,598,371 | <p>I have these numpy arrays:</p>
<pre><code>array1 = np.array([-1, -1, 1, 1, 2, 1, 2, 2])
array2 = np.array([34.2, 11.2, 22.1, 78.2, 55.0, 66.87, 33.3, 11.56])
</code></pre>
<p>Now I want to return a 2d array in which there is the mean for each distinctive value from array1 so my output would look something like thi... | 2 | 2016-09-20T15:39:58Z | 39,601,232 | <p>This is a typical grouping operation, and the <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) provides extensions to numpy to perform these type of operations efficiently and concisely:</p>
<pre><code>import numpy_indexed as n... | 1 | 2016-09-20T18:25:03Z | [
"python",
"arrays",
"performance",
"numpy"
] |
Convert Hex Column in Pandas Without Iterating | 39,598,449 | <p>I am trying to bin a Pandas dataframe in Python 3 in order to have more efficient grouping over a large dataset. Currently the performance bottleneck is in iterating over the dataframe using the .apply() method.</p>
<p>All entries within the column are in hex, so it seems like the pd.to_numeric function should do e... | 1 | 2016-09-20T15:43:35Z | 39,793,260 | <p>After some assists from the comments above: a faster way to accomplish this is to use a generator function. That way it can deal with any exceptions if provided data that cannot be converted from hex.</p>
<pre><code>def bin_vals(lst):
for item in lst:
try:
yield int(item, 16) % __NUM_BINS__... | 0 | 2016-09-30T13:57:28Z | [
"python",
"pandas",
"dataframe"
] |
How to replace an image in WordPress via REST API 2.0? | 39,598,454 | <p>I have some images uploaded on a WordPress site that is to be completely REST controlled and I'm having trouble updating them. Altering image data is simple, via <code>POST</code> requests to <code>.../media/<id></code>, but I can find no way to actually replace the image <strong>content</strong> with another ... | 1 | 2016-09-20T15:44:02Z | 39,624,040 | <p>It seems that this <a href="https://github.com/WP-API/WP-API/issues/2715" rel="nofollow">cannot be done</a> and the media records have to be deleted and recreated.</p>
| 0 | 2016-09-21T18:30:47Z | [
"python",
"wordpress",
"rest",
"api",
"curl"
] |
Alternating row color using xlsxwriter in Python 3 | 39,598,568 | <p>Has anybody implemented alternating row color while generating excel using xlsxwriter in Python3?</p>
<pre><code>data_format = workbook.add_format(
{
'bg_color': '#FFC7CE'
})
worksheet.write(data_row, data_col + 1, row[1], data_format)
</code></pre>
<p>This sets the color for each column.</p>
| 0 | 2016-09-20T15:48:57Z | 39,599,296 | <p>There is nothing stopping you from setting the formats manually as follows:</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()
data_format1 = workbook.add_format({'bg_color': '#FFC7CE'})
data_format2 = workbook.add_format({'bg_color': '#00C7CE'})
fo... | 2 | 2016-09-20T16:25:59Z | [
"python",
"python-3.x",
"xlsxwriter"
] |
Pandas Filter on date for quarterly ends | 39,598,618 | <p>In the index column I have a list of dates:</p>
<pre><code>DatetimeIndex(['2010-12-31', '2011-01-02', '2011-01-03', '2011-01-29',
'2011-02-26', '2011-02-28', '2011-03-26', '2011-03-31',
'2011-04-01', '2011-04-03',
...
'2016-02-27', '2016-02-29', '2016-03-26', '2016-03-31'... | 3 | 2016-09-20T15:51:03Z | 39,598,726 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.is_quarter_end.html#pandas.Series.dt.is_quarter_end" rel="nofollow"><code>is_quarter_end</code></a> to filter the row labels:</p>
<pre><code>In [151]:
df = pd.DataFrame(np.random.randn(400,1), index= pd.date_range(start=dt.d... | 3 | 2016-09-20T15:56:15Z | [
"python",
"datetime",
"pandas"
] |
Django Db routing | 39,598,666 | <p>I am trying to run my Django application with two db's (1 master, 1 read replica). My problem is if I try to read right after a write the code explodes. For example:</p>
<ul>
<li>p = Product.objects.create()</li>
<li><ol>
<li>Product.objects.get(id=p.id)</li>
</ol></li>
</ul>
<p>OR</p>
<ul>
<li><ol start="2">
<li... | 7 | 2016-09-20T15:53:07Z | 39,661,311 | <p>Depending on the size of the data and the application I'd tackle this with either of the following methods:</p>
<ol>
<li>Database pinning:</li>
</ol>
<p>Extend your database router to allow pinning functions to specific databases. For example:</p>
<pre><code>from customrouter.pinning import use_master
@use_maste... | 1 | 2016-09-23T12:54:16Z | [
"python",
"django"
] |
Django Db routing | 39,598,666 | <p>I am trying to run my Django application with two db's (1 master, 1 read replica). My problem is if I try to read right after a write the code explodes. For example:</p>
<ul>
<li>p = Product.objects.create()</li>
<li><ol>
<li>Product.objects.get(id=p.id)</li>
</ol></li>
</ul>
<p>OR</p>
<ul>
<li><ol start="2">
<li... | 7 | 2016-09-20T15:53:07Z | 39,698,943 | <p>Solved it with : </p>
<pre><code>class Model(models.Model):
objects = models.Manager() -> objects only access master
sobjects = ReplicasManager() -> sobjects access either master and replicas
class Meta:
abstract = True -> so django doesn't create a table
</code></pre>
<p>make eve... | 1 | 2016-09-26T09:17:13Z | [
"python",
"django"
] |
Django Db routing | 39,598,666 | <p>I am trying to run my Django application with two db's (1 master, 1 read replica). My problem is if I try to read right after a write the code explodes. For example:</p>
<ul>
<li>p = Product.objects.create()</li>
<li><ol>
<li>Product.objects.get(id=p.id)</li>
</ol></li>
</ul>
<p>OR</p>
<ul>
<li><ol start="2">
<li... | 7 | 2016-09-20T15:53:07Z | 39,764,116 | <p>IN master replica conf the new data will take few millisecond to replicate the data on all other replica server/database.</p>
<p>so whenever u tried to read after write it wont gives you correct result.</p>
<p>Instead of reading from replica you can use master to read immediately after write by using <code>using(... | 0 | 2016-09-29T07:33:45Z | [
"python",
"django"
] |
UnboundLocalError: local variable 'k' referenced before assignment | 39,598,720 | <p>I have read <a href="https://stackoverflow.com/questions/17097273/unboundlocalerror-local-variable-referenced-before-assignment">StackQ1</a> and <a href="https://stackoverflow.com/questions/20873285/unboundlocalerror-local-variable-input-referenced-before-assignment">stackQ2</a> But unable to solve my error.
The gi... | 1 | 2016-09-20T15:55:51Z | 39,598,974 | <pre><code>class My_Class(object):
def __init__(self, **kwargs):
super(My_Class, self).__init__()
self.k = "hello"
def data(self, *args):
print "call data"
return self.k
my_class = My_Class()
print my_class.data()
</code></pre>
| 0 | 2016-09-20T16:08:38Z | [
"python"
] |
UnboundLocalError: local variable 'k' referenced before assignment | 39,598,720 | <p>I have read <a href="https://stackoverflow.com/questions/17097273/unboundlocalerror-local-variable-referenced-before-assignment">StackQ1</a> and <a href="https://stackoverflow.com/questions/20873285/unboundlocalerror-local-variable-input-referenced-before-assignment">stackQ2</a> But unable to solve my error.
The gi... | 1 | 2016-09-20T15:55:51Z | 39,599,055 | <p>The problem is resolved and posting it for the newbies</p>
<pre><code>class myClass:
k=0
def data(self):
def data2(k):
for j in range(5):
self.k=self.k+1
return self.k
for i in range(5):
self.k=self.k+1
data2(sel... | 0 | 2016-09-20T16:13:23Z | [
"python"
] |
UnboundLocalError: local variable 'k' referenced before assignment | 39,598,720 | <p>I have read <a href="https://stackoverflow.com/questions/17097273/unboundlocalerror-local-variable-referenced-before-assignment">StackQ1</a> and <a href="https://stackoverflow.com/questions/20873285/unboundlocalerror-local-variable-input-referenced-before-assignment">stackQ2</a> But unable to solve my error.
The gi... | 1 | 2016-09-20T15:55:51Z | 39,599,305 | <p>For my explanation, I reindent and annotate your code:</p>
<pre><code>class myClass: # <- [1]
global k # <- [2]
k = 0 # <- [3]
def data(self):
def data2(k): # <- [4]
for j in range(5):
k = k + 1
return k # <- [5]
for i in ... | 0 | 2016-09-20T16:26:26Z | [
"python"
] |
Convert KNN train from Opencv 3 to 2 | 39,598,724 | <p>I am reading a tutorial for training KNN using Opencv. The code is written for Opencv 3 but I need to use it in Opencv 2. The original training is:</p>
<pre><code>cv2.ml.KNearest_create().train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
</code></pre>
<p>I tried using this:</p>
<pre><code>cv2.KNear... | 4 | 2016-09-20T15:56:14Z | 39,684,278 | <p>Here the changes that appear to have made the <a href="https://github.com/MicrocontrollersAndMore/OpenCV_3_KNN_Character_Recognition_Python/blob/master/TrainAndTest.py" rel="nofollow">full code</a> work for me for OpenCV 2.4.13:</p>
<pre><code>60c60
< kNearest = cv2.ml.KNearest_create() # i... | 0 | 2016-09-25T06:59:58Z | [
"python",
"python-2.7",
"opencv",
"opencv3.0"
] |
Convert KNN train from Opencv 3 to 2 | 39,598,724 | <p>I am reading a tutorial for training KNN using Opencv. The code is written for Opencv 3 but I need to use it in Opencv 2. The original training is:</p>
<pre><code>cv2.ml.KNearest_create().train(npaFlattenedImages, cv2.ml.ROW_SAMPLE, npaClassifications)
</code></pre>
<p>I tried using this:</p>
<pre><code>cv2.KNear... | 4 | 2016-09-20T15:56:14Z | 39,684,564 | <ul>
<li>Unlike the generic <a href="http://docs.opencv.org/2.4/modules/ml/doc/statistical_models.html#bool%20CvStatModel::train%28const%20Mat&%20train_data,%20[int%20tflag,]%20...,%20const%20Mat&%20responses,%20...,%20[const%20Mat&%20var_idx,]%20...,%20[const%20Mat&%20sample_idx,]%20...%20[const%20Mat&... | 0 | 2016-09-25T07:49:41Z | [
"python",
"python-2.7",
"opencv",
"opencv3.0"
] |
Using gdb's Python to backtrace different OS threads, when gdb is not OS-aware | 39,598,893 | <p>I am still learning about debugging C using python within gdb (arm-none-eabi-gdb, in my case). I am trying to use this facility to get thread information of a real-time OS running on ARM Cortex-M. Reading some OS structures, I can access <em>the</em> thread control blocks of the OS. I know the PC and the SP of each... | 0 | 2016-09-20T16:05:06Z | 39,780,899 | <p>After some more reading and trying to make use of old debugger knowledge that I have accumulated over the years, I managed to get this working. It lacks optimization but for now, I'm very please. This can be considered a poor-man's debugger making use of GDB's Python support to track the active threads in the system... | 0 | 2016-09-29T22:19:36Z | [
"python",
"c",
"debugging",
"operating-system",
"gdb"
] |
Why Pylint says print('foo', end='') is an invalid syntax? | 39,598,921 | <p>This very simple code:</p>
<pre><code>#!/usr/bin/python3
print('foo', end='')
</code></pre>
<p>Makes Pylint unhappy (both on Python2 and Python3):</p>
<pre><code>pylint ./pylint.py
No config file found, using default configuration
************* Module pylint
E: 2, 0: invalid syntax (syntax-error)
</code></pre>
... | 0 | 2016-09-20T16:06:02Z | 39,600,882 | <p>I got this error when running pylint. But my pylint only had support for python2. So it errored:</p>
<pre><code>$ pylint foo.py
No config file found, using default configuration
************* Module foo
E: 2, 0: invalid syntax (syntax-error)
</code></pre>
<p>So I did <code>pip3 install pylint</code>.</p>
<p>And... | 4 | 2016-09-20T18:04:49Z | [
"python",
"pylint"
] |
Theano fails to be imported with theano configuration cnmem = 1 | 39,599,014 | <p>Theano fails to be imported with theano configuration cnmem = 1</p>
<p>Any idea how to make sure the GPU is totally allocated to the theano python script?</p>
<blockquote>
<p><strong>Note:</strong> Display is not used to avoid its GPU usage</p>
</blockquote>
<p><strong>File: .theanorc</strong></p>
<pre><code>c... | 2 | 2016-09-20T16:10:58Z | 39,602,112 | <p><a href="https://github.com/Theano/Theano/issues/4302#issuecomment-202067917" rel="nofollow">https://github.com/Theano/Theano/issues/4302#issuecomment-202067917</a></p>
<blockquote>
<p>Could you try with 1.0 instead of 1? according to the docs, it needs
to be a float. Also, it is limited to 0.95 to allow space ... | 1 | 2016-09-20T19:15:12Z | [
"python",
"neural-network",
"deep-learning",
"theano",
"theano-cuda"
] |
Run multiple Django application tests with one command | 39,599,054 | <p>I have a Django project with multiple apps, <code>app_1</code>, <code>app_2</code>, and <code>app_3</code>. Currently, in order to run the test suite, I use the standard testing command: <code>python manage.py test</code>. This runs the tests for all of my apps. I am also able to run tests for a single app, specific... | 0 | 2016-09-20T16:13:21Z | 39,599,322 | <p>You can supply multiple labels to the <code>test</code> command:</p>
<pre><code>python manage.py test app_1 app_2
</code></pre>
<p>This will run all tests in <code>app_1</code> and <code>app_2</code>. </p>
| 1 | 2016-09-20T16:26:58Z | [
"python",
"django",
"unit-testing"
] |
Writing multiple lists to CSV rows in python | 39,599,085 | <p>I am writing a program that extracts the history from the Google Chrome history database and outputs this to a CSV file. I am trying to put the information in multiple rows, for example a list of URL's in the first row and the webpage Title in the second row. However, when I do this, I receive the following error:</... | 0 | 2016-09-20T16:14:56Z | 39,599,372 | <p>Using Pandas can help you a lot with CSV files:</p>
<pre><code>import sqlite3
import datetime
import pandas
def urls():
urls = []
titles = []
counts = []
last = []
conn = sqlite3.connect('C:\Users\username\Desktop\History.sql')
cursor = conn.execute("SELECT url, title, visit_count, last_vis... | 1 | 2016-09-20T16:29:31Z | [
"python",
"sql",
"list",
"csv",
"unicode"
] |
Writing multiple lists to CSV rows in python | 39,599,085 | <p>I am writing a program that extracts the history from the Google Chrome history database and outputs this to a CSV file. I am trying to put the information in multiple rows, for example a list of URL's in the first row and the webpage Title in the second row. However, when I do this, I receive the following error:</... | 0 | 2016-09-20T16:14:56Z | 39,599,608 | <p>This is not easy to answer without seeing the DB. But something like this should work, potentially with a few small modifications depending on your actual data. </p>
<pre><code>import sqlite3
import datetime
import csv
def urls():
conn = sqlite3.connect('C:\Users\username\Desktop\History.sql')
c = conn.cur... | 1 | 2016-09-20T16:44:35Z | [
"python",
"sql",
"list",
"csv",
"unicode"
] |
I want to add values while a recursive loop unfolds | 39,599,102 | <p>This is a bottom up approach to check if the tree is an AVL tree or not. So how this code works is:</p>
<p>Suppose this is a tree :</p>
<pre><code> 8
3 10
2
1
</code></pre>
<p>The leaf node is checked that it is a leaf node(here 1). It then unfolds one recursion when the node with data 2 is the ... | 1 | 2016-09-20T16:15:39Z | 39,600,226 | <p>Your immediate problem is that you don't seem to understand local and global variables. <strong>cl</strong> and <strong>cr</strong> are local variables; with the given control flow, the only values they can ever have are 0 and 1. Remember that each instance of the routine gets a new set of local variables: you set... | 1 | 2016-09-20T17:22:04Z | [
"python",
"recursion",
"binary-tree",
"avl-tree"
] |
Fill in time data in pandas | 39,599,192 | <p>I have data that is every 15 seconds. But, there are some values that are missing. These are not tagged with NaN, but simply are not present. How can I fill in those values?<br>
I have tried to resample, but that also shifts my original data. So, why doesn't this work:</p>
<pre><code>a=pd.Series([1.,3.,4.,3.,5.]... | 3 | 2016-09-20T16:20:00Z | 39,599,390 | <p>you need to use the <code>loffset</code> argument</p>
<pre><code>a.resample('15S', loffset='5S')
</code></pre>
<p><a href="http://i.stack.imgur.com/rQK52.png" rel="nofollow"><img src="http://i.stack.imgur.com/rQK52.png" alt="enter image description here"></a></p>
| 3 | 2016-09-20T16:30:45Z | [
"python",
"pandas"
] |
Fill in time data in pandas | 39,599,192 | <p>I have data that is every 15 seconds. But, there are some values that are missing. These are not tagged with NaN, but simply are not present. How can I fill in those values?<br>
I have tried to resample, but that also shifts my original data. So, why doesn't this work:</p>
<pre><code>a=pd.Series([1.,3.,4.,3.,5.]... | 3 | 2016-09-20T16:20:00Z | 39,599,454 | <p>For the sake of completeness, the <code>base</code> argument works too:</p>
<pre><code>a.resample('15S', base=5).mean()
Out[4]:
2016-05-25 00:00:35 1.0
2016-05-25 00:00:50 3.0
2016-05-25 00:01:05 4.0
2016-05-25 00:01:20 NaN
2016-05-25 00:01:35 3.0
2016-05-25 00:01:50 NaN
2016-05-25 00:02:05 5.... | 3 | 2016-09-20T16:34:29Z | [
"python",
"pandas"
] |
Fill in time data in pandas | 39,599,192 | <p>I have data that is every 15 seconds. But, there are some values that are missing. These are not tagged with NaN, but simply are not present. How can I fill in those values?<br>
I have tried to resample, but that also shifts my original data. So, why doesn't this work:</p>
<pre><code>a=pd.Series([1.,3.,4.,3.,5.]... | 3 | 2016-09-20T16:20:00Z | 39,599,529 | <p>Both @IanS and @piRSquared address the shifting of the base. As for filling <code>NaN</code>s: pandas has methods for forward-filling (<code>.ffill()</code>/<code>.pad()</code>) and backward-filling (<code>.bfill()</code>/<code>.backfill()</code>), but not for taking the mean. A quick way of doing it is by taking th... | 4 | 2016-09-20T16:39:11Z | [
"python",
"pandas"
] |
Fill in time data in pandas | 39,599,192 | <p>I have data that is every 15 seconds. But, there are some values that are missing. These are not tagged with NaN, but simply are not present. How can I fill in those values?<br>
I have tried to resample, but that also shifts my original data. So, why doesn't this work:</p>
<pre><code>a=pd.Series([1.,3.,4.,3.,5.]... | 3 | 2016-09-20T16:20:00Z | 39,734,514 | <p>An answer was posted to my <a href="https://github.com/pydata/pandas/issues/14297" rel="nofollow">bug report</a> that I wanted to share here for completeness. It is not my post, but does just what I had wanted:</p>
<p>Try this (maybe this is what interpolate should do by default, interpolating before re-sampling?)<... | 0 | 2016-09-27T21:22:31Z | [
"python",
"pandas"
] |
plotting box plot with seaborn with multidimensional data | 39,599,409 | <p>I am trying to create a box plot with seaboard as follows:</p>
<p>I have some synthetic data where I have 24 different categories which are generated as:</p>
<pre><code>import numpy as np
x = np.arange(10, 130, step=5)
</code></pre>
<p>Now, for each of these categories I generate 5 random observations as follows:... | 0 | 2016-09-20T16:32:01Z | 39,600,353 | <p>The problem, as you point out, is the shape of your input data. Without trying to make too many assumptions as to what you are trying to do, I think you are looking for something like</p>
<pre><code>x = np.arange(10, 130, step=5)
y = 4 * np.random.randn(x.size, 5) + 3
x_for_boxplot = np.repeat(x, 5)
y_for_boxplot ... | 0 | 2016-09-20T17:30:31Z | [
"python",
"matplotlib",
"plot",
"seaborn"
] |
crontab not fully working. only echo statements being run | 39,599,420 | <p>I have a job in my crontab to run a script (<code>/home/sys_bio/username/tracer.sh</code>) every minute. The script contains</p>
<pre><code>#!/usr/bin/env bash
echo "starting"
/home/sys_bio/username/p35/bin/python3.5 -m qefunctional.qe.tests.prodprobe -p post -j test.json
echo "finised"
</code></pre>
<p>When I am... | 1 | 2016-09-20T16:32:25Z | 39,600,001 | <p>Including the path to bash shell might be needed:</p>
<pre><code>* * * * * /bin/sh /home/sys_bio/username/tracer.sh >> ...
</code></pre>
<p><code>cron</code> otherwise might not really know what to do. </p>
<p>The same principle also applies to what is included in your script. Using relative file names can ... | 1 | 2016-09-20T17:07:38Z | [
"python",
"bash",
"cron"
] |
Vertices with edges not drawn with plotly in a network graph | 39,599,460 | <p>I have been following the instruction from here to draw a network graph:
<a href="http://nbviewer.jupyter.org/gist/empet/07ea33b2e4e0b84193bd" rel="nofollow">http://nbviewer.jupyter.org/gist/empet/07ea33b2e4e0b84193bd</a></p>
<p>I have been replicating the networkx example as I have had troubles to compile and inst... | 0 | 2016-09-20T16:34:34Z | 39,612,303 | <p>After further investigation, I found out the root of the problem. There was a mismatch between the identifiers of the nodes and the edges.</p>
<p>I was still using the labels of the nodes to add the edges instead of the node identifiers (integers used for positioning). As a consequence, plotly did not know where to... | 0 | 2016-09-21T09:16:06Z | [
"python",
"plotly"
] |
Pymongo replace_one modified_count always 1 even if not changing anything | 39,599,480 | <p>Why and how can this work like this?</p>
<pre><code>item = db.test.find_one()
result = db.test.replace_one(item, item)
print(result.raw_result)
# Gives: {u'n': 1, u'nModified': 1, u'ok': 1, 'updatedExisting': True}
print(result.modified_count)
# Gives 1
</code></pre>
<p>when the equivalent in mongodb shell is alwa... | 2 | 2016-09-20T16:35:26Z | 39,714,522 | <p>This is because MongoDB stores documents in binary (<a href="http://bsonspec.org/" rel="nofollow">BSON</a>) format. Key-value pairs in a BSON document can have any order (except that _id is always first).
Let's start with the <a href="https://docs.mongodb.com/manual/mongo/" rel="nofollow">mongo shell</a> first. The... | 3 | 2016-09-27T00:56:43Z | [
"python",
"mongodb",
"pymongo"
] |
NumPy: Limited cumulative sum | 39,599,512 | <p>Is there some way to avoid the <code>for</code> loop in this code:</p>
<pre><code>X = numpy array ~8000 long
running_total = 0
for x in X:
this_step = min(x, running_total)
running_total += this_step
</code></pre>
<p>In words, that's calculating a cumulative sum of a series where the difference between sam... | -1 | 2016-09-20T16:38:09Z | 39,607,277 | <p>Not sure but guessing from your explanation (assuming x is nonnegative)</p>
<pre><code>X = [1 ... 999]
running_total = X[0]
for x in X[1:]:
this_step = min(x, running_total)
running_total += this_step
</code></pre>
| 0 | 2016-09-21T03:55:41Z | [
"python",
"numpy"
] |
NumPy: Limited cumulative sum | 39,599,512 | <p>Is there some way to avoid the <code>for</code> loop in this code:</p>
<pre><code>X = numpy array ~8000 long
running_total = 0
for x in X:
this_step = min(x, running_total)
running_total += this_step
</code></pre>
<p>In words, that's calculating a cumulative sum of a series where the difference between sam... | -1 | 2016-09-20T16:38:09Z | 39,614,414 | <p>Easiest quick-fix for this kind of problem i find is to use numba. E.g.</p>
<pre><code>from numba import jit
import numpy as np
def cumsumcapped(X):
running_total = 0
for x in X:
this_step = min(x, running_total)
running_total += this_step
@jit
def cumsumcappedjit(X):
running_total = 0... | 0 | 2016-09-21T10:47:38Z | [
"python",
"numpy"
] |
Adding numbers in a list gives TypeError: unsupported operand type(s) for +: 'int' and 'str' | 39,599,596 | <p>I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is:</p>
<pre><code>Traceback (most recent call last):
File "Calculator.py", line 17,... | -1 | 2016-09-20T16:43:52Z | 39,599,634 | <p>Try casting value to an int.</p>
<pre><code>value = int(raw_input())
</code></pre>
<p>Edit:
See the other answers, mine throw an exception when "Done" is typed into the prompt.</p>
| -2 | 2016-09-20T16:45:52Z | [
"python"
] |
Adding numbers in a list gives TypeError: unsupported operand type(s) for +: 'int' and 'str' | 39,599,596 | <p>I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is:</p>
<pre><code>Traceback (most recent call last):
File "Calculator.py", line 17,... | -1 | 2016-09-20T16:43:52Z | 39,599,641 | <p>When using <code>raw_input()</code> you're storing a string in <code>value</code>. Convert it to an int before appending it to your list, e.g.</p>
<pre><code>inputs.append( int( value ) )
</code></pre>
| 0 | 2016-09-20T16:46:37Z | [
"python"
] |
Adding numbers in a list gives TypeError: unsupported operand type(s) for +: 'int' and 'str' | 39,599,596 | <p>I´m writing a simple calculator program that will let a user add a list of integers together as a kind of entry to the syntax of python. I want the program to allow the user to add as many numbers together as they want. My error is:</p>
<pre><code>Traceback (most recent call last):
File "Calculator.py", line 17,... | -1 | 2016-09-20T16:43:52Z | 39,599,661 | <p><a href="https://docs.python.org/2/library/functions.html#raw_input" rel="nofollow"><code>raw_input</code></a> returns strings, not numbers. <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum</code></a> operates only on numbers.</p>
<p>You can convert each item to an int as you ... | 1 | 2016-09-20T16:47:48Z | [
"python"
] |
Regular expression, matching final group | 39,599,616 | <p>I'm making a c parser using python, and my function pattern is producing very strange results.</p>
<p>My pattern is:</p>
<pre><code>([\w\*\[\]]*)\W*([A-Za-z_][\w]+)\W*\(\W*([\w ,\*\[\]]*)\)\W*\{([\w\W]+)return.*;\n\};\n
</code></pre>
<p>When I supply the string:</p>
<pre><code>int main(int argc, char* argv[]) {
... | -1 | 2016-09-20T16:44:57Z | 39,599,847 | <p>It's this part:</p>
<pre><code>return.*
</code></pre>
<p>The <code>.</code> is greedy, and it's simply going to match the entire rest of the document. You could make it non-greedy.</p>
<pre><code>return.*?
</code></pre>
<p>Or match anything <em>except</em> a newline</p>
<pre><code>return[^\n]*
</code></pre>
| 0 | 2016-09-20T16:58:40Z | [
"python",
"c",
"regex"
] |
CSV breaks up values on non delimeter | 39,599,628 | <p>I am trying to read mixed CSV fields, where there are quoted fields and non-quoted numerical with the following :</p>
<pre><code>from csv import reader
bar = """1234,"abc,def","dasd",341234234"""
foo = reader(bar)
[x for x in foo]
</code></pre>
<p>this returns </p>
<pre><code>[['1'], ['2'], ['3'], ['4'], ['', ''... | 0 | 2016-09-20T16:45:45Z | 39,599,811 | <p>csv reader works on file objects. Here is what you could do</p>
<pre><code>from csv import reader
import StringIO
bar = """1234,"abc,def","dasd",341234234"""
f = StringIO.StringIO(bar)
foo = reader(f, delimiter=',')
print [x for x in foo]
</code></pre>
<p>This will give you o/p</p>
<pre><code>[['1234', 'abc,def... | 2 | 2016-09-20T16:56:15Z | [
"python",
"csv"
] |
Use map and filter instead of a for loop? | 39,599,642 | <p>How do I write an equivalent of the code below using map and filter?</p>
<pre><code>res = []
for x in range(5):
if x % 2 == 0:
for y in range(5):
if y % 2 == 1:
res.append((x, y))
</code></pre>
<p>This is the expected result:</p>
<pre><code>[(0, 1), (0, 3), (2, 1), (2, 3)... | 0 | 2016-09-20T16:46:42Z | 39,599,688 | <p>You can write it as (in Python 2.x):</p>
<pre><code>xs = filter(lambda x: x % 2 == 0, range(5))
ys = filter(lambda y: y % 2 == 1, range(5))
res = [(x, y) for x in xs for y in ys]
</code></pre>
<p>This also uses a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">li... | 3 | 2016-09-20T16:49:10Z | [
"python",
"dictionary",
"filter",
"functional-programming"
] |
Use map and filter instead of a for loop? | 39,599,642 | <p>How do I write an equivalent of the code below using map and filter?</p>
<pre><code>res = []
for x in range(5):
if x % 2 == 0:
for y in range(5):
if y % 2 == 1:
res.append((x, y))
</code></pre>
<p>This is the expected result:</p>
<pre><code>[(0, 1), (0, 3), (2, 1), (2, 3)... | 0 | 2016-09-20T16:46:42Z | 39,599,722 | <p>You don't even need map and filter, you could do the whole thing in a list comprehension</p>
<pre><code>[(x,y) for x in range(5) for y in range(5) if not x%2 and y%2]
</code></pre>
| 2 | 2016-09-20T16:51:38Z | [
"python",
"dictionary",
"filter",
"functional-programming"
] |
Use map and filter instead of a for loop? | 39,599,642 | <p>How do I write an equivalent of the code below using map and filter?</p>
<pre><code>res = []
for x in range(5):
if x % 2 == 0:
for y in range(5):
if y % 2 == 1:
res.append((x, y))
</code></pre>
<p>This is the expected result:</p>
<pre><code>[(0, 1), (0, 3), (2, 1), (2, 3)... | 0 | 2016-09-20T16:46:42Z | 39,599,855 | <p>You need to use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>product</code></a> method from <a href="https://docs.python.org/3/library/itertools.html" rel="nofollow"><code>itertools</code></a>, which produces cartesian product of input iterables.</p>
<pre><code>x... | 1 | 2016-09-20T16:59:15Z | [
"python",
"dictionary",
"filter",
"functional-programming"
] |
Use map and filter instead of a for loop? | 39,599,642 | <p>How do I write an equivalent of the code below using map and filter?</p>
<pre><code>res = []
for x in range(5):
if x % 2 == 0:
for y in range(5):
if y % 2 == 1:
res.append((x, y))
</code></pre>
<p>This is the expected result:</p>
<pre><code>[(0, 1), (0, 3), (2, 1), (2, 3)... | 0 | 2016-09-20T16:46:42Z | 39,599,960 | <p>An alternative, you can make use of the fact that odd or even numbers can be captured by using the 3rd <code>step</code> argument of <code>range</code>:</p>
<pre><code>>>> sorted((x,y) for y in range(1,5,2) for x in range(0,5,2))
[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]
</code></pre>
| 1 | 2016-09-20T17:05:14Z | [
"python",
"dictionary",
"filter",
"functional-programming"
] |
metaheuristic-algorithms-python throws import error but is definitely installed (this package is only tested in python3 and I'm using python 2.7) | 39,599,691 | <p>I can't import the <a href="https://pypi.python.org/pypi/metaheuristic-algorithms-python/0.1.6#downloads" rel="nofollow">metaheuristic-algorithms-python</a> library after installing it in python. Why isn't this working? It is installed in my site-packages but it cannot be imported. The docs say this is only tested f... | -1 | 2016-09-20T16:49:34Z | 39,599,864 | <p>You know how they said they don't support Python 2? Well, this is one of those things that works on Python 3 and not Python 2. Specifically, this package has no <code>__init__.py</code>.</p>
<p>On Python 3, a package with no <code>__init__.py</code> is a <a href="https://www.python.org/dev/peps/pep-0420/" rel="nofo... | 2 | 2016-09-20T16:59:47Z | [
"python",
"python-2.7",
"python-3.x",
"pip",
"importerror"
] |
UnicodeEncodeError in Python when trying to encrypt and write to a file | 39,599,747 | <p>second post here (on the same code). However this time it is a different issue. It only happens every so often but it stumps me as to why. This is the output and error: </p>
<pre><code>Phrase to be encrypted: Hello world
Shift keyword, Word only: Hello
:-) :-) :-) Encrypting Phrase 10%... :-) :-) :-)
:-) :-) :-) ... | 1 | 2016-09-20T16:52:43Z | 39,611,041 | <p>Okay. So anyone else viewing this post knows. All you need to do is put </p>
<p><code>import codecs</code> </p>
<p>at the top and then when you write the file type </p>
<p><code>encoding = "utf8"</code> </p>
<p>inside the write parenthesis. Hope I have helped your issue and thank you to all that helped me come t... | 0 | 2016-09-21T08:16:11Z | [
"python",
"encryption",
"unicode",
"python-unicode"
] |
Why does django 1.9 keeps using python2.7 when my virtualenv have python3.5? | 39,599,769 | <p>Im having problems with python versions, im actually developing a web page with python3.5 under Windows 7. But in my server (CentOS 7) i created a virtualenv with python3.5 (because the default version of python in linux is 2.7). </p>
<p>The problem is that when i get an error, it says that django is using python2.... | 1 | 2016-09-20T16:54:13Z | 39,600,214 | <p>That manual doesn't seem right, since it doesnt tell how to use the virtualenv on the server. Even though the last line of the apache config points to a wsgi config, it does not explain what should be in there. </p>
<p>try something like this:</p>
<pre><code>#/home/user/project/project/wsgi.py
import os
import sy... | -1 | 2016-09-20T17:21:02Z | [
"python",
"django",
"apache",
"mod-wsgi",
"centos7"
] |
Why does django 1.9 keeps using python2.7 when my virtualenv have python3.5? | 39,599,769 | <p>Im having problems with python versions, im actually developing a web page with python3.5 under Windows 7. But in my server (CentOS 7) i created a virtualenv with python3.5 (because the default version of python in linux is 2.7). </p>
<p>The problem is that when i get an error, it says that django is using python2.... | 1 | 2016-09-20T16:54:13Z | 39,604,286 | <p>You need to rebuild <strong>mod_wsgi</strong> from source for Python 3.</p>
<p>Download <strong>mod_wsgi</strong>. Unpack it.</p>
<pre><code>tar xvfz mod_wsgi-X.Y.tar.gz
</code></pre>
<p>Configure for Python 3.5:</p>
<pre><code>./configure --with-apxs=/usr/local/apache/bin/apxs \
--with-python=/path/to/python3... | 1 | 2016-09-20T21:52:30Z | [
"python",
"django",
"apache",
"mod-wsgi",
"centos7"
] |
Python Conditionally Add Class to <td> Tags in HTML Table | 39,599,802 | <p>I have some data in the form of a csv file that I'm reading into Python and converting to an HTML table using Pandas.</p>
<p>Heres some example data:</p>
<pre><code>name threshold col1 col2 col3
A 10 12 9 13
B 15 18 17 23
C 20 19 22 25
</code></pre>
<p>And some c... | 0 | 2016-09-20T16:55:55Z | 39,600,120 | <p>Using <em>BeautifulSoup</em> you can add a class to the tags attrs as you would set a key/value in a dictionary:</p>
<pre><code>soup = BeautifulSoup(html,"html.parser")
for row in soup.select("tbody tr"):
tds = row.find_all("td")
if int(tds[3].text) < int(tds[1].text):
tds[3]["class"] = "c... | 0 | 2016-09-20T17:14:51Z | [
"python",
"html",
"pandas",
"beautifulsoup"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.