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
How to remove brackets from RDD output?
39,430,416
<p>When I print an RDD I get the following result:</p> <pre><code>[(46, u'15910'), (43, u'15287'), (43, u'15237'), (42, u'15923'), (41, u'15298')] </code></pre> <p>I want to save the RDD output to a csv file without brackets or the 'u' sign, similar to below:</p> <pre><code>46, 15910 43, 15287 43, 15237 42, 15923 41, 15298 </code></pre>
0
2016-09-10T20:43:25Z
39,430,739
<p>Either write csv:</p> <pre><code>&gt;&gt;&gt; rdd.toDF().write.csv("path") </code></pre> <p>or format:</p> <pre><code>&gt;&gt;&gt; rdd.map(lambda (k, v): "{0},{1}".format(k, v)).saveAsTextFile("path") </code></pre>
3
2016-09-10T21:29:31Z
[ "python", "apache-spark", "pyspark", "rdd" ]
Why is my function that I made getting the TypeError: f() takes 0 positional arguments but 1 was given
39,430,440
<p>I am working with pandas DataFrames and I am adding new columns for more advanced analysis. My f function is giving me an error TypeError: f() takes 0 positional arguments but 1 was given. I can't figure out why, I have my f function documented in the code if you need to know what it does. </p> <pre><code>from pandas_datareader import data as dreader import pandas as pd from datetime import datetime import dateutil.parser # Sets the max rows that can be displayed # when the program is executed pd.options.display.max_rows = 200 # df is the name of the dataframe, it is # reading the csv file containing date loaded # from yahoo finance(Date,Open,High,Low,Close # volume,adj close,)the name of the ticker # is placed before _data.csv i.e. the ticker aapl # would have a csv file named aapl_data.csv. df = pd.read_csv("cde_data.csv") # the following code will allow for filtering of the datafram # based on the year, day of week (dow), and month. It then gets # applied to the dataframe and then can be used to sort data i.e # print(df[(df.year == 2015) &amp; (df.month == 5) &amp; (df.dow == 4)]) # which will give you all the days in the month of May(df.month == 5), # that fall on a Thursday(df.dow == 4), in the year 2015 # (df.year == 2015) # # Month Day Year # January = 1 Monday = 1 The year will be dispaly in a four # February = 2 Tuesday = 2 digit format i.e. 2015 # March = 3 Wednesday = 3 # April = 4 Thursday = 4 # May = 5 Friday = 5 # June = 6 # July = 7 # August = 8 # September = 9 # October = 10 # November = 11 # December = 12 def year(x): return(x.year) def dow(x): return(x.isoweekday()) def month(x): return(x.month) # f is a function that checks to see if the up_down column # has a value that is greater than, less than, or equal to # zero. The value in the up_down column is derived from # subtracting the opening price of the stock(open column) # from closing price of the stock(close column). If up_down # has a negative value than the stocks price was Down, a positive # value then Up, and no change is Flat def f(): if up_down &gt; 0: x = Up elif up_down &lt; 0: x = Down else: x = Flat return (f) df.reset_index() df.Date = df.Date.apply(dateutil.parser.parse) df['year'] = df.Date.apply(year) df['dow'] = df.Date.apply(dow) df['month'] = df.Date.apply(month) df['up_down'] = df['Close'] - df['Open'] df['up_down_flat'] = df.up_down.apply(f) df2= (df[(df.year &gt; 1984) &amp; (df.month == 5) &amp; (df.dow == 1)]) print (df2) </code></pre> <p>This is the error</p> <pre><code>Traceback (most recent call last): File "dframt1est.py", line 77, in &lt;module&gt; df['up_down_flat'] = df.up_down.apply(f) File "C:\Users\Zac\AppData\Local\Programs\Python\Python35-32\lib\site-packages\pandas\core\series.py", line 2220, in apply mapped = lib.map_infer(values, f, convert=convert_dtype) File "pandas\src\inference.pyx", line 1088, in pandas.lib.map_infer (pandas\lib.c:63043) TypeError: f() takes 0 positional arguments but 1 was given Press any key to continue . . . </code></pre> <p>This a sample csv</p> <pre><code> Date Open High Low Close Volume Adj Close \ 0 1990-04-12 26.875000 26.875000 26.625 26.625 6100 250.576036 1 1990-04-16 26.500000 26.750000 26.375 26.750 500 251.752449 2 1990-04-17 26.750000 26.875000 26.750 26.875 2300 252.928863 3 1990-04-18 26.875000 26.875000 26.500 26.625 3500 250.576036 4 1990-04-19 26.500000 26.750000 26.500 26.750 700 251.752449 5 1990-04-20 26.750000 26.875000 26.750 26.875 2100 252.928863 6 1990-04-23 26.875000 26.875000 26.750 26.875 700 252.928863 7 1990-04-24 27.000000 27.000000 26.000 26.000 2400 244.693970 8 1990-04-25 25.250000 25.250000 24.875 25.125 9300 236.459076 </code></pre>
2
2016-09-10T20:46:38Z
39,430,538
<p>You're passing <code>f</code> as the function in <code>apply</code>. That function is called for each row in the dataframe, and needs to take the row as its parameter.</p> <p>Note also that you're returning the function itself as the result; I'm pretty sure you meant to return <code>x</code> not <code>f</code>. Also, you don't seem to have defined <code>Up</code>, <code>Down</code> and <code>Flat</code> anywhere.</p>
4
2016-09-10T21:02:02Z
[ "python", "pandas", "if-statement", "dataframe" ]
storing serialized data in postgres by SQLAlchemy
39,430,466
<p>I am building an App by using Flask with Postgress and SQLAlchemy. There is a table column where I need to store serialized data (JSON). How do I define the field in the model class? </p> <p>Can I just use string field for the column?</p> <pre><code>from flask.ext.sqlalchemy import SQLAlchemy from main import app db = SQLAlchemy(app) class Fame (db.Model): __tablename__ = "toto" id = db.Column('id', db.Integer, primary_key=True) data = db.Column('data', db.JSON) creation_date = db.Column('creation_date', db.Date, default=datetime.utcnow) </code></pre> <p>But I got this error:</p> <blockquote> <p>AttributeError: 'SQLAlchemy' object has no attribute 'JSON'</p> </blockquote>
0
2016-09-10T20:50:37Z
39,430,915
<p>You need to import <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSON" rel="nofollow"><code>JSON</code></a> or <a href="http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSONB" rel="nofollow"><code>JSONB</code></a> from <code>sqlalchemy.dialects.postgresql</code></p>
0
2016-09-10T21:50:18Z
[ "python", "json", "postgresql", "sqlalchemy", "flask-sqlalchemy" ]
Pick random coordinates in Numpy array based on condition
39,430,572
<p>I have used convolution2d to generate some statistics on conditions of local patterns. To be complete, I'm working with images and the value 0.5 is my 'gray-screen', I cannot use masks before this unfortunately (dependence on some other packages). I want to add new objects to my image, but it should overlap at least 75% of non-gray-screen. Let's assume the new object is square, I mask the image on gray-screen versus the rest, do a 2-d convolution with a n by n matrix filled with 1s so I can get the sum of the number of gray-scale pixels in that patch. This all works, so I have a matrix with suitable places to place my new object. How do I efficiently pick a random one from this matrix?</p> <p>Here is a small example with a 5x5 image and a 2x2 convolution matrix, where I want a random coordinate in my last matrix with a 1 (because there is at most 1 0.5 in that patch)</p> <p>Image:</p> <pre><code>1 0.5 0.5 0 1 0.5 0.5 0 1 1 0.5 0.5 1 1 0.5 0.5 1 0 0 1 1 1 0 0 1 </code></pre> <p>Convolution matrix:</p> <pre><code>1 1 1 1 </code></pre> <p>Convoluted image:</p> <pre><code>3 3 1 0 4 2 0 1 3 1 0 1 1 0 0 0 </code></pre> <p>Conditioned on &lt;= 1:</p> <pre><code>0 0 1 1 0 0 1 1 0 1 1 1 1 1 1 1 </code></pre> <p>How do I get a uniformly distributed coordinate of the 1s efficiently?</p>
2
2016-09-10T21:06:19Z
39,430,720
<p><code>np.where</code> and <code>np.random.randint</code> should do the trick :</p> <pre><code>#we grab the indexes of the ones x,y = np.where(convoluted_image &lt;=1) #we chose one index randomly i = np.random.randint(len(x)) random_pos = [x[i],y[i]] </code></pre>
2
2016-09-10T21:27:25Z
[ "python", "numpy" ]
Python: Can't decode a json string
39,430,752
<pre><code>import json from gfycat.client import GfycatClient client = GfycatClient() r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard") robject = json.loads(r) print robject['gifUrl'] </code></pre> <p>This is my current source code. It's meant to get a gifurl in the json text, but it just doesn't. If I don't use robject I get KeyError: 'gifUrl'and if I do use the above code I get some generic errors. </p>
-1
2016-09-10T21:30:53Z
39,430,790
<p><code>gifUrl</code> is inside <code>gfyItem</code>, so you should try <code>robject['gfyItem']['gifUrl']</code></p>
0
2016-09-10T21:35:04Z
[ "python", "json", "decode" ]
Python: Can't decode a json string
39,430,752
<pre><code>import json from gfycat.client import GfycatClient client = GfycatClient() r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard") robject = json.loads(r) print robject['gifUrl'] </code></pre> <p>This is my current source code. It's meant to get a gifurl in the json text, but it just doesn't. If I don't use robject I get KeyError: 'gifUrl'and if I do use the above code I get some generic errors. </p>
-1
2016-09-10T21:30:53Z
39,430,792
<pre><code>import json from gfycat.client import GfycatClient client = GfycatClient() r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard") print r['gfyItem']['gifUrl'] </code></pre>
-1
2016-09-10T21:35:09Z
[ "python", "json", "decode" ]
Python: Can't decode a json string
39,430,752
<pre><code>import json from gfycat.client import GfycatClient client = GfycatClient() r = client.query_gfy("CandidOffensiveAfricanaugurbuzzard") robject = json.loads(r) print robject['gifUrl'] </code></pre> <p>This is my current source code. It's meant to get a gifurl in the json text, but it just doesn't. If I don't use robject I get KeyError: 'gifUrl'and if I do use the above code I get some generic errors. </p>
-1
2016-09-10T21:30:53Z
39,430,837
<p>Your JSON sample is invalid with multiple different errors. Run it through the JSON validator linked below to get a detailed list.</p> <p><a href="https://jsonformatter.curiousconcept.com/" rel="nofollow">https://jsonformatter.curiousconcept.com/</a></p>
0
2016-09-10T21:40:19Z
[ "python", "json", "decode" ]
Use metaclass to allow forward declarations
39,430,798
<p>I want to do something decidedly unpythonic. I want to create a class that allows for forward declarations of its class attributes. (If you must know, I am trying to make some sweet syntax for parser combinators.)</p> <p>This is the kind of thing I am trying to make:</p> <pre><code>a = 1 class MyClass(MyBaseClass): b = a # Refers to something outside the class c = d + b # Here's a forward declaration to 'd' d = 1 # Declaration resolved </code></pre> <p>My current direction is to make a metaclass so that when <code>d</code> is not found I catch the <code>NameError</code> exception and return an instance of some dummy class I'll call <code>ForwardDeclaration</code>. I take some inspiration from <a href="https://bugs.python.org/issue26988" rel="nofollow"><code>AutoEnum</code></a>, which uses metaclass magic to declare enum values with bare identifiers and no assignment.</p> <p>Below is what I have so far. The missing piece is: how do I continue normal name resolution and catch the <code>NameError</code>s:</p> <pre><code>class MetaDict(dict): def __init__(self): self._forward_declarations = dict() def __getitem__(self, key): try: ### WHAT DO I PUT HERE ??? ### # How do I continue name resolution to see if the # name already exists is the scope of the class except NameError: if key in self._forward_declarations: return self._forward_declarations[key] else: new_forward_declaration = ForwardDeclaration() self._forward_declarations[key] = new_forward_declaration return new_forward_declaration class MyMeta(type): def __prepare__(mcs, name, bases): return MetaDict() class MyBaseClass(metaclass=MyMeta): pass class ForwardDeclaration: # Minimal behavior def __init__(self, value=0): self.value = value def __add__(self, other): return ForwardDeclaration(self.value + other) </code></pre>
2
2016-09-10T21:36:08Z
39,431,036
<p>To start with:</p> <pre><code> def __getitem__(self, key): try: return super().__getitem__(key) except KeyError: ... </code></pre> <p>But that won't allow you to retrieve the global variables outside the class body. You can also use the <code>__missin__</code> method which is reserved exactly for subclasses of dict:</p> <pre><code>class MetaDict(dict): def __init__(self): self._forward_declarations = dict() # Just leave __getitem__ as it is on "dict" def __missing__(self, key): if key in self._forward_declarations: return self._forward_declarations[key] else: new_forward_declaration = ForwardDeclaration() self._forward_declarations[key] = new_forward_declaration return new_forward_declaration </code></pre> <p>As you can see, that is not that "UnPythonic" - advanced Python stuff such as SymPy and SQLAlchemy have to resort to this kind of behavior to do their nice magic - just be sure to get it very well documented and tested.</p> <p>Now, to allow for global (module) variables, you have a to get a little out of the way - and possibly somthing that may not be avaliablein all Python implementations - that is: introspecting the frame where the class body is to get its globals:</p> <pre><code>import sys ... class MetaDict(dict): def __init__(self): self._forward_declarations = dict() # Just leave __getitem__ as it is on "dict" def __missing__(self, key): class_body_globals = sys._getframe().f_back.f_globals if key in class_body_globals: return class_body_globals[key] if key in self._forward_declarations: return self._forward_declarations[key] else: new_forward_declaration = ForwardDeclaration() self._forward_declarations[key] = new_forward_declaration return new_forward_declaration </code></pre> <p>Now that you are here - your special dictionaries are good enough to avoid NameErrors, but your <code>ForwardDeclaration</code> objects are far from smart enough - when running:</p> <pre><code>a = 1 class MyClass(MyBaseClass): b = a # Refers to something outside the class c = d + b # Here's a forward declaration to 'd' d = 1 </code></pre> <p>What happens is that <code>c</code> becomes a <code>ForwardDeclaration</code> object, but summed to the instant value of <code>d</code> which is zero. On the next line, <code>d</code> is simply overwritten with the value <code>1</code> and is no longer a lazy object. So you might just as well declare <code>c = 0 + b</code> . </p> <p>To overcome this, <code>ForwardDeclaration</code> has to be a class designed in a smartway, so that its values are always lazily evaluated, and it behaves as in the "reactive programing" approach: i.e.: updates to a value will cascade updates into all other values that depend on it. I think giving you a full implementation of a working "reactive" aware FOrwardDeclaration class falls off the scope of this question. - I have some toy code to do that on github at <a href="https://github.com/jsbueno/python-react" rel="nofollow">https://github.com/jsbueno/python-react</a> , though.</p> <p>Even with a proper "Reactive" ForwardDeclaration class, you have to fix your dictionary again so that the <code>d = 1</code> class works:</p> <pre><code>class MetaDict(dict): def __init__(self): self._forward_declarations = dict() def __setitem__(self, key, value): if key in self._forward_declarations: self._forward_declations[key] = value # Trigger your reactive update here if your approach is not # automatic return None return super().__setitem__(key, value) def __missing__(self, key): # as above </code></pre> <p>And finally, there is a way to avoid havign to implement a fully reactive aware class - you can resolve all pending FOrwardDependencies on the <code>__new__</code> method of the metaclass - (so that your ForwardDeclaration objects are manually "frozen" at class creation time, and no further worries - )</p> <p>Something along:</p> <pre><code>from functools import reduce sentinel = object() class ForwardDeclaration: # Minimal behavior def __init__(self, value=sentinel, dependencies=None): self.dependencies = dependencies or [] self.value = value def __add__(self, other): if isinstance(other, ForwardDeclaration): return ForwardDeclaration(dependencies=self.dependencies + [self]) return ForwardDeclaration(self.value + other) class MyMeta(type): def __new__(metacls, name, bases, attrs): for key, value in list(attrs.items()): if not isinstance(value, ForwardDeclaration): continue if any(v.value is sentinel for v in value.dependencies): continue attrs[key] = reduce(lambda a, b: a + b.value, value.dependencies, 0) return super().__new__(metacls, name, bases, attrs) def __prepare__(mcs, name, bases): return MetaDict() </code></pre> <p>And, depending on your class hierarchy and what exactly you are doing, rememebr to also update one class' dict <code>_forward_dependencies</code> with the <code>_forward_dependencies</code> created on its ancestors. AND if you need any operator other than <code>+</code>, as you will have noted, you will have to keep information on the operator itself - at this point, hou might as well jsut use <code>sympy</code>. </p>
1
2016-09-10T22:09:25Z
[ "python", "python-3.x", "metaclass" ]
How to detect screen rotation on Android in Kivy?
39,430,824
<p>I have been searching for a Kivy solution to capture the Android device rotation from one orientation to another. I have tried both of the window methods below but neither executes the <code>on_rotate</code> or <code>rotate_screen</code> routines when I rotate the device. I see there is an <code>onConfigurationChanged</code> event in java but I can't find the same event handling for Kivy.</p> <pre><code> Window.on_rotate(self.on_rotate) Window.bind(on_rotate=self.rotate_screen) </code></pre> <p>What I do get in the logcat is the following messages indicating the device has rotated but my app never see these events.</p> <pre><code>I/InputReader(270): Reconfiguring input devices. changes=0x00000004 I/InputReader(270): Device reconfigured: id=3, name='ilitek_i2c', surface size is now 1280x800, mode is 1 I/ActivityManager(270): Config changed: {1.0 0mcc0mnc en_US sw800dp w1280dp h752dp xlrg land finger -keyb/v/h -nav/h s.8} </code></pre>
2
2016-09-10T21:38:43Z
39,431,581
<p>I think on_rotate only tracks Kivy's internal rotation (this is done in OpenGL and doesn't relate to the Android level rotation).</p> <p>You can probably use pyjnius to work with the normal Java methods for this, but I don't know the details. A simple solution that may work just as well is to watch <code>Window.size</code> (<code>from kivy.core.window import Window</code>) - this should detect the change from portrait to landscape.</p>
0
2016-09-10T23:44:48Z
[ "android", "python", "rotation", "kivy", "onconfigurationchanged" ]
subprocess.call and ending current program
39,430,972
<p>My main program checks if a new version of itself is available and if so it downloads the new installer file and runs it: <code>subprocess.call(["installer.exe"], shell=True)</code> But in order to overwrite the old files, it needs to exit itself after calling the subprocess. How can I achieve this?</p>
3
2016-09-10T21:58:36Z
39,431,001
<p>In Windows, just <code>start</code> your installer program instead of waiting for it.</p> <pre><code>import subprocess subprocess.call(["start","installer.exe"],shell=True) print("out") </code></pre> <p>Running this will print <code>out</code> immediately and returns to the console if this is the last statement (or call <code>sys.exit()</code>)</p>
2
2016-09-10T22:02:59Z
[ "python", "subprocess" ]
Why GridSearchCV return score so different from the score returned by running model directly?
39,430,998
<p>I used GridSearchCV to find the best alpha for lasso model.</p> <pre><code>alphas = np.logspace(-5, 2, 30) grid = GridSearchCV(estimator=Lasso(), param_grid=dict(alpha=alphas), cv=10, scoring='r2') grid.fit(self.X, self.Y) # entire datasets were fed here print grid.best_params_, grid.best_score_ # score -0.0470788758558 for params, mean_score, scores in grid.grid_scores_: print mean_score, params </code></pre> <p>I got the best parameter as 0.0014873521072935117, with negative r2 score -0.0470788758558.</p> <hr> <p>Then I tried this alpha on the model directly. I ran the following code in a loop.</p> <pre><code>X_train, X_test, y_train, y_test = train_test_split(self.X, self.Y, train_size=0.7) lasso = Lasso(alpha=0.001487) lasso.fit(X_train, y_train) print lasso.score(X_test, y_test) </code></pre> <p>Notice that I didn't set the random state, so it should work as a cross-validation. But the score I got here is around 0.11 (0.11-0.12) not matter how many times I ran the code.</p> <hr> <p><strong>Question</strong></p> <p>Why are the scores -0.0470788758558 and 0.11 so different for the two approaches? </p>
1
2016-09-10T22:02:45Z
39,438,123
<p>I found the reason. </p> <p>cv should be set like this:</p> <pre><code>cv = ShuffleSplit(n=len(X), n_iter=10, test_size=.3) </code></pre> <p>when cv equals to integer, it means how many folds there are in each iteration not the number of iterations. </p>
0
2016-09-11T16:13:43Z
[ "python", "scikit-learn", "linear-regression", "grid-search", "lasso" ]
How do I use a different index for each row in a numpy array?
39,431,085
<p>I have a NxM numpy array filled with zeros and a 1D numpy array of size N with random integers between 0 to M-1. As you can see the dimension of the array matches the number of rows in the matrix. Each element in the integer array means that at that given position in its corresponding row must be set to 1. For example:</p> <pre><code># The matrix to be modified a = np.zeros((2,10)) # Indices array of size N indices = np.array([1,4]) # Indexing, the result must be a = a[at indices per row] print a [[0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0]] </code></pre> <p>I tried using the indexing <code>a[:,indices]</code> but this sets the same indices for each row, and this finally sets all the rows with ones. How can I set the given index to 1 <strong>per row</strong>?</p>
2
2016-09-10T22:18:20Z
39,431,109
<p>Use <code>np.arange(N)</code> in order to address the rows and indices for columns:</p> <pre><code>&gt;&gt;&gt; a[np.arange(2),indices] = 1 &gt;&gt;&gt; a array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]]) </code></pre> <p>Or:</p> <pre><code>&gt;&gt;&gt; a[np.where(indices)+(indices,)] = 1 &gt;&gt;&gt; a array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.]]) </code></pre>
2
2016-09-10T22:22:36Z
[ "python", "arrays", "numpy", "matrix-indexing" ]
Updating label keeps previous text
39,431,091
<p>In the program I made, the user presses enter and the text typed is then shown as a label in the program. So the label keeps getting updated and then written on the next line. The problem is that in the textbox the previous line the user typed stays there, which means u have to keep manually deleting the string in the textbox to write a new line. How can I make it so that you start out with a cleared textbox? Also, the enter button works but it seems that when i click on the "Return" button it gives me an error:</p> <p>TypeError: evaluate() missing 1 required positional argument: 'event'</p> <p>Here's the code:</p> <pre><code>from tkinter import * window = Tk() window.geometry("200x300") def evaluate(event): thetext = StringVar() labeloutput = Label(app, textvariable = thetext) n = e.get() thetext.set(n) labeloutput.grid() app = Frame(window) app.pack() e = Entry(window) e.pack() b= Button(window, text="Return", command=evaluate) b.pack() window.bind("&lt;Return&gt;", evaluate) mainloop() </code></pre>
-1
2016-09-10T22:19:36Z
39,431,135
<p>Since you bind <code>evaluate</code> as a callback and you use it as a button command, when you use it in the button you have to use a lambda and pass <code>None</code> to the event. <code>event</code> argument is needed because of the binding, but there is no event when you call it from button click, so just pass <code>None</code> to get rid of the error. You can delete by doing <code>entry.delete(0, 'end')</code>.</p> <pre><code>from tkinter import * window = Tk() window.geometry("200x300") def evaluate(event): thetext = StringVar() labeloutput = Label(app, textvariable = thetext) n = e.get() thetext.set(n) labeloutput.grid() e.delete(0, 'end') # Here we remove text inside the entry app = Frame(window) app.pack() e = Entry(window) e.pack() b = Button(window, text="Return", command=lambda: evaluate(None)) # Here we have a lambda to pass None to the event b.pack() window.bind("&lt;Return&gt;", evaluate) mainloop() </code></pre> <p>Of course, if you want to prevent the lambda from being used, you would have to create a function to handle the key binding, and a separate one for the button click.</p>
1
2016-09-10T22:26:59Z
[ "python", "python-3.x", "tkinter", "event-handling", "label" ]
Unable to remove objects from a list in another object
39,431,106
<p>Here is some test code to describe my problem. I have created two classes as follows...</p> <pre><code>class Card: def __init__(self, suit, rank): self.suit = suit self.rank = rank class Deck: def __init__(self): self.cards = [] for suit in range(4): for rank in range(13): card = Card(suit, rank) self.cards.append(card) d = Deck() d.cards.remove(Card(1, 1)) </code></pre> <p>After the last remove command, I get the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#111&gt;", line 1, in &lt;module&gt; d.cards.remove(Card(1, 1)) ValueError: list.remove(x): x not in list </code></pre> <p>Does anyone know why this is occurring? I can confirm the d object gets initialized with 52 total Card objects from (0, 0) to (3, 13). Why does it not detect this with the remove module? Furthermore, I can do the following commands after the initialization and it works with no problem.</p> <pre><code>d.cards.append(Card(1, 1)) d.cards.remove(Card(1, 1)) </code></pre> <p>This adds and then remove the Card that was just added to the list, but it will not remove the card that was initialized with the same value.</p>
3
2016-09-10T22:22:07Z
39,431,119
<p>You didn't define when two <code>Card</code> instances are equal. Without such a definition, <code>list.remove()</code> can't find anything that is equal (<code>obj1 == obj2</code> is true). The default implementation for custom classes is to be equal only when the object is <em>identical</em> (the exact same object, <code>reference1 is reference2</code> is true).</p> <p>Add an <a href="https://docs.python.org/3/reference/datamodel.html#object.__eq__" rel="nofollow"><code>__eq__</code> method</a> to your class to define what equality means for <code>Card</code> instances.</p> <p>For example, if two <code>Card</code> instances are equal if and when both <code>rank</code> and <code>suit</code> are equal, then implement that test:</p> <pre><code>def __eq__(self, other): if not isinstance(other, Card): return NotImplemented return self.rank == other.rank and self.suit == other.suit </code></pre> <p>Now <code>list.remove()</code> can find the first object that tests equal to the one you passed in to that method.</p> <p>Note that:</p> <pre><code>d.cards.append(Card(1, 1)) d.cards.remove(Card(1, 1)) </code></pre> <p><em>can't work</em> without <code>__eq__</code> defined. That code creates two separate instances, and without a custom <code>__eq__</code> method two separate instances never test as equal.</p> <p>You most likely did this instead:</p> <pre><code>card = Card(1, 1) d.cards.append(card) d.cards.remove(card) </code></pre> <p>because only then would the object test as equal; it is, after all, <em>the same object</em>.</p>
5
2016-09-10T22:24:23Z
[ "python" ]
Does the position of python import statements affect performance
39,431,169
<p>I was wondering if the position of import statements in a python program has any affect on performance. For example if I have this</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 import json import requests from flask import render_template, request, Flask, session, Markup, jsonify, send_from_directory from wit import Wit from os import urandom from datetime import datetime from uuid import uuid1 from random import choice from FAAWrapper import FAA_API from bs4 import BeautifulSoup def function1(): from OpenSSL import SSL from fuzzywuzzy import process continue def function2(): continue </code></pre> <p>Would performance be adversely affected by calling function1() being that function1 contains import statements? Should all of my imports be placed at the top or does the import only happen once the first time the function is called? </p>
0
2016-09-10T22:32:24Z
39,431,201
<p>Importing does <em>two</em> things:</p> <ol> <li><p>If there is no <code>sys.modules</code> entry yet, find and load the module; if Python code, executing the top-level code produces the namespace for that module. This step is skipped if the module has already been loaded.</p></li> <li><p>Bind a name in the current namespace to the imported object. <code>import foo</code> sets the name <code>foo</code>. <code>from foo import bar</code> binds the name <code>bar</code>, etc.</p></li> </ol> <p>Now, <em>local</em> names (in functions) have a speed advantage in that Python stores these in a C array and uses indices in the bytecode to reference them. <em>Global</em> names are stored in a dictionary and have a small hashing overhead each time you do a lookup.</p> <p>So importing something into a function results in a local, accessing which is faster than referencing a global. This is offset by the hash lookup in <code>sys.modules</code> each time your function runs so only if the name is used in a loop would you notice this. </p> <p>However, you should only make such optimisations if that code is used on a critical path, in code that is executed a lot. You are paying a maintenance price by hiding imports in functions, and that cost needs to be weighed against the (marginal) speed benefits.</p>
6
2016-09-10T22:36:59Z
[ "python" ]
How do I dynamically create instances of all classes in a directory with python?
39,431,287
<p>I'm trying to do something like this:</p> <pre><code>from A.AA import Q, W from A.AB import E from A.B.ABA import R from A.B.ABB import T, Y, U objs = [] objs.append(Q()) objs.append(W()) objs.append(E()) objs.append(R()) objs.append(T()) # and so on... </code></pre> <p>The above code is very large, and would take up a bunch of unnecessary time to update it every time I add a new class or module. Instead, I would like a way to dynamically initialize an object from each of the classes within a directory and all nested directories. Something that would abstract down to the following.</p> <pre><code>objs = [] for py_file in directory: for class in py_file: objs.append(construct_object_of_type(class)) </code></pre> <p>As a side note, all of those classes inherit from a single base class. This code would also be called from a python file in the top level directory.</p>
0
2016-09-10T22:50:01Z
39,431,379
<p>If you want to instantiate all the imported objects, you can access them through the global name space with <code>global()</code> built-in function.</p> <pre><code>from A.AA import Q, W from A.AB import E from A.B.ABA import R from A.B.ABB import T, Y, U instances = [obj() for name, obj in globals().items() if not name.startswith('__')] </code></pre> <p>Also note that basically creating all the instances at once is not a good idea, one reason is that you may don't want to use all of them all ways, and another one might be the problem with passing the specific arguments to constructors for each (or some) class, or if you have some imported objects that you don't want to instantiate, then have to take care of them too, and another problems as well.</p>
0
2016-09-10T23:08:49Z
[ "python", "dynamic", "constructor" ]
How do I dynamically create instances of all classes in a directory with python?
39,431,287
<p>I'm trying to do something like this:</p> <pre><code>from A.AA import Q, W from A.AB import E from A.B.ABA import R from A.B.ABB import T, Y, U objs = [] objs.append(Q()) objs.append(W()) objs.append(E()) objs.append(R()) objs.append(T()) # and so on... </code></pre> <p>The above code is very large, and would take up a bunch of unnecessary time to update it every time I add a new class or module. Instead, I would like a way to dynamically initialize an object from each of the classes within a directory and all nested directories. Something that would abstract down to the following.</p> <pre><code>objs = [] for py_file in directory: for class in py_file: objs.append(construct_object_of_type(class)) </code></pre> <p>As a side note, all of those classes inherit from a single base class. This code would also be called from a python file in the top level directory.</p>
0
2016-09-10T22:50:01Z
39,431,683
<p>So I managed to figure out how to do this.</p> <p>Here's the code for it:</p> <pre><code>import os import imp import inspect obj_list = [] dir_path = os.path.dirname(os.path.realpath(__file__)) pattern = "*.py" for path, subdirs, files in os.walk(dir_path): for name in files: if fnmatch(name, pattern): found_module = imp.find_module(name[:-3], [path]) module = imp.load_module(name, found_module[0], found_module[1], found_module[2]) for mem_name, obj in inspect.getmembers(module): if inspect.isclass(obj) and inspect.getmodule(obj) is module: obj_list.append(obj()) </code></pre>
0
2016-09-11T00:05:36Z
[ "python", "dynamic", "constructor" ]
Django: TypeError: 'x' is an invalid keyword argument for this function
39,431,318
<p>The view below works, which is utilising the "update_or_create" feature, brilliantly when something exists and therefore updates a record. However, if it does not exist and has to use the create option to create a new record I get the following error:</p> <pre><code>TypeError at /selectteams/1025/3/ 'soccerseasonid_id' is an invalid keyword argument for this function </code></pre> <p>View Below:</p> <pre><code>if request.method == 'POST': form = SelectTwoTeams(request.POST,user=request.user) if form.is_valid(): teamSelection1, created = UserSelection.objects.update_or_create(user_id=currentUserID, fixturematchday=fixturematchday, soccerseason_id=soccerseason, teamselection1or2=1, defaults={"campaignno":11, "teamselection1or2":1, "teamselectionid_id":request.POST['team1'], "user_id":currentUserID, "fixturematchday":fixturematchday, "soccerseasonid_id":soccerseason}) teamSelection2, created = UserSelection.objects.update_or_create(user_id=currentUserID, fixturematchday=fixturematchday, soccerseason_id=soccerseason, teamselection1or2=2, defaults={"campaignno":11, "teamselection1or2":2, "teamselectionid_id":request.POST['team2'], "user_id":currentUserID, "fixturematchday":fixturematchday, "soccerseasonid_id":soccerseason}) </code></pre> <p>Models Below:</p> <pre><code>class StraightredSeason(models.Model): seasonid = models.IntegerField(primary_key = True) seasonyear = models.CharField(max_length = 4) seasonname = models.CharField(max_length = 36) def __unicode__(self): return self.seasonid class Meta: managed = True db_table = 'straightred_season' class UserSelection(models.Model): userselectionid = models.AutoField(primary_key=True) campaignno = models.CharField(max_length=36,unique=False) user = models.ForeignKey(User, related_name='selectionUser') teamselection1or2 = models.PositiveSmallIntegerField() teamselectionid = models.ForeignKey('straightred.StraightredTeam', db_column='teamselectionid', related_name='teamID') fixturematchday = models.IntegerField(null=True) soccerseason = models.ForeignKey('straightred.StraightredSeason', db_column='soccerseasonid', related_name='fixture_seasonUserSelection') class Meta: managed = True db_table = 'straightred_userselection' </code></pre> <p>Any help would be appreciated, many thanks, Alan.</p>
1
2016-09-10T22:56:05Z
39,431,669
<p>It looks like it is using your defaults where you have "soccerseasonid_id" specified instead of "soccerseason_id". "soccerseason_id" should work.</p>
2
2016-09-11T00:03:12Z
[ "python", "mysql", "django" ]
Monkey Theorem - pick random letters until input string is generated
39,431,322
<p>I wanted to make a code resembles the infinite monkey theorem <strong>the theorem states that:</strong> </p> <blockquote> <p>a monkey hitting keys at random on a typewriter keyboard for infinite amount of time will almost surely type a given text such as the complete works of Shakespeare.</p> </blockquote> <p>well , suppose we replace a monkey with a python to generate one sentence of Shakespeare ? and calculate the trials</p> <p>for example: "methinks it is like a weasel"</p> <p>Here is what I wrote:</p> <pre><code>def Monkey_Theorem(sentence): sentence.lower() string_letters = 'abcdefghijklmnopqrstuvwxyz' import random a = [] l = '' x = 0 trials = 0 while x &lt; (len(sentence) - 1): trials += 1 z = random.choice(string_letters) if z == sentence[x]: a.append(z) x += 1 elif z == " ": trials -= 1 a.append(" ") if x &gt; (len(sentence) - 1): l = ''.join(l) break return l and trials </code></pre> <p>I wrote this into python 2.7 IDLE , pressed enter then wrote:</p> <pre><code>Monkey_Theorem("methinks it is like a weasel") </code></pre> <p>after that I pressed enter.. it moved to the next line and didn't come up with the (>>>) </p> <p>and after sometime no result and when trying to close the IDLE with despair on my face , it says program still running</p> <p><strong>HERE'S THE QUESTION :</strong> </p> <p>(A) is the while loop an infinite one ??<br> (B) or my IDLE is slow ??<br> (C) other cause<br> and how to fix the reason</p> <p><strong>One more request</strong> how to detect the case if I encounter this situation in the future whether it's (A) , (B) , (C)?</p>
1
2016-09-10T22:56:54Z
39,431,414
<p>In your code, you set <code>string_letters = 'abcdefghijklmnopqrstuvwxyz'</code>. Notice that there is no space in <code>string_letters</code>, so when you have matched the entire first word <code>'methinks'</code> it is impossible to match the space after that word. So your loop continues infinitely.</p> <p>You can solve that particular problem by adding a space to the end of the definition string of <code>string_letters</code>. But as others are pointing out, your code has other problems as well.</p> <p>As for detecting which it is, include a way to stop your loop by a keypress or pressing ctrl+C or something similar. Then print the value of <code>trials</code> and see if it is a <em>very</em> large number. If so, you have an infinite or extremely long-running loop.</p>
1
2016-09-10T23:15:19Z
[ "python" ]
Monkey Theorem - pick random letters until input string is generated
39,431,322
<p>I wanted to make a code resembles the infinite monkey theorem <strong>the theorem states that:</strong> </p> <blockquote> <p>a monkey hitting keys at random on a typewriter keyboard for infinite amount of time will almost surely type a given text such as the complete works of Shakespeare.</p> </blockquote> <p>well , suppose we replace a monkey with a python to generate one sentence of Shakespeare ? and calculate the trials</p> <p>for example: "methinks it is like a weasel"</p> <p>Here is what I wrote:</p> <pre><code>def Monkey_Theorem(sentence): sentence.lower() string_letters = 'abcdefghijklmnopqrstuvwxyz' import random a = [] l = '' x = 0 trials = 0 while x &lt; (len(sentence) - 1): trials += 1 z = random.choice(string_letters) if z == sentence[x]: a.append(z) x += 1 elif z == " ": trials -= 1 a.append(" ") if x &gt; (len(sentence) - 1): l = ''.join(l) break return l and trials </code></pre> <p>I wrote this into python 2.7 IDLE , pressed enter then wrote:</p> <pre><code>Monkey_Theorem("methinks it is like a weasel") </code></pre> <p>after that I pressed enter.. it moved to the next line and didn't come up with the (>>>) </p> <p>and after sometime no result and when trying to close the IDLE with despair on my face , it says program still running</p> <p><strong>HERE'S THE QUESTION :</strong> </p> <p>(A) is the while loop an infinite one ??<br> (B) or my IDLE is slow ??<br> (C) other cause<br> and how to fix the reason</p> <p><strong>One more request</strong> how to detect the case if I encounter this situation in the future whether it's (A) , (B) , (C)?</p>
1
2016-09-10T22:56:54Z
39,431,448
<p>You can print something within the loop to see if it is infinite... For example, if <code>z</code> is never equal to the <code>sentence[x]</code>, then you won't increment it, and the loop never stops. </p> <p>That will happen when you need to guess a space character because you have not put one into your string. Therefore, even <code>elif z == " ":</code> will never be entered. </p> <p>Here is a working version of your code.</p> <p>Some things to note: Keeping track of <code>a</code> or <code>l</code> is pointless. At the end of the function, you will be returning the exact same input as <code>sentence</code>. Also, there is a simple import to get all the english letters. </p> <pre><code>from string import ascii_lowercase as alpha import random # add space character to possible choices alpha += ' ' def Monkey_Theorem(sentence): sentence = sentence.lower() x = 0 trials = 0 while x &lt; len(sentence): trials += 1 z = random.choice(alpha) if z == sentence[x]: if z == " ": # this isn't really necessary trials -= 1 print "guessed %s at trial %d" % (z, trials) x += 1 return trials trials = Monkey_Theorem("hello world") print "number of trials = ", trials </code></pre> <p>Output </p> <pre><code>guessed h at trial 49 guessed e at trial 52 guessed l at trial 58 guessed l at trial 107 guessed o at trial 145 guessed at trial 157 guessed w at trial 168 guessed o at trial 197 guessed r at trial 232 guessed l at trial 248 guessed d at trial 269 number of trials = 269 </code></pre>
1
2016-09-10T23:21:43Z
[ "python" ]
how can i correct this Regex phone number extractor in python
39,431,340
<p>The results i'm getting when i run this after copying a set of UK phone numbers to the clipboard are coming out in a very bizarre kind of way. (i have imported both modules before you ask)</p> <pre><code>phoneRegex = re.compile(r'''( (\d{5}|\(\d{5}\))? #area code (\s|-|\.)? #separator (\d{6}) #main 6 digits )''', re.VERBOSE) emailRegex = re.compile(r'''( [a-zA-Z0-9._%+-]+ #username @ #obligatory @ symbol [a-zA-Z0-9.-]+ #domain name (\.[a-zA-Z]{2,5}) #dot-something )''', re.VERBOSE) text = str(pyperclip.paste()) matches = [] for groups in phoneRegex.findall(text): phoneNum = '-'.join([groups[1], groups[3]]) if groups[3] != '': phoneNum += ' ' + groups[3] matches.append(phoneNum) for groups in emailRegex.findall(text): matches.append(groups[0]) if len(matches) &gt; 0: pyperclip.copy('\n'.join(matches)) print('Copied to clipboard:') print('\n'.join(matches)) else: print('No phone numbers or email addresses found') </code></pre> <p>The mistake is somewhere here:</p> <pre><code>for groups in phoneRegex.findall(text): phoneNum = '-'.join([groups[1], groups[3]]) if groups[3] != '': phoneNum += ' ' + groups[3] matches.append(phoneNum) </code></pre> <p><strong>The numbers copied to clipboard:</strong> <br/> 07338 754433<br/> 01265768899<br/> (01283)657899<br/></p> <p><strong>Expected results:</strong><br/> Copied to clipboard:<br/> 07338 754433<br/> 01265 768899<br/> 01283 657899<br/></p> <p><strong>return results:</strong><br/> Copied to clipboard:<br/> 07338-754433 754433<br/> -012657 012657<br/> (01283)-657899 657899</p>
0
2016-09-10T22:59:38Z
39,435,853
<p>I see three issues:</p> <ol> <li><p>the python code joins the two parts of the phone number together with a <code>-</code> and then adds a space and the third part again:</p> <pre><code> phoneNum = '-'.join([groups[1], groups[3]]) if groups[3] != '': phoneNum += ' ' + groups[3] </code></pre> <p>Since <code>groups[3]</code> will always not be blank, what you need to do is:</p> <pre><code> if groups[1] != '': phoneNum = ' '.join(groups[1], groups[3]) else: phoneNum = groups[3] </code></pre></li> <li><p>Your <code>phoneRegex</code> regular expression is not anchored to the beginning and end of the lines. You need to (a) compile it with the <code>re.MULTILINE</code> option and (b) anchor the regular expression between <code>^</code> and <code>$</code>:</p> <pre><code>phoneRegex = re.compile(r'''^( (\d{5}|\(\d{5}\))? #area code (\s|-|\.)? #separator (\d{6}) #main 6 digits )$''', re.VERBOSE + re.MULTILINE) </code></pre> <p>This will prevent a long string of digits with no separator as being just group 3 with a bunch of digits after it.</p></li> <li><p>Your match for the area code includes the matched parentheses within the group match. To fix this, you either need to change the regular expression to make sure the parentheses are not part of the group, or you need to change your code to strip the parentheses out if needed.</p> <ul> <li><p>Avoid parentheses in the regular expression:</p> <pre><code> (?:(\d{5})|\((\d{5})\))? #area code </code></pre> <p>The <code>(?:...)</code> is a non-grouping form of parentheses, so it won't be returned by the find. Within that, you have two alternatives: 5 digits in a group - <code>(\d{5})</code> - or literal parentheses that enclose 5 digits in a group - <code>\((\d{5})\)</code>.</p> <p>However, this change also affects your phone number recombination logic, because your area code is <em>either</em> in <code>groups[1]</code> or <code>groups[2]</code>, and your main number is now in <code>groups[4]</code>.</p> <pre><code> if groups[1] != '': phoneNum = ' '.join(groups[1], groups[4]) elif groups[2] != '': phoneNum = ' '.join(groups[2], groups[4]) else: phoneNum = groups[4] </code></pre> <ul> <li><p>This could be made easier by changing the outer set of parentheses and the parentheses around the separator into non-grouping parentheses. You could then do a single join on a filtered result of the groups:</p> <pre><code>phoneRegex = re.compile(r'''(?: (?:(\d{5})|\((\d{5})\))? #area code (?:\s|-|\.)? #separator (\d{6}) #main 6 digits )''', re.VERBOSE) # ... phoneNum = ' '.join([group for group in groups if group != '']) </code></pre> <p>The modified <code>phoneRegex</code> ensures that the returned <code>groups</code> contain only an optional area code in <code>groups[0]</code> or <code>groups[1]</code> followed by the main number in <code>groups[2]</code>, no extraneous matches returned. The code then filters out any groups that are empty and returns the rest of the groups joined by a space.</p></li> </ul></li> <li><p>Strip parentheses in code:</p> <pre><code> if groups[1] != '': phoneNum = ' '.join(groups[1].lstrip('(').rstrip(')'), groups[3]) else: phoneNum = groups[3] </code></pre></li> </ul></li> </ol>
1
2016-09-11T12:02:16Z
[ "python", "regex" ]
Python boto: filter on tag and value
39,431,353
<p>Filtering by tag key works just fine:</p> <pre><code>ec2.get_all_instances(filters={'tag-key': 'MachineType'}) </code></pre> <p>How can I filter by key and value?</p> <pre><code>"MachineType=DB" </code></pre>
1
2016-09-10T23:03:39Z
39,432,630
<p><strong>Boto</strong></p> <pre><code>ec2.get_all_instances(filters={"tag:MachineType" : "DB"}) </code></pre> <p><strong>Boto3</strong></p> <pre><code>import boto3 ec2 = boto3.resource('ec2') inst_filter = [{'Name':'tag: MachineType', 'Values':['DB']}] insts = list(ec2.instances.filter(Filters=inst_filter)) for inst in insts: print inst.id </code></pre>
1
2016-09-11T03:41:40Z
[ "python", "amazon-web-services", "boto" ]
Angular2 and Django: CSRF Token Headache
39,431,386
<p><strong>The Issue I'm Having</strong></p> <ul> <li>I'm making an Ajax POST request from my <strong>Angular2</strong> client to my <strong>Django</strong> (v1.9) backend (both on localhost, different ports). I'm not yet using the Django REST framework, I'm just dumping the JSON in Django without any add-ons.</li> <li>I have been issued a <strong>csrf token</strong> by the server, and I'm manually sending it back in the HTTP headers (I can see it there when I make the call). </li> <li>However, I still get the error from django: <strong>Forbidden (CSRF cookie not set.)</strong></li> <li>I've read a number of other threads, and tried a few things, but still can't get Django to accept the CSRF token.</li> </ul> <p><strong>Client side code:</strong></p> <pre><code>private _editUserUri = "http://127.0.0.1:8000/search/edit/user/"; constructor(private _http: Http){} getCookie(name) { let value = "; " + document.cookie; let parts = value.split("; " + name + "="); if (parts.length == 2) return parts.pop().split(";").shift(); } validateData(userdata) { return true; } editUser(userdata) { console.log("UserService: createUser function called"); console.log(JSON.stringify(userdata)); if(this.validateData(userdata)) { let headers = new Headers({ 'Content-Type': 'application/json', 'X-CSRFToken': this.getCookie('csrftoken') }); let options = new RequestOptions({ headers: headers }); return this._http .post( this._editUserUri, JSON.stringify(userdata), options) .map(res =&gt; { console.log(res.json()); return res.json(); }) } } </code></pre> <p><strong>Screenshot of csrf token in header (x-csrftoken). This is exactly how Django expects it</strong> (<a href="https://docs.djangoproject.com/en/1.9/ref/csrf/" rel="nofollow">source</a>) <a href="http://i.stack.imgur.com/sAFUD.png" rel="nofollow"><img src="http://i.stack.imgur.com/sAFUD.png" alt="Screenshot"></a></p> <p><strong>What I've tried / considered</strong></p> <ul> <li><p>I thought that perhaps the csrf token is out of date. I've tried to generate a new one, but I haven't yet managed to get Django to issue me a new one. I've tried using the @ensure_csrf_cookie decorator, but still nothing. If I have a csrf token in a cookie which was placed this morning, would I expect it to be replaced by a new, up-to-date version?</p></li> <li><p>Another thought was that the header name (x-csrftoken) is in lower case. Django specifies that the header name should be the following: <strong>X-CSRFToken</strong>. However, from reading online it seems that headers should generally be case sensitive. In any case, Angular2 is automatically converting the header name to lower case.</p></li> <li><p>I tried some other solutions I found on Stack Overflow (<a href="http://stackoverflow.com/questions/34494876/what-is-the-right-way-to-use-angular2-http-requests-with-django-csrf-protection">example</a>) but had no luck.</p></li> <li><p>I thought that maybe this was related to CORS, but the first OPTIONS request returns a 200 from my Django server. This pre-flight request wouldn't need to include the csrf token in its headers also, would it? (excuse my ignorance)</p></li> <li><p>I'm pretty sure my settings are fine. I have 'django.middleware.csrf.CsrfViewMiddleware' in MIDDLEWARE_CLASSES, <strong>CSRF_COOKIE_SECURE = False</strong>, <strong>CORS_ALLOW_CREDENTIALS = True</strong> and <strong>CORS_ORIGIN_ALLOW_ALL = True</strong></p></li> </ul> <p>If anyone could help I'd greatly appreciate it!</p> <p>Nick</p>
1
2016-09-10T23:10:03Z
39,436,142
<p>I think the problem is that your request only has the CSRF token header, but not the cookie (see the <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Double_Submit_Cookie" rel="nofollow">double submit</a> mitigation against CSRF, the header you're sending should be compared to the cookie).</p> <p>I don't quite understand what exactly is happening though. If you elaborate a bit more on where the Angular app is downloaded from and how it gets the CSRF cookie from Django, which is a different origin, I can probably edit this answer to help more. What I don't get is that if the Angular app is downloaded from port A, from where does it have a CSRF cookie for Django on port B.</p> <p><strong>Edit:</strong></p> <p>Ah you're using CORS. I think you need <code>withCredentials</code> in the jQuery request so that the csrf cookie is sent with the request:</p> <pre><code>xhrFields: { withCredentials: true } </code></pre> <p>Django then needs to send <code>Access-Control-Allow-Credentials: true</code> I think.</p>
0
2016-09-11T12:33:39Z
[ "python", "django", "angular2", "cors", "csrf" ]
Making a loop with lists
39,431,455
<p>I am new to Python and would like to create a print function that repeats itself for each item in a list (this is only an example my actual code will be for something else)</p> <pre><code>cars.list = [Honda, Chevrolet, Suzuki, Ford] price.list = [5600, 11500, 6600, 1020] </code></pre> <p>The prices and car lists are in the same order so Honda is $5600, Chevrolet is 11500 ect. I'd like it to run a loop for each of the cars that prints this:</p> <pre><code>while count in cars.list: print("The car type is" Honda/Chev ect. "The price is" 5600, 11500 ect" </code></pre> <p>I want it to repeat the loop for as many cars are in the <code>cars.list</code>, as I will add an option for the user to add more cars so the program cannot rely on knowing the specific cars in a list and copying the print statement for each one. It needs to repeat the print statement for every car, replacing the price and car type each time with the next one in the list.</p>
0
2016-09-10T23:22:42Z
39,431,512
<p>You can use <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> to associate the cars and prices together in an iterator of tuples, then iterate over those tuples while printing what you want.</p> <pre><code>cars = ['Honda', 'Chevrolet', 'Suzuki', 'Ford'] prices = [5600, 11500, 6600, 1020] for car, price in zip(cars, prices): print('The car type is {} and the price is {}.'.format(car, price)) </code></pre> <p><strong>Output:</strong></p> <pre><code>The car type is Honda and the price is 5600. The car type is Chevrolet and the price is 11500. The car type is Suzuki and the price is 6600. The car type is Ford and the price is 1020. </code></pre>
1
2016-09-10T23:32:09Z
[ "python", "list", "python-3.x", "printing", "count" ]
Performing an operation on every document in a MongoDB instance
39,431,475
<p>I have a mongoDB collection with 1.5 million documents, all of which have the same fields, and I want to take the contents of Field A (which is unique in every document) and perform <code>f(A)</code> on it, then create and populate Field B. Pseudocode in Python:</p> <pre><code>for i in collection.find(): x = i**2 collection.update(i,x) #update i with x </code></pre> <p>NOTE: I am aware that the update code is probably wrong, but unless it affects the speed of operation, I chose to leave it there for the sake of simplicity</p> <p>The problem is, this code is really really slow, primarily because it can run through 1000 documents in about a second, then the server cuts off the cursor for about a minute,then it allows another 1000. I'm wondering if there is any way to optimize this operation, or if I'm stuck with this slow bottleneck.</p> <p>Additional notes:</p> <ol> <li><p>I have adjusted <code>batch_size</code> as an experiment, it is faster, but it's not efficient, and still takes hours</p></li> <li><p>I am also aware that SQL could probably do this faster, there are other reasons I am using an noSQL DB that are not relevant to this problem</p></li> <li><p>The instance is running locally so for all intents and purposes, there is not network latency</p></li> <li><p>I have seen <a href="http://stackoverflow.com/questions/21716314/performance-tuning-mongodb-query-update">this</a> question, but it's answer doesn't really address my problem</p></li> </ol>
2
2016-09-10T23:25:27Z
39,431,701
<p>Database clients tend to be extremely abstracted from actual database activity, so observed delay behaviors can be deceptive. It's likely that you are actually hammering the database in that time, but the activity is all hidden from the Python interpreter.</p> <p>That said, there are a couple things you can do to make this lighter.</p> <p>1) Put an index on the property <code>A</code> that you're basing the update on. This will allow it to return much faster.</p> <p>2) Put a projection operator on your <code>find</code> call:</p> <pre><code>for doc in collection.find(projection=['A']): </code></pre> <p>That will ensure that you only return the fields you need to, and if you've properly indexed the unique <code>A</code> property, will ensure your results are drawn entirely from the very speedy index.</p> <p>3) Use an update operator to ensure you only have to send the new field back. Rather than send the whole document, send back the dictionary:</p> <pre><code>{'$set': {'B': a**2}} </code></pre> <p>which will create the field <code>B</code> in each document without affecting any of the other content.</p> <p>So, the whole block will look like this:</p> <pre><code>for doc in collection.find(projection=['A', '_id']): collection.update(filter={'_id': doc['_id']}, update={'$set': {'B': doc['A']**2}}) </code></pre> <p>That should cut down substantially on the work that Mongo has to do, as well as (currently irrelevant to you) network traffic.</p>
0
2016-09-11T00:10:44Z
[ "python", "mongodb", "performance", "optimization" ]
Performing an operation on every document in a MongoDB instance
39,431,475
<p>I have a mongoDB collection with 1.5 million documents, all of which have the same fields, and I want to take the contents of Field A (which is unique in every document) and perform <code>f(A)</code> on it, then create and populate Field B. Pseudocode in Python:</p> <pre><code>for i in collection.find(): x = i**2 collection.update(i,x) #update i with x </code></pre> <p>NOTE: I am aware that the update code is probably wrong, but unless it affects the speed of operation, I chose to leave it there for the sake of simplicity</p> <p>The problem is, this code is really really slow, primarily because it can run through 1000 documents in about a second, then the server cuts off the cursor for about a minute,then it allows another 1000. I'm wondering if there is any way to optimize this operation, or if I'm stuck with this slow bottleneck.</p> <p>Additional notes:</p> <ol> <li><p>I have adjusted <code>batch_size</code> as an experiment, it is faster, but it's not efficient, and still takes hours</p></li> <li><p>I am also aware that SQL could probably do this faster, there are other reasons I am using an noSQL DB that are not relevant to this problem</p></li> <li><p>The instance is running locally so for all intents and purposes, there is not network latency</p></li> <li><p>I have seen <a href="http://stackoverflow.com/questions/21716314/performance-tuning-mongodb-query-update">this</a> question, but it's answer doesn't really address my problem</p></li> </ol>
2
2016-09-10T23:25:27Z
39,431,878
<p>Maybe you should do your updates in multiple threads. I think it may be better to load data in one thread, split it into multiple parts and pass that parts to parallel worker threads that will perform updates. It will be faster.</p> <p>EDIT:</p> <p>I suggest you doing paginated queries. Python pseudocode: </p> <pre><code>count = collection.count() page_size = 20 i = 0; while(i &lt; count): for row in collection.find().limit(pageSize).skip(i): x = i**2 collection.update(i, x); i += page_size </code></pre>
0
2016-09-11T00:48:47Z
[ "python", "mongodb", "performance", "optimization" ]
PyOpenCL Kronecker Product Kernel
39,431,504
<p>I have the following code for confirming a hand written method for computing the kronecker product of two square matrices. The first portion indeed validates that my method of repeating and tiling <code>a</code> and <code>b</code> respectively yields the same output.</p> <pre><code>import pyopencl as cl import numpy from time import time N = 3 num_iter = 1 a = numpy.random.rand(N,N) b = numpy.random.rand(N,N) c = numpy.kron(a, b) abig = numpy.repeat(numpy.repeat(a,N,axis=1),N,axis=0) bbig = numpy.tile(b,(N,N)) cbig = abig*bbig print(numpy.allclose(c,cbig)) </code></pre> <p>I then attempt to port this multiplication over to the GPU using PyOpenCL. I first allocate <code>biga</code> and <code>bigb</code> as <code>d_a</code> and <code>d_b</code> respectively on the GPU memory. I also allocate <code>h_C</code> as an empty array on the host and <code>d_C</code> as the same size on the device.</p> <pre><code>context = cl.create_some_context() queue = cl.CommandQueue(context) h_C = numpy.empty(cbig.shape) d_a = cl.Buffer(context, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=abig) d_b = cl.Buffer(context, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=bbig) d_c = cl.Buffer(context, cl.mem_flags.WRITE_ONLY, h_C.nbytes) kernelsource = open("../GPUTest.cl").read() program = cl.Program(context, kernelsource).build() kronecker = program.kronecker kronecker.set_scalar_arg_dtypes([numpy.int32, None, None, None]) for i in range(num_iter): kronecker(queue, (N**2, N**2), None, N**2, d_a, d_b, d_c) queue.finish() cl.enqueue_copy(queue, h_C, d_c) print(h_C) </code></pre> <p>Here is the contents of GPUTest.cl:</p> <pre><code>__kernel void kronecker(const int N,__global float* A,__global float*B,__global float* C) { int i = get_global_id(0); int j = get_global_id(1); C[i,j] = A[i,j]*B[i,j]; } </code></pre> <p>However, my output is no where close. I believe my mistakes lie in how I'm handling the thread id's. From reading another example on matrix dot products, I was under the impression that the id's were essentially the location of the element within the block and since this is elementwise, I would only need to pull the element at the same location from A and B to multiply them together. Do these id's need to be combined into a single index to better address the way that the memory is actually allocated? </p> <p>And only slightly related, but is there a way to utilize a tiling or memory sharing method? This was only a naiive attempt at the simplest way to do the calculation, I'm hoping to get to an algorithm that does not need the repeated/tiled versions of <code>a</code> and <code>b</code>. Something along the lines of taking a single element of <code>a</code>, multiplying the entirity of <code>b</code> by it, and then storing the result in a tile of <code>c</code>.</p>
0
2016-09-10T23:31:10Z
39,431,689
<p>The issue is that the kernel does not take indices for the input and output memory addresses. The arguments should be <code>C[i+j*N]</code> in order to move throughout the whole block of memory appropriately.</p>
0
2016-09-11T00:07:09Z
[ "python", "opencl", "gpgpu", "matrix-multiplication", "pyopencl" ]
Extracting text from find_next_sibling(), BeautifulSoup
39,431,506
<p>I am trying to extract the description of the Chinese character from this website: <a href="http://www.hsk.academy/en/hsk_1" rel="nofollow">http://www.hsk.academy/en/hsk_1</a></p> <p>Example html: </p> <pre><code> &lt;tr&gt; &lt;td&gt; &lt;span class="hanzi"&gt;&lt;a href="/en/characters/%E7%88%B1"&gt;爱&lt;/a&gt;&lt;/span&gt; &lt;br/&gt;ài&lt;/td&gt; &lt;td&gt;to love; affection; to be fond of; to like&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I would like the last td tag's text be put into a list for each description of the character. However, currently I am given the whole tag including the tags themselves. I can't .text the find_next_sibling(): AttributeError: 'NoneType' object has no attribute 'text'.</p> <p>This is my code:</p> <pre><code>for item in soup.find_all("td"): EnglishItem = item.find_next_sibling() if EnglishItem: if not any(EnglishItem in s for s in EnglishDescriptionList): EnglishDescriptionList.insert(count, EnglishItem) count += 1 print EnglishDescriptionList </code></pre>
0
2016-09-10T23:31:20Z
39,431,819
<p>Try this:</p> <pre><code>english_descriptions = [] table = soup.find('table', id='flat_list') for e in table.select('.hanzi'): english_desc = e.parent.find_next_sibling().text if not any(english_desc in s for s in english_descriptions): english_descriptions.append(english_desc) </code></pre> <p>This selects (finds) all tags of class <code>hanzi</code> (within the table with <code>id="flat_list"</code>) which will be the <code>&lt;span&gt;</code> tags. Then the parent of each <code>&lt;span&gt;</code> is accessed - this is the first <code>&lt;td&gt;</code> in each row. Finally the next sibling is accessed and this is the target tag that contains the English description.</p> <p>You can do away with the <code>count</code> and just append items to the list with</p> <pre><code>english_descriptions.append() </code></pre> <p>Also, I don't think that you need to check whether the current english description is a substring of an existing one (is that what you're trying to do?). If not you can simplify to this list comprehension:</p> <pre><code>table = soup.find('table', id='flat_list') english_descriptions = [e.parent.find_next_sibling().text for e in table.select('.hanzi')] </code></pre>
1
2016-09-11T00:36:30Z
[ "python", "python-2.7", "beautifulsoup" ]
Why is the execution time for my sorting code inconsistent?
39,431,517
<p>I'm learning python and I've implemented a quicksort algorithm (kind of). I do know that python's <code>sort()</code> method would be faster but I wanted to know by how much, so I've used the <code>timeit</code> module for comparison.</p> <p>I created a 'wrapper' function for the <code>sort()</code> method so it works with the same syntax as my implementation (and stops being an in-place sort) and called <code>timeit.repeat(3, 2000)</code> for both functions.</p> <p>Here are the results for my function:</p> <pre><code>[0.00019502639770507812, 0.00037097930908203125, 0.00013303756713867188] </code></pre> <p>And for python's sort():</p> <pre><code>[0.0001671314239501953, 0.0001678466796875, 0.00016808509826660156] </code></pre> <p>As you can see, python's algorithm has execution times much more consistent than my own's. Does anyone know why?</p> <p><strong>Code:</strong></p> <pre><code>import timeit import random def quick(lst): if not lst: return [] else: first, rest = lst[0], lst[1:] great = [] less = [] for item in rest: great.append(item) if item &gt;= first else less.append(item) return quick(less) + [first] + quick(great) def sort(lst): lst.sort() return lst x = [random.randint(1, 10000) for i in xrange(1, 1000)] quick_t = timeit.Timer("'quick(x)'") print quick_t.repeat(3, 2000) sort_t = timeit.Timer("'sort(x)'") print sort_t.repeat(3, 2000) </code></pre>
3
2016-09-10T23:33:14Z
39,431,566
<p>Your timing is horribly wrong in multiple ways. First, your <code>sort</code> wrapper still mutates its input instead of returning a new list:</p> <pre><code>&gt;&gt;&gt; x = [2, 1] &gt;&gt;&gt; sort(x) [1, 2] &gt;&gt;&gt; x [1, 2] </code></pre> <p>Second, you're not timing either sort at all. You're timing the evaluation of the string literal <code>'quick(x)'</code> or <code>'sort(x)'</code>. No sorting actually takes place.</p> <p>Here's how you'd <em>actually</em> perform the timing:</p> <pre><code>&gt;&gt;&gt; x = [random.randint(1, 10000) for i in xrange(1, 1000)] &gt;&gt;&gt; print timeit.repeat('quick(x)', 'from __main__ import quick, x', repeat=3, number=500) [1.1500223235169074, 1.0714474915748724, 1.0657452245240506] &gt;&gt;&gt; print timeit.repeat('sorted(x)', 'from __main__ import quick, x', repeat=3, number=500) [0.0944752552401269, 0.10085532031979483, 0.09799135718691332] </code></pre>
5
2016-09-10T23:41:20Z
[ "python", "performance", "sorting", "time" ]
Scapy - sending IPv6 Router Advertisement failing with lifetime > 0
39,431,563
<p>I am attempting to create a tool using Scapy to discover link-local IPv6 hosts by sending a fake router advertisement to the FF02::1 multicast address.</p> <pre><code>*SNIP* router_advertisement = scapy.IPv6(src=ra_src_addr, dst='FF02::1')/scapy.ICMPv6ND_RA(routerlifetime=0, reachabletime=0)/scapy.ICMPv6NDOptSrcLLAddr(lladdr=hw_addr)/scapy.ICMPv6NDOptPrefixInfo(prefixlen=64, validlifetime=0x6, preferredlifetime=0x6, prefix='dead::') answer, unanswer = scapy.sr(router_advertisement, timeout=10, multi=True) for reply in answer: print(reply[1][scapy.Ether].src + ' : ' + reply[1]scapy.IPv6].src) </code></pre> <p>Everything above the snip is mostly setting up the parameters of the router advertisement (ra_prefix, hw_addr, etc). I've put the full script on pastebin to avoid cluttering the question: <a href="http://pastebin.com/4Q3JheXh" rel="nofollow">http://pastebin.com/4Q3JheXh</a></p> <p>The problem with the above is that while Scapy is successfully sending the router advertisement packet, and I'm seeing neighbor solicitation responses, Scapy is exiting in error before I can view answers with sr().</p> <p>Full output:</p> <pre><code> WARNING: No route found for IPv6 destination :: (no default route?) Begin emission: Finished to send 1 packets. ...Traceback (most recent call last): File "find_ipv6_local.py", line 40, in &lt;module&gt; answer, unanswer = scapy.sr(router_advertisement, timeout=10, multi=True) File "/usr/lib/python2.7/site-packages/scapy/sendrecv.py", line 317, in sr a,b=sndrcv(s,x,*args,**kargs) File "/usr/lib/python2.7/site-packages/scapy/sendrecv.py", line 141, in sndrcv h = r.hashret() File "/usr/lib/python2.7/site-packages/scapy/layers/inet6.py", line 423, in hashret return struct.pack("B", nh)+self.payload.hashret() File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 711, in hashret return self.payload.hashret() File "/usr/lib/python2.7/site-packages/scapy/layers/inet6.py", line 1317, in hashret return struct.pack("HH",self.mladdr)+self.payload.hashret() struct.error: pack expected 2 items for packing (got 1) </code></pre> <p>Interestingly, when I set <strong>validlifetime</strong> and <strong>preferredlifetime</strong> to 0, Scapy does not crash and burn. However, this is less than helpful, as a lifetime of 0 does not get me any responses.</p> <p>Have I screwed up somewhere in the script, or is Scapy a little <em>off</em> when it comes to IPv6?</p>
1
2016-09-10T23:40:45Z
39,439,585
<p>I would argue that <code>scapy</code> is a little dodgy in this respect. Your trackeback here:</p> <pre><code>return struct.pack("HH",self.mladdr)+self.payload.hashret() </code></pre> <p>Should contain the following:</p> <pre><code>return struct.pack("HH", 0, 0)+"" </code></pre> <p>That <code>struct.pack</code> has no chance of working, it at least should be:</p> <pre><code>return struct.pack("HH", *self.mladdr)+self.payload.hashnet() </code></pre> <p>So that <code>struct.pack</code> has no chance of receiving the two arguments needed for "HH". That <strong>is</strong> a bug.</p> <p>Since you do not care about the payload you can change the scapy code for <code>ICMPv6MLQuery</code> from:</p> <pre><code>class ICMPv6MLQuery(_ICMPv6ML): # RFC 2710 name = "MLD - Multicast Listener Query" type = 130 mrd = 10000 mladdr = "::" # 10s for mrd overload_fields = {IPv6: { "dst": "ff02::1", "hlim": 1, "nh": 58 }} def hashret(self): if self.mladdr != "::": return struct.pack("HH",self.mladdr)+self.payload.hashret() else: return self.payload.hashret() </code></pre> <p>To</p> <pre><code>class ICMPv6MLQuery(_ICMPv6ML): # RFC 2710 name = "MLD - Multicast Listener Query" type = 130 mrd = 10000 mladdr = "::" # 10s for mrd overload_fields = {IPv6: { "dst": "ff02::1", "hlim": 1, "nh": 58 }} def hashret(self): return self.payload.hashret() </code></pre> <p>i.e. kill the <code>struct.pack</code> altogether.</p> <hr> <p>On another note: this:</p> <pre><code>WARNING: No route found for IPv6 destination :: (no default route?) </code></pre> <p>May prevent you from receiving an answer (the NIC may decide that nothing could have arrived and ignore it). It is wise to configure at least some trivial route, e.g.</p> <pre><code>$ route -6 Kernel IPv6 routing table Destination Next Hop Flag Met Ref Use If ::/0 [::] U 256 0 0 eth0 </code></pre>
1
2016-09-11T19:00:02Z
[ "python", "networking", "ipv6", "scapy" ]
Install pybrain in ubuntu 16.04 "ImportError: No module named pybrain.structure"
39,431,684
<p>I'm getting that error:</p> <p><code>ImportError: No module named pybrain.structure</code></p> <p>When executing:</p> <p><code> from pybrain.pybrain.structure import FeedForwardNetwork </code></p> <p>From the pybrain tutorial.</p> <p>I installed pybrain running:</p> <p><code>sudo python setup.py install</code></p>
1
2016-09-11T00:05:44Z
39,431,699
<p>The problem was resolved replacing <code>pybrain.pybrain</code> by <code>pybrain</code>.</p>
0
2016-09-11T00:09:24Z
[ "python", "pybrain" ]
Error in my function
39,431,688
<p>When I run my code, I get this error: </p> <pre><code>&lt;function setDegreesAndMinutes at 0x10e7cf6e0&gt; </code></pre> <p>My code is:</p> <pre><code>def setDegreesAndMinutes(self, degrees,minutes): self.degrees = int(input()) self.minutes = float(input()) if(not(isinstance(degrees, int))): raise ValueError("degrees shoule be int") if(not(isinstance(minutes(int,float)))): raise ValueError("minutes shoule be int or float") x = degrees y = minutes return str(x)+'d'+str(y) returnValue = setDegreesAndMinutes print returnValue </code></pre> <p>it will be great, if anyone knows what happened!</p>
-2
2016-09-11T00:07:00Z
39,432,052
<p>That is not an error at all... You printed a <em>function object</em>. </p> <p>You never <em>called</em> the function passing in <code>(self, degrees, minutes)</code> as parameters to <code>setDegreesAndMinutes</code>. </p> <p>Also, typically <code>self</code> means you have defined that method in a class, so you need an instance of that class to even call <code>setDegreesAndMinutes</code>. In which case, you'd need <code>returnValue = some_class.setDegreesAndMinutes(degrees, minutes)</code></p> <p>Then, do you really <em>need</em> parameters? You called <code>input</code>, which means you are prompting for values, therefore re-assigning the values that you otherwise would have passed into the method. If you do want to prompt for input from the method, then remove <code>degrees, minutes</code> from <code>(self, degrees, minutes)</code> and then you can do <code>returnValue = some_class.setDegreesAndMinutes()</code></p> <p>And finally, setters aren't really necessary in Python, in my opinion. Plus, they usually don't return a value or prompt for input on their own. Make it simple - just <em>set</em> the value. </p> <p>All in all, I think you are looking for something like this </p> <pre><code>class Foo(): def __init__(self, degrees, minutes): self.degrees = degrees self.minutes = minutes degrees = int(input("degrees: ")) if not isinstance(degrees, int): raise ValueError("degrees should be int") minutes = float(input("minutes: ")) if not isinstance(minutes, (int,float)): # I think you had extra parenthesis after minutes raise ValueError("minutes should be int or float") f = Foo(degrees, minutes) print(str(f.degrees) + 'd' + str(f.minutes)) </code></pre> <p>And if you need to set the values, then do <code>f.degrees = X</code> for any <code>X</code> value, for example</p>
2
2016-09-11T01:29:27Z
[ "python", "function" ]
How to make a python program run just by typing the name alone at the terminal?
39,431,697
<p>I am not sure what I am supposed to be searching, because everything I have been trying to look up has not really given me the answers that I need.</p> <p>If anyone can point me in the right direction of exactly what I should be looking at, I would greatly appreciate it. Basically, I want to know the best way to go about making a python program which I can distribute (not publicly). </p> <p>Once someone has the file they run a script, or run the make command, and the result of this would be that the user can invoke the program from within any directory on the computer by just typing the name (and passing args) in the terminal. </p> <p>I only know of one way to do this, which I believe is the wrong way. My idea was something as follows:</p> <p>1.) A main folder, let's call it Ghoul. It would contain 3 files:</p> <blockquote> <pre><code>setup.sh ghoul.sh ghoul.py </code></pre> </blockquote> <p>2.) The user would have to run setup.sh, which would make ghoul.sh an executable and it would change the name to ghoul and then I would move it to /bin</p> <p>3.) Within the ghoul file which is now in /bin, the file itself would contain "python /home/user/Ghoul/ghoul.py $@" And this would allow the program to run from any directory just by typing "ghoul"</p> <p>I hope it's clear what I am trying to accomplish, I know this can't be the appropriate way of doing this. What should I be looking up and reading on to accomplish this? I would like to know how I can do this on Ubuntu and if also ..Windows. </p> <p>I am also interested if I can limit the "ghoul" command to work only in the Ghoul directory, but of course in any directory that is within the Ghoul directory instead of from within any directory on the system.</p> <p>Thank you.</p>
1
2016-09-11T00:08:51Z
39,431,730
<p>On Unix like systems</p> <pre><code>#! /usr/bin/env python </code></pre> <p>in the very first line of your chmod +x script file will make it executable from the current directory using ./filename</p> <p>If you want completely straightforward execution from anywhere you can put it on the path somewhere however you choose. </p> <p>On windows its more complicated, if you want commandline execution the default install should give you the ability to execute </p> <pre><code>myscript.py </code></pre> <p>If its in your path. to drop the .py you need to get .py into the PATHEXT variable. Alternatively if it neds to be distributed to someone without any python install check out www.py2exe.org</p>
2
2016-09-11T00:16:35Z
[ "python", "linux", "bash", "shell", "scripting" ]
werkzeug.routing.BuildError BuildError: ('oauth_authorize', {'provider': 'twitter'}, None)
39,431,737
<p>I'm trying to add Login with twitter redirect in my login page. Which is called login.html.</p> <pre><code>&lt;li&gt;&lt;a href="{{ url_for('oauth_authorize', provider='twitter') }}"&gt;Login with Twitter&lt;/a&gt;&lt;/li&gt; </code></pre> <p>upon clicking that URL it throws me BUILDERROR.</p> <pre><code>BuildError: ('oauth_callback', {'provider': 'twitter'}, None) </code></pre> <p>Here is the code.</p> <pre><code>@user_blueprint.route('/authorize/&lt;provider&gt;') def oauth_authorize(provider): if not current_user.is_anonymous: return rredirect(url_for('main.home')) oauth = OAuthSignIn.get_provider(provider) return oauth.authorize() </code></pre> <p>That is my views.py the oauth_authorize function. @user_blueprint.route('/callback/')</p> <pre><code>def oauth_callback(provider): if not current_user.is_anonymous: return redirect(url_for('main.home')) oauth = OAuthSignIn.get_provider(provider) social_id, username, email = oauth.callback() if social_id is None: flash('Authentication failed.') return redirect(url_for('user.login')) user = User.query.filter_by(social_id=social_id).first() if not user: user = UserProfile(social_id=social_id, nickname=username, email=email) db.session.add(user) db.session.commit() login_user(user, True) return redirect(url_for('user.login')) </code></pre> <p>I've been trying to debug the problem. I have a mixture feelings about the oauth.py code I have.</p> <pre><code>from rauth import OAuth1Service, OAuth2Service from flask import current_app, url_for, request, redirect, session class OAuthSignIn(object): providers = None def __init__(self, provider_name): self.provider_name = provider_name credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name] self.consumer_id = credentials['id'] self.consumer_secret = credentials['secret'] def authorize(self): pass def callback(self): pass def get_callback_url(self): return url_for('oauth_callback', provider=self.provider_name, _external=True) @classmethod def get_provider(self, provider_name): if self.providers is None: self.providers = {} for provider_class in self.__subclasses__(): provider = provider_class() self.providers[provider.provider_name] = provider return self.providers[provider_name] class FacebookSignIn(OAuthSignIn): def __init__(self): super(FacebookSignIn, self).__init__('facebook') self.service = OAuth2Service( name='facebook', client_id='512038548997732', client_secret='a5a480e8da592d5c16feeee5426976b4', authorize_url='https://graph.facebook.com/oauth/authorize', access_token_url='https://graph.facebook.com/oauth/access_token', base_url='https://graph.facebook.com/' ) def authorize(self): return redirect(self.service.get_authorize_url( scope='email', response_type='code', redirect_uri=self.get_callback_url()) ) def callback(self): if 'code' not in request.args: return None, None, None oauth_session = self.service.get_auth_session( data={'code': request.args['code'], 'grant_type': 'authorization_code', 'redirect_uri': self.get_callback_url()} ) me = oauth_session.get('me?fields=id,email').json() return ( 'facebook$' + me['id'], me.get('email').split('@')[0], # Facebook does not provide # username, so the email's user # is used instead me.get('email') ) class TwitterSignIn(OAuthSignIn): def __init__(self): super(TwitterSignIn, self).__init__('twitter') self.service = OAuth1Service( name='twitter', consumer_key='pNU7LEHOLEAJH3lQRNwOjiJMH', consumer_secret='WFe5DVdi5JZ6KtuyRWYP9BkC8905EUp0N56junLtde1vL5w2NR', request_token_url='https://api.twitter.com/oauth/request_token', authorize_url='https://api.twitter.com/oauth/authorize', access_token_url='https://api.twitter.com/oauth/access_token', base_url='https://api.twitter.com/1.1/' ) def authorize(self): request_token = self.service.get_request_token( params={'oauth_callback': self.get_callback_url()} ) session['request_token'] = request_token return redirect(self.service.get_authorize_url(request_token[0])) def callback(self): request_token = session.pop('request_token') if 'oauth_verifier' not in request.args: return None, None, None oauth_session = self.service.get_auth_session( request_token[0], request_token[1], data={'oauth_verifier': request.args['oauth_verifier']} ) me = oauth_session.get('account/verify_credentials.json').json() social_id = 'twitter$' + str(me.get('id')) username = me.get('screen_name') return social_id, username, None # Twitter does not provide email </code></pre> <p>This is a traceback error</p> <pre><code>Traceback (most recent call last): File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__ return self.wsgi_app(environ, start_response) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e)) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request() File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request rv = self.handle_user_exception(e) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request rv = self.dispatch_request() File "/usr/local/lib/python2.7/site-packages/flask_debugtoolbar/__init__.py", line 125, in dispatch_request return view_func(**req.view_args) File "/Users/Ben/Desktop/flask_practise/project/user/views.py", line 81, in oauth_authorize return oauth.authorize() File "/Users/Ben/Desktop/flask_practise/oauth.py", line 86, in authorize params={'oauth_callback': self.get_callback_url()} File "/Users/Ben/Desktop/flask_practise/oauth.py", line 22, in get_callback_url _external=True) File "/usr/local/lib/python2.7/site-packages/flask/helpers.py", line 312, in url_for return appctx.app.handle_url_build_error(error, endpoint, values) File "/usr/local/lib/python2.7/site-packages/flask/app.py", line 1641, in handle_url_build_error reraise(exc_type, exc_value, tb) File "/usr/local/lib/python2.7/site-packages/flask/helpers.py", line 305, in url_for force_external=external) File "/usr/local/lib/python2.7/site-packages/werkzeug/routing.py", line 1616, in build raise BuildError(endpoint, values, method) BuildError: ('oauth_callback', {'provider': 'twitter'}, None) </code></pre> <p>SOULUTION ---- Woops! I feel like an idiot. I had been changing file on a wrong directory. All I had to do was add the user_blueprint at my oauth.py file. Now it works fine!</p>
0
2016-09-11T00:17:47Z
39,431,952
<p>Because you're using Blueprints, in your Jinja template you'll need to call the endpoint like this</p> <pre><code>url_for('user_blueprint.oauth_authorize', provider='twitter') </code></pre>
1
2016-09-11T01:07:15Z
[ "python", "redirect", "flask" ]
Is there any way to run .js scripts in phantomjs via Python+selenium?
39,431,791
<p>I'm currently using selenium in Python to create a session of Phantomjs browser and I was wondering if there is any way of running .js scripts on that browser (since I can't find anything on Phantomjs docs) or if I have to switch to Firefox and install an extension like Tampermonkey or such. Thanks for help and sorry for bad english.</p>
-2
2016-09-11T00:30:01Z
39,431,827
<p>PhantomJS is essentially a headless browser and script runner. You can write and run any arbitrary Javascript and run it with PhantomJS. Here's a reference: <a href="http://phantomjs.org/page-automation.html" rel="nofollow">http://phantomjs.org/page-automation.html</a></p>
0
2016-09-11T00:38:23Z
[ "python", "selenium", "firefox", "phantomjs" ]
'float' object is not iterable error
39,431,830
<p>I am trying to get a a variable that reads out a load value (given in xml document) for a given length of a time (also a list of values). The list for t is from a value 'start' to 'end' with an interval of 15 min. Essentially what I want is that I want one load value to print for the entire length of its respective time list. So if its time list is [0 15 30 45 60] then I want its load value to be in a list repeating 5 times. The xml document and code I am running are below and I keep getting an error with my potW assignment saying "'float' object is not iterable." I know this is a lot but any suggestions? </p> <pre><code>import xml.etree.ElementTree as ET import os class WaterModel: def __init__(self,fn): self.tree = ET.parse(fn) self.root = self.tree.getroot() self.title, self.start, self.end, self.load, self.duration, self.Type = [],[],[],[],[],[] for child in self.root: self.title.append(child.find('title').text) sh = int(child.find('startHour').text) sm = int(child.find('startMinute').text) self.duration.append(int(child.find('duration').text)) self.start.append(sh*60+sm) self.end.append(self.start[-1] + self.duration[-1]) self.Type.append(child.find('Type').text) self.load.append(float(child.find('load').text)) def Wp(self): greyW = 0 for i in range(len(self.root)): if self.Type[i] == 'greywater': greyW += self.load[i]*self.duration[i] t = range(self.start[i], self.end[i]+1, 15) for i in range(len(self.root)): for j in range(len(t)): if self.Type[i] == 'potable': potW = [a for a in self.load[j]] fn = 'SD2017NominalWaterUse.xml' a = WaterModel(fn) b = a.Wp() print(b) </code></pre> <p>xml file 'SD2017NominalWaterUse.xml' that is read into the code above:</p> <pre><code>&lt;WaterNominalDay&gt; &lt;event&gt; &lt;title&gt;Evening Washer&lt;/title&gt; &lt;Type&gt;greywater&lt;/Type&gt; &lt;startHour&gt;19&lt;/startHour&gt; &lt;startMinute&gt;30&lt;/startMinute&gt; &lt;duration units = 'min'&gt;270&lt;/duration&gt; &lt;load units = 'gal/min'&gt;.051852&lt;/load&gt; &lt;comment&gt; '' &lt;/comment&gt; &lt;/event&gt; &lt;event&gt; &lt;title&gt;Morning Cooking&lt;/title&gt; &lt;Type&gt;potable&lt;/Type&gt; &lt;startHour&gt;7&lt;/startHour&gt; &lt;startMinute&gt;30&lt;/startMinute&gt; &lt;duration units = 'min'&gt;180&lt;/duration&gt; &lt;load units = 'gal/min'&gt;.003331&lt;/load&gt; &lt;comment&gt; '5 lb water is .5995 gal' &lt;/comment&gt; &lt;/event&gt; &lt;event&gt; &lt;title&gt;Evening Cooking&lt;/title&gt; &lt;Type&gt;potable&lt;/Type&gt; &lt;startHour&gt;19&lt;/startHour&gt; &lt;startMinute&gt;30&lt;/startMinute&gt; &lt;duration units = 'min'&gt;180&lt;/duration&gt; &lt;load units = 'gal/min'&gt;.003331&lt;/load&gt; &lt;comment&gt; '5 lb water is .5995 gal' &lt;/comment&gt; &lt;/event&gt; &lt;event&gt; &lt;title&gt;Leaks&lt;/title&gt; &lt;Type&gt;potable&lt;/Type&gt; &lt;startHour&gt;0&lt;/startHour&gt; &lt;startMinute&gt;00&lt;/startMinute&gt; &lt;duration units = 'min'&gt;1440&lt;/duration&gt; &lt;load units = 'gal/min'&gt;.006944&lt;/load&gt; &lt;comment&gt; '' &lt;/comment&gt; &lt;/event&gt; &lt;/WaterNominalDay&gt; </code></pre>
-1
2016-09-11T00:39:26Z
39,431,855
<p><code>self.load</code> i an array of <code>float</code>s, so <code>self.load[j]</code> will be a float, which is what you are trying to iterate over; hence the error message.</p>
0
2016-09-11T00:43:07Z
[ "python", "xml", "list", "floating-point" ]
How to distribute code to be executed by an external command? Bash script?
39,431,958
<p>EDIT: Based on discussions below, I think my question really code apply to any language. Python naturally has a packaging system and installation procedure via <code>pip</code>. But let's say this was C code or a perl script. Users still would download the program files, and have a way to execute the code in the command line via <code>capsall input.txt</code>. </p> <p>I have a python script that takes an input file and gives an output file.</p> <p>For a concrete example, this script <code>file1.py</code> takes in an input text file and outputs a text file with all letters capitalized:</p> <pre><code>import sys inFile = sys.argv[1] outFile = sys.argv[2] with open(inFile,'r') as input_file: lines = input_file.readlines() # process the input file somehow # here we simply capitalize the text, # but naturally something more complex is possible capitalized_lines = [] for line in lines: capitalized_lines.append(line.upper()) with open(outFile,'w') as output_file: for line in capitalized_lines: output_file.write(line) </code></pre> <p>The way users execute this code now with </p> <pre><code>python file1.py input.txt output.txt </code></pre> <p>Let's say I wanted to distribute this code such that users would download a tarball and be able to execute the above in the command line with (for example)</p> <pre><code>capsall input.txt </code></pre> <p>which would run <code>python file1.py</code> and output the file <code>output.txt</code>. Does one write a bash script? If so, how do you distribute the code such that users will have this in their PATH? </p>
2
2016-09-11T01:09:39Z
39,432,028
<p>Add a "hash bang" at the top of the script file to tell bash to invoke the Python interpreter. Also make your script executable:</p> <pre><code>#!/usr/bin/env python import sys inFile = sys.argv[1] outFile = sys.argv[2] ... </code></pre> <p>Make the script file executable:</p> <pre><code>$ cp file1.py capsall $ chmod +x capsall </code></pre> <p>Now you can run the script with:</p> <pre><code>$ ./capsall input.txt output.txt </code></pre> <p>Or if <code>capsall</code> is on your path:</p> <pre><code>$ capsall input.txt output.txt </code></pre>
1
2016-09-11T01:22:42Z
[ "python", "bash", "shell", "unix", "command" ]
How to distribute code to be executed by an external command? Bash script?
39,431,958
<p>EDIT: Based on discussions below, I think my question really code apply to any language. Python naturally has a packaging system and installation procedure via <code>pip</code>. But let's say this was C code or a perl script. Users still would download the program files, and have a way to execute the code in the command line via <code>capsall input.txt</code>. </p> <p>I have a python script that takes an input file and gives an output file.</p> <p>For a concrete example, this script <code>file1.py</code> takes in an input text file and outputs a text file with all letters capitalized:</p> <pre><code>import sys inFile = sys.argv[1] outFile = sys.argv[2] with open(inFile,'r') as input_file: lines = input_file.readlines() # process the input file somehow # here we simply capitalize the text, # but naturally something more complex is possible capitalized_lines = [] for line in lines: capitalized_lines.append(line.upper()) with open(outFile,'w') as output_file: for line in capitalized_lines: output_file.write(line) </code></pre> <p>The way users execute this code now with </p> <pre><code>python file1.py input.txt output.txt </code></pre> <p>Let's say I wanted to distribute this code such that users would download a tarball and be able to execute the above in the command line with (for example)</p> <pre><code>capsall input.txt </code></pre> <p>which would run <code>python file1.py</code> and output the file <code>output.txt</code>. Does one write a bash script? If so, how do you distribute the code such that users will have this in their PATH? </p>
2
2016-09-11T01:09:39Z
39,442,272
<p>I would recommend using python packaging (e.g., [pip]) for this. You could use the OS specific packaging method as well, something like <em>apt</em>, <em>yum</em>, <em>msiexec</em>, whatever, but I wouldn't unless you have to. Your users already have python installed since they are used to explicitly passing your script to the interpreter already. If you are interested in using python packaging, then read on.</p> <p>First, I would put your script into a package along with whatever other processing is necessary. Let's call it <code>mylibrary</code>. Your project should look something like:</p> <pre><code>myproject |-- README.rst `-- myproject |-- __init__.py `-- capsall.py </code></pre> <p>Keep <em>__init__.py</em> simple and make sure that you can import it <strong>without</strong> dependencies. I use something like:</p> <pre><code>version_info = (0, 0, 0) version = '.'.join(str(v) for v in version_info) </code></pre> <p>Next, add a file named <em>setup.py</em> at the root. This is what will define your package, it's metadata, and the scripts to install into your user's <code>$PATH</code>. The following will work nicely:</p> <pre><code>#!/usr/bin/env python import setuptools import myproject setuptools.setup( name='myproject', version=myproject.version, description='Package of useful utilities.', long_description=open('README.rst').read(), url='https://github.com/me/myproject', author='Me', author_email='me@example.com', packages=['myproject'], entry_points={ 'console_scripts': ['capsall=myproject.capsall:main'], }, license='BSD', ) </code></pre> <p>If you plan on uploading to pypi.python.org, then you will need at least that much metadata. I would recommend adding <code>classifiers</code> as well. The <a href="https://packaging.python.org/distributing/" rel="nofollow">Python Packaging Authority docs</a> on writing a <em>setup.py</em> are invaluable.</p> <p>The part that you are most interested in is the <code>entry_points</code> keyword parameter. It defines various ways that your package can be invoked. You are looking for <code>console_scripts</code> since it creates shell scripts that are installed into the local path. See the <a href="https://setuptools.readthedocs.io/en/latest/setuptools.html#automatic-script-creation" rel="nofollow">setuptools documentation</a> for more details.</p> <p>The <code>console_scripts</code> definition that I gave above creates a script named <em>capsall</em> that invokes the <code>my project.capsall.main</code> function. I would repackage your code into a project. Bundle your script into the <em>main</em> function of the <em>capsall.py</em> module. Then generate a source repository and upload it to pypi.python.org (<code>./setup.py sdist register upload</code>). Once you have it uploaded, your users can install it using <code>pip install myproject</code>.</p> <p>Chances are that you have code that you don't want to give to the outside world. If that is the case, then you can generate a source distribution and make the tarball available on an internal server -- <code>./setup.py sdist</code> will generate a tarball in the <em>dist</em> directory. Then <code>pip install whatever/myproject-0.0.0.tar.gz</code> will install your script.</p>
1
2016-09-12T01:27:47Z
[ "python", "bash", "shell", "unix", "command" ]
Scrapy - Use proxy middleware but disable proxy for specific requests
39,432,024
<p>I want to use proxy middleware in my Scrapy but not every request needs a proxy. I don't want to abuse the proxy usage and make the proxy prone to get banned.</p> <p>Is there a way for me to disable proxy in some requests when the proxy middleware is turned on?</p>
-1
2016-09-11T01:22:25Z
39,432,238
<p>It's in the <a href="http://scrapy.readthedocs.io/en/latest/topics/downloader-middleware.html#module-scrapy.downloadermiddlewares.httpproxy" rel="nofollow">docs</a>. </p> <p>You can set the meta key <code>proxy</code> per-request, to a value like <code>http://some_proxy_server:port</code>.</p>
0
2016-09-11T02:13:44Z
[ "python", "web-scraping", "scrapy", "screen-scraping", "scrapy-spider" ]
How to use lists from a text file in python?
39,432,057
<p>i have been trying to read/write values(lists) in a .txt file and using them later, but i can't find a function or something to help me use these values as lists and not strings, since using the <code>readline</code> function doesn't help.</p> <p>Also, im don't want to use multiple text files to make up 1 list</p> <p>example:</p> <pre><code>v=[] f = open("test.txt","r+",-1) f.seek(0) v.append(f.readline()) print(v) </code></pre> <p>in test.txt</p> <pre><code>cat, dog, dinosaur, elephant cheese, hotdog, pizza, sushi 101, 23, 58, 23 </code></pre> <p>im expecting to the list <code>v = [cat, dog, dinosaur, elephant]</code> in separate indexes, but by doing this code (which is totally wrong) i get this instead <code>v = ['cat,dog,dinosaur,elephant']</code> which is what i don't want</p>
2
2016-09-11T01:29:53Z
39,432,175
<p>Sounds like you want to read it as comma separated values.</p> <p>Try the following</p> <pre><code>import csv with open('test.txt', newline='') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row) </code></pre> <p>I believe that will put you on the right track. For more information about how the csv parser works, have a look at the docs</p> <p><a href="https://docs.python.org/3/library/csv.html" rel="nofollow">https://docs.python.org/3/library/csv.html</a></p>
1
2016-09-11T01:56:12Z
[ "python", "list", "file", "python-3.x" ]
How to use lists from a text file in python?
39,432,057
<p>i have been trying to read/write values(lists) in a .txt file and using them later, but i can't find a function or something to help me use these values as lists and not strings, since using the <code>readline</code> function doesn't help.</p> <p>Also, im don't want to use multiple text files to make up 1 list</p> <p>example:</p> <pre><code>v=[] f = open("test.txt","r+",-1) f.seek(0) v.append(f.readline()) print(v) </code></pre> <p>in test.txt</p> <pre><code>cat, dog, dinosaur, elephant cheese, hotdog, pizza, sushi 101, 23, 58, 23 </code></pre> <p>im expecting to the list <code>v = [cat, dog, dinosaur, elephant]</code> in separate indexes, but by doing this code (which is totally wrong) i get this instead <code>v = ['cat,dog,dinosaur,elephant']</code> which is what i don't want</p>
2
2016-09-11T01:29:53Z
39,432,176
<p>To me, it looks like you're trying to read a file, and split it by <code>,</code>.<br> This can be accomplished by</p> <pre><code>f = open("test.txt", "r+").read() v = f.split(",") print(v) </code></pre> <p>It should output</p> <blockquote> <p>['cat', ' dog', ' dinosaur', ' elephant\ncheese', ...]</p> </blockquote> <p>And so forth.</p>
1
2016-09-11T01:56:31Z
[ "python", "list", "file", "python-3.x" ]
Can I include a for loop inside my print statement?
39,432,063
<p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p> <pre><code> for items in winners: print(items) </code></pre> <p>Can I include this in a print statement? I want:</p> <pre><code> print("The winners of {} were: {} with a score of {}".format(sport, winners, max_result)) </code></pre> <p>Is there a way of integrating the for loop into the print statement, or another way of eliminating the quotes and square brackets such that I can include it in the statement?</p> <p>Thanks.</p>
2
2016-09-11T01:30:44Z
39,432,094
<p>If <code>winners</code> is a list of strings, you can concatenate them using <code>str.join</code>.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; winners = ['John', 'Jack', 'Jill'] &gt;&gt;&gt; ', '.join(winners) 'John, Jack, Jill' </code></pre> <p>So you can put <code>', '.join(winners)</code> in your print call instead of <code>winners</code> and it will print the winners separated by commas.</p>
0
2016-09-11T01:35:51Z
[ "python", "python-3.x" ]
Can I include a for loop inside my print statement?
39,432,063
<p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p> <pre><code> for items in winners: print(items) </code></pre> <p>Can I include this in a print statement? I want:</p> <pre><code> print("The winners of {} were: {} with a score of {}".format(sport, winners, max_result)) </code></pre> <p>Is there a way of integrating the for loop into the print statement, or another way of eliminating the quotes and square brackets such that I can include it in the statement?</p> <p>Thanks.</p>
2
2016-09-11T01:30:44Z
39,432,097
<p>You can't include a for loop but you can join your list of winners into a string.</p> <pre><code>winners = ['Foo', 'Bar', 'Baz'] print('the winners were {}.'.format(', '.join(winners))) </code></pre> <p>This would print</p> <blockquote> <p>the winners were Foo, Bar, Baz.</p> </blockquote>
5
2016-09-11T01:36:44Z
[ "python", "python-3.x" ]
Can I include a for loop inside my print statement?
39,432,063
<p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p> <pre><code> for items in winners: print(items) </code></pre> <p>Can I include this in a print statement? I want:</p> <pre><code> print("The winners of {} were: {} with a score of {}".format(sport, winners, max_result)) </code></pre> <p>Is there a way of integrating the for loop into the print statement, or another way of eliminating the quotes and square brackets such that I can include it in the statement?</p> <p>Thanks.</p>
2
2016-09-11T01:30:44Z
39,432,198
<p>A for loop can only be supplied to <code>print</code> in the form of a comprehension.</p> <p>But, if the list contents are in the respective order you require you can simply do:</p> <pre><code>print("The winners of {} were: {} with a score of {}".format(*winners)) </code></pre> <p>This just matches each bracket with each item in the list. If you need to order this differently you just supply their relative position:</p> <pre><code>print("The winners of {1} were: {0} with a score of {2}".format(*winners)) </code></pre>
0
2016-09-11T02:02:10Z
[ "python", "python-3.x" ]
Can I include a for loop inside my print statement?
39,432,063
<p>I have a list of winners of an event. I want to print them out at the end of my code, minus the brackets and quotes, and I am currently using:</p> <pre><code> for items in winners: print(items) </code></pre> <p>Can I include this in a print statement? I want:</p> <pre><code> print("The winners of {} were: {} with a score of {}".format(sport, winners, max_result)) </code></pre> <p>Is there a way of integrating the for loop into the print statement, or another way of eliminating the quotes and square brackets such that I can include it in the statement?</p> <p>Thanks.</p>
2
2016-09-11T01:30:44Z
39,439,409
<p>First note, in Python 3 <code>print</code> is a function, but it was a statement in Python 2. Also you can't use a <code>for</code> statement as an argument. Only such weird solution comes to my mind, which only looks like a for loop:</p> <pre><code>data = ['Hockey','Swiss', '3'] print("Sport is {}, winner is {}, score is {}".format(*( _ for _ in data ))) </code></pre> <p>Of course, because <code>print</code> is a function, you can write your own function with all stuff you need, as an example:</p> <pre><code>def my_print(pattern, *data): print(pattern.format(*( _ for _ in data))) my_print("Sport is {}, winner is {}, score is {}", 'Hockey', 'Swiss', '3') </code></pre> <p>You can also read about <strong>f-strings</strong> <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow">"Literal String Interpolation" PEP 498</a>, which will be introduced in Python 3.6. This f-strings will provide a way to embed expressions inside string literals, using a minimal syntax.</p>
0
2016-09-11T18:39:19Z
[ "python", "python-3.x" ]
I can't expand the template django
39,432,090
<p>I can't expand the template <code>base.html</code> template <code>header.html</code></p> <p>Content <code>base.html</code></p> <pre><code>&lt;div id="main-container"&gt; &lt;!-- HEADER --&gt; {% block header %}{% endblock %} &lt;!-- END HEADER --&gt; &lt;/div&gt; </code></pre> <p>Content <code>header.html</code></p> <pre><code>{% extends "blog/base.html" %} {% block header %} &lt;header id="header"&gt; *** &lt;/header&gt; {% endblock %} </code></pre> <p>The output in the browser get the code:</p> <pre><code>&lt;div id="main-container"&gt; &lt;!-- HEADER --&gt; &lt;!-- END HEADER --&gt; </code></pre> <p>Why not be able to extend the template? Using <code>{% include "blog/header.html"%}</code> code inserted. using <code>extends</code> no. Use Django 1.10.1</p> <p><code>views.py</code></p> <pre><code>from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/index.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404 (Post, pk=pk) return render(request, 'blog/base.html', {'post': post}) def header(request): return render(request, 'blog/header.html') </code></pre> <p>Through <code>{% include "blog/header.html" %}</code> works. So the way spelled out correctly.</p> <p>Thought the error here:</p> <p><code>def header(request): return(request, 'blog/header.html')</code></p> <p><code>def header(request): render(request, 'blog/header.html')</code></p> <p><code>def header(request): return render_to_response (request, 'blog/header.html')</code></p> <p>Not working (((</p>
4
2016-09-11T01:35:19Z
39,433,889
<p>I think you would have confused between the include and extend in django templates. </p> <p>Based on your file names, I assume that <code>header.html</code> is the partial which is to be included in the base.html and you are rendering <code>base.html</code> . </p> <p>Django templating engine does not work this way.</p> <p>Use <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#include" rel="nofollow">include</a> <code>{% include "path/to/header.html" %}</code> in <code>base.html</code> and juse have the header html in <code>header.html</code>. </p>
0
2016-09-11T07:38:23Z
[ "python", "django", "templates" ]
I can't expand the template django
39,432,090
<p>I can't expand the template <code>base.html</code> template <code>header.html</code></p> <p>Content <code>base.html</code></p> <pre><code>&lt;div id="main-container"&gt; &lt;!-- HEADER --&gt; {% block header %}{% endblock %} &lt;!-- END HEADER --&gt; &lt;/div&gt; </code></pre> <p>Content <code>header.html</code></p> <pre><code>{% extends "blog/base.html" %} {% block header %} &lt;header id="header"&gt; *** &lt;/header&gt; {% endblock %} </code></pre> <p>The output in the browser get the code:</p> <pre><code>&lt;div id="main-container"&gt; &lt;!-- HEADER --&gt; &lt;!-- END HEADER --&gt; </code></pre> <p>Why not be able to extend the template? Using <code>{% include "blog/header.html"%}</code> code inserted. using <code>extends</code> no. Use Django 1.10.1</p> <p><code>views.py</code></p> <pre><code>from django.shortcuts import render from django.utils import timezone from .models import Post from django.shortcuts import render, get_object_or_404 def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/index.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404 (Post, pk=pk) return render(request, 'blog/base.html', {'post': post}) def header(request): return render(request, 'blog/header.html') </code></pre> <p>Through <code>{% include "blog/header.html" %}</code> works. So the way spelled out correctly.</p> <p>Thought the error here:</p> <p><code>def header(request): return(request, 'blog/header.html')</code></p> <p><code>def header(request): render(request, 'blog/header.html')</code></p> <p><code>def header(request): return render_to_response (request, 'blog/header.html')</code></p> <p>Not working (((</p>
4
2016-09-11T01:35:19Z
39,437,525
<p>If you want to extend some template, you should render template with {% extends ... %} tag (in your case header.html), if you want to include something to renedered template, you should use {% include ... %} tag. You can make new template for particular page and ovreload {% block head %}, for example:</p> <p>base.html:</p> <pre><code>{% block header %} {% include 'std_header.html' %} {% endblock %} {% block content %} {% endblock %} {% block footer%} {% endblock %} </code></pre> <p>And particular page, for example landing page will overload default header:</p> <p>landing.html:</p> <pre><code>{% extends 'base.html' %} {% block header %} {% include 'landing_header.html' %} {% endblock %} {% block content %} &lt;!-- landing page content --&gt; {% endblock %} </code></pre> <p>So for view called landing_page you have to render landing.html template.</p>
0
2016-09-11T15:11:54Z
[ "python", "django", "templates" ]
pandas: Keep only every row that has cumulated change by a threshold?
39,432,140
<p>I'm interested to extract the rows where a column's value has either gone up cumulatively by at least 5 or gone down cumulatively by at least 5, then get the signs of these cumulative changes, <code>up_or_down</code>.</p> <p>For example, let's say I want to apply this to column <code>y</code> in the following:</p> <pre><code>df = pd.DataFrame({'x': range(16), 'y': [1,10,14,12,13,9,4,2,6,7,10,11,16,17,14,11]}) </code></pre> <p>It should yield:</p> <pre><code>x y # up_or_down 1 10 # +1 6 4 # -1 10 10 # +1 12 16 # +1 15 11 # -1 </code></pre> <p>My dataframe is quite large so I was hoping that there is a nice vectorized way to do this natively with pandas's API rather than looping through it with <code>iterrows()</code>.</p>
4
2016-09-11T01:47:12Z
39,432,516
<p>You can't get it vectorized through the standard functions pandas exposed: the nth point to find moving by +/-5 from n-1th is dynamically found and will depend on the position of n-1th, which itself depends on the n-2 first dynamically determined points. Thus there is no math associated to rolling or expanding set of functions that can project you in a vector space requiring this dynamism. So you have to write you iteration ad-hoc. </p>
1
2016-09-11T03:17:45Z
[ "python", "pandas", "numpy" ]
pandas: Keep only every row that has cumulated change by a threshold?
39,432,140
<p>I'm interested to extract the rows where a column's value has either gone up cumulatively by at least 5 or gone down cumulatively by at least 5, then get the signs of these cumulative changes, <code>up_or_down</code>.</p> <p>For example, let's say I want to apply this to column <code>y</code> in the following:</p> <pre><code>df = pd.DataFrame({'x': range(16), 'y': [1,10,14,12,13,9,4,2,6,7,10,11,16,17,14,11]}) </code></pre> <p>It should yield:</p> <pre><code>x y # up_or_down 1 10 # +1 6 4 # -1 10 10 # +1 12 16 # +1 15 11 # -1 </code></pre> <p>My dataframe is quite large so I was hoping that there is a nice vectorized way to do this natively with pandas's API rather than looping through it with <code>iterrows()</code>.</p>
4
2016-09-11T01:47:12Z
39,433,126
<p>see <a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1751/indexing-and-selecting-data/19351/path-dependent-slicing#t=201609082151350926644">Path Dependent Slicing</a></p> <p>This is the core of the solution</p> <pre><code>def big_diff(y): val = y.values r = val[0] for i, x in enumerate(val): d = r - x if abs(d) &gt;= 5: yield i, 1 if d &lt; 0 else -1 r = x </code></pre> <p>Then you can do something like this</p> <pre><code>slc = np.array(list(big_diff(df.y))) df_slcd = pd.DataFrame(df.values[slc[:, 0]], df.index[slc[:, 0]], df.columns) signs = pd.Series(slc[:, 1], df.index[slc[:, 0]], name='up_or_down') df_slcd </code></pre> <p><a href="http://i.stack.imgur.com/ns6V5.png" rel="nofollow"><img src="http://i.stack.imgur.com/ns6V5.png" alt="enter image description here"></a></p> <pre><code>signs 1 1 6 -1 10 1 12 1 15 -1 Name: up_or_down, dtype: int64 </code></pre> <hr> <pre><code>pd.concat([df_slcd, signs], axis=1) </code></pre> <p><a href="http://i.stack.imgur.com/xGzIR.png" rel="nofollow"><img src="http://i.stack.imgur.com/xGzIR.png" alt="enter image description here"></a></p>
3
2016-09-11T05:20:09Z
[ "python", "pandas", "numpy" ]
How can I speed this up? (urllib2, requests)
39,432,156
<p>Problem: I am trying to validate a captcha can be anything from 0000-9999, using the normal requests module it takes around 45 minutes to go through all of them (0000-9999). How can I multithread this or speed it up? Would be really helpful if I can get the HTTP Status Code from the site to see if i successfully got the code correct or if it is incorrect (200 = correct, 400 = incorrect) If I could get two examples (GET and POST) of this that would be fantastic!</p> <p>I have been searching for quite some time, most of the modules I look at are outdated (I have been using grequests recently)</p> <pre><code>example url = https://www.google.com/ example params = captcha=0001 example post data = {"captcha":0001} </code></pre> <p>Thank you!</p>
-2
2016-09-11T01:52:39Z
39,432,188
<p><strong>You really shouldn't be trying to bypass a captcha programmatically!</strong></p> <p>You could use several threads to make simultaneous requests but at that point the service you're attacking will most likely ban your IP. At the very least, they've probably got throttling on the service; There's a reason it's supposed to take 45 minutes.</p> <p><a href="https://docs.python.org/2/library/threading.html" rel="nofollow">Threading in Python</a> is usually achieved by creating a thread object with a <code>run()</code> method containing your long running code. In your case, you might want to create a thread object which takes a number range to poll. Once instantiated, you'd call the <code>.start()</code> method to have that thread begin working. If any thread should get a success message it would return a message to the main thread, halt itself, and the main thread could then tell all the other threads in the thread pool to stop.</p>
5
2016-09-11T01:59:01Z
[ "python", "python-requests", "urllib2" ]
Optimizing Keras to use all available CPU resources
39,432,170
<p>Ok, I don't really know what I'm talking about here so bear with me. </p> <p>I am running Keras with Theano backend to run a basic neural net (just a tutorial set up for now) on MNIST images. In the past, I have been using my old HP laptop because I have a dual boot setup with Windows and Ubuntu 16.06. I am trying to replace this laptop so I can retire it and use my new(er) Sony laptop. I set up the same dual boot with Ubuntu 16.06 and Windows 10. Here is the issue:</p> <p>When I run it on my old HP (Ubuntu), I get significantly better performance (in terms of time). I ran the same program on both machines at the same time and, using the Ubuntu system monitor, found that the old HP machine uses all 4 cores and, thus, 100% of available CPU. The newer Sony only uses 1 core and caps out at ~26% CPU. </p> <p>I would prefer to avoid having to deal with manually multi-threading if at all possible. I have tried using openmp to no avail, and the HP uses all 4 cores without it anyway.</p> <p>I'm pretty sure that I followed the same setup on both machines but I may have installed extra packages on the HP since I did that a while ago and may have forgotten what I installed. I have also tried using Python (2.7) and python3, each with the same setup.</p> <p>I don't know what I'm looking for, but any ideas or input would be greatly appreciated. I'm happy to provide any more information as I'm not sure what is relevant in this case. And thank you in advance.</p>
2
2016-09-11T01:54:36Z
39,432,216
<p>Ok of course I figured it out right after I posted the question. Sorry if I wasted anyone's time. </p> <p>I just reinstalled everything using apt-get instead of pip and that worked. Not sure why, maybe I missed something the first time. Anyway, </p> <pre><code>sudo apt-get install python-numpy python-scipy python-dev python-nose g++ libblas-dev git </code></pre> <p>fixed it. Not sure which package. I think I just used <code>sudo apt-get install theano</code> the the first time. </p>
2
2016-09-11T02:06:45Z
[ "python", "multithreading", "ubuntu", "theano", "keras" ]
Finding the Dot Product of two different key-value lists within a single dictionary
39,432,185
<p>I am using this method to create a dictionary where the keys are Names which are paired with a list of values</p> <pre><code>def create_voting_dict(strlist): return {line.split()[0]:[int(x) for x in line.split()[3:]] for line in strlist} </code></pre> <p>However, now I have to take the dot product of the values of two keys found in the dictionary. This new problem begins as follows:</p> <pre><code>def policy_compare(sen_a, sen_b, voting_dict): </code></pre> <p>I am having issues trying to find what to return in this situation. Any help is welcome! Thanks in advance!</p> <p>Oh! An example of an expected outcome would look like this:</p> <pre><code> ...voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]} ...policy_compare('Fox-Epstein','Ravella', voting_dict) ...-2 </code></pre>
1
2016-09-11T01:58:49Z
39,432,239
<p>I hope this is what you need. </p> <pre><code>def create_voting_dict(strlist): return {line.split()[0]:[int(x) for x in line.split()[3:]] for line in strlist} def dot(K, L): if len(K) != len(L): return 0 return sum(i[0] * i[1] for i in zip(K, L)) def policy_compare(sen_a, sen_b, voting_dict): return dot(voting_dict[sen_a], voting_dict[sen_b]) voting_dict = {'Fox-Epstein':[-1,-1,-1,1],'Ravella':[1,1,1,1]} print(policy_compare('Fox-Epstein','Ravella', voting_dict)) </code></pre> <p>It returns -2. </p>
0
2016-09-11T02:14:35Z
[ "python", "list", "dictionary", "product", "dot" ]
Django Twitter clone. How to restrict user from liking a tweet more than once?
39,432,191
<p>I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.</p> <p>models.py</p> <pre><code>class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) published_date = models.DateTimeField(default=timezone.now) like_count = models.IntegerField(default=0) rehowl_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('howl:index') def __str__(self): return self.content </code></pre> <p>views.py</p> <pre><code>class HowlLike(UpdateView): model = Howl fields = [] def form_valid(self, form): instance = form.save(commit=False) instance.like_count += 1 instance.save() return redirect('howl:index') </code></pre> <p>Django Twitter clone. How to restrict user from liking a tweet more than once?</p>
1
2016-09-11T01:59:33Z
39,432,287
<p>An idea could be adding a column to your table named <code>likers</code> and before incrementing like_counts check if the models.likers contains the new liker or not. If not increment the likes, if yes don't.</p>
0
2016-09-11T02:25:00Z
[ "python", "django" ]
Django Twitter clone. How to restrict user from liking a tweet more than once?
39,432,191
<p>I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.</p> <p>models.py</p> <pre><code>class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) published_date = models.DateTimeField(default=timezone.now) like_count = models.IntegerField(default=0) rehowl_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('howl:index') def __str__(self): return self.content </code></pre> <p>views.py</p> <pre><code>class HowlLike(UpdateView): model = Howl fields = [] def form_valid(self, form): instance = form.save(commit=False) instance.like_count += 1 instance.save() return redirect('howl:index') </code></pre> <p>Django Twitter clone. How to restrict user from liking a tweet more than once?</p>
1
2016-09-11T01:59:33Z
39,432,323
<p>As well as tracking how many <code>Likes</code> a post has, you'll probably also want to track who has "Liked" each post. You can solve both of these problems by creating a joining table <code>Likes</code> with a unique key on <code>User</code> and <code>Howl</code>.</p> <p>The unique key will prevent any <code>User</code> from doing duplicate likes.</p> <p>You can do this in Django with a <a href="https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/" rel="nofollow"><code>ManyToManyField</code></a>, note that since this means adding a second <code>User</code> relationship to <code>Howl</code>, we need to disambiguate the relationship by providing a <code>related_name</code></p> <p>Eg:</p> <pre><code>class Howl(models.Model): author = models.ForeignKey(User, null=True, related_name='howls_authored') liked_by = models.ManyToManyField(User, through='Like') # ...rest of class as above class Like(models.Model): user = models.ForeignKey(User) howl = models.ForeignKey(Howl) class Meta: unique_together = (('user', 'howl')) </code></pre> <p><code>like_count</code> count then becomes redundant, since you can use <code>Howl.liked_by.count()</code> instead.</p> <p>The other benefit of this is that it allows you to store information about the <code>Like</code> - eg when it was added.</p>
1
2016-09-11T02:31:16Z
[ "python", "django" ]
Django Twitter clone. How to restrict user from liking a tweet more than once?
39,432,191
<p>I'm not sure where to start. Right now, the user can press like as many times they want and it'll just add up the total likes for that tweet.</p> <p>models.py</p> <pre><code>class Howl(models.Model): author = models.ForeignKey(User, null=True) content = models.CharField(max_length=150) published_date = models.DateTimeField(default=timezone.now) like_count = models.IntegerField(default=0) rehowl_count = models.IntegerField(default=0) def get_absolute_url(self): return reverse('howl:index') def __str__(self): return self.content </code></pre> <p>views.py</p> <pre><code>class HowlLike(UpdateView): model = Howl fields = [] def form_valid(self, form): instance = form.save(commit=False) instance.like_count += 1 instance.save() return redirect('howl:index') </code></pre> <p>Django Twitter clone. How to restrict user from liking a tweet more than once?</p>
1
2016-09-11T01:59:33Z
39,432,360
<p>Changed liked_count in my models.py to </p> <pre><code>liked_by = models.ManyToManyField(User, related_name="likes") </code></pre> <p>views.py </p> <pre><code>class HowlLike(UpdateView): model = Howl fields = [] def form_valid(self, form): instance = form.save(commit=False) instance.liked_by.add(self.request.user) instance.like_count = instance.liked_by.count() instance.save() return redirect('howl:index') </code></pre> <p>index.html</p> <pre><code>{{howl.liked_by.count}} </code></pre>
0
2016-09-11T02:41:55Z
[ "python", "django" ]
Python - How to find UUID of computer and set as variable
39,432,305
<p>I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python. </p> <p>Some of the ways I tried doing didn't work.</p> <p>Original idea:</p> <pre><code>import os x = os.system("wmic diskdrive get serialnumber") print(x) </code></pre> <p>However this does not work, and only returns 0. </p> <p>I am wondering if their is a way i can find a unique Harddrive ID or any other type of identifier in python. </p>
0
2016-09-11T02:28:11Z
39,432,381
<p>You can use <a href="https://docs.python.org/2/library/uuid.html#uuid.uuid1" rel="nofollow"><code>uuid1</code></a> from the standard library <code>uuid</code> module:</p> <pre><code>import uuid myuuid = uuid.uuid1() </code></pre> <p>This can be used to:</p> <blockquote> <p>Generate a UUID from a host ID, sequence number, and the current time.</p> </blockquote> <p>However, please note that you should be careful where you use this uuid because it </p> <blockquote> <p>may compromise privacy since it creates a UUID containing the computer’s network address.</p> </blockquote> <p>If this is not what you are looking for, <a href="https://docs.python.org/2/library/uuid.html#module-uuid" rel="nofollow">the <code>uuid</code> modul</a>e has lots of other good ways to generate uuids.</p> <p>Also, see <a href="http://stackoverflow.com/a/4194146/3642398">this answer</a> for detailed instructions on how to get a harddrive serial number with Python, if that is what you are looking for.</p>
0
2016-09-11T02:46:48Z
[ "python", "python-3.x", "hwid" ]
Python - How to find UUID of computer and set as variable
39,432,305
<p>I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python. </p> <p>Some of the ways I tried doing didn't work.</p> <p>Original idea:</p> <pre><code>import os x = os.system("wmic diskdrive get serialnumber") print(x) </code></pre> <p>However this does not work, and only returns 0. </p> <p>I am wondering if their is a way i can find a unique Harddrive ID or any other type of identifier in python. </p>
0
2016-09-11T02:28:11Z
39,432,621
<p>The os.system function returns the exit code of the executed command, not the standard output of it.</p> <p>According to <a href="https://docs.python.org/3.4/library/os.html#os.system" rel="nofollow">Python official documentation</a>:</p> <blockquote> <p>On Unix, the return value is the exit status of the process encoded in the format specified for wait(). </p> <p>On Windows, the return value is that returned by the system shell after running command.</p> </blockquote> <p>To get the output as you want, the recommended approach is to use some of the functions defined in the subprocess module. Your scenario is pretty simple, so subprocess.check_output works just fine for it.</p> <p>You just need to replace the code you posted code with this instead:</p> <pre><code>import subprocess x = subprocess.check_output('wmic csproduct get UUID') print(x) </code></pre>
1
2016-09-11T03:38:46Z
[ "python", "python-3.x", "hwid" ]
Python - How to find UUID of computer and set as variable
39,432,305
<p>I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python. </p> <p>Some of the ways I tried doing didn't work.</p> <p>Original idea:</p> <pre><code>import os x = os.system("wmic diskdrive get serialnumber") print(x) </code></pre> <p>However this does not work, and only returns 0. </p> <p>I am wondering if their is a way i can find a unique Harddrive ID or any other type of identifier in python. </p>
0
2016-09-11T02:28:11Z
39,432,627
<p>If the aim is to get the serial number of the HDD, then one can do:</p> <p>In Linux (replace /dev/sda with the block disk identifier for which you want the info):</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.popen("hdparm -I /dev/sda | grep 'Serial Number'").read().split()[-1] </code></pre> <p>In Windows:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; os.popen("wmic diskdrive get serialnumber").read().split()[-1] </code></pre>
2
2016-09-11T03:41:29Z
[ "python", "python-3.x", "hwid" ]
How do I calculate cosine similarity from TfidfVectorizer?
39,432,350
<p>I have two CSV files - train and test, with 18000 reviews each. I need to use the train file to do feature extraction and calculate the similarity metric between each review in the train file and each review in the test file. </p> <p>I generated a vocabulary based on words from the train and test set - I eliminated stop words but did not remove typos and stem.</p> <p>The problem I'm facing is - I don't know how to use the output from TfIdfVectorizer to generate cosine similarities between the train and test data. </p> <p>This is the code snippet that fits my train data to <code>vocabulary</code>: </p> <pre><code>vect = TfidfVectorizer(sublinear_tf=True, min_df=0.5, vocabulary=vocabulary) X = vect.fit_transform(train_list) vocab = vect.get_feature_names() # train_matrix = X.todense() train_idf = vect.idf_ print vocab print X.todense() </code></pre> <p>The output I get from X.todense() is </p> <pre><code>[[ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.] ..., [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.] [ 0. 0. 0. ..., 0. 0. 0.]] </code></pre> <p>If I simply print X, it looks like this : </p> <pre><code>(0, 28137) 0.114440020953 (0, 27547) 0.238913278498 (0, 26519) 0.14777362826 (0, 26297) 0.247716207254 (0, 26118) 0.178776605168 (0, 26032) 0.15139993147 (0, 25771) 0.10334152493 (0, 25559) 0.157584788446 (0, 25542) 0.0909693864147 (0, 25538) 0.179738937276 (0, 21762) 0.112899547719 (0, 21471) 0.159940534946 (0, 21001) 0.0931693893501 (0, 13960) 0.134069984961 (0, 12535) 0.198190713402 (0, 11918) 0.142570540903 : : (18505, 18173) 0.237810781785 (18505, 17418) 0.233931974117 (18505, 17412) 0.129587180209 (18505, 17017) 0.130917070234 (18505, 17014) 0.137794139419 (18505, 15943) 0.130040669343 (18505, 15837) 0.0790013472346 (18505, 11865) 0.158061557865 (18505, 10896) 0.0708161593204 (18505, 10698) 0.0846731116968 (18505, 10516) 0.116681527108 (18505, 8668) 0.122364898181 (18505, 7956) 0.174450779875 (18505, 1111) 0.191477939381 (18505, 73) 0.257945257626 </code></pre> <p>I don't know how to read the output from X.todense() or print X and I'm not sure how to find the cosine distance between the test and train sets (probably using pairwise similarity? - <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html" rel="nofollow">http://scikit-learn.org/stable/modules/generated/sklearn.metrics.pairwise.pairwise_distances.html</a> ?)</p> <p>Edit:</p> <p>I repeated the same steps for my test data. Now I have two sparse matrices X and Y of type <code>scipy.sparse.csr.csr_matrix</code> - but since they're both sparse and of type <code>(doc, term) tf-idf</code> I can't directly get the cosine similarity between X and Y by direct multiplication. </p> <p>Converting X and Y with <code>todense()</code> gives me a MemoryError - which means it's inefficient.</p> <p>What should I do next? </p> <p>I need to get some sort of matrix with pairwise cosine similarities of dimensions 18000 * 18000, or a sparse matrix but I don't know how to do that. </p> <p>This is for homework and no amount of reading sklearn documentation is helping me at this stage. </p>
1
2016-09-11T02:39:21Z
39,432,596
<p>You are almost there. Using <code>vect.fit_transform</code> returns a sparse-representation of a <a href="https://en.wikipedia.org/wiki/Document-term_matrix" rel="nofollow">document-term matrix.</a> It is the document-term matrix representation of your training set. You would then need to transform the testing set with the same model. Hint: use the <code>transform</code> method on <code>test_list</code>. You are in luck, because <code>sklearn.metrics.pairwise.pairwise_distances(X, Y)</code> takes sparse matrices for <code>X</code> and <code>Y</code> when <code>metric='euclidean'</code> is passed (i.e. the metric you want). It should be pretty straightforward what you need to do from here.</p>
1
2016-09-11T03:33:13Z
[ "python", "numpy", "scikit-learn", "sparse-matrix", "tf-idf" ]
Installing flask extension: ext = Ext(app) versus Ext(app)
39,432,374
<p>I'm learning flask web development by following a tutorial. Currently, the first few lines of my app is:</p> <pre><code>from flask import Flask, render_template from flask_bootstrap import Bootstrap app = Flask(__name__) bootstrap = Bootstrap(app) </code></pre> <p>However, when I change <code>bootstrap = Bootstrap(app)</code> to <code>Bootstrap(app)</code>, nothing breaks. So what's the purpose of storing the <code>Bootstrap</code> instance in a variable, which is not used in the rest of code?</p>
-1
2016-09-11T02:44:21Z
39,433,780
<p>With your current code, it's true there is no need to keep the instance into a variable, </p> <p>But in practice, you would create the Bootstrap instance without passing the <code>app</code> instance, then on some initialization method, you would call the <code>init_app</code> method of the Bootstrap instance to initialize it with <code>app</code>, like so:</p> <pre><code>bootstrap = Bootstrap() def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) bootstrap.init_app(app) return app </code></pre> <p>This will also include all other instances of other tools, like Flask-SQLALchemy, Moment, Mail...etc</p>
1
2016-09-11T07:20:52Z
[ "python", "flask", "flask-extensions" ]
Python: sorting sublist values in nested list
39,432,385
<p>I have a nested list: <code>list = [[3,2,1],[8,7,9],[5,6,4]]</code></p> <p>I want to sort each sublist in ascending order. My though was to loop through the list, but it only wants to sort the last sublist.</p> <p><code>for i in list: newList = sorted[i]</code></p> <p>So for this example the for loop would loop through the whole list, but only sort the last sublist [5,6,4]. How do I make it sort all the sublists?</p> <p>Python version: 2.7.10 </p> <p>OS: OS X El Capitan</p>
0
2016-09-11T02:48:21Z
39,432,402
<p>You are creating a new list and assigning it to a new name, then throwing it away. Use the <code>sort</code> method to sort each list reference to in-place. Also note that it doesn't make sense to use a list reference to index the main list, and that you should avoid naming variables with the same name as built-in functions (<code>list</code> in this case).</p> <pre><code>&gt;&gt;&gt; l = [[3,2,1],[8,7,9],[5,6,4]] &gt;&gt;&gt; for i in l: ... i.sort() ... &gt;&gt;&gt; l [[1, 2, 3], [7, 8, 9], [4, 5, 6]] </code></pre>
1
2016-09-11T02:51:46Z
[ "python", "python-2.7" ]
Python: sorting sublist values in nested list
39,432,385
<p>I have a nested list: <code>list = [[3,2,1],[8,7,9],[5,6,4]]</code></p> <p>I want to sort each sublist in ascending order. My though was to loop through the list, but it only wants to sort the last sublist.</p> <p><code>for i in list: newList = sorted[i]</code></p> <p>So for this example the for loop would loop through the whole list, but only sort the last sublist [5,6,4]. How do I make it sort all the sublists?</p> <p>Python version: 2.7.10 </p> <p>OS: OS X El Capitan</p>
0
2016-09-11T02:48:21Z
39,432,404
<p>You are replacing the value of newList on each iteration in the for loop. Hence, after the for loop ends, the value of newList is equal to the sorted value of the last list in the original nested list. Do this:</p> <pre><code>&gt;&gt;&gt; list = [[3,2,1],[8,7,9],[5,6,4]] &gt;&gt;&gt; newlist = map(sorted, list) &gt;&gt;&gt; newlist [[1, 2, 3], [7, 8, 9], [4, 5, 6]] </code></pre>
1
2016-09-11T02:51:56Z
[ "python", "python-2.7" ]
Python: sorting sublist values in nested list
39,432,385
<p>I have a nested list: <code>list = [[3,2,1],[8,7,9],[5,6,4]]</code></p> <p>I want to sort each sublist in ascending order. My though was to loop through the list, but it only wants to sort the last sublist.</p> <p><code>for i in list: newList = sorted[i]</code></p> <p>So for this example the for loop would loop through the whole list, but only sort the last sublist [5,6,4]. How do I make it sort all the sublists?</p> <p>Python version: 2.7.10 </p> <p>OS: OS X El Capitan</p>
0
2016-09-11T02:48:21Z
39,432,476
<p>The reason your code is not working is because you are creating a new sorted list (<code>sorted()</code> creates a new list) and assigning it to a variable (<code>newList</code>). This variable goes unused.</p> <p>Python lists have a <code>.sort()</code> method. So your loop code can work as follows</p> <pre><code>for sublist in list: sublist.sort() #sorts the sublist in place print list #all sublists will be sorted in ascending order </code></pre> <p>As mentioned by Nehal J Wani, you can also use a map to apply one function to each element of a list.</p> <pre><code>newSortedList = map(sorted,list) #newSortedList will have all sublists sorted </code></pre>
0
2016-09-11T03:08:02Z
[ "python", "python-2.7" ]
issues with python virtual environment
39,432,392
<p><br> I am facing following 2 issues:<br></p> <ol> <li>python command is not using the virtualenvwrapper python.<br> After activating my virtual environment if I type python then the code still uses the native python libraries. I can easily install libraries etc with pip to my virtual environment but I cannot run any command using python.<br> e.g. if I execute <br><b>$ ./manage.py runserver</b><br>then it is fine and I can run a django server <br> but if I try <br><b>$ python manage.py runserver</b><br> or even just<br> <b>$ python</b><br> then it uses the native python libraries and that should not happen<br></li> </ol> <p>This is while using iterm or terminal in osx. I have never faced this problem in any linux based os</p> <ol start="2"> <li>While using any os (linux based or osx), the <b>workon</b> command doesn't work inside any shell script, while it works normally in a terminal<br></li> </ol> <p>os: osx</p>
0
2016-09-11T02:50:17Z
39,432,512
<ol> <li><p>sounds like Python might be using the packages in site-packages, which means you should use the <code>--no-site-packages</code> flag when creating your virtualenv (although it seems like <a href="https://virtualenv.pypa.io/en/stable/reference/#cmdoption--no-site-packages" rel="nofollow">this is the default</a> in the current version of virtualenv).</p></li> <li><p>In order to access the <code>virtualenvwrapper</code> functions from a shell script, you will first need to <code>source</code> it: <code>$ source /usr/local/bin/virtualenvwrapper.sh</code> (the path might be different in your case).</p></li> </ol>
0
2016-09-11T03:16:54Z
[ "python", "linux", "django", "osx" ]
issues with python virtual environment
39,432,392
<p><br> I am facing following 2 issues:<br></p> <ol> <li>python command is not using the virtualenvwrapper python.<br> After activating my virtual environment if I type python then the code still uses the native python libraries. I can easily install libraries etc with pip to my virtual environment but I cannot run any command using python.<br> e.g. if I execute <br><b>$ ./manage.py runserver</b><br>then it is fine and I can run a django server <br> but if I try <br><b>$ python manage.py runserver</b><br> or even just<br> <b>$ python</b><br> then it uses the native python libraries and that should not happen<br></li> </ol> <p>This is while using iterm or terminal in osx. I have never faced this problem in any linux based os</p> <ol start="2"> <li>While using any os (linux based or osx), the <b>workon</b> command doesn't work inside any shell script, while it works normally in a terminal<br></li> </ol> <p>os: osx</p>
0
2016-09-11T02:50:17Z
39,433,252
<p>You could try install virtualenv and virtualenvwrapper from pip3.</p> <pre><code>pip3 install virtualenv virtualenvwrapper </code></pre> <p>And then find where virtualenvwrapper.sh file is:</p> <pre><code>find / -name 'virualenvwrapper.sh' </code></pre> <p>I have mine in <code>/usr/local/bin/virtualenvwrapper.sh</code>. But it seems that you have it in some different directory. So you must change below config to fit your needs. And then in your <code>.bashrc</code> or <code>.zshrc</code>:</p> <pre><code># Python3 virtualenv/venvwrapper export WORKON_HOME=~/.virtualenvs VIRTUALENVWRAPPER_PYTHON='/usr/bin/python3' # This needs to be placed before the virtualenvwrapper command export PROJECT_HOME=$HOME/Projects source /usr/local/bin/virtualenvwrapper.sh # your path to virtualenvwrapper.sh </code></pre> <p>Let me know if it works :)</p>
0
2016-09-11T05:48:59Z
[ "python", "linux", "django", "osx" ]
Mutability of lists in python
39,432,396
<p>Example one: Changing the value that has been appended to b changes the value in the original list l</p> <pre><code>&gt;&gt;&gt; l = [1 , 2, 3] &gt;&gt;&gt; b = [] &gt;&gt;&gt; b.append(l) &gt;&gt;&gt; b[0].append(4) &gt;&gt;&gt; b [[1, 2, 3, 4]] &gt;&gt;&gt; l [1, 2, 3, 4] </code></pre> <p>Example 2: l1 is appended to ans and then the value of l1 is modified. However, the value in ans remains the same.</p> <pre><code>&gt;&gt;&gt; l1 = [1, 2, 3] &gt;&gt;&gt; ans = [] &gt;&gt;&gt; ans.append(l1) &gt;&gt;&gt; ans [[1, 2, 3]] &gt;&gt;&gt; l1 = [2, 3, 4] &gt;&gt;&gt; ans [[1, 2, 3]] </code></pre> <p>I seem to be missing some fundamental point about the mutability of lists. Could someone please point it out?</p>
1
2016-09-11T02:50:35Z
39,432,418
<p>You are not mutating <code>l1</code>. You are assigning a new object to the same name, which makes that name point to a new object. You are moving a label, not modifying an object. The only remaining reference to the list that <code>l1</code> used to point to is now <code>ans[0]</code>.</p>
3
2016-09-11T02:54:44Z
[ "python", "list", "mutable" ]
Mutability of lists in python
39,432,396
<p>Example one: Changing the value that has been appended to b changes the value in the original list l</p> <pre><code>&gt;&gt;&gt; l = [1 , 2, 3] &gt;&gt;&gt; b = [] &gt;&gt;&gt; b.append(l) &gt;&gt;&gt; b[0].append(4) &gt;&gt;&gt; b [[1, 2, 3, 4]] &gt;&gt;&gt; l [1, 2, 3, 4] </code></pre> <p>Example 2: l1 is appended to ans and then the value of l1 is modified. However, the value in ans remains the same.</p> <pre><code>&gt;&gt;&gt; l1 = [1, 2, 3] &gt;&gt;&gt; ans = [] &gt;&gt;&gt; ans.append(l1) &gt;&gt;&gt; ans [[1, 2, 3]] &gt;&gt;&gt; l1 = [2, 3, 4] &gt;&gt;&gt; ans [[1, 2, 3]] </code></pre> <p>I seem to be missing some fundamental point about the mutability of lists. Could someone please point it out?</p>
1
2016-09-11T02:50:35Z
39,432,426
<p>Replace </p> <pre><code>&gt;&gt;&gt; l1 = [2, 3, 4] </code></pre> <p>with</p> <pre><code>&gt;&gt;&gt; l1[:] = [2, 3, 4] </code></pre> <p>That will not assign a new list to l1.</p>
0
2016-09-11T02:56:41Z
[ "python", "list", "mutable" ]
Mutability of lists in python
39,432,396
<p>Example one: Changing the value that has been appended to b changes the value in the original list l</p> <pre><code>&gt;&gt;&gt; l = [1 , 2, 3] &gt;&gt;&gt; b = [] &gt;&gt;&gt; b.append(l) &gt;&gt;&gt; b[0].append(4) &gt;&gt;&gt; b [[1, 2, 3, 4]] &gt;&gt;&gt; l [1, 2, 3, 4] </code></pre> <p>Example 2: l1 is appended to ans and then the value of l1 is modified. However, the value in ans remains the same.</p> <pre><code>&gt;&gt;&gt; l1 = [1, 2, 3] &gt;&gt;&gt; ans = [] &gt;&gt;&gt; ans.append(l1) &gt;&gt;&gt; ans [[1, 2, 3]] &gt;&gt;&gt; l1 = [2, 3, 4] &gt;&gt;&gt; ans [[1, 2, 3]] </code></pre> <p>I seem to be missing some fundamental point about the mutability of lists. Could someone please point it out?</p>
1
2016-09-11T02:50:35Z
39,432,437
<p>In your first example, <code>l</code> is a pointer, as well as <code>b</code>.</p> <p><code>l</code> is then appended to b, so <code>b[0]</code> now refers to the pointer.</p> <p>Next, you append 4 to <code>b[0]</code>, which is the same thing as <code>l</code>, so 4 is added to both <code>b[0]</code> <em>and</em> <code>l</code>.</p> <hr> <p>In your second example, <code>ans</code> contains the pointer of <code>l1</code>, just like <code>b</code> contained the pointer of <code>l</code></p> <p>Then, you changed <code>l1</code> itself by assigning it to a different array, so <code>l1</code> changed but <code>ans[0]</code> did not.</p> <hr> <p>The biggest takeaway from this is that <code>append</code> just changes the list, and the pointer remains the same. But when you set a variable to a different list, the pointer changes.</p>
2
2016-09-11T02:59:42Z
[ "python", "list", "mutable" ]
Python tkinter checkbutton value always equal to 0
39,432,539
<p>I put the <code>checkbutton</code> on the <code>text</code> widget, but everytime I select a <code>checkbutton</code>, the function <code>checkbutton_value</code> is called, and it returns 0.</p> <p>Part of the code is :</p> <pre><code>def callback(): file_name=askopenfilename() column_1rowname,column_name=draw_column(file_name) root = Tk() root.resizable(width=False,height=False) root.wm_title("Column") S = Scrollbar(root,orient="vertical") text=Text(root,width=15,height=10,yscrollcommand=S.set) S.config(command=text.yview) S.pack(side="right",fill="y") text.pack(side="left",fill="both",expand=True) #check the value of the checkbutton def checkbutton_value(): if(var.get()): print 1 else: print 0 var=BooleanVar() chk = Checkbutton(root, text=column_1rowname[1], variable=var, command=checkbutton_value) text.window_create("end", window=chk) text.config(state=DISABLED) errmsg='Error!' Button(text='File Open',command=callback).pack(fill=X) mainloop() </code></pre>
-2
2016-09-11T03:22:03Z
39,452,648
<p>The problem is that you have more than one root window. You should only ever create exactly one instance of <code>Tk</code>, and call <code>mainloop</code> exactly once. If you need additional windows, create instances of <code>Toplevel</code>.</p> <p>Each root window (and all of its children, and all related <code>StringVar</code>s etc.) start a new, <em>independent</em> tcl interpreter. Widgets and variables associated with this window can't be used in another tcl interpreter. In your case, the <code>StringVar</code> is associated with the first root window, but the widget is associated with the second. You can't share data between root windows like that.</p>
0
2016-09-12T14:24:41Z
[ "python", "checkbox", "tkinter" ]
Why continue doesn't work while raising errors
39,432,543
<p>I'm trying to figure out why continue doesn't work when I'm rising errors:</p> <pre><code>while True: a = int(raw_input('Type integer with 9 numbers ')) if len(str(a)) &lt; 9 or len(str(a)) &gt;9: raise NameError('Wrong Number. Try again...') continue if not istance(a, int): raise ValueError("Oops! That was no valid number. Try again...") continue else: print a break </code></pre> <p>Could you point out my mistake(s)?</p>
1
2016-09-11T03:22:26Z
39,432,565
<p>Try <code>print 'Wrong Number. Try again...'</code> instead of <code>raise</code>.</p> <p><code>raise</code> will trigger an exception, which basically means your program is interrupted when the instruction is reached, the the exception is propagated up the call stack until it is caught by a <code>try...except</code> statement.</p> <p>What you seem to achieve here is to <em>display</em> an error message to the user because the input is incorrect. Simply use the <code>print</code> statement for that purpose.</p>
3
2016-09-11T03:28:02Z
[ "python" ]
Why continue doesn't work while raising errors
39,432,543
<p>I'm trying to figure out why continue doesn't work when I'm rising errors:</p> <pre><code>while True: a = int(raw_input('Type integer with 9 numbers ')) if len(str(a)) &lt; 9 or len(str(a)) &gt;9: raise NameError('Wrong Number. Try again...') continue if not istance(a, int): raise ValueError("Oops! That was no valid number. Try again...") continue else: print a break </code></pre> <p>Could you point out my mistake(s)?</p>
1
2016-09-11T03:22:26Z
39,432,763
<p><code>raise</code> will trigger an exception and the program will terminate.</p> <p>I find a few contradictions in your code: </p> <blockquote> <p>You are converting the user input to an int class, so <code>if isinstance(a, int)</code> is not at all required because <code>a</code> will point to an int class already. If in case, user input could not be converted to "int" then <code>ValueError</code> exception will be raised and program execution would end right there, so not event the first <code>if ...</code> statement will be evaluated.</p> </blockquote> <p>I would rewrite the code with little changes:</p> <pre><code>while True: try: a = int(raw_input('Type integer with 9 numbers ')) except ValueError: print "Non-numeric chars were entered" continue if len(str(a)) != 9: print "Wrong number" continue else: #do whatever you wanna do print 'You entered nine digits...hurray' break </code></pre>
1
2016-09-11T04:09:59Z
[ "python" ]
Error: Unsupported Operand Types
39,432,551
<p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &amp;: 'list' and 'list'. Why can't I use the '&amp;' operand for two lists in Python?</p> <pre><code>def dot(L, K): if L+K == []: return 0 elif L == [] &amp; K != []: return 0 elif K == [] &amp; L != []: return 0 else: return L[-1] * K[-1] + dot(L[:-1], K[:-1]) </code></pre>
0
2016-09-11T03:23:42Z
39,432,663
<p>I would probably do something like this:</p> <pre><code>def dot(L, K): if L + K == [] or len(L) != len(K): # this only needs to be checked once return 0 return dot_recurse(L, K) def dot_recurse(L, K): if len(L) &gt; 0: return L[-1] * K[-1] + dot_recurse(L[:-1], K[:-1]) else: return 0; </code></pre>
1
2016-09-11T03:48:16Z
[ "python", "math" ]
Error: Unsupported Operand Types
39,432,551
<p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &amp;: 'list' and 'list'. Why can't I use the '&amp;' operand for two lists in Python?</p> <pre><code>def dot(L, K): if L+K == []: return 0 elif L == [] &amp; K != []: return 0 elif K == [] &amp; L != []: return 0 else: return L[-1] * K[-1] + dot(L[:-1], K[:-1]) </code></pre>
0
2016-09-11T03:23:42Z
39,432,671
<pre><code>def dot(L, K): if len(L)!=len(K): # return 0 before the first recursion return 0 elif not L: # test if L is [] - previous test implies K is [] so no need to retest return 0 else: return L[-1] * K[-1] + dot(L[:-1], K[:-1]) </code></pre>
0
2016-09-11T03:48:59Z
[ "python", "math" ]
Error: Unsupported Operand Types
39,432,551
<p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &amp;: 'list' and 'list'. Why can't I use the '&amp;' operand for two lists in Python?</p> <pre><code>def dot(L, K): if L+K == []: return 0 elif L == [] &amp; K != []: return 0 elif K == [] &amp; L != []: return 0 else: return L[-1] * K[-1] + dot(L[:-1], K[:-1]) </code></pre>
0
2016-09-11T03:23:42Z
39,432,675
<p>If you check out python's <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow">Operator Precedence</a> you will see that <code>&amp;</code> has lower precedence than <code>==</code> and <code>and</code></p> <p>This means you are doing the following:</p> <pre class="lang-py prettyprint-override"><code>if (L == ([] &amp; K)) != []: ... </code></pre> <p>As suggested by priya you should be using <code>and</code>.</p> <pre class="lang-py prettyprint-override"><code>def dot(L, K): if L+K == []: return 0 elif L == [] and K != []: return 0 elif K == [] and L != []: return 0 else: return L[-1] * K[-1] + dot(L[:-1], K[:-1]) </code></pre> <p>However if you wanted to use <code>&amp;</code> (which is the <strong>Binary AND</strong>, and isn't the same thing) you could just use <code>()</code> to force precedence</p> <pre class="lang-py prettyprint-override"><code>def dot(L, K): if L+K == []: return 0 elif (L == []) &amp; (K != []): return 0 elif (K == []) &amp; (L != []): return 0 else: return L[-1] * K[-1] + dot(L[:-1], K[:-1]) </code></pre> <hr/> <p>If you're curious why <code>&amp;</code> is likely not what you want read on:</p> <ul> <li><code>AND</code> takes two values, converts them to Booleans (<code>True</code> or <code>False</code>) and check that both are <code>True</code></li> <li><strong>Binary AND</strong> (<code>&amp;</code>) takes two values, converts them to a Number-like value, then performs an operation on their bits</li> </ul> <hr/> <p>Here is how I would implement this function</p> <pre class="lang-py prettyprint-override"><code>def dot(L, K): if len(L) != len(K): # Ensure the lists are the same length raise ValueError('Can not perform dot product on two differently sized lists') elif len(L) + len(K) == 0: # See if we've reached the base case return 0 else: # Recurse doing dot product return L[-1] * K[-1] + dot(L[:-1], K[:-1]) print(dot([6, 2, 6], [5, 1])) </code></pre>
0
2016-09-11T03:49:44Z
[ "python", "math" ]
Error: Unsupported Operand Types
39,432,551
<p>I'm trying to use recursion to return the dot product of two lists, and I'm trying to account for the situation in which I get two lists of different length: I return 0. However, when I try to check for that condition, I get the error: unsupported operand type(s) for &amp;: 'list' and 'list'. Why can't I use the '&amp;' operand for two lists in Python?</p> <pre><code>def dot(L, K): if L+K == []: return 0 elif L == [] &amp; K != []: return 0 elif K == [] &amp; L != []: return 0 else: return L[-1] * K[-1] + dot(L[:-1], K[:-1]) </code></pre>
0
2016-09-11T03:23:42Z
39,432,708
<p>Your code is a bit more complicated than it really needs to be. It is not possible to take the dot product of two vectors which are not the same size. There are a couple of ways to deal with receiving vectors of different sizes.</p> <p>1) Lop off the remaining unused numbers from the larger vector. Below is a modified version of your function. I changed it to only require one check for if either of the vectors is empty (there is no need to check this in multiple ways), and also changed it to start from the beginning of the vectors instead of the end. Was there a particular reason you started from the end?</p> <pre><code>def dot(L, K): if(L == [] or K == []): return 0 else: return L[0] + K[0] + dot(L[1:], K[1:]) </code></pre> <p>While this option works, it does not give the user any indication that they made a mistake in attempting to dot product two different sized vectors.</p> <p>2) Give the user an error upon receiving two different sized vectors.</p> <pre><code>def dot(L, K): if(len(L) != len(K)): print('Vector sizes do not match, please pass two same-sized vectors') return 0 #not sure exactly how you are wanting to do error handling here. elif(L == [] or K == []): return 0 else: return L[0] + K[0] + dot(L[1:], K[1:]) </code></pre>
0
2016-09-11T03:57:49Z
[ "python", "math" ]
How to enter data in the form and go to the next page with cookie in python
39,432,648
<p>I would like to enter data in a form and login in the website, and then download the source of the current page. With curl from the terminal I do the following commands:</p> <pre><code>curl -c cookie.txt --data "email=my@email.com&amp;pass=MyPass&amp;submit=login" https://mywebsite.com/pageA curl -b cookie.txt https://mywebsite.com/pageB&gt; down.txt </code></pre> <p>How i can do the same with pycurl?</p>
0
2016-09-11T03:45:37Z
39,437,904
<p>Building up from the example in <a href="http://pycurl.io/docs/latest/quickstart.html#sending-form-data" rel="nofollow">docs</a>:</p> <pre><code>from __future__ import print_function import pycurl try: # python 3 from urllib.parse import urlencode except ImportError: # python 2 from urllib import urlencode c = pycurl.Curl() c.setopt(c.URL, 'https://mywebsite.com/pageA') post_data = {'email': 'my@email.com', 'pass': 'MyPass', 'submit': 'login'} # Form data must be provided already urlencoded. postfields = urlencode(post_data) # Sets request method to POST, # Content-Type header to application/x-www-form-urlencoded # and data to send in request body. c.setopt(c.POSTFIELDS, postfields) c.setopt(c.COOKIEJAR, 'cookie.txt') c.setopt(c.COOKIEFILE, 'cookie.txt') try: c.perform() c.setopt(c.URL, 'https://mywebsite.com/pageB') c.perform() except pycurl.error as error: errno, errstr = error print('An error occurred: ', errstr) c.close() </code></pre>
0
2016-09-11T15:51:08Z
[ "python", "curl", "cookies", "pycurl" ]
python os.walk returns nothing
39,432,660
<p>I have a problem with using <code>os.walk</code> on Mac. If I call it from <code>python terminal</code>, it works perfect, but if I call it via a <code>python script</code>, it returns empty list. For example:</p> <pre><code> import os path = "/Users/temp/Desktop/test/" for _ ,_ , files in os.walk(path): test = [my_file for my_file in files] print test </code></pre> <p>then, it prints:</p> <pre><code> [] </code></pre> <p>and I am pretty sure that the <code>path</code> does exists. Any idea what is the problem? </p>
0
2016-09-11T03:47:42Z
39,432,689
<p>You most likely need to intantiate the test list outside the for loop, for this to work.</p> <pre><code>import os path = "/Users/temp/Desktop/test/" test = [] for _ ,_ , files in os.walk(path): test.extend([my_file for my_file in files]) print test </code></pre>
1
2016-09-11T03:54:11Z
[ "python" ]
Remove portion of plot that lies outside of circle
39,432,735
<p>I have written a python script that produces vector field plots of the electric and magnetic field vectors for EM waves in various modes of propagation in a cylindrical waveguide. I have used <code>streamplot</code> to produce the vector field plots. This question would be asked much more easily if I were able to post an image of my plot but I am currently unable to since my reputation is currently below 10.</p> <p>Although the mathematics of the script is formulated in cylindrical coordinates, due to the difficulty of using <code>streamplot</code> on a polar plot, I have plotted the cross sectional (electric) field vectors on a standard square grid using: <code>pyplot.streamplot(X, Y, UE, VE, linewidth=lwE, density=6,color='r')</code>. If you're interested, lwE is defined elsewhere in my script and simply scales the line widths according to the magnitude of the vector at that point.</p> <p>Anyway, my problem is that, naturally, due to being plotted on a square grid, the field vectors extend slightly outside the boundary of the cross section of the cylinder in the corners of the plot. I just want the plot to display the vector fields <em>inside</em> the cylinder, not outside. This problem can be solved by using a polar plot, but I cannot get <code>streamplot</code> to work on a polar plot. In short - matplotlib returns a square plot; I want to 'cut out' the parts of the plot that lie outside of the circular cross section of my cylinder.</p> <p>I would like to know the best way to 'cut out' these unwanted portions of the plot. My first thought was to plot a 'circ' function (circular aperture type function available in some software packages) that is only nonzero inside of a certain radius; sadly, there does not appear to be such a function available. I have tried overlaying transparent circles onto my plot, and whilst they do clearly highlight the region of interest, the 'unwanted' regions outside the circle are still present; I want these portions completely removed.</p> <p>I can set the (x,y) limits of the plot using <code>axes.set_xlim([-a,a])</code> and <code>axes.set_ylim([-a,a])</code> ; what would be useful is a polar version of this (say <code>axes.set_rlim([0,a]</code>). This is obviously trivial if one is able to use a polar plot in the first place, but does such a limit command exist if one is using Cartesian axes?</p>
0
2016-09-11T04:04:32Z
39,432,752
<p>You can use a clip path. Matplotib's documentation has a nice example: <a href="http://matplotlib.org/examples/images_contours_and_fields/image_demo_clip_path.html" rel="nofollow">http://matplotlib.org/examples/images_contours_and_fields/image_demo_clip_path.html</a></p>
0
2016-09-11T04:07:27Z
[ "python", "matplotlib" ]
String replace with re sub matching the exact string
39,432,754
<p>I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.</p> <p>My code :</p> <pre><code>input_file = "foo afooa" input_file = re.sub(r'^foo$', 'bar', input_file) print input_file </code></pre> <p>So, I'm expecting result like this :</p> <pre><code>bar afooa </code></pre> <p>Thanks in advance</p>
0
2016-09-11T04:07:36Z
39,432,825
<p>Instead of ^ and $ , use \b to match boundary.</p> <pre><code>&gt;&gt;&gt; a="foo afooa" &gt;&gt;&gt; b= re.sub(r"\bfoo\b",'bar',a) &gt;&gt;&gt; b 'bar afooa' &gt;&gt;&gt; </code></pre>
0
2016-09-11T04:20:58Z
[ "python", "regex" ]
String replace with re sub matching the exact string
39,432,754
<p>I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.</p> <p>My code :</p> <pre><code>input_file = "foo afooa" input_file = re.sub(r'^foo$', 'bar', input_file) print input_file </code></pre> <p>So, I'm expecting result like this :</p> <pre><code>bar afooa </code></pre> <p>Thanks in advance</p>
0
2016-09-11T04:07:36Z
39,432,835
<p>From the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">doc</a>, you can set <code>count = 1</code> of <code>re.sub()</code>to just change the first occurrence of the pattern. Also, remove the <code>^</code> and <code>$</code> since you donot want to search for the whole line containing only the word <code>foo</code>. Sample code:</p> <pre><code>import re; input_file = "foo afooa"; input_file = re.sub(r'foo', 'bar', input_file, count = 1); print input_file; </code></pre>
1
2016-09-11T04:24:10Z
[ "python", "regex" ]
String replace with re sub matching the exact string
39,432,754
<p>I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.</p> <p>My code :</p> <pre><code>input_file = "foo afooa" input_file = re.sub(r'^foo$', 'bar', input_file) print input_file </code></pre> <p>So, I'm expecting result like this :</p> <pre><code>bar afooa </code></pre> <p>Thanks in advance</p>
0
2016-09-11T04:07:36Z
39,433,082
<p>Your regex is currently <code>r'^foo$'</code> which basically matches the string 'foo' <strong><em>only</em></strong>.</p> <p>If you just changed it to <code>r'^foo'</code> it will match as long as 'foo' is found at the start of the string, but unlike your previous pattern it doesn't care about what follows foo.</p> <p>Here is an example:</p> <pre><code>input_file = "foo afooa" input_file = re.sub(r'^foo', 'bar', input_file) input_file2 = "foob afooa" input_file2 = re.sub(r'^foo', 'bar', input_file2) print input_file print input_file2 </code></pre> <p>output:</p> <pre><code>bar afooa barb afooa </code></pre> <p>Now if you don't want to match a part of a string, but match the whole string 'foo' at the start of the line, then you need to add a boundary '\b' match like shown below:</p> <pre><code>input_file = "foo afooa" input_file = re.sub(r'^foo\b', 'bar', input_file) input_file2 = "foob afooa" input_file2 = re.sub(r'^foo\b', 'bar', input_file2) print input_file print input_file2 </code></pre> <p>output:</p> <pre><code>bar afooa foob afooa </code></pre> <p>Or if you want to just replace the first occurrence of the full word 'foo', then use the pattern suggested by @DineshPundkar and limit the number of substitutions to 1 like @Tuan333 just mentioned. </p> <p>So, in this case your code will look like:</p> <pre><code>input_file = "a foo afooa foo bazfooz" input_file = re.sub(r'\bfoo\b', 'bar', input_file, 1) print input_file </code></pre> <p>output:</p> <pre><code>a bar afooa foo bazfooz </code></pre>
1
2016-09-11T05:11:07Z
[ "python", "regex" ]
Python list insertion when iterating
39,432,758
<p>I'm working with python 3.5, and insert isn't behaving as I expect it to.</p> <pre><code>scorelist = ["x","x"] for q in range(0, len(scorelist)): if scorelist[q] == "x": scorelist.insert((q), " ") </code></pre> <p>I'd expect that to leave the least reading as follows</p> <pre><code>scorelist = ["x", " ", "x", " "] </code></pre> <p>Instead, it leaves me with</p> <pre><code>scorelist = [" ", " ", "x", "x"] </code></pre> <p>I'm pretty stumped as to why this is the output. Any guidance would be greatly appreciated.</p>
1
2016-09-11T04:08:52Z
39,432,796
<p>It's generally a Bad Idea to mutate any container while iterating over it.</p> <p>In your case, <code>len(scorelist)</code> is evaluated once, at the time the <code>for</code> loop begins. The length is 2 at that time, so the range is just <code>[0, 1]</code>. Nothing later can possibly change that.</p> <p>In the first iteration, <code>q</code> is 0, and <code>scorelist[0]</code> is <code>"x"</code>, so</p> <pre><code>scorelist.insert(0, " ") </code></pre> <p>leaves <code>scorelist</code> as</p> <pre><code>[" ", "x", "x"] </code></pre> <p>In the second iteration, <code>q</code> is 1, and for the new value of <code>scorelist</code>, <code>scorelist[1]</code> is still <code>"x"</code>, so</p> <pre><code>scorelist.insert(1, " ") </code></pre> <p>leaves <code>scorelist</code> as</p> <pre><code>[" ", " ", "x", "x"] </code></pre> <p>Then the loop ends. There's nothing really mysterious about it, but it's far from obvious either - which is <em>why</em> it's a Bad Idea to mutate containers while iterating over them ;-)</p> <h2>EDIT: GETTING WHAT YOU WANT</h2> <p>If you're determined to insert a blank at the end, and between every pair of elements before that, here's one obscure way to do it:</p> <pre><code>for q in reversed(range(1, len(scorelist) + 1)): scorelist.insert(q, " ") </code></pre> <p>Then, e.g., if <code>scorelist</code> starts as</p> <pre><code>['x', 'y', 'z'] </code></pre> <p>that loop will leave it as</p> <pre><code>['x', ' ', 'y', ' ', 'z', ' '] </code></pre> <p>By iterating "backwards", the insertions don't interfere with the original indices of the original list elements. If that's confusing (hint: it is! ;-) ), just work it out one iteration at a time, as I spelled it out for your original code.</p>
6
2016-09-11T04:15:56Z
[ "python" ]
working with "load more" button using scrapy
39,432,791
<p>I was working on ratemyprofessor which has a load more button to load more professor, and I use debugger to analyze network, it shows up a js request. <a href="https://www.ratemyprofessors.com/campusRatings.jsp?sid=1273" rel="nofollow">ratemyprofessorwebsite</a></p> <p>I was thinking, for the request URL, there is a start and rows, so I just increase the start by 20 each time, will this work? </p> <p>And someone told me that I could try formdata, but in this case, there is no formdata and it is not a POST method, am I right?</p> <p>I am really new to scrapy and python, hope u guys can give me some insight. Really appreciate it </p> <p>they don't allow me to upload image... but anyway</p> <pre><code>Request URL:https://search-a.akamaihd.net/typeahead/suggest/?solrformat=true&amp;rows=10&amp;callback=noCB&amp;q=*%3A*+AND+schoolid_s%3A1273&amp;defType=edismax&amp;qf=teacherfullname_t%5E1000+autosuggest&amp;bf=pow(total_number_of_ratings_i%2C2.1)&amp;sort=total_number_of_ratings_i+desc&amp;siteName=rmp&amp;rows=20&amp;start=20&amp;fl=pk_id+teacherfirstname_t+teacherlastname_t+total_number_of_ratings_i+averageratingscore_rf+schoolid_s Request Method:GET Status Code:200 OK Remote Address:23.212.53.206:443 </code></pre> <p>QUERY STING PARAMETERS</p> <pre><code>solrformat:true rows:10 callback:noCB q:*:* AND schoolid_s:1273 defType:edismax qf:teacherfullname_t^1000 autosuggest bf:pow(total_number_of_ratings_i,2.1) sort:total_number_of_ratings_i desc siteName:rmp rows:20 start:20 fl:pk_id teacherfirstname_t teacherlastname_t total_number_of_ratings_iaverageratingscore_rf schoolid_s </code></pre>
0
2016-09-11T04:14:39Z
39,436,426
<p>Yes, you are correct - formdata is not required, and this is straight forward using GET method calls.</p> <p>using the following parameters, grab the json response with:</p> <pre><code>data = json.loads(response.body) records = data['response']['docs'] </code></pre> <hr> <p>parameters to use : <strong>start, rows</strong></p> <p>parameter to avoid : <strong>callback</strong></p> <p>parameters with explanation:</p> <pre><code>solrformat:true #callback:noCB # Drop this parameter, this will give you response data in json format q:*:* AND schoolid_s:1273 defType:edismax qf:teacherfullname_t^1000 autosuggest bf:pow(total_number_of_ratings_i,2.1) sort:total_number_of_ratings_i desc siteName:rmp rows:20 # rows: the amount of records you want in a single response, this will give you 20 # you can try with maximum that can be returned in single response i.e 500, 1000..etc, this will minimize no of request made to website start:20 #start :you can start this from 0,10,20,30,40 manually as well if you know the total number of records. fl:pk_id teacherfirstname_t teacherlastname_t total_number_of_ratings_iaverageratingscore_rf schoolid_s </code></pre>
0
2016-09-11T13:07:06Z
[ "python", "scrapy" ]
How to change the order of tables in a LEFT JOIN clause with SQLAlchemy
39,432,853
<p>I wish to execute the following SQL:</p> <pre><code>SELECT c.name, count(1) FROM post p LEFT JOIN category_post cp ON (p.id = cp.post_id) LEFT JOIN category c ON (cp.category_id = c.id) WHERE 1=1 AND post.is_published = 1 GROUP BY c.name; </code></pre> <p>A post has 0 or more categories. This post will return the count of each category, <strong>including the uncategorized posts</strong>, as I LEFT JOIN from post-->category, as opposed to the other way around, which would not include the count of uncategorized posts.</p> <p>In SQLAlchemy, I can get part of the solution using the following, however it doesn't return the count of uncategorized posts because the LEFT JOIN is going in the wrong direction:</p> <pre><code>from sqlalchemy.sql import func q = session.query(Category.name, func.count(1)) \ .outerjoin(CategoryPost) \ .outerjoin(Post) \ .filter(Post.is_published == True) \ .group_by(Category.name) </code></pre> <p>The SQL generated by this is:</p> <pre><code>SELECT category.name AS category_name, count(1) AS count_1 FROM category LEFT OUTER JOIN category_post ON category.id = category_post.category_id LEFT OUTER JOIN post ON post.id = category_post.post_id WHERE post.is_published = 1 GROUP BY category.name </code></pre> <p>If I could change the order of the tables in the JOIN clause somehow, or even just do a RIGHT JOIN while keeping the same order, I could acccomplish my goal.</p>
0
2016-09-11T04:27:24Z
39,433,307
<p>Use <a href="http://docs.sqlalchemy.org/en/latest/orm/query.html#sqlalchemy.orm.query.Query.select_from" rel="nofollow"><code>select_from()</code></a>:</p> <pre><code>session.query(Category.name, func.count(1)) \ .select_from(Post) \ .outerjoin(CategoryPost) \ .outerjoin(Category) \ ... </code></pre>
1
2016-09-11T06:01:03Z
[ "python", "sqlalchemy" ]
"list index out of range" exception (Python3)
39,432,878
<p>I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the <code>if</code> or <code>elif</code> part of the second <code>if</code> statement, depending on what the user inputs. I know that when the user input is split the list is created correctly because I print it out... So I'm a little lost about why I'm getting that error.</p> <pre><code>if __name__ == '__main__': for line in sys.stdin: s = line.strip() if not s: break if (str(s) is "quit") == True: quit() elif (str(s) is "quit") == False: a = s.split() print(a) if (len(a) == 2) == True: first(a) elif (len(a) == 3) == True: first(a) else: print("Invalid Input. Please Re-enter.") </code></pre> <p>The first method is: (The methods it calls in the if statement just print things out at the moment)</p> <pre><code>def first(self, a = list()): word = a[0] if word is ls: ls(a[1]) elif word is format: form(a[1]) # EDIT: was format elif word is reconnect: reconnect(a[1]) elif word is mkfile: mkfile(a[1]) elif word is mkdir: mkdir(a[1]) elif word is append: append(a[1], a[2]) elif word is delfile: delfile(a[1]) elif word is deldir: deldir(a[1]) else: print("Invalid Prompt. Please Re-enter.") </code></pre> <p>Other methods:</p> <pre><code> def reconnect(one = ""): print("Reconnect") def ls(one = ""): print("list") def mkfile(one = ""): print("make file") def mkdir(one = ""): print("make drive") def append(one = "", two = ""): print("append") def form(one = ""): print("format") def delfile(one = ""): print("delete file") def deldir(one = ""): print("delete directory") def quit(): print("quit") sys.exit(0) </code></pre>
1
2016-09-11T04:33:42Z
39,432,957
<h2>Real issue:</h2> <p>To solve your error you have to <strong>remove</strong> the <code>self</code> parameter of the <code>first</code> function </p> <pre><code>def first(a=list()) </code></pre> <p>Basically the <strong>self</strong> is only used for object orientation creating methods. Function like yours can't use self otherwise you will passing the first parameter to self not to a which you want to. </p> <p>My second issue I can point out is that, You are trying to compare using <code>is</code> between a <strong>string</strong> and a <strong>function</strong>. </p> <pre><code> def first(a = list()): word = a[0] if word is "ls": ls(a[1]) elif word is "format": format(a[1]) elif word is "reconnect": reconnect(a[1]) elif word is "mkfile": mkfile(a[1]) elif word is "mkdir": mkdir(a[1]) elif word is "append": append(a[1], a[2]) elif word is "delfile": delfile(a[1]) elif word is "deldir": deldir(a[1]) else: print("Invalid Prompt. Please Re-enter.") </code></pre> <h2>Extra</h2> <p>The <code>is</code> function on built in operations in Python. <code>is</code> compare the equity of the objects. </p> <p>But this expression: </p> <pre><code>if (str(s) is "quit") == True: </code></pre> <p>Can be simpler like:</p> <pre><code>if str(s) == "quit": </code></pre> <p>Or: </p> <pre><code>if str(s) is "quit": </code></pre> <p>The <code>== True</code> is meaningless either <code>== False</code> you can use <code>not</code> more pythonicly. </p>
0
2016-09-11T04:48:39Z
[ "python", "list" ]
"list index out of range" exception (Python3)
39,432,878
<p>I keep getting a list index out of range exception when I check the length of the list a. The error pops up for either the <code>if</code> or <code>elif</code> part of the second <code>if</code> statement, depending on what the user inputs. I know that when the user input is split the list is created correctly because I print it out... So I'm a little lost about why I'm getting that error.</p> <pre><code>if __name__ == '__main__': for line in sys.stdin: s = line.strip() if not s: break if (str(s) is "quit") == True: quit() elif (str(s) is "quit") == False: a = s.split() print(a) if (len(a) == 2) == True: first(a) elif (len(a) == 3) == True: first(a) else: print("Invalid Input. Please Re-enter.") </code></pre> <p>The first method is: (The methods it calls in the if statement just print things out at the moment)</p> <pre><code>def first(self, a = list()): word = a[0] if word is ls: ls(a[1]) elif word is format: form(a[1]) # EDIT: was format elif word is reconnect: reconnect(a[1]) elif word is mkfile: mkfile(a[1]) elif word is mkdir: mkdir(a[1]) elif word is append: append(a[1], a[2]) elif word is delfile: delfile(a[1]) elif word is deldir: deldir(a[1]) else: print("Invalid Prompt. Please Re-enter.") </code></pre> <p>Other methods:</p> <pre><code> def reconnect(one = ""): print("Reconnect") def ls(one = ""): print("list") def mkfile(one = ""): print("make file") def mkdir(one = ""): print("make drive") def append(one = "", two = ""): print("append") def form(one = ""): print("format") def delfile(one = ""): print("delete file") def deldir(one = ""): print("delete directory") def quit(): print("quit") sys.exit(0) </code></pre>
1
2016-09-11T04:33:42Z
39,433,163
<p>The problem seems to be the definition of <code>first()</code>. You invoke it as a function:</p> <pre><code>if (len(a) == 2) == True: first(a) elif (len(a) == 3) == True: first(a) </code></pre> <p>But you define it as a method:</p> <pre><code>def first(self, a = list()): </code></pre> <p>The array of command and argument gets put into <code>self</code> and <code>a</code> is always an empty list which you attempt to index and fail. Also, you shouldn't use a mutable type like <code>list()</code> as a default value unless you're certain what you are doing. I suggest simply:</p> <pre><code>def first(a): </code></pre> <p>As far as your <code>__main__</code> code goes, simplify:</p> <pre><code>if __name__ == '__main__': for line in sys.stdin: string = line.strip() if not string: break if string == "quit": quit() tokens = string.split() length = len(tokens) if 2 &lt;= length &lt;= 3: first(tokens) else: print("Invalid Input. Please Re-enter.") </code></pre>
2
2016-09-11T05:28:11Z
[ "python", "list" ]
Matplotlib: make figure that has x and y labels square in aspect ratio
39,432,931
<p>The question is bettered explained with examples. Let's say below is a figure I tried to plot: <a href="http://i.stack.imgur.com/15sdi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/15sdi.jpg" alt="in matlab"></a></p> <p>So the figure region is square in shape, and there are axis labels explaining the meaning of the values. In MATLAB the code is simple and works as expected.</p> <pre><code>t = linspace(0, 2*pi, 101); y = sin(t); figure(1) h = gcf; set(h,'PaperUnits','inches'); set(h,'PaperSize',[3.5 3.5]); plot(t, y) xlim([0, 2*pi]) ylim([-1.1, 1.1]) xlabel('Time (s)') ylabel('Voltage (V)') axis('square') </code></pre> <p>Now let's work with Python and Matplotlib. The code is below:</p> <pre><code>from numpy import * from matplotlib import pyplot as plt t = linspace(0, 2*pi, 101) y = sin(t) plt.figure(figsize = (3.5, 3.5)) plt.plot(t, y) plt.xlim(0, 2*pi) plt.ylim(-1.1, 1.1) plt.xlabel('Time (s)') plt.ylabel('Voltage (V)') plt.axis('equal') # square / tight plt.show() </code></pre> <p>It does not work, see the first row of the figure below, where I tried three options of the axis command ('equal', 'square' and 'tight'). I wondered if this is due to the order of axis() and the xlim/ylim, they do affect the result, yet still I don't have what I want. <a href="http://i.stack.imgur.com/33Z1J.png" rel="nofollow"><img src="http://i.stack.imgur.com/33Z1J.png" alt="Python"></a> I found this really confusing to understand and frustrating to use. The relative position of the curve and axis seems go haywire. I did extensive research on stackoverflow, but couldn't find the answer. It appears to me adding axis labels would compress the canvas region, but it really should not, because the label is just an addon to a figure, and they should have separate space allocations. </p>
0
2016-09-11T04:43:27Z
39,433,143
<p>It doesn't explain the figures you obtain but here is one way to achieve square axes with the right axes limits. In this example, I just calculate the axes aspect ratio using the x and y range:</p> <pre><code>plt.figure() ax = plt.axes() ax.plot(t, y) xrange = (0, 2*pi) yrange = (-1.1, 1.1) plt.xlim(xrange) plt.ylim(yrange) plt.xlabel('Time (s)') plt.ylabel('Voltage (V)') ax.set_aspect((xrange[1]-xrange[0])/(yrange[1]-yrange[0])) plt.show() </code></pre> <p>Another method is to create a square figure and square axes:</p> <pre><code>plt.figure(figsize = (5, 5)) ax = plt.axes([0.15, 0.15, 0.7, 0.7]) ax.plot(t, y) plt.xlim(0, 2*pi) plt.ylim(-1.1, 1.1) plt.xlabel('Time (s)') plt.ylabel('Voltage (V)') plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/9fA4C.png" rel="nofollow"><img src="http://i.stack.imgur.com/9fA4C.png" alt="enter image description here"></a></p>
0
2016-09-11T05:23:15Z
[ "python", "matlab", "matplotlib" ]
Matplotlib: make figure that has x and y labels square in aspect ratio
39,432,931
<p>The question is bettered explained with examples. Let's say below is a figure I tried to plot: <a href="http://i.stack.imgur.com/15sdi.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/15sdi.jpg" alt="in matlab"></a></p> <p>So the figure region is square in shape, and there are axis labels explaining the meaning of the values. In MATLAB the code is simple and works as expected.</p> <pre><code>t = linspace(0, 2*pi, 101); y = sin(t); figure(1) h = gcf; set(h,'PaperUnits','inches'); set(h,'PaperSize',[3.5 3.5]); plot(t, y) xlim([0, 2*pi]) ylim([-1.1, 1.1]) xlabel('Time (s)') ylabel('Voltage (V)') axis('square') </code></pre> <p>Now let's work with Python and Matplotlib. The code is below:</p> <pre><code>from numpy import * from matplotlib import pyplot as plt t = linspace(0, 2*pi, 101) y = sin(t) plt.figure(figsize = (3.5, 3.5)) plt.plot(t, y) plt.xlim(0, 2*pi) plt.ylim(-1.1, 1.1) plt.xlabel('Time (s)') plt.ylabel('Voltage (V)') plt.axis('equal') # square / tight plt.show() </code></pre> <p>It does not work, see the first row of the figure below, where I tried three options of the axis command ('equal', 'square' and 'tight'). I wondered if this is due to the order of axis() and the xlim/ylim, they do affect the result, yet still I don't have what I want. <a href="http://i.stack.imgur.com/33Z1J.png" rel="nofollow"><img src="http://i.stack.imgur.com/33Z1J.png" alt="Python"></a> I found this really confusing to understand and frustrating to use. The relative position of the curve and axis seems go haywire. I did extensive research on stackoverflow, but couldn't find the answer. It appears to me adding axis labels would compress the canvas region, but it really should not, because the label is just an addon to a figure, and they should have separate space allocations. </p>
0
2016-09-11T04:43:27Z
39,433,186
<p>I do not have a computer at hand right now but it seems this answer might work: <a href="http://stackoverflow.com/a/7968690/2768172">http://stackoverflow.com/a/7968690/2768172</a> Another solution might be to add the axis with a fixed size manually with: <code>ax=fig.add_axes(bottom, left, width, height)</code>. If width and height are the same the axis should be squared.</p>
0
2016-09-11T05:33:28Z
[ "python", "matlab", "matplotlib" ]
(Errno 22) invalid argument when trying to run a python program from a bat file
39,432,939
<p>I'm following this exactly but it is not working <a href="https://youtu.be/qHcHUHF_Qfo?t=438" rel="nofollow">https://youtu.be/qHcHUHF_Qfo?t=438</a> </p> <p>I type the location in the run window:</p> <pre><code>C:\Users\Zachary lastName\mypythonscripts\hello.py </code></pre> <p>I get error message: </p> <blockquote> <p>can't open file 'c:\users"Zachary': [Errno 22] invalid argument</p> </blockquote> <p>The bat file is:</p> <pre><code>@py C:\Users\Zachary lastName\mypythonscripts\hello.py %* @pause </code></pre> <p>I've searched everywhere and can't find an answer, I also edited the path environment variable so I can just type the name of the program in the run window but again I get the error. Any help is appreciated!</p>
0
2016-09-11T04:45:02Z
39,432,958
<p>You have to enclose the path name in quotes because the space means a new argument is expected, and it's not finding the file:</p> <pre><code>@py "C:\Users\Zachary lastName\mypythonscripts\hello.py" %* @pause </code></pre> <p>Now the file path should not interfere. Usernames with spaces can become a problem for paths as their space can cause issues. Just enclose it in quotes to convert to string.</p>
0
2016-09-11T04:48:45Z
[ "python", "batch-file", "errno" ]
Adding "Invalid Entry" To Python Dice Roller
39,432,951
<p>I have a Python dice rolling simulator:</p> <pre><code>from random import randint play = True while play: roll = randint(1, 6) print(roll) answer = input("Roll again? (y/n)") print(answer) if answer == "y": play = True elif answer == "n": break </code></pre> <p>If you input anything other than "y" or "n" it will roll again. I would like to make it so that it will say something like "invalid entry" instead of rolling again. How could I change this to do so? Thank you.</p>
0
2016-09-11T04:47:28Z
39,433,030
<p>You can validate the answer and ask again if it is invalid like</p> <pre><code>from random import randint play = True while play: roll = randint(1, 6) print(roll) ask = True while ask: answer = input("Roll again? (y/n)") print(answer) if (answer != "y") and (answer != "n"): print("Invalid input") else: ask = False if answer == "y": play = True elif answer == "n": break </code></pre>
0
2016-09-11T05:01:10Z
[ "python", "python-3.5" ]
How do I preform a check only once?
39,432,952
<p>So I have this question that I have to do for homework.</p> <p>Next, write ind( e, L ). Here is its description:</p> <p>Write ind(e, L), which takes in a sequence L and an element e. L might be a string or, more generally, a list. Your function ind should return the index at which e is first found in L. Counting begins at 0, as is usual with lists. If e is NOT an element of L, then ind(e, L) should return the integer equal to len(L). Here are a few examples:</p> <pre><code>ind(42, [ 55, 77, 42, 12, 42, 100 ]) returns 2 ind(42, range(0,100)) returns 42 ind('hi', [ 'hello', 42, True ]) returns 3 ind('hi', [ 'well', 'hi', 'there' ]) returns 1 ind('i', 'team') returns 4 ind(' ', 'outer exploration') returns 5 </code></pre> <p>In this last example, the first input to ind is a string of a single space character, not the empty string.</p> <p>Hint: Just as you can check whether an element is in a sequence with</p> <p>if e in L: you can also check whether an element is not in a sequence with</p> <p>if e not in L: This latter syntax is useful for the ind function! As with dot, ind is probably most similar to mylen from the class examples.</p> <p>And here it once of the many codes I have written for this problem.</p> <pre><code>def ind( e, L): num = 0 if e not in L and num == 0: return len(L) else: if e == L[0]: num += 1 + ind( e, L[1:] ) return num else: return ind( e, L[1:] ) </code></pre> <p>So the problem is that everytime e is no longer in the list. It takes the length of the remainder of the list and adds that to num. How do I fix this???</p>
0
2016-09-11T04:47:43Z
39,434,686
<blockquote> <p>And here it(!) once(!) of the many codes I have written for this problem.</p> </blockquote> <p>You should pay more attention to what you're writing and probably also to what you are coding.</p> <p>Unless you are explicitly asked to write a recursive function for this task, I'd advise against it.</p> <p>Try to break down the task to smaller subproblems. Some of them are already solved:</p> <ul> <li>If the element is not contained in the list, return the length of the list (done)</li> <li>Loop over the list, keeping track of the current index <ul> <li>if the current list element is the one you are looking for, return the current index</li> <li>else, look at the next element</li> </ul></li> <li>since you can be sure that the element is in the list once you enter the loop (why?), you are done.</li> </ul> <hr> <p>If you have to do it recursively, the "hints" are rather misleading. The <code>not in</code> syntax is not useful. Did you look at the <code>mylen</code> function? I suppose it looks like</p> <pre><code>def mylen(s): if not s: return 0 return 1 + mylen(s[1:]) </code></pre> <p>Now, to find the (first) index of a given element:</p> <pre><code> def ind(e, l): if not l: # list is exhausted, element was not found return 0 elif l[0] == e: # element found return 0 else # element not found yet return 1 + ind(e, l[1:]) </code></pre>
0
2016-09-11T09:28:35Z
[ "python", "python-2.7" ]
How do I preform a check only once?
39,432,952
<p>So I have this question that I have to do for homework.</p> <p>Next, write ind( e, L ). Here is its description:</p> <p>Write ind(e, L), which takes in a sequence L and an element e. L might be a string or, more generally, a list. Your function ind should return the index at which e is first found in L. Counting begins at 0, as is usual with lists. If e is NOT an element of L, then ind(e, L) should return the integer equal to len(L). Here are a few examples:</p> <pre><code>ind(42, [ 55, 77, 42, 12, 42, 100 ]) returns 2 ind(42, range(0,100)) returns 42 ind('hi', [ 'hello', 42, True ]) returns 3 ind('hi', [ 'well', 'hi', 'there' ]) returns 1 ind('i', 'team') returns 4 ind(' ', 'outer exploration') returns 5 </code></pre> <p>In this last example, the first input to ind is a string of a single space character, not the empty string.</p> <p>Hint: Just as you can check whether an element is in a sequence with</p> <p>if e in L: you can also check whether an element is not in a sequence with</p> <p>if e not in L: This latter syntax is useful for the ind function! As with dot, ind is probably most similar to mylen from the class examples.</p> <p>And here it once of the many codes I have written for this problem.</p> <pre><code>def ind( e, L): num = 0 if e not in L and num == 0: return len(L) else: if e == L[0]: num += 1 + ind( e, L[1:] ) return num else: return ind( e, L[1:] ) </code></pre> <p>So the problem is that everytime e is no longer in the list. It takes the length of the remainder of the list and adds that to num. How do I fix this???</p>
0
2016-09-11T04:47:43Z
39,434,893
<p>When working with indicies in sequence, Python has great built-in named <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> which helps a lot with keeping track of index in consise and simple manner.</p> <blockquote> <p>Return an enumerate object. <code>sequence</code> must be a sequence, an iterator, or some other object which supports iteration. The <code>next()</code> method of the iterator returned by <code>enumerate()</code> returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence</p> </blockquote> <p>Sample:</p> <pre><code>seq = ['hello', 42, True] for index, obj in enumerate(seq): print index, obj </code></pre> <p>Output:</p> <pre><code>0 hello 1 42 2 True </code></pre> <p>We can use it to ease up processing significantly. Since we can iterate over <code>L</code> and retrieve both index and value of current element, we have to do do comparison with requested value now. When value is found, we may simply return it and skip searching through rest of sequence</p> <pre><code>def ind(e, L): for index, value in enumerate(L): if value == e: return index </code></pre> <p>What's missing now is case when value is not found, but adding support for it is fairly simple:</p> <pre><code>def ind(e, L): for index, value in enumerate(L): if value == e: return index return len(L) # this will be executed only if any value wasn't found earlier </code></pre> <p>It passes all testcases:</p> <pre><code>assert ind(42, [ 55, 77, 42, 12, 42, 100 ]) == 2 assert ind(42, range(0,100)) == 42 assert ind('hi', [ 'hello', 42, True ]) == 3 assert ind('hi', [ 'well', 'hi', 'there' ]) == 1 assert ind('i', 'team') == 4 assert ind(' ', 'outer exploration') == 5 </code></pre> <p>And bonus, with using all tricks Python provides:</p> <pre><code>def ind(e, L): return next((idx for idx, obj in enumerate(L) if obj == e), len(L)) </code></pre> <p>Have fun with figuring out what happens here :) </p>
1
2016-09-11T09:55:49Z
[ "python", "python-2.7" ]
Python: Inserting DataFrames into larger DataFrame at given index value
39,432,964
<p>I'm certain this is a trivial question but I cannot seem to find a solution. I have the following DataFrame: </p> <pre><code>&gt;&gt;&gt; df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [1, 2, 3, 4, 5], 'C': [1, 2, 3, 4, 5]}) &gt;&gt;&gt; df A B C 0 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 </code></pre> <p>I also have some additional DataFrames (<code>df_a</code>, <code>df_b</code>) that I wish to insert into the the primary DataFrame (<code>df</code>). The additional DataFrames are saved to a dictionary with the key being the index of the row that I wish to insert the additional DataFrames after. </p> <pre><code>df_a = pd.DataFrame({'A': ['X', 'Y'], 'B': ['X', 'Y'], 'C': ['X', 'Y']}) df_b = pd.DataFrame({'A': ['X', 'Y'], 'B': ['X', 'Y'], 'C': ['X', 'Y']}) idx_dict = {} idx_dict[1] = df_a idx_dict[3] = df_b </code></pre> <p>The final result would resemble this:</p> <pre><code>&gt;&gt;&gt; result A B C 0 1 1 1 1 2 2 2 0 X X X 1 Y Y Y 2 3 3 3 3 4 4 4 0 X X X 1 Y Y Y 4 5 5 5 </code></pre> <p>I've read through the python <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">concatenate</a> docs but can't seem to find out how to specify the particular location I wish to insert the DataFrame. Found a similar question <a href="http://stackoverflow.com/questions/20424932/concatenating-dataframes-by-index-columns-elements">here</a> but as my DataFrame indexes don't match this solution does not work for me. </p>
1
2016-09-11T04:49:10Z
39,433,385
<p>At least what you want can be achieved by slicing and concatenating:</p> <pre><code>from collections import OrderedDict idx_dict = OrderedDict(sorted(idx_dict.items())) dfs = [] start_idx = 0 for idx in idx_dict: dfs.append(df.iloc[start_idx:idx + 1]) dfs.append(idx_dict[idx]) start_idx = idx + 1 dfs.append(df.iloc[start_idx:]) result = pd.concat(dfs) </code></pre> <p>I think "inserting" <code>df_a</code> and <code>df_b</code> is difficult because the pandas data is actually a numpy array, which cannot be resized.</p>
3
2016-09-11T06:14:54Z
[ "python", "pandas", "dictionary", "dataframe", "insert" ]
TypeError: expected a character buffer object (while writing dictionary keys to text file)
39,432,965
<p>Below code doesn't work:</p> <pre><code>with open("testfile.txt",'w') as fw: for key in a: fw.write(a[key]) </code></pre> <p>Below is the error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 3, in &lt;module&gt; TypeError: expected a character buffer object` </code></pre> <p>Below code works:</p> <pre><code>with open('myfile.txt', 'w') as f: for key, value in a.items(): f.write('%s:%s\n' % (key, value)) </code></pre> <p>Can someone help me understand what's wrong in first block?</p>
1
2016-09-11T04:49:11Z
39,433,402
<p>As the error message says: you can write only a character buffer object to a file. For example a <code>string</code>. However the entries in your dictionary are <code>int</code>s - which aren't character buffer objects. So you have first to convert the values to a string and than write it to a file, for example this conversion can be done via <code>'%d\n' % a[key]</code> or <code>'{0]\n'.format(a[key])</code>.</p> <p>You could actually could use <code>'%s\n' % a[key]</code> and it would also work even if elements in the dictionary aren't integers. <code>%s</code> in python means that the conversion is done using the <code>str()</code> function, which is different from the usage in C, because in C <code>%s</code> means the formating of a null terminated string of characters. You could observe this in your second program and the reason I first thought the elements in your dictionary are <code>string</code>s.</p>
0
2016-09-11T06:18:46Z
[ "python", "python-2.7", "file", "dictionary" ]
how to use the split in Python
39,432,991
<pre><code>import xlrd import urllib.request workbook = xlrd.open_workbook('test.xlsx'); sheet = workbook.sheet_by_index(0); num_rows = sheet.nrows -1; print(num_rows); print('\n'); inputI=str(300); inputP=str(15); inputF='d'; content=sheet.cell_value(0,0); address='http://www.google.com/finance/getprices? q='+content+'&amp;i='+inputI+'&amp;p='+inputP+'d&amp;f='+inputF; response = urllib.request.urlopen(address); data = response.readlines().split('\n'); print(data); </code></pre> <p>When I run it, it will always show that 'list' object has no attribute 'split'. what should I do to fix it? Really appreciate it. </p>
0
2016-09-11T04:54:00Z
39,433,091
<p>Response.readlines() provides a list of lines. So it means that you are trying to split the list, which is not possible.</p> <p>Instead try to take each line and then perform any processing you want to.</p>
0
2016-09-11T05:12:54Z
[ "python", "excel" ]
how to use the split in Python
39,432,991
<pre><code>import xlrd import urllib.request workbook = xlrd.open_workbook('test.xlsx'); sheet = workbook.sheet_by_index(0); num_rows = sheet.nrows -1; print(num_rows); print('\n'); inputI=str(300); inputP=str(15); inputF='d'; content=sheet.cell_value(0,0); address='http://www.google.com/finance/getprices? q='+content+'&amp;i='+inputI+'&amp;p='+inputP+'d&amp;f='+inputF; response = urllib.request.urlopen(address); data = response.readlines().split('\n'); print(data); </code></pre> <p>When I run it, it will always show that 'list' object has no attribute 'split'. what should I do to fix it? Really appreciate it. </p>
0
2016-09-11T04:54:00Z
39,433,220
<blockquote> <p>The method readlines() reads until EOF using readline() and returns a list containing the lines.</p> </blockquote> <p>You can do something like:</p> <pre><code>data = response.readlines() for line in data: # I guess you will get byte here, so you have to convert them to utf-8 print(line.decode("utf-8", errors='ignore').split("\n")[0]) </code></pre> <p>And also you can use readline() to do this.</p>
0
2016-09-11T05:42:23Z
[ "python", "excel" ]
Why are non integral builtin types allowed in python slices?
39,433,018
<p>I've just improving test coverage for a <a href="https://github.com/JaggedVerge/mmap_backed_array" rel="nofollow">library</a> that has to support slices and I've noticed that slices can contain non-integral types:</p> <pre><code>&gt;&gt;&gt; slice(1, "2", 3.0) slice(1, '2', 3.0) &gt;&gt;&gt; sl = slice(1, "2", 3.0) &gt;&gt;&gt; [1,2,3][sl] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: slice indices must be integers or None or have an __index__ method </code></pre> <p>This might just be my static-typing background but it seems strange to me that the builtin types without <code>__index__</code> can be passed in here without a <code>TypeError</code>. Why is this so? Would I be right in assuming that arbitrary types are allowed in order to support duck typing for types that implement <code>__index__</code>? Is the lack of a type check due to performance reasons for the most commonly used cases?</p> <p>Prior to <a href="https://www.python.org/dev/peps/pep-0357/" rel="nofollow">PEP 357</a> was the slice in the example invalid?</p>
6
2016-09-11T04:59:21Z
39,437,208
<blockquote> <p>Would I be right in assuming that arbitrary types are allowed in order to support duck typing for types that implement <code>__index__</code>?</p> </blockquote> <p>There's no actual reason as to why you should restrict the types passed when initializing <code>slice</code> objects. Exactly as stated in the rational for <code>PEP 357</code>, <code>numpy</code> and the numeric types it utilizes can't inherit from object so strict <code>issubclass</code> checks of the type passed will make them unusable as index values. So duck typing is employed, if it defines the appropriate method (<code>__index__</code>), it's usable.</p> <p>Also take note that this (the presence of <code>__index__</code>) is enforced only when applying the slice (as you saw, the <code>TypeError</code> was raised during the <code>__getitem__</code>, i.e <a href="https://github.com/python/cpython/blob/master/Objects/sliceobject.c#L194" rel="nofollow"><code>list_subscript</code></a> ) operation when <a href="https://github.com/python/cpython/blob/master/Objects/sliceobject.c#L114" rel="nofollow"><code>PySlice_GetIndicesEx</code></a> is called to try and get the values you passed.</p> <p>The <a href="https://github.com/python/cpython/blob/master/Objects/sliceobject.c#L114" rel="nofollow">slice objects initializer</a> makes no discrimination on what type it accepts, all <code>PyObject</code>'s can apply as can be seen from its signature:</p> <pre><code>PyObject * PySlice_New(PyObject *start, PyObject *stop, PyObject *step) { /* rest omitted */ </code></pre> <blockquote> <p>Prior to <code>PEP 357</code> was the slice in the example invalid?</p> </blockquote> <p>I just built a <code>2.4</code> version of Python and tested it (<code>PEP 357</code> appeared in <code>2.5</code> if I'm not mistaken), again the check if the arguments are numeric is not done during initialization but when <code>__getitem__</code> is invoked; the only thing that differs is the exception message which doesn't make any notice about the <code>__index__</code> dunder (which then obviously didn't exist):</p> <pre><code>Python 2.4 (#1, Sep 11 2016, 18:13:11) [GCC 5.4.0 20160609] on linux4 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; s = slice(0, Ellipsis) &gt;&gt;&gt; [1, 2, 3][s] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? TypeError: slice indices must be integers </code></pre>
2
2016-09-11T14:41:03Z
[ "python", "python-3.x", "slice", "python-internals" ]
Why are non integral builtin types allowed in python slices?
39,433,018
<p>I've just improving test coverage for a <a href="https://github.com/JaggedVerge/mmap_backed_array" rel="nofollow">library</a> that has to support slices and I've noticed that slices can contain non-integral types:</p> <pre><code>&gt;&gt;&gt; slice(1, "2", 3.0) slice(1, '2', 3.0) &gt;&gt;&gt; sl = slice(1, "2", 3.0) &gt;&gt;&gt; [1,2,3][sl] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: slice indices must be integers or None or have an __index__ method </code></pre> <p>This might just be my static-typing background but it seems strange to me that the builtin types without <code>__index__</code> can be passed in here without a <code>TypeError</code>. Why is this so? Would I be right in assuming that arbitrary types are allowed in order to support duck typing for types that implement <code>__index__</code>? Is the lack of a type check due to performance reasons for the most commonly used cases?</p> <p>Prior to <a href="https://www.python.org/dev/peps/pep-0357/" rel="nofollow">PEP 357</a> was the slice in the example invalid?</p>
6
2016-09-11T04:59:21Z
39,438,963
<p>Third-party libraries may want to implement slicing for their own objects, and there's no reason for the core language to restrict those third-party libraries to only using integers or integer-like objects (i.e., objects whose type provides the <code>__index__</code> method) in their slices. Here are two notable examples of packages using non-integers in slicing: in NumPy, some objects accept a complex step, for example:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; numpy.mgrid[0:2:5j] array([ 0. , 0.5, 1. , 1.5, 2. ]) </code></pre> <p>And in Pandas, you can slice a <code>Series</code> or <code>Dataframe</code> object by label. That label could be a string, or a <code>datetime</code> object (for example).</p> <pre><code>&gt;&gt;&gt; import pandas &gt;&gt;&gt; s = pandas.Series(range(4), index=['a', 'b', 'c', 'd']) &gt;&gt;&gt; s['b':'d'] b 1 c 2 d 3 dtype: int64 </code></pre> <p>So it wouldn't make sense for the core language to raise an exception when constructing a slice containing non-integers; that would break the above libraries. Instead, the actual slicing operation should raise an exception if the slice components (start, stop, step) are not of the appropriate type.</p>
3
2016-09-11T17:48:57Z
[ "python", "python-3.x", "slice", "python-internals" ]
Pythonic way to access the shifted version of numpy array?
39,433,019
<p>What is a pythonic way to access the shifted, either right or left, of a <code>numpy</code> array? A clear example:</p> <pre><code>a = np.array([1.0, 2.0, 3.0, 4.0]) </code></pre> <p>Is there away to access:</p> <pre><code>a_shifted_1_left = np.array([2.0, 3.0, 4.0, 1.0]) </code></pre> <p>from the <code>numpy</code> library?</p>
4
2016-09-11T04:59:23Z
39,433,047
<p>You are looking for <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html" rel="nofollow"><code>np.roll</code></a> -</p> <pre><code>np.roll(a,-1) # shifted left np.roll(a,1) # shifted right </code></pre> <p>Sample run -</p> <pre><code>In [28]: a Out[28]: array([ 1., 2., 3., 4.]) In [29]: np.roll(a,-1) # shifted left Out[29]: array([ 2., 3., 4., 1.]) In [30]: np.roll(a,1) # shifted right Out[30]: array([ 4., 1., 2., 3.]) </code></pre> <p>If you want more shifts, just go <code>np.roll(a,-2)</code> and <code>np.roll(a,2)</code> and so on.</p>
4
2016-09-11T05:04:01Z
[ "python", "arrays", "numpy" ]
Find when integral of an interpolated function is equal to a specific value (python)
39,433,108
<p>I have arrays <code>t_array</code> and <code>dMdt_array</code> of x and y points. Let's call <code>M = trapz(dMdt_array, t_array)</code>. I want to find at what value of t the integral of dM/dt vs t is equal to a certain value -- say <code>0.05*M</code>. In python, is there a nice way to do this?</p> <p>I was thinking something like <code>F = interp1d(t_array, dMdt_array)</code>. Then some kind of root find for where the integral of F is equal to 0.05*M. Can I do this in python?</p>
0
2016-09-11T05:16:36Z
39,433,909
<p>One simple way is to use the CubicSpline class instead. Then it's <code>CubicSpline(x, y).antiderivative().solve(0.05*M)</code> or thereabouts.</p>
1
2016-09-11T07:41:29Z
[ "python", "scipy" ]