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
listlengths
1
5
IndexError: index 3 is out of bounds for axis 1 with size 3
38,324,610
<p>I would like to solve the error: </p> <blockquote> <p>IndexError: index 3 is out of bounds for axis 1 with size 3</p> </blockquote> <pre><code>from numpy import * from pylab import * def SIR2(I0, beta, gama, w, sigma, p, dt, tmax): N = int(tmax / dt) + 1 # nombre de pas de temps T = zeros([N + 1, 3]) ...
-1
2016-07-12T09:14:12Z
38,324,732
<p>Indices of arrays in <code>numpy</code> start from <code>0</code>. So an array with a second axis of 3, will be <em>subscriptable</em> up to a maximum index of 2.</p> <p>So the following will not work for <code>T[:,3]</code>:</p> <pre><code>T=zeros([N+1,3]) </code></pre> <p>If you intend to index on 0,1,2 and 3, ...
1
2016-07-12T09:19:35Z
[ "python", "numpy" ]
Class in class in class in python, how to share information
38,324,614
<p>I am trying to create a class for a database using peewee in python. This results in nested classes due to peewee's use of a class named meta in the models. My question is, how do I define the database (=db) within the class Meta? Is there perhaps a better way?</p> <pre><code>import peewee as pe class DataBase...
0
2016-07-12T09:14:20Z
38,331,759
<p>Instead of nesting classes, try inheritance. <a href="http://stackoverflow.com/a/6581949/6469907" title="What is a metaclass in Python?">This post</a> has some fairly decent information on how to use inheritance and metaclasses in Python.</p> <p>Looking at the quickstart example for <a href="http://docs.peewee-orm...
2
2016-07-12T14:30:08Z
[ "python", "database", "peewee" ]
Class in class in class in python, how to share information
38,324,614
<p>I am trying to create a class for a database using peewee in python. This results in nested classes due to peewee's use of a class named meta in the models. My question is, how do I define the database (=db) within the class Meta? Is there perhaps a better way?</p> <pre><code>import peewee as pe class DataBase...
0
2016-07-12T09:14:20Z
38,337,776
<p>I ended up using <a href="http://docs.peewee-orm.com/en/latest/peewee/database.html#run-time-database-configuration" rel="nofollow">this approach</a> from peewee documentation. It works and I avoid the nested classes:</p> <pre><code>import peewee as pe database = pe.SqliteDatabase(None) class BaseModel(pe.Model): ...
0
2016-07-12T19:52:48Z
[ "python", "database", "peewee" ]
Auto checkout Paypal API python or autoform
38,324,622
<p>I want to make a program to make auto checkout on different website. For this I have already make a "add to cart" and a "live stock checker", now I need to do autocheckout. But I fail with 2 different options: </p> <p>First one: I try to make a autoform on Paypal website to put my email adress and my password autom...
0
2016-07-12T09:14:40Z
38,372,637
<p>Please,i don't know how to do that and can't understand why selenium return this error , furthermore PAYPAL doc is too bad :/</p>
0
2016-07-14T11:10:43Z
[ "python", "google-chrome", "selenium", "paypal" ]
How does python's scikit measures the 'best output' for k-means
38,324,640
<p>Python's k-means does a given number of iterations (n_init) to find the best output of the algorithm in terms of inertia. I know how k-means works but my question is: how is the best output measured? Number of iterations needed until convergence? What is meant by terms of inertia? </p>
0
2016-07-12T09:15:22Z
38,324,763
<p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans" rel="nofollow">The documentation states</a> that the k-means algorithm is run <code>n_init</code> time and then of the results obtained it returns the one with minimum inertia:</p> <blockquote> <p><code>n...
0
2016-07-12T09:20:22Z
[ "python", "scikit-learn", "k-means" ]
Hough Line Transform identifies only one line even though image contains many lines in OpenCV in Python
38,324,838
<p>I used the Laplacian transform in OpenCV for edge detection and then used Hough Line Transform for detecting lines in it. These identified lines need to eventually removed from the image.</p> <pre><code>import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('Feb_16-0.jpg',0) kernel = np...
1
2016-07-12T09:24:45Z
38,325,713
<p>It seems to me that you are only reading the first element of "lines" in:</p> <pre><code>for x1,y1,x2,y2 in lines[0]: cv2.line(cst,(x1,y1),(x2,y2),(0,255,0),2) </code></pre> <p>Thus, you are only drawing the first (most significant) line, that has been found ( the longest, most thick). I suggest you to try: </...
2
2016-07-12T10:03:51Z
[ "python", "opencv", "image-processing", "computer-vision", "hough-transform" ]
How to return XLS file with spyne?
38,325,034
<p>I am trying to return XLS file throught webservice created with spyne.</p> <p>Here is mine code, now, I don't know what to do..</p> <pre><code>@spyne.srpc(Unicode, _returns=Iterable(Unicode)) def Function(A): GetXLS(A) kalist = open("file.xls", 'r'); return kalist </code></pre> <p>The most...
0
2016-07-12T09:33:46Z
38,348,480
<p>The best way to do this is to set the return type to <code>File</code> (<a href="http://spyne.io/docs/2.10/reference/model/binary.html" rel="nofollow">docs</a>) and return a <code>File.Value</code> object.</p> <p>For your case, that means:</p> <pre><code>@spyne.rpc(Unicode, _returns=File) def kalibracniList(ct...
0
2016-07-13T10:02:11Z
[ "python", "excel", "web-services", "spyne" ]
regr.score and r2_score give different values
38,325,068
<p>I am using sklearn.linear_model.LogisticRegression and using that I calculate the R^2 value as follows</p> <p><code>regr.score(xtest, ytest)</code> </p> <p>and I get a score of 0.65</p> <p>Now, just to compare i used the metric provided by sklearn.metrics.r2_score¶ and I calculate the score as follows</p> <p><c...
0
2016-07-12T09:35:25Z
38,337,751
<p>The reason you get different values because the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html#sklearn.linear_model.LogisticRegression.score" rel="nofollow"><code>score</code></a> function in <code>LogisticRegression</code> class by default calculates the <a hr...
2
2016-07-12T19:51:38Z
[ "python", "python-2.7", "scipy", "scikit-learn", "regression" ]
where to Include '\n'?
38,325,117
<p>i am trying to get the following:</p> <pre><code>[A1, B1, C1] [A2, B2, C2] [A3, B3, C3] </code></pre> <p>using list comprehension. i have gotten to this, but it only prints stuff in one line:</p> <pre><code>listeHoriz = ['A','B','C'] listeVert = ['1','2','3'] def generatechess (): return [[z+y for z in list...
0
2016-07-12T09:37:43Z
38,325,332
<p>You can do it like this :</p> <pre><code>listeHoriz = ['A','B','C'] listeVert = ['1','2','3'] def generatechess(): combinations = [str([z+y for z in listeHoriz ]) for y in listeVert] return ("\n").join(combinations) print(generatechess()) </code></pre> <p>or simply this :</p> <pre><code>listeHoriz = ['A'...
1
2016-07-12T09:46:46Z
[ "python", "python-2.7", "python-3.x" ]
where to Include '\n'?
38,325,117
<p>i am trying to get the following:</p> <pre><code>[A1, B1, C1] [A2, B2, C2] [A3, B3, C3] </code></pre> <p>using list comprehension. i have gotten to this, but it only prints stuff in one line:</p> <pre><code>listeHoriz = ['A','B','C'] listeVert = ['1','2','3'] def generatechess (): return [[z+y for z in list...
0
2016-07-12T09:37:43Z
38,325,556
<p>Try this in your <code>def</code> function:</p> <pre><code>def generatechess(): print(*[[z+y for z in listeHoriz ] for y in listeVert], sep = '\n') generatechess() ['A1', 'B1', 'C1'] ['A2', 'B2', 'C2'] ['A3', 'B3', 'C3'] </code></pre> <p>Incase you want to try this in Python 2.7, you must specify <code>from...
2
2016-07-12T09:56:34Z
[ "python", "python-2.7", "python-3.x" ]
How to perform multivariable linear regression with scikit-learn?
38,325,164
<p>Forgive my terminology, I'm not an ML pro. I might use the wrong terms below.</p> <p>I'm trying to perform multivariable linear regression. Let's say I'm trying to work out user gender by analysing page views on a web site.</p> <p>For each user whose gender I know, I have a feature matrix where each row represents...
1
2016-07-12T09:39:58Z
38,325,352
<p>You need to create <code>xs</code> in a different way. According to the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression.fit" rel="nofollow">docs</a>:</p> <blockquote> <pre><code>fit(X, y, sample_weight=None) </code></pre> ...
2
2016-07-12T09:47:54Z
[ "python", "machine-learning", "scikit-learn", "linear-regression" ]
How do I detect computer suspension using python?
38,325,321
<p>I'm making an alarm using python, and I'm using time.sleep() to wait for alarm time. But if I suspend my computer, the sleep will suspend too, causing the alarm to sound after what was intended if I turn the computer on again.</p> <p>I need a way for the program to detect when the computer is going to be suspended,...
1
2016-07-12T09:46:17Z
38,325,569
<p>It is very easily to detect if it was <em>likely</em> suspended:</p> <pre><code>before = datetime.now() sleep(1) after = datetime.now() if (after - before).total_seconds() &gt; X: # suspended </code></pre> <p><code>after - before</code> will never be exactly 1 second, but they should not be significantly large...
1
2016-07-12T09:57:24Z
[ "python" ]
How to combine columns in a layout (colspan feature)
38,325,350
<p>I have this code:</p> <pre><code>#!/usr/bin/env python3 from PyQt5.QtWidgets import * import sys class Window(QWidget): def __init__(self): QWidget.__init__(self) layout = QGridLayout() self.setLayout(layout) label_1 = QLabel("label 1") layout.addWidget(label_1, 0...
1
2016-07-12T09:47:48Z
38,332,682
<p>The fourth and fifth arguments of <a href="http://doc.qt.io/qt-5/qgridlayout.html#addWidget-2" rel="nofollow">addWidget</a> allow you to specify how many rows and columns to span:</p> <pre><code>label_3 = QLabel("label 3") layout.addWidget(label_3, 1, 0, 1, 2) </code></pre>
1
2016-07-12T15:06:34Z
[ "python", "qt", "layout", "pyqt", "pyqt5" ]
How to combine columns in a layout (colspan feature)
38,325,350
<p>I have this code:</p> <pre><code>#!/usr/bin/env python3 from PyQt5.QtWidgets import * import sys class Window(QWidget): def __init__(self): QWidget.__init__(self) layout = QGridLayout() self.setLayout(layout) label_1 = QLabel("label 1") layout.addWidget(label_1, 0...
1
2016-07-12T09:47:48Z
38,333,902
<p>This is the example code for layout the QLabel. It is PyQt4, but you can try with PyQt5 with small changes.</p> <pre><code>import sys from PyQt4 import QtGui class Window (QtGui.QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) self.verticalLayout = Q...
1
2016-07-12T16:02:00Z
[ "python", "qt", "layout", "pyqt", "pyqt5" ]
python: how to access class.__dict__ from class variable?
38,325,370
<p>I need to define a class variable, named "class". I want to do this directly in class namespace, not in a class method. Obviously, I cannot directly say:</p> <pre><code>class MyClass(object): a = 1 b = 2 class = 3 </code></pre> <p>So, I want to do something like:</p> <pre><code>class MyClass(object): ...
2
2016-07-12T09:48:32Z
38,325,441
<p>You could do:</p> <pre><code>class MyClass(object): a = 1 b = 2 vars()['class'] = 3 </code></pre> <p>But since <code>class</code> is a reserved keyword, then you have to access the variable using <code>getattr</code> and <code>setattr</code>, so that <code>class</code> remains a string.</p> <pre><code...
1
2016-07-12T09:51:25Z
[ "python", "django", "django-rest-framework" ]
python: how to access class.__dict__ from class variable?
38,325,370
<p>I need to define a class variable, named "class". I want to do this directly in class namespace, not in a class method. Obviously, I cannot directly say:</p> <pre><code>class MyClass(object): a = 1 b = 2 class = 3 </code></pre> <p>So, I want to do something like:</p> <pre><code>class MyClass(object): ...
2
2016-07-12T09:48:32Z
38,325,512
<p>You cannot it while creating class - technically that object does not exist yet.</p> <p>You could consider:</p> <pre><code>class MyClass(object): a = 1 b = 2 # class is already created MyClass.__dict__["class"] = 3 </code></pre> <p>But <code>MyClass.__dict__</code> is not a dict, but a <code>dictproxy</c...
0
2016-07-12T09:54:32Z
[ "python", "django", "django-rest-framework" ]
python: how to access class.__dict__ from class variable?
38,325,370
<p>I need to define a class variable, named "class". I want to do this directly in class namespace, not in a class method. Obviously, I cannot directly say:</p> <pre><code>class MyClass(object): a = 1 b = 2 class = 3 </code></pre> <p>So, I want to do something like:</p> <pre><code>class MyClass(object): ...
2
2016-07-12T09:48:32Z
38,325,673
<p>Use '''setattr''' to set a class attribute immediately after you finish the class definition. Outside the definition, of course. Pass '''MyClass''' for parameter, and it will create an attribute of your class.</p> <p>Dict of members should not be used, especially for modifying an object. In fact, it is rarely need...
0
2016-07-12T10:02:21Z
[ "python", "django", "django-rest-framework" ]
python: how to access class.__dict__ from class variable?
38,325,370
<p>I need to define a class variable, named "class". I want to do this directly in class namespace, not in a class method. Obviously, I cannot directly say:</p> <pre><code>class MyClass(object): a = 1 b = 2 class = 3 </code></pre> <p>So, I want to do something like:</p> <pre><code>class MyClass(object): ...
2
2016-07-12T09:48:32Z
38,325,736
<p>You can create your class from <code>type</code> and add the attribute <code>class</code> to the class dictionary:</p> <pre><code>&gt;&gt;&gt; MyClass = type('MyClass', (), {'class': 3, 'a':1, 'b':2}) &gt;&gt;&gt; getattr(MyClass, 'class') 3 </code></pre> <p>You can't directly access the name <code>class</code> wi...
1
2016-07-12T10:05:13Z
[ "python", "django", "django-rest-framework" ]
python: how to access class.__dict__ from class variable?
38,325,370
<p>I need to define a class variable, named "class". I want to do this directly in class namespace, not in a class method. Obviously, I cannot directly say:</p> <pre><code>class MyClass(object): a = 1 b = 2 class = 3 </code></pre> <p>So, I want to do something like:</p> <pre><code>class MyClass(object): ...
2
2016-07-12T09:48:32Z
38,325,749
<p>You don't need to name the attribute <code>class</code>, which can lead to all kinds of problems. You can name the attribute <code>class_</code>, but still have it pull from a source attribute named <code>class</code> and render out to JSON as <code>class</code>.</p> <p>You can do this by overriding the metaclass ...
1
2016-07-12T10:05:52Z
[ "python", "django", "django-rest-framework" ]
Appium Python How to launch hybrid app then switch to webview after
38,325,412
<p>I have to automate an app. In some section user can browse dropbox, gdrive but has to login before. The login screen is opened in a browser. Here I need to access browser elements which can be done via webview. The issue:</p> <p>I cant switch from Native context to Webview. With command print driver.contexts only u...
0
2016-07-12T09:50:21Z
38,361,321
<p>Webview debugging needs to be set to true by developer in order to perform actions in web view </p>
0
2016-07-13T20:41:47Z
[ "android", "python", "webview", "appium" ]
Appium Python How to launch hybrid app then switch to webview after
38,325,412
<p>I have to automate an app. In some section user can browse dropbox, gdrive but has to login before. The login screen is opened in a browser. Here I need to access browser elements which can be done via webview. The issue:</p> <p>I cant switch from Native context to Webview. With command print driver.contexts only u...
0
2016-07-12T09:50:21Z
38,995,001
<p>Provide some sleep or implicit wait so that all contexts loads and see whether you app is printing Webview or not use and if not then ask developers are they using crosswalk or not. If they are using crosswalk(<a href="https://github.com/appium/appium/issues/4597" rel="nofollow">https://github.com/appium/appium/issu...
0
2016-08-17T11:10:47Z
[ "android", "python", "webview", "appium" ]
Spark: Dataframe.subtract returns everything when key is not the first in the Row
38,325,416
<p>I'm trying to use <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.subtract" rel="nofollow">SQLContext.subtract()</a> in Spark 1.6.1 to remove rows from a dataframe based on a column from another dataframe. Let's use an example:</p> <pre><code>from pyspark.sql import R...
2
2016-07-12T09:50:33Z
38,327,578
<p>Well there are some bugs here (the first issue looks like related to to the same problem as <a href="https://issues.apache.org/jira/browse/SPARK-6231" rel="nofollow">SPARK-6231</a>) and JIRA looks like a good idea, but <code>SUBTRACT</code> / <code>EXCEPT</code> is no the right choice for partial matches. Instead yo...
1
2016-07-12T11:26:56Z
[ "python", "apache-spark", "dataframe", "pyspark" ]
How update numpy 1.11 on Windows
38,325,568
<p>Firtable, i know that subject is a duplicate, but if i understood the problem solving, i won't come here ask my question. So i read : <a href="http://stackoverflow.com/questions/14570011/explain-why-numpy-should-not-be-imported-from-source-directory">Explain why numpy should not be imported from source directory</a...
0
2016-07-12T09:57:19Z
38,330,782
<p>Pip is the easiest way to go installing packages. Your first problem appears to be that windows isn't recognising python as a command. In order to fix this you need to add it to the PATH environment variable. </p> <ol> <li>Open Start Menu and right click My Computer. Click on Advanced System Settings. </li> <li>Cli...
0
2016-07-12T13:48:14Z
[ "python", "windows", "numpy" ]
How update numpy 1.11 on Windows
38,325,568
<p>Firtable, i know that subject is a duplicate, but if i understood the problem solving, i won't come here ask my question. So i read : <a href="http://stackoverflow.com/questions/14570011/explain-why-numpy-should-not-be-imported-from-source-directory">Explain why numpy should not be imported from source directory</a...
0
2016-07-12T09:57:19Z
38,331,064
<p>Both numpy and scipy have problems installing from <a href="https://pypi.python.org/pypi" rel="nofollow">pypi</a> (the default repository of pip) on windows. The way I always install it it to download the <code>.whl</code> files from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">Christoper Goh...
0
2016-07-12T13:59:45Z
[ "python", "windows", "numpy" ]
How to avoid "list index out of range" in BeautifulSoup (Python)
38,325,603
<p>When executing this code, I always get the error message: "IndexError: list index out of range". What can I do to avoid this?</p> <pre><code>import urllib thisurl = "http://www.tutti.ch/stgallen/fahrzeuge/autos" handle = urllib.urlopen(thisurl) html_gunk = handle.read() from bs4 import BeautifulSoup soup = Beautif...
-1
2016-07-12T09:58:55Z
38,325,861
<p>You are missing a check to see if list is empty or not. Try this</p> <pre><code>import urllib thisurl = "http://www.tutti.ch/stgallen/fahrzeuge/autos" handle = urllib.urlopen(thisurl) html_gunk = handle.read() from bs4 import BeautifulSoup soup = BeautifulSoup(html_gunk, 'html.parser') for first in soup.find_all(...
0
2016-07-12T10:10:42Z
[ "python", "beautifulsoup", "python-2.x" ]
Deleting rows across an excel workbook with 31 sheets then joining the sheets into 1 df in pandas
38,325,623
<p>I have a workbook that has a sheet named 1-31 for everyday of the month. </p> <p>What I'm trying to do is read the book with <code>excel_read()</code>, then delete the first 4 rows as it is header rubbish. I need to do this across all sheets.</p> <p>After that I want to concatenate all the sheets into one data fra...
0
2016-07-12T09:59:53Z
38,330,239
<p>No need to import and delete, just don't import it.</p> <p>df.read_excel(filename, <strong>skiprows=4,</strong> header=None)</p>
0
2016-07-12T13:25:56Z
[ "python", "excel", "pandas" ]
Tmux split window and activate a python virtualenv
38,325,737
<p>My favorite python developement environment is:</p> <ul> <li>One large left pan for vim</li> <li>Two small pans on the right for interactive consoles</li> </ul> <p>Each pan shoud run a python virtualenv (using virtualenvwrapper). So here is the list of commands I have to type to setup my environment:</p> <pre><co...
2
2016-07-12T10:05:15Z
38,326,405
<p>First create all of your panes.</p> <p>Use send-keys to write your commands into the specified pane and execute them using C-m. For example:</p> <p><code>tmux send-keys -t development:0.1 "workon some_env" C-m </code></p> <p>If you have three panes, then the second and third would be <code>SESSION_NAME:0.1</code>...
3
2016-07-12T10:34:34Z
[ "python", "linux", "shell", "virtualenv", "tmux" ]
How to deal with single quote in xpath
38,325,753
<p>I have a line where I check if a certain element by partial text exists on the page.</p> <pre><code>self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text) </code></pre> <p>So it is possible that <code>item_text</code> has a single quote in the string. For example <code>"Hanes Men's Graphic "</cod...
0
2016-07-12T10:06:01Z
38,325,870
<p>try as below :-</p> <pre><code>self.b.find_element_by_xpath(".//*[contains(text(), \"Hanes Men's Graphic\")]") </code></pre> <p>or</p> <pre><code>self.b.find_element_by_xpath('.//*[contains(text(), "%s")]' % item_text) </code></pre> <p>or</p> <pre><code>self.b.find_element_by_xpath(".//*[contains(text(), \"%s\"...
2
2016-07-12T10:11:10Z
[ "python", "selenium", "xpath" ]
How to deal with single quote in xpath
38,325,753
<p>I have a line where I check if a certain element by partial text exists on the page.</p> <pre><code>self.b.find_element_by_xpath(".//*[contains(text(), '%s')]" % item_text) </code></pre> <p>So it is possible that <code>item_text</code> has a single quote in the string. For example <code>"Hanes Men's Graphic "</cod...
0
2016-07-12T10:06:01Z
38,326,329
<p>It might be that the xpath implementation won't allow double quotes for the string so you'll need to do something like</p> <pre><code>if (item_text.find("'")): item_text= item_text.replace("'", "', \"'\", '") item_text= "concat('" + item_text+ "')" else: item_text = "'" + item_text + "'" self.b.find_el...
0
2016-07-12T10:31:38Z
[ "python", "selenium", "xpath" ]
Python - what is the difference between these 3 methods of printing variables?
38,325,782
<p>I am trying to teach my friend Python and showed him 3 methods of printing variables of different types without the need for converting them to strings first, but he wants to know which one should he use and I don't know as I have not used Python in a long time so hopefully you can help us out:</p> <pre><code>print...
-1
2016-07-12T10:07:00Z
38,325,858
<p>The Python style guide recommends using the <code>format</code> method. Here is the link to that document: <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow" title="PEP 3101">"PEP 3101"</a></p>
2
2016-07-12T10:10:38Z
[ "python", "string", "variables", "printing" ]
Python - what is the difference between these 3 methods of printing variables?
38,325,782
<p>I am trying to teach my friend Python and showed him 3 methods of printing variables of different types without the need for converting them to strings first, but he wants to know which one should he use and I don't know as I have not used Python in a long time so hopefully you can help us out:</p> <pre><code>print...
-1
2016-07-12T10:07:00Z
38,326,628
<p>With regards to <code>%</code> vs. <code>.format</code> please see similar questions like <a href="http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format">this</a>, as others have pointed out.</p> <p>Regarding</p> <pre><code>print("There are", num_people, "people in total") </code></pre> <p...
1
2016-07-12T10:44:57Z
[ "python", "string", "variables", "printing" ]
Query `pg_stat_database` view through sqlalchemy
38,325,896
<p>I am trying to access <code>pg_stat_database</code> view through sqlalchemy metadata, but its throwing error. Here is my code </p> <pre><code>engine = "Some_engine_specification" metadata = MetaData() metadata.reflect(engine, views=True, only=["table", "table2", "pg_stat_database"] base = automap_base(metadata=meta...
0
2016-07-12T10:12:12Z
38,327,975
<p>You will not be able to automap the view as a model because there is no primary key:</p> <blockquote> <p>... then, each <strong>viable</strong> Table within the MetaData will get a new mapped class generated automatically.</p> </blockquote> <p>and</p> <blockquote> <p><strong>Note</strong></p> <p>By <stro...
3
2016-07-12T11:44:06Z
[ "python", "postgresql", "sqlalchemy" ]
What is the best SDN Controller for research purposes?
38,325,932
<p>I am interested in starting my research in the field of SDN. I looked around the internet for which SDN controller is the most suitable for research purposes, but it seems that the SDN community does not agree on a specific controller.</p> <p>I would like to get advice about which controller is optimum taking into ...
0
2016-07-12T10:13:40Z
38,327,718
<p>There are many solutions and what is the best depends on the individual needs. If you prefer to use Python. Look at the <a href="https://osrg.github.io/ryu/" rel="nofollow">Ryu</a> controller if POX does not match your requirements. Ryu is Python based an has a good <a href="https://osrg.github.io/ryu/resources.html...
1
2016-07-12T11:33:04Z
[ "python", "user-interface", "controller", "sdn" ]
Get value from a dictionary until next key is reached in Python
38,325,962
<p>The title is not explaining my problem at all, but I'll show you here. I am parsing emails from GMail account using Google API. From each email I need to get some values. The email body is formed like:</p> <p>Object: Something.</p> <p>Procedure: Something.</p> <p>...</p> <p>(Many fields)</p> <p>...</p> <p>Requ...
-1
2016-07-12T10:14:57Z
38,328,071
<p>A slight modification to your code should do the trick:</p> <pre><code>import collections key_list = ['Object','Procedure','Request'] dict_list = [] msg1 = 'Object: the object\nProcedure: the procedure\n' msg1 += 'some data\nsome more data\n' msg1 += 'Request: request line 1\nrequest line2\nrequest line3\n' msg2 = ...
1
2016-07-12T11:48:20Z
[ "python", "dictionary", "key" ]
tkinter (unsure of my error possibly due to .destroy())
38,326,068
<pre><code>from Tkinter import * import random menu = Tk() subpage = Tk() entry_values = [] population_values = [] startUpPage = Tk() def main_menu(window): window.destroy() global menu menu = Tk() frame1 = Frame(menu) menu.resizable(width=FALSE, height=FALSE) button0 = Button(menu, text="Set...
1
2016-07-12T10:20:08Z
38,326,529
<p>heres some code that does what you want.. make a window, destroy it when button is clicked and then make a new window...</p> <pre><code>from Tkinter import * import random def main_menu(): global root root = Tk() b = Button(root,text='our text button',command = next_page) b.pack() def next_page()...
1
2016-07-12T10:39:58Z
[ "python", "python-2.7", "tkinter" ]
tkinter (unsure of my error possibly due to .destroy())
38,326,068
<pre><code>from Tkinter import * import random menu = Tk() subpage = Tk() entry_values = [] population_values = [] startUpPage = Tk() def main_menu(window): window.destroy() global menu menu = Tk() frame1 = Frame(menu) menu.resizable(width=FALSE, height=FALSE) button0 = Button(menu, text="Set...
1
2016-07-12T10:20:08Z
38,327,342
<p>As a general rule, you should create exactly one instance of <code>Tk</code> for the life of your program. That is how Tkinter is designed to be used. You can break this rule when you understand the reasoning behind it, though there are very few good reasons to break the rule.</p> <p>The simplest solution is to imp...
1
2016-07-12T11:16:56Z
[ "python", "python-2.7", "tkinter" ]
Extracting sequences from RDD in Pyspark
38,326,233
<p>I'm trying to prepare my data for a machine learning algorithm on Spark using pyspark. I have an RDD containing epoch date-times, IDs and classes (0 or 1). It simply looks like below:</p> <pre><code>rdd = sc.parallelize([Row(my_date=1465488788,id=4,my_class=1), Row(my_date=1465488790,id=5,my_class=0), Row(my_date=1...
0
2016-07-12T10:27:35Z
38,327,394
<pre><code>time_window = 20 clustered_logs.groupBy(lambda x: (int(x /time_window), x.my_class) )\ .map(lambda x: Row(my_class=x[0][1], my_seq=[ t.id for t in x[1]]) ) </code></pre> <ul> <li>identify the window by <code>int(x /time_window)</code> </li> <li>Group by the window and class. The grouping key is a tupl...
0
2016-07-12T11:19:11Z
[ "python", "apache-spark", "pyspark" ]
Byte string spanning more than one line
38,326,297
<p>I need to parse byte string which spans more than one line in the source code. Like this</p> <pre><code>self.file.write(b'#compdef %s\n\n' '_arguments -s -A "-*" \\\n' % (self.cmdName,)) </code></pre> <p>this line throws the following exception</p> <pre><code>builtins.SyntaxError: cannot mix b...
0
2016-07-12T10:30:07Z
38,326,315
<p>You are fine to use multiple string literals, but they need to be of the same <em>type</em>. You are missing the <code>b</code> prefix on the second line:</p> <pre><code>self.file.write(b'#compdef %s\n\n' b'_arguments -s -A "-*" \\\n' % (self.cmdName,)) </code></pre> <p>Only when using string liter...
3
2016-07-12T10:30:58Z
[ "python", "python-3.x", "literals", "string-literals", "bytestring" ]
How can I get rid of Unicode Encode Error while trying to output web scraping result in a .txt file
38,326,357
<p><strong>following is my code in python for the scraping and output efforts</strong></p> <pre><code>html = urlopen("http://www.imdb.com/news/top") wineReviews = BeautifulSoup(html) lines = [] for headLine in imdbNews.findAll("h2"): #headLine.encode('ascii', 'ignore') imdb_news = headLine.get_text() ...
0
2016-07-12T10:32:19Z
38,326,856
<pre><code> s = u'\u2018Battlefield\u2019'.encode('utf-8') with open("some_file", "w") as f: f.write(s) </code></pre> <p>just add .encode('utf-8') to your strings before writing them to a file</p>
0
2016-07-12T10:55:45Z
[ "python", "unicode" ]
How can I get rid of Unicode Encode Error while trying to output web scraping result in a .txt file
38,326,357
<p><strong>following is my code in python for the scraping and output efforts</strong></p> <pre><code>html = urlopen("http://www.imdb.com/news/top") wineReviews = BeautifulSoup(html) lines = [] for headLine in imdbNews.findAll("h2"): #headLine.encode('ascii', 'ignore') imdb_news = headLine.get_text() ...
0
2016-07-12T10:32:19Z
38,326,964
<p><strong>UPDATE</strong></p> <p>Since you don't want the <code>\u</code> characters in your string. This should work :</p> <pre><code>html = urlopen("http://www.imdb.com/news/top") wineReviews = BeautifulSoup(html) lines = [] for headLine in imdbNews.findAll("h2"): imdb_news = headLine.get_text() ...
0
2016-07-12T10:59:58Z
[ "python", "unicode" ]
At Thrift Python server, how to configure the max threads in pool by using TThreadPoolServer?
38,326,358
<p>I have a python service called by thrift. And I want to try <strong>TThreadPoolServer</strong> instead of <strong>TThreadedServer</strong>. After my trying, I found that TThreadPoolServer mod have lower cpu rate but lower speed. I guess the default max threads in pool is small. But i do not know how to configure thi...
1
2016-07-12T10:32:23Z
38,326,702
<p>See definitions in the source code, <a href="https://github.com/apache/thrift/blob/0.9.3/lib/py/src/server/TServer.py" rel="nofollow">TServer.py</a>.</p> <p>The default number of threads in the pool of <code>TThreadPoolServer</code> is 10. See line 143 in the source code, under the definition of the <code>TThreadPo...
1
2016-07-12T10:48:45Z
[ "python", "thrift" ]
How to get percentiles on groupby column in python?
38,326,387
<p>I have a dataframe as below:</p> <pre><code>df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3, 'office_id': list(range(1, 7)) * 2, 'sales': [np.random.randint(100000, 999999) for _ in range(12)]}) </code></pre> <p>To get percentiles of sales,state wise,I have written below code...
0
2016-07-12T10:33:49Z
38,327,836
<p>How about this?</p> <pre><code>quants = np.arange(.1,1,.1) pd.concat([df.groupby('state')['sales'].quantile(x) for x in quants],axis=1,keys=[str(x) for x in quants]) </code></pre>
0
2016-07-12T11:38:09Z
[ "python", "pandas" ]
Select Classes (plugins) from a Python list
38,326,506
<p>I have a list of classes(plugins) in python, i read them from a folder and store them in a list plugins, like this:</p> <pre><code>#Read all classes from plugin folder plugnplay.plugin_dirs = ['./plugins'] plugnplay.load_plugins() plugins = PluginAlerter.implementors() </code></pre> <p>then all my classes is s...
1
2016-07-12T10:39:02Z
38,326,764
<p>NEW suggestion</p> <p>I think you're replacing the <code>plugins</code> list with a single plugin (which isn't iterable)</p> <ul> <li>You say you're running <code>plugins = plugins[1]</code> which would replace the iterable plugins with the 2nd plugin, making <code>for plugin in plugins</code> fail</li> <li>The er...
1
2016-07-12T10:51:37Z
[ "python", "list", "python-2.7", "class", "object" ]
Select Classes (plugins) from a Python list
38,326,506
<p>I have a list of classes(plugins) in python, i read them from a folder and store them in a list plugins, like this:</p> <pre><code>#Read all classes from plugin folder plugnplay.plugin_dirs = ['./plugins'] plugnplay.load_plugins() plugins = PluginAlerter.implementors() </code></pre> <p>then all my classes is s...
1
2016-07-12T10:39:02Z
38,327,773
<p>You try to iterate over a single item of type "plugins" instead of a list of plugins:</p> <pre><code># plugins is a list plugins = plugins[1] # now plugins is a single element </code></pre> <p>You can force plugins to always be a list:</p> <pre><code>self.plugins = [self.plugins[1]] </code></pre> <p>or more gene...
2
2016-07-12T11:35:36Z
[ "python", "list", "python-2.7", "class", "object" ]
How to get the field values from vector layer in the list using gdal
38,326,748
<p>I have a list with the field names and i am trying to get the field values using the code snippet:</p> <pre><code>from osgeo import osr,ogr, gdal shp="filepath" driver = ogr.GetDriverByName('ESRI Shapefile') dataSource = driver.Open(shp,0) layer=dataSource.GetLayer() list=['field1','field2','field3'] for i in layer...
0
2016-07-12T10:50:58Z
38,335,086
<ol> <li>Try not using <code>list</code> a variable name as it is a reserved Python word. </li> <li>Your code works fine for me, it looks like the error comes from your list of field.</li> </ol> <p>This works fine for me:</p> <pre><code>from osgeo import ogr shp= "your_shapefile_path" driver = ogr.GetDriverByName('E...
0
2016-07-12T17:06:23Z
[ "python", "gdal" ]
Python keeping count of totals based on user input
38,326,753
<p>I have a function in my item ordering system where the goal is to keep totals of how many items were ordered and print each item and the amount they were ordered</p> <pre><code>class Totals(object): def __init__(self, total): self.total = total def total(order_amount, coffee_id): count = 0 print("Cof...
-1
2016-07-12T10:51:16Z
38,326,857
<p>You should save a dictionary that map from the coffee id to it amount of orders and update it on each order.</p> <pre><code>class Totals(object): def __init__(self): self.total = {} def order(self, order_amount, coffee_id): if coffee_id not in self.total.keys(): self.total[coff...
2
2016-07-12T10:55:47Z
[ "python", "python-3.x" ]
Python keeping count of totals based on user input
38,326,753
<p>I have a function in my item ordering system where the goal is to keep totals of how many items were ordered and print each item and the amount they were ordered</p> <pre><code>class Totals(object): def __init__(self, total): self.total = total def total(order_amount, coffee_id): count = 0 print("Cof...
-1
2016-07-12T10:51:16Z
38,328,204
<p>This is personally how I believe you should manage the items ordered. This example has a dictionary mapping a Coffee object to the number of times it was ordered.</p> <pre><code>class Order(object): ID = 0 def __init__(self): self._orders = {} self._order_id = Order.ID Order.ID += 1 ...
0
2016-07-12T11:54:32Z
[ "python", "python-3.x" ]
memory management for dictionary in python
38,326,787
<p>I have following code , i don't understand the scenario behind this please any one can explain.</p> <pre><code>import sys data={} print sys.getsizeof(data) ######output is 280 data={ 1:2,2:1,3:2,4:5,5:5,6:6,7:7,8:8,9:9,0:0,11:11,12:12,13:13,14:14,15:15} print sys.getsizeof(data) ######output is 1816 data={1:2,2:1,3...
4
2016-07-12T10:52:44Z
39,766,471
<blockquote> <p><code>getsizeof()</code> calls the object’s <code>__sizeof__</code> method and adds an additional garbage collector overhead if the object is managed by the garbage collector.</p> </blockquote> <p>Windows x64 - If did like below:</p> <pre><code>data={ 1:2,2:1,3:2,4:5,5:5,6:6,7:7,8:8,9:9,0:0,11:11,...
0
2016-09-29T09:25:39Z
[ "python", "python-2.7" ]
How to render multiple forms - radiobuttons for answers
38,326,906
<p>I can't figure out how to create a page with multiple <code>Question</code>s and their <code>Answer</code>s. The main thing is that I want <code>User</code> to take a <code>Quiz</code> which contain's multiple <code>Questions</code> and <code>Questions</code> have multiple <code>Answers</code>.</p> <p>The first thi...
0
2016-07-12T10:57:29Z
38,326,972
<p>A Django form field <code>choices</code> argument should be an iterable of 2-tuples, see <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/models/fields/#choices</a></p> <p>You probably want to say something like</p> <pre><code>choic...
1
2016-07-12T11:00:16Z
[ "python", "django", "django-models", "django-forms" ]
Using scapy through RPyC
38,326,909
<p>I need to use scapy on remote server to dump traffic like this</p> <pre><code>sniff(filter='icmp', iface='eth1', timeout=5) </code></pre> <p>To connect to remote server I'm using RPyC.</p> <pre><code>conn = rpyc.classic.connect(HOST_IP) </code></pre> <p>but I can not understand how to use scapy on remote server....
2
2016-07-12T10:57:38Z
38,560,116
<p>You shouldn't be sniffing with an <code>icmp</code> filter. You'll need to filter for <code>tcp</code> to get RPyC connections, which go over TCP.</p>
0
2016-07-25T05:10:02Z
[ "python", "scapy", "rpyc" ]
how to rotate a 3D surface in matplotlib
38,326,983
<p>I have written code to plot a 3D surface of a parabaloid in matplotlib.</p> <p>How would I rotate the figure so that the figure remains in place (i.e. no vertical or horizontal shifts) however it rotates around the line y = 0 and z = 0 through an angle of theta ( I have highlighted the line about which the figure s...
2
2016-07-12T11:00:46Z
38,327,573
<p>Something like this?</p> <pre><code>ax.view_init(-140, 30) </code></pre> <p>Inset it just before your <code>plt.show()</code> command.</p>
0
2016-07-12T11:26:42Z
[ "python", "matplotlib" ]
how to rotate a 3D surface in matplotlib
38,326,983
<p>I have written code to plot a 3D surface of a parabaloid in matplotlib.</p> <p>How would I rotate the figure so that the figure remains in place (i.e. no vertical or horizontal shifts) however it rotates around the line y = 0 and z = 0 through an angle of theta ( I have highlighted the line about which the figure s...
2
2016-07-12T11:00:46Z
38,328,316
<p>The best I could come up with is to rotate the data itself.</p> <pre><code>#parabaloid import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from math import sin, cos, pi fig = plt.figure() ax = fig.add_subplot(111, projection='3d') #creating grid y = np.linspace(-1,1,200...
1
2016-07-12T11:59:51Z
[ "python", "matplotlib" ]
how to rotate a 3D surface in matplotlib
38,326,983
<p>I have written code to plot a 3D surface of a parabaloid in matplotlib.</p> <p>How would I rotate the figure so that the figure remains in place (i.e. no vertical or horizontal shifts) however it rotates around the line y = 0 and z = 0 through an angle of theta ( I have highlighted the line about which the figure s...
2
2016-07-12T11:00:46Z
38,329,603
<p>Following my comment:</p> <pre><code>import mayavi.mlab as mlab import numpy as np x,y = np.mgrid[-1:1:0.001, -1:1:0.001] z = x**2+y**2 s = mlab.mesh(x, y, z) alpha = 30 # degrees mlab.view(azimuth=0, elevation=90, roll=-90+alpha) mlab.show() </code></pre> <p><a href="http://i.stack.imgur.com/9yY2a.png" rel="nof...
2
2016-07-12T12:58:07Z
[ "python", "matplotlib" ]
How to print a dictionary which has function names in it?
38,327,053
<p>I want to print function names using this dictionary-</p> <pre><code>def pressKey() : print "is pressed" def userLogin() : print "Code to login to &lt;Server Name&gt; with &lt;username&gt;" act={'Login':userLogin,'press':pressKey} </code></pre> <p>I tried via this (took from an answer)</p> <pre><code>fo...
0
2016-07-12T11:04:02Z
38,327,132
<p>If you know that they are all functions you could use the <code>__name__</code> attribute to get the name of the function:</p> <pre><code>for key, value in act.iteritems(): print value.__name__, '()\t', act[key]() </code></pre> <p>note that you actually don't need <code>key</code> since you could use <cod...
1
2016-07-12T11:07:55Z
[ "python", "function", "dictionary", "printing" ]
How to print a dictionary which has function names in it?
38,327,053
<p>I want to print function names using this dictionary-</p> <pre><code>def pressKey() : print "is pressed" def userLogin() : print "Code to login to &lt;Server Name&gt; with &lt;username&gt;" act={'Login':userLogin,'press':pressKey} </code></pre> <p>I tried via this (took from an answer)</p> <pre><code>fo...
0
2016-07-12T11:04:02Z
38,327,144
<p>Try this:</p> <pre><code>def pressKey() : print "is pressed" def userLogin() : print "Code to login to &lt;Server Name&gt; with &lt;username&gt;" act={'Login':userLogin,'press':pressKey} for key, value in act.iteritems() : print value.__name__,'()\t', act[key]() </code></pre>
1
2016-07-12T11:08:24Z
[ "python", "function", "dictionary", "printing" ]
Python: using loop to add new column to dataframe
38,327,123
<p>I have column from dataframe</p> <pre><code>url http://www.utt66.ru/cat/13972/ https://yandex.ru/yandsearch?clid=2186618&amp;text=%D0%BA%D0%B0%D0%BB%D1%8C%D1%8F%D0%BD%D1%8B%20khalil%20mamoon%20%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C%20 http://yandex.ru/clck/jsredir?from=yandex.ru%3Byandsearch%3Bweb%3B%3B&amp;text=...
0
2016-07-12T11:07:17Z
38,327,650
<p>In your loop, you did not assign <strong>any</strong> value when none of those addresses are matched. Add <code>else</code> statement and add either empty string or <code>Null</code> - number of elements in <code>searching_val</code> <strong>must be equal</strong> to number of rows in dataframe (or <code>url</code> ...
0
2016-07-12T11:30:19Z
[ "python", "loops", "pandas" ]
Getting information about function execution time/billing and if the function call was successful
38,327,327
<p>I'm using SNS to trigger lambda functions in AWS. This works fine and as expected, but I'm wondering if there is a way to get feedback about the execution times and if an exception was raised within the function.</p> <p>Obviously there is exception handling code in my lambda functions for most of the business logic...
0
2016-07-12T11:15:58Z
38,329,761
<p>Exceptions of Lambda functions will be in your logs, which are streamed to AWS CloudWatch Logs. Execution time is stored as the Lambda Duration metric in CloudWatch. You would need to setup CloudWatch alerts on those items to be notified.</p>
0
2016-07-12T13:04:50Z
[ "python", "amazon-web-services", "aws-lambda", "amazon-sns" ]
Sorting a list with entries in string format
38,327,389
<p>In Python, have a list with items (strings) that look like this:</p> <pre><code>"1.120e+03 8.140e+02 3.234e+01 1.450e+00 1.623e+01 7.940e+02 3.113e+01 1.580e+00 1.463e+01" </code></pre> <p>I want to sort this list based on the size of the first number in each string (smallest to largest). In the above case that wo...
0
2016-07-12T11:19:05Z
38,327,694
<p>If you are sorting it more than once, I suggest you create your Class for the data and override methods for comparing such as <code>__lt__</code>.</p>
0
2016-07-12T11:32:08Z
[ "python", "sorting" ]
Why is no result in this code?
38,327,415
<p>emp.csv</p> <pre><code> index empno ename job mgr hiredate sal comm deptno 0, 7839, KING, PRESIDENT, 0, 1981-11-17, 5000, 0, 10 1, 7698, BLAKE, MANAGER, 7839, 1981-05-01, 2850, 0, 30 2, 7782, CLARK, MANAGER, 7839, 1981-05-09, 2450, 0, ...
-1
2016-07-12T11:19:57Z
38,327,630
<p><code>Job</code> has to be some kind of container to be used with the <code>in</code> keyword. That does not mean that you cannot have it with <strong>user input</strong>. For example you can do this:</p> <pre><code>keywords = input('Provide the search strings separated by commas (','):\t').split(',') </code></pre>...
1
2016-07-12T11:29:00Z
[ "python" ]
Why is no result in this code?
38,327,415
<p>emp.csv</p> <pre><code> index empno ename job mgr hiredate sal comm deptno 0, 7839, KING, PRESIDENT, 0, 1981-11-17, 5000, 0, 10 1, 7698, BLAKE, MANAGER, 7839, 1981-05-01, 2850, 0, 30 2, 7782, CLARK, MANAGER, 7839, 1981-05-09, 2450, 0, ...
-1
2016-07-12T11:19:57Z
38,327,859
<p>There are two problems:</p> <ul> <li>The input of the user has to be broken into individual tokens, this can be done with <code>job = input('Enter the job : ').split(",")</code></li> <li>the statement <code>if all(s in job for s in row[2])</code> looks weird to me. You check whether every character of column 2 is c...
0
2016-07-12T11:39:08Z
[ "python" ]
Not able to generate a random array of categorical labels
38,327,441
<p>I have a random state with a fixed seed I am using to make my predictive results replicable:</p> <pre><code>rng = np.random.RandomState(101) len(finalTestSentences) = 500 </code></pre> <p>I am trying to use this seed to generate an array of random categorical variables using a unique list of possibilities. Here's ...
0
2016-07-12T11:20:49Z
38,397,350
<p>If you look at the definition of <a href="https://github.com/numpy/numpy/blob/c62b20d10c05c07511553972d1c21e5845aa7d6f/numpy/random/mtrand/mtrand.pyx#L1293" rel="nofollow"><code>np.random.choice</code></a>, you'll see that <code>a</code>, the population, is converted to a numpy array by</p> <pre><code>a = np.array(...
0
2016-07-15T13:28:15Z
[ "python", "arrays", "numpy", "random", "random-seed" ]
Create new record with the self rererenced Foreignkey relation
38,327,496
<p>Below is the my models.py and made a self reference Foreignkey relationship.</p> <pre><code>class emp_details(models.Model): emp_id = models.AutoField(primary_key = True) emp_first_name = models.CharField(max_length = 50,null = False) emp_manager_id = models.ForeignKey('sel...
0
2016-07-12T11:23:49Z
38,327,551
<p>In your case, <code>emp_manager_id</code> is the foreign key field, so you should assign the id to <code>emp_manager_id_id</code>.</p> <pre><code>a1 = emp_details(emp_first_name = "ramesh", emp_manager_id_id=2) </code></pre> <p>It would be better to change the field name to <code>emp_manager</code>. Note it's reco...
1
2016-07-12T11:26:06Z
[ "python", "django", "foreign-key-relationship" ]
Number of rows into a HDF5
38,327,600
<p>there's a method for have the number of rows of a .hdf5 without load it in ram ?</p> <p>I'm using Python 3.4 with pydev on Liclipse (WIndows 10)</p> <p>Thanky you </p>
0
2016-07-12T11:27:48Z
38,357,163
<p>if you use the h5py library, you can simply run <code>len(dataset)</code> or <code>dataset.len()</code> (which is recommended). </p> <p>See <a href="http://docs.h5py.org/en/latest/high/dataset.html?highlight=len#length-and-iteration" rel="nofollow">here</a> for more infos.</p>
1
2016-07-13T16:32:04Z
[ "python", "pydev", "hdf5", "liclipse" ]
Create a matrix made of matrices with different sizes
38,327,610
<p>I want to create a matrix which elements are matrices (with different sizes), vectors and numbers. For example, I have the next two matrices, one vector and one number: </p> <pre><code>A = [1 2 3 4 5 6 7 8 9] B = [10 11 12 13] C = [14 15 16] D = 17 </code></pre> <p>And I would like t...
0
2016-07-12T11:28:07Z
38,330,062
<p>First, store the 4 objects in a 2D list, then make the list into a <code>numpy.matrix</code>.</p> <pre><code>K = matrix([[A, B], [C, D]) </code></pre>
2
2016-07-12T13:18:32Z
[ "python", "numpy", "matrix" ]
Create a matrix made of matrices with different sizes
38,327,610
<p>I want to create a matrix which elements are matrices (with different sizes), vectors and numbers. For example, I have the next two matrices, one vector and one number: </p> <pre><code>A = [1 2 3 4 5 6 7 8 9] B = [10 11 12 13] C = [14 15 16] D = 17 </code></pre> <p>And I would like t...
0
2016-07-12T11:28:07Z
38,335,145
<p>After reading the answers I created a 2D list but I did not use <code>numpy.matrix</code> because with the list I can choose the element of the "matrix" I want. Here the answer: </p> <pre><code>&gt;&gt;&gt; K = [ ] &gt;&gt;&gt; K.append([ ]) &gt;&gt;&gt; K.append([ ]) &gt;&gt;&gt; K[0].append[A] &gt;&gt;&gt; K...
0
2016-07-12T17:10:16Z
[ "python", "numpy", "matrix" ]
How to sum values of particular rows in pandas?
38,327,613
<p>I am not much familiar with Python yet. I have a pandas data frame that looks like this:</p> <pre><code> 0 1 2 3 55 Alice 12896399 8 45 45 Bob 16891982 0 0 90 Cybill 1800407 1 1 05 Alice 12896399 100 200 33 Bob 16891982 0.5 0 42 Bob...
2
2016-07-12T11:28:12Z
38,327,643
<p>IIUC you can <code>groupby</code> and <code>sum</code> on the cols of interest:</p> <pre><code>In [13]: df.groupby('0')[['2','3']].sum() Out[13]: 2 3 0 Alice 108.0 245.0 Bob 0.0 -0.5 Cybill 1.0 1.0 </code></pre>
1
2016-07-12T11:29:57Z
[ "python", "pandas", "sum", "rows" ]
split string without removal of delimiter in python
38,327,668
<p>I need to split a string without removal of delimiter in Python.</p> <p>Eg: </p> <pre><code>content = 'This 1 string is very big 2 i need to split it 3 into paragraph wise. 4 But this string 5 not a formated string.' content = content.split('\s\d\s') </code></pre> <p>After this I am getting like this:</p> <pre>...
2
2016-07-12T11:31:07Z
38,327,893
<p>Why not just store the output, iterate over it, and place your delimiters back where you want them? If the delimiters need to change each time, you could use the index of the loop that you use to iterate to decide what they are/need to be.</p> <p>You might find <a href="http://stackoverflow.com/questions/7866128/py...
0
2016-07-12T11:40:22Z
[ "python", "split" ]
split string without removal of delimiter in python
38,327,668
<p>I need to split a string without removal of delimiter in Python.</p> <p>Eg: </p> <pre><code>content = 'This 1 string is very big 2 i need to split it 3 into paragraph wise. 4 But this string 5 not a formated string.' content = content.split('\s\d\s') </code></pre> <p>After this I am getting like this:</p> <pre>...
2
2016-07-12T11:31:07Z
38,327,923
<p>Use regex module provided by python. by <code>re.sub</code> you can find a regex group and replace it with your desired string. <code>\g&lt;0&gt;</code> is used to use the matched group ( in this case the numbers ).</p> <p>Example:</p> <pre><code>import re content = 'This 1 string is very big 2 i need to split it...
2
2016-07-12T11:41:36Z
[ "python", "split" ]
split string without removal of delimiter in python
38,327,668
<p>I need to split a string without removal of delimiter in Python.</p> <p>Eg: </p> <pre><code>content = 'This 1 string is very big 2 i need to split it 3 into paragraph wise. 4 But this string 5 not a formated string.' content = content.split('\s\d\s') </code></pre> <p>After this I am getting like this:</p> <pre>...
2
2016-07-12T11:31:07Z
38,328,081
<p>You could use <code>re.split</code> with forward lookahead:</p> <pre><code>import re re.split('\s(?=\d\s)',content) </code></pre> <p>resulting in:</p> <pre><code>['This', '1 string is very big', '2 i need to split it', '3 into paragraph wise.', '4 But this string', '5 not a formated string.'] </code></pre> <p>Th...
0
2016-07-12T11:48:53Z
[ "python", "split" ]
split string without removal of delimiter in python
38,327,668
<p>I need to split a string without removal of delimiter in Python.</p> <p>Eg: </p> <pre><code>content = 'This 1 string is very big 2 i need to split it 3 into paragraph wise. 4 But this string 5 not a formated string.' content = content.split('\s\d\s') </code></pre> <p>After this I am getting like this:</p> <pre>...
2
2016-07-12T11:31:07Z
38,328,141
<p>You can try this</p> <pre><code>import re content = 'This 1 string is very big 2 i need to split it 3 into paragraph wise. 4 But this string 5 not a formated string.' [ i.group(0).strip() for i in re.finditer('\S\d?[^\d]+', content)] </code></pre> <p>This one stops matching the string when it reaches a digit, but ...
0
2016-07-12T11:51:56Z
[ "python", "split" ]
split string without removal of delimiter in python
38,327,668
<p>I need to split a string without removal of delimiter in Python.</p> <p>Eg: </p> <pre><code>content = 'This 1 string is very big 2 i need to split it 3 into paragraph wise. 4 But this string 5 not a formated string.' content = content.split('\s\d\s') </code></pre> <p>After this I am getting like this:</p> <pre>...
2
2016-07-12T11:31:07Z
38,328,458
<p>If it is a question of new lines only, then use the string method splitlines() with keepends=True:</p> <pre><code>&gt;&gt;&gt; "This\nis\na\ntest".splitlines(True) ["This\n", "is\n", "a\n", "test"] </code></pre> <p>Otherwise you can:</p> <pre><code>def split (s, d="\n"): d = str(d) if d=="": raise ValueEr...
0
2016-07-12T12:06:25Z
[ "python", "split" ]
Efficient way to extract data within double quotes
38,327,682
<p>I need to extract the data within double quotes from a string.</p> <p>Input:</p> <pre><code>&lt;a href="Networking-denial-of-service.aspx"&gt;Next Page →&lt;/a&gt; </code></pre> <p>Output:</p> <pre><code>Networking-denial-of-service.aspx </code></pre> <p>Currently, I am using following method to do this and i...
1
2016-07-12T11:31:49Z
38,334,125
<p>I am taking the question exactly as written - how to get data between two double quotes. I agree with the comments that an HTMLParser might be better...</p> <p>Using regular expression might help, particularly if you want to find more than one. For example, this is a possible set of code</p> <pre><code>import re s...
0
2016-07-12T16:14:15Z
[ "python", "python-2.7", "beautifulsoup" ]
Efficient way to extract data within double quotes
38,327,682
<p>I need to extract the data within double quotes from a string.</p> <p>Input:</p> <pre><code>&lt;a href="Networking-denial-of-service.aspx"&gt;Next Page →&lt;/a&gt; </code></pre> <p>Output:</p> <pre><code>Networking-denial-of-service.aspx </code></pre> <p>Currently, I am using following method to do this and i...
1
2016-07-12T11:31:49Z
38,339,693
<p>You tagged this beautifulsoup so I don't see why you want a regex, if you want the href from all anchors then you can use a css select <code>'a[href]'</code> which will only find anchor tags that have href attributes:</p> <pre><code>h = '''&lt;a href="Networking-denial-of-service.aspx"&gt;Next Page →&lt;/a&gt;'''...
2
2016-07-12T22:12:19Z
[ "python", "python-2.7", "beautifulsoup" ]
Pytest - run multiple tests from a single file
38,327,684
<p>I'm using Pytest (Selenium) to execute my functional tests. I have the tests split across 2 files in the following structure:</p> <p>My_Positive_Tests.py</p> <pre><code>class Positive_tests: def test_pos_1(): populate_page() check_values() def test_pos_2(): process_entry() validate_result() ...
1
2016-07-12T11:31:53Z
38,327,874
<p>You don't have to run your tests manually. <a href="http://pytest.org/latest/goodpractices.html#choosing-a-test-layout-import-rules" rel="nofollow">Pytest finds and executes them automatically</a>:</p> <pre><code># tests/test_positive.py def test_pos_1(): populate_page() check_values() def test_pos_2(): ...
0
2016-07-12T11:39:43Z
[ "python", "selenium", "py.test" ]
Pytest - run multiple tests from a single file
38,327,684
<p>I'm using Pytest (Selenium) to execute my functional tests. I have the tests split across 2 files in the following structure:</p> <p>My_Positive_Tests.py</p> <pre><code>class Positive_tests: def test_pos_1(): populate_page() check_values() def test_pos_2(): process_entry() validate_result() ...
1
2016-07-12T11:31:53Z
38,351,790
<p>You need to change the class name</p> <pre><code>class Positive_tests: to--&gt; class Test_Positive: </code></pre> <p>The class name should also start with "Test" in order to be discovered by Pytest. If you don't want to use "Test" in front of your class name you can configure that too, official doc <a href="http...
0
2016-07-13T12:29:56Z
[ "python", "selenium", "py.test" ]
Pytest - run multiple tests from a single file
38,327,684
<p>I'm using Pytest (Selenium) to execute my functional tests. I have the tests split across 2 files in the following structure:</p> <p>My_Positive_Tests.py</p> <pre><code>class Positive_tests: def test_pos_1(): populate_page() check_values() def test_pos_2(): process_entry() validate_result() ...
1
2016-07-12T11:31:53Z
38,361,888
<h1>Start file names and tests with either <code>test_</code> or end with <code>_test.py</code>. Classes should begin with <code>Test</code></h1> <p>Directory example:<br> |-- files<br> |--|-- stuff_in stuff<br> |--|--|-- blah.py<br> |--|-- example.py<br> |<br> |-- tests<br> |--|-- stuff_in stuff<br> |--|--|-- test_bl...
0
2016-07-13T21:20:15Z
[ "python", "selenium", "py.test" ]
Can I use %f and %d to format floats and ints to strings in a list?
38,327,803
<p>I am a starter with python ,without any programming experience and here's my question</p> <p>I have a list called n</p> <pre><code>n = [ (1.1,5) , (2.4,7) , (5.4,6) , (9.8,14) , (10,4) ] </code></pre> <p>and I want to create a list which looks like</p> <pre><code>k = [ ('1.1' , {'num' : '5'}) , ('2.4' , {'num'...
4
2016-07-12T11:36:43Z
38,328,009
<p>The numbers are already floats and ints, respectively. Your expected <code>k</code> looks like it converts them to strings. So you can build it that way with a list comprehension:</p> <pre><code>&gt;&gt;&gt; n = [ (1.1,5) , (2.4,7) , (5.4,6) , (9.8,14) , (10,4) ] &gt;&gt;&gt; k = [ (str(x) , {'num': str(y)}) for x,...
3
2016-07-12T11:45:32Z
[ "python", "list", "typeerror" ]
I have too fix something in my Copy&Paste program in Python
38,327,807
<p>This is my Copy&amp;Paste program:</p> <pre><code>from tkinter import * import Pmw class CopyTextWindow(Frame): def __init__(self): Frame.__init__(self) Pmw.initialise() self.pack(expand=YES, fill=BOTH) self.master.title("ScrolledText Demo") self.frame1=Frame(self, bg="W...
0
2016-07-12T11:36:55Z
38,332,075
<p>For a reason I ignore, the event doesn't seem to be triggered when the bind is on the Text or on the Frame, but it works when it's on the main window:</p> <pre><code>from tkinter import * import Pmw class CopyTextWindow(Frame): def __init__(self, master=None): # I've added a master option to pass to th...
1
2016-07-12T14:43:48Z
[ "python", "tkinter", "pmw" ]
Struggling to get a simple function running from command line
38,327,810
<p>I'm trying to get the below function running from the command line by simply using</p> <pre><code>python filename.py </code></pre> <p>However, it isn't doing what I want.</p> <p>Could someone please help me out with this? I'm sure I'm missing something very simple...</p> <pre><code> inFile = "" inFile = raw_inp...
0
2016-07-12T11:37:00Z
38,327,913
<p>There are two problems:</p> <ul> <li>You're opening the file in write mode. This deletes all the contents of the file. Drop the <code>"w"</code> parameter.</li> <li>You can't add strings (as read from the file) to an integer. You need to convert them to integers first: <code>sum += int(i)</code></li> </ul> <p>Also...
5
2016-07-12T11:41:12Z
[ "python", "input", "terminal" ]
Struggling to get a simple function running from command line
38,327,810
<p>I'm trying to get the below function running from the command line by simply using</p> <pre><code>python filename.py </code></pre> <p>However, it isn't doing what I want.</p> <p>Could someone please help me out with this? I'm sure I'm missing something very simple...</p> <pre><code> inFile = "" inFile = raw_inp...
0
2016-07-12T11:37:00Z
38,328,491
<p>A more pythonic version...</p> <pre><code>def line_to_int(line): line = line.strip() if not line: # handles the case of empty lines return 0 return int(line) def sumfile(f): return sum(line_to_int(line) for line in f) if __name__ == "__main__": fname = raw_input("Enter the Fil...
3
2016-07-12T12:07:55Z
[ "python", "input", "terminal" ]
Flask-Restless & Marshmallow: 'dict' object has no attribute '_sa_instance_state'
38,327,857
<p>I'm working on a basic CRUD JSON REST API using Flask-Restless, Flask-SQLAlchemy and Marshmallow.</p> <p>I'm experiencing a problem using this combination of libraries, but only when I enable deserialization using Marshmallow.</p> <p>I've extensively googled the error, however I only find similar issues when using...
0
2016-07-12T11:38:51Z
38,351,120
<p>Turns out I had to add a <code>__tablename__</code> to the model definition and extend the Schema:</p> <pre><code>class CaseSchema(Schema): [...] @post_load def make_case(self, data): return Case(**data) </code></pre>
0
2016-07-13T11:57:45Z
[ "python", "flask", "flask-sqlalchemy", "flask-restless", "marshmallow" ]
Creating new matrix from dataframe and matrix in pandas
38,327,890
<p>I have a dataframe <code>df</code> which looks like this:</p> <pre><code> id1 id2 weights 0 a 2a 144.0 1 a 2b 52.5 2 a 2c 2.0 3 a 2d 1.0 4 a 2e 1.0 5 b 2a 2.0 6 b 2e 1.0 7 b 2f 1.0 8 b 2b 1.0 9 b 2c 0.008 </code></pre> <p>And a similarity m...
0
2016-07-12T11:40:16Z
38,330,329
<p>The following clocks in at 6&ndash;7ms (vs. around 30ms that your approach takes on my machine).</p> <pre><code>import io import pandas as pd raw_df = io.StringIO("""\ id1 id2 weights 0 a 2a 144.0 1 a 2b 52.5 2 a 2c 2.0 3 a 2d 1.0 4 a 2e 1.0 5 b 2a 2.0 6 b 2e ...
1
2016-07-12T13:30:05Z
[ "python", "pandas", "similarity" ]
How can I fix these errors when I run manage.py
38,327,898
<p>I am moving a Python Django project from one server to another server. I am using Debian 7, which has python 2.7.3 installed as standard on the target server (the original server was also using Debian 7). </p> <p>The project I am trying to move has the following directories in it's parent folder: - </p> <pre><code...
2
2016-07-12T11:40:31Z
38,328,027
<p><code>dal</code> means <a href="https://github.com/yourlabs/django-autocomplete-light" rel="nofollow">django-autocomplete-light</a>. May be someone forgot to include this package in requirements. You can also check your INSTALLED_APPS to see if it is actually needed.</p> <p>To install it with pip you should execute...
3
2016-07-12T11:46:05Z
[ "python", "django", "pip", "virtualenv", "django-autocomplete-light" ]
Changing default runtime serverless v1.0
38,327,946
<p>Trying to use serverless v1.0 alpha, but cannot set the runtime variable. I tried setting it in serverless.yaml as:</p> <pre><code>service: want_python provider: aws functions: hello: runtime: python handler: handler.hello </code></pre> <p>But it always shows a runtime of nodejs. I also tried p...
0
2016-07-12T11:42:50Z
38,773,392
<p>Unless it's changed very recently, only Node.js is supported in the alpha. </p> <blockquote> <p>At the moment we only support Node.js in this alpha, but other languages will follow.</p> </blockquote> <p><a href="http://blog.serverless.com/serverless-v1-0-alpha1-announcement/" rel="nofollow">http://blog.serverl...
0
2016-08-04T17:02:34Z
[ "python", "lambda", "serverless-framework" ]
Changing default runtime serverless v1.0
38,327,946
<p>Trying to use serverless v1.0 alpha, but cannot set the runtime variable. I tried setting it in serverless.yaml as:</p> <pre><code>service: want_python provider: aws functions: hello: runtime: python handler: handler.hello </code></pre> <p>But it always shows a runtime of nodejs. I also tried p...
0
2016-07-12T11:42:50Z
39,615,669
<p>Starting with <a href="https://serverless.com/blog/serverless-v1-0-beta-release-1/" rel="nofollow">Serverless v1.0-Beta.1</a> you're already able to use python. </p> <p>You can create a python service this way:</p> <pre><code>sls create -t aws-python </code></pre> <p>Then you'll get a <code>serverless.yml</code> ...
1
2016-09-21T11:45:07Z
[ "python", "lambda", "serverless-framework" ]
Passing several variables from Excel to Python with XLwings
38,328,021
<p>I have the same question as this post but with multiple variable (and with a macro instead of a function) (<a href="http://stackoverflow.com/questions/34167920/passing-a-variable-from-excel-to-python-with-xlwings">Passing a variable from Excel to Python with XLwings</a>)</p> <p>I try this </p> <pre><code>Sub Hello...
0
2016-07-12T11:45:54Z
38,330,438
<p>Your string resolves to a single argument. Fix the single quotes like this:</p> <pre><code>RunPython ("import Test; Test.sayhi('" &amp; Name1 &amp; "' , '" &amp; Name2 &amp; "')" </code></pre>
1
2016-07-12T13:34:35Z
[ "python", "xlwings" ]
How to use dictionary for simpler invocation of attributes
38,328,111
<p>I am exploring composition(has-a relationship) logic in python and for this I have a class <code>Student</code> which has an <code>Address</code> . I am trying to store multiple student records by using student_dict inside Student. I have a <code>GraduateStudent</code> <code>subclass</code>ing <code>Student</code>. ...
0
2016-07-12T11:50:13Z
38,329,579
<p>Just define the details of the classes Student and GraduateStudent as attributes. Each instance can have a unique id by defining a class attribute <code>studentid</code>:</p> <pre><code>class Student(object): studentid = -1 def __init__(self, name, dob): Student.studentid += 1 self.id = ...
2
2016-07-12T12:57:15Z
[ "python", "dictionary", "inheritance" ]
Getting a unique hardware ID with Python
38,328,176
<p>I have a process that requires me to identify different machines, and I'm not sure what's the best way to do it. I do not want to save that ID on a text file or something, but I want to generate it from hardware every time I need it (in case the text with the ID gets deleted or something)</p> <p>I've checked <a hre...
2
2016-07-12T11:53:37Z
38,328,732
<p>You could use <code>dmidecode</code>.</p> <p><strong>Linux:</strong></p> <pre><code>import subprocess def get_id(): return subprocess.Popen('hal-get-property --udi /org/freedesktop/Hal/devices/computer --key system.hardware.uuid'.split()) </code></pre> <p><strong>Windows:</strong><br> NOTE: Requires <a href=...
1
2016-07-12T12:19:55Z
[ "python", "hardware", "uniqueidentifier", "mac-address" ]
Getting a unique hardware ID with Python
38,328,176
<p>I have a process that requires me to identify different machines, and I'm not sure what's the best way to do it. I do not want to save that ID on a text file or something, but I want to generate it from hardware every time I need it (in case the text with the ID gets deleted or something)</p> <p>I've checked <a hre...
2
2016-07-12T11:53:37Z
39,957,437
<p>Please note that you can get the same UUID from Windows without installing any additional software with the following command:</p> <pre><code>C:\&gt; wmic csproduct get uuid </code></pre>
1
2016-10-10T11:40:35Z
[ "python", "hardware", "uniqueidentifier", "mac-address" ]
Getting a unique hardware ID with Python
38,328,176
<p>I have a process that requires me to identify different machines, and I'm not sure what's the best way to do it. I do not want to save that ID on a text file or something, but I want to generate it from hardware every time I need it (in case the text with the ID gets deleted or something)</p> <p>I've checked <a hre...
2
2016-07-12T11:53:37Z
40,075,369
<p>For windows this seems to get same uuid every time por each device based on the MAC address: </p> <p>str(uuid.uuid1(uuid.getnode(),0))[24:]</p> <p>But it does not seem to keep same ID on Android 4.4.2.</p>
0
2016-10-16T20:55:14Z
[ "python", "hardware", "uniqueidentifier", "mac-address" ]
Calling coroutine from coroutine in python
38,328,185
<p>I came across this issue today and I'm not quite certain why it works like this:</p> <pre><code>def outside(): print 'before' inside() print 'after' yield 'World' def inside(): print 'inside' yield 'Hello' for n in outside(): print n </code></pre> <p>(Naive) expectation of output:</p>...
1
2016-07-12T11:53:51Z
38,328,469
<p>It is totally possible. when you call <code>inside()</code> it <em>creates</em> a coroutine. In order to yield the result, you need to initialize the coroutine and yield from it as follows:</p> <pre><code>def outside(): print 'before' for i in inside(): yield i print 'after' yield 'Worl...
2
2016-07-12T12:07:08Z
[ "python", "python-2.7" ]
Packing a rectangle with equal sized circles python
38,328,194
<p>I have a rectangular bounding box defined by width <code>w</code> and height <code>h</code> and area <code>A</code>.</p> <p>How can we pack <code>n</code> number of circles of equal area <code>a</code> inside this rectangle such that <code>A-n*a</code> is minimal. </p> <p>In other words, how can we calculate the o...
1
2016-07-12T11:54:07Z
38,328,292
<p><strong>Edit</strong>: Edited to help the OP get a number that can help in deciding the number of k-means clusters based on fitting circles in a plane and minimizing the uncovered places.</p> <pre><code>from math import sqrt, pi def get_approximate_k(rectangle_area, circle_area): # Making use of the fact that ...
1
2016-07-12T11:59:00Z
[ "python" ]
Counting Unique Values of Categories of Column Given Condition on other Column
38,328,213
<p>I have a data frame where the rows represent a transaction done by a certain user. Note that more than one row can have the same user_id. Given the column names <strong>gender</strong> and <strong>user_id</strong> running:</p> <pre><code>df.gender.value_counts() </code></pre> <p>returns the frequencies but they ar...
1
2016-07-12T11:55:08Z
38,328,624
<p>You want to use panda's <code>groupby</code> on your dataframe:</p> <pre><code>users = {'A': 'male', 'B': 'female', 'C': 'female'} ul = [{'id': k, 'gender': users[k]} for _ in range(50) for k in random.choice(users.keys())] df = pd.DataFrame(ul) print(df.groupby('gender')['id'].nunique()) </code></pre> <p>This yi...
2
2016-07-12T12:14:05Z
[ "python", "pandas" ]
Counting Unique Values of Categories of Column Given Condition on other Column
38,328,213
<p>I have a data frame where the rows represent a transaction done by a certain user. Note that more than one row can have the same user_id. Given the column names <strong>gender</strong> and <strong>user_id</strong> running:</p> <pre><code>df.gender.value_counts() </code></pre> <p>returns the frequencies but they ar...
1
2016-07-12T11:55:08Z
38,330,474
<p>I agree with the first post but just to make the groupby simpler:</p> <pre><code>df.groupby('user_id').first().count() will give you counts of each variable </code></pre> <p>or alternatively:</p> <pre><code>pd.value_counts(df.groupby('user_id').first().reset_index().gender) </code></pre>
0
2016-07-12T13:35:29Z
[ "python", "pandas" ]
Remove a nested list if any of multiple values is found
38,328,242
<p>I have a list of lists and I'd like to remove all nested lists which contain any of multiple values.</p> <pre><code>list_of_lists = [[1,2], [3,4], [5,6]] indices = [i for i,val in enumerate(list_of_lists) if (1,6) in val] print(indices) [0] </code></pre> <p>I'd like a lists of indices where this conditions is so ...
1
2016-07-12T11:56:36Z
38,328,333
<p>You could use a set operation:</p> <pre><code>if not {1, 6}.isdisjoint(val) </code></pre> <p>A set is disjoint if none of the values appear in the other sequence or set:</p> <pre><code>&gt;&gt;&gt; {1, 6}.isdisjoint([1, 2]) False &gt;&gt;&gt; {1, 6}.isdisjoint([3, 4]) True </code></pre> <p>Or just test both valu...
3
2016-07-12T12:00:48Z
[ "python", "python-3.x", "list-comprehension", "nested-lists" ]
Find fileS and then find a string in those files
38,328,273
<p>I have written a function that finds all of the version.php files in a path. I am trying to take the output of that function and find a line from that file. The function that finds the files is:</p> <pre><code>def find_file(): for root, folders, files in os.walk(acctPath): for file in files: if file =...
0
2016-07-12T11:58:06Z
38,328,861
<p>Since you want to use the output of your function, you have to <code>return</code> something. Printing it does not cut it. Assuming everything works it has to be slightly modified as follows:</p> <pre><code>import os def find_file(): for root, folders, files in os.walk(acctPath): for file in files: ...
0
2016-07-12T12:25:56Z
[ "python", "wordpress", "content-management-system", "cpanel" ]
dateutils rrule returns dates that 2 months apart
38,328,313
<p>I am new to Python and also <code>dateutil</code> module. I am passing the following arguments:</p> <pre><code>disclosure_start_date = resultsDict['fd_disclosure_start_date'] disclosure_end_date = datetime.datetime.now() disclosure_dates = [dt for dt in rrule(MONTHLY, dtstart=disclosure_start_date, until=disclosure...
1
2016-07-12T11:59:42Z
38,555,283
<p>The issue you are coming up against comes from the fact that <code>datetime.datetime(2012, 10, 31, 0, 0)</code> is the 31st of the month, and not all months have a 31st. Since the <code>rrule</code> module is an implementation of RFC 2445. Per RFC 3.3.10:</p> <blockquote> <p>Recurrence rules may generate recurren...
1
2016-07-24T18:21:39Z
[ "python", "date", "datetime", "python-dateutil", "rrule" ]
REGEX to make string start from specific point
38,328,338
<p>I have to split a string using regular expressions: say <code>Nikolaus Kopernikus -&gt; 1473-1543</code></p> <p>I tried the following, but it only gives me a list without <code>-&gt;</code></p> <p>What I need is the years 1473-1543, preferably in list <code>['1473','1543']</code></p> <pre><code>import re print (...
0
2016-07-12T12:01:09Z
38,328,394
<p>Use <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>str.split</code></a>:</p> <pre><code>'Nikolaus Kopernikus -&gt; 1473-1543'.split('-&gt;')[1].strip().split('-') # ['1473', '1543'] </code></pre> <p>From the docs:</p> <blockquote> <p>Return a list of the words in the st...
2
2016-07-12T12:03:36Z
[ "python", "python-2.7", "python-3.x" ]
REGEX to make string start from specific point
38,328,338
<p>I have to split a string using regular expressions: say <code>Nikolaus Kopernikus -&gt; 1473-1543</code></p> <p>I tried the following, but it only gives me a list without <code>-&gt;</code></p> <p>What I need is the years 1473-1543, preferably in list <code>['1473','1543']</code></p> <pre><code>import re print (...
0
2016-07-12T12:01:09Z
38,330,334
<p>If you want to use a regular expression:</p> <pre><code>import re re.match('.*-&gt;[^\d]*(\d+)-(\d+)','Nikolaus Kopernikus -&gt; 1473-1543').groups() #output: ('1473', '1543') </code></pre> <p>If you need a list instead of a tuple use the <code>list</code> function.</p>
2
2016-07-12T13:30:10Z
[ "python", "python-2.7", "python-3.x" ]
Python - Run function with parameters in command line
38,328,340
<p>Is it possible to run a python script with parameters in command line like this:</p> <pre><code>./hello(var=True) </code></pre> <p>or is it mandatory to do like this:</p> <pre><code>python -c "from hello import *;hello(var=True)" </code></pre> <p>The first way is shorter and simpler.</p>
0
2016-07-12T12:01:11Z
38,329,168
<p>Most shells use parentheses for grouping or sub-shells. So you can't call any commands like <code>command(arg)</code> from a normal shell ...but you can write a python script (./hello.py) that takes an argument.</p> <pre><code>import optparse parser = optparse.OptionParser() parser.add_option('-f', dest="f", action...
0
2016-07-12T12:39:13Z
[ "python", "command-line" ]