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
Regular expression to add additional argument to php function in source
37,736,855
<p>I want to add an additional argument to my function using regular expressions and Python.</p> <p>My function looks like this: </p> <pre><code>mail(arg1, arg2, arg3, arg4); </code></pre> <p>Can anyone help with regular expression to get this result:</p> <pre><code>mail(arg1, arg2, arg3, arg4, arg5); </code></pre>...
0
2016-06-09T21:57:47Z
37,753,765
<p>I'd like to propose a different answer than the one you are asking for.</p> <p>Consider a couple of other alternatives. Assuming the 5th argument is always the same, there are a couple of other approaches.</p> <p>(1) Write a new function call. Let's call it <code>newmail</code>. </p> <pre><code>function newmai...
0
2016-06-10T17:10:13Z
[ "python", "regex" ]
Webscrape Flashscore with Python/Selenium
37,736,938
<p>I started to learn scrape websites with Python and Selenium. I choose selenium because I need to navigate through the website and I also have to login.</p> <p>I wrote an script that is able to open a firefox window and it opens the website www.flashscore.com. With this script I also be able to login and navigate to...
1
2016-06-09T22:03:27Z
37,737,451
<p>No, the iframes are not the problem in this case. The "Live games" element is not inside an <code>iframe</code>. Locate it by link text and click:</p> <pre><code>live_games_link = driver.find_element_by_link_text("LIVE Games") live_games_link.click() </code></pre> <p>You may need to <em>wait for this link to be cl...
0
2016-06-09T22:52:32Z
[ "python", "selenium", "web-scraping" ]
Is there a View function in Python to rotate plots like in Matlab?
37,736,947
<p>I have an image that I would like to rotate. Namely, exchange the <code>x</code> and <code>y</code> axes. It is of a spectrogram. The basic code is</p> <pre><code>import matplotlib.pyplot as plt Sxx, f, t, im = plt.specgram(dataArray, NFFT=2**8, Fs = 100, noverlap = 128) plt.show() </code></pre> <p>This is what ...
1
2016-06-09T22:04:04Z
37,757,381
<p>You can use scipy <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.interpolation.rotate.html" rel="nofollow">rotate</a> to rotate your data (from the array point of view). The following example:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from scipy import ndim...
0
2016-06-10T21:26:04Z
[ "python", "python-3.x", "matplotlib", "plot" ]
Removing sublists of empty entries from a list
37,737,000
<p>I've got a list that looks like this:</p> <pre><code>some_list = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['', '', '', '']] </code></pre> <p>I want to remove all empty sublists within the list, so that the product is just</p> <pre><code>clean_list = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']] </code></pre> ...
0
2016-06-09T22:08:02Z
37,737,021
<p>Use the <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any()</code> function</a> to <em>select</em> lists with non-empty values:</p> <pre><code>clean_list = [sublist for sublist in some_list if any(sublist)] </code></pre> <p><code>any()</code> short-circuits; iterating over the...
3
2016-06-09T22:09:54Z
[ "python", "list", "python-2.7" ]
Python TypeError: 'Generic' object is not subscriptable - How to Declare and Instantiate a Generic Base Class
37,737,027
<p>I am trying to create an Abstract Generic Base class in python utilizing the new type annotation functionality in python 3 and the support for generics.</p> <p>I have a base class and a derived class defined as such:</p> <pre><code>from abc import ABCMeta, abstractmethod from typing import TypeVar, Generic, Iterat...
1
2016-06-09T22:10:14Z
37,737,088
<p>This line:</p> <pre><code>class FileReader(Generic(_T)): </code></pre> <p>should use brackets for <code>Generic[_T]</code>:</p> <pre><code>class FileReader(Generic[_T]): </code></pre> <p><code>Generic</code> is generic, and like any other generic ABC, you specify its type parameters in brackets.</p>
2
2016-06-09T22:17:01Z
[ "python", "generics", "base-class", "typing" ]
using scipy.integrate.odeint with dictionary [Python]
37,737,029
<p>I'm trying to solve decay equations using scipy.integrate.odeint. I'm trying to have initial values from a dictionary, but it isn't working and I'm not sure if it can work. Here is the code I'm working with:</p> <pre><code>from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt def de...
0
2016-06-09T22:10:16Z
37,737,216
<p>If this works:</p> <pre><code>init = [5,0,0] time = np.linspace(0, 10, 101) soln = odeint(decay, init ,time) </code></pre> <p>then this should as well:</p> <pre><code>adict = {'a':5, 'b':0, 'c':0} init = [adict['a'],adict['b'],adict['c']] time = np.linspace(0, 10, 101) soln = odeint(decay, init ,time) </code></...
1
2016-06-09T22:28:07Z
[ "python", "scipy" ]
Send file contents over ftp python
37,737,040
<p>I have this Python Script</p> <pre><code> import os import random import ftplib from tkinter import Tk # now, we will grab all Windows clipboard data, and put to var clipboard = Tk().clipboard_get() # print(clipboard) # this feature will only work if a string is in the clipboard. not files. # so if ...
-1
2016-06-09T22:11:10Z
37,737,265
<p>Your library expects the file to be open in binary mode, it appears. Try the following:</p> <pre><code>f = open(filename, 'rb') </code></pre> <p>This ensures that the data read from the file is a <code>bytes</code> object rather than <code>str</code> (for text).</p>
0
2016-06-09T22:33:19Z
[ "python", "ftp" ]
Python - Project Euler #57, understanding the error
37,737,084
<p>When I run this code to calculate convergents of the root 2 continued fraction:</p> <pre><code>def root_two_expansion(): total=0 a=(3,2) b=(7,5) x=3 while x&lt;=1000: c=((sum(a)+sum(b)),sum(b)) if len(str(c[0]))&gt;len(str(c[1])): total+=1 a=b,b=c x+=1...
0
2016-06-09T22:16:35Z
37,737,136
<p>The line </p> <pre><code>a=b,b=c </code></pre> <p>unpacks the tuple <code>c</code> in <code>b</code> and <code>b</code>, so only the second int is saved in <code>b</code>. In the next loop step you try to call <code>sum</code> on this int.</p> <p>Did you mean</p> <pre><code>a, b = b, c </code></pre>
5
2016-06-09T22:21:21Z
[ "python", "iteration" ]
Is it possible to use multiprocessing in a module with windows?
37,737,085
<p>I'm currently going through some pre-existing code with the goal of speeding it up. There's a few places that are extremely good candidates for parallelization. Since Python has the GIL, I thought I'd use the multiprocess module. </p> <p>However from my understanding the only way this will work on windows is if I c...
2
2016-06-09T22:16:40Z
37,737,176
<p>On ms-windows, you should be able to import the <em>main module</em> of a program without side effects like starting a process.</p> <p>When Python imports a module, it actually runs it.</p> <p>So one way of doing that is in the <code>if __name__ is '__main__'</code> block.</p> <p>Another way is to do it from with...
0
2016-06-09T22:24:51Z
[ "python", "windows", "multiprocessing" ]
Is it possible to use multiprocessing in a module with windows?
37,737,085
<p>I'm currently going through some pre-existing code with the goal of speeding it up. There's a few places that are extremely good candidates for parallelization. Since Python has the GIL, I thought I'd use the multiprocess module. </p> <p>However from my understanding the only way this will work on windows is if I c...
2
2016-06-09T22:16:40Z
37,737,747
<p>As explained in comments, perhaps you could do something like</p> <pre><code>#client_main.py from mylib.mpSentinel import MPSentinel #client logic if __name__ == "__main__": MPSentinel.As_master() #mpsentinel.py class MPSentinel(object): _is_master = False @classmethod def As_master(cls): cls._is_...
0
2016-06-09T23:27:50Z
[ "python", "windows", "multiprocessing" ]
Compare time with timezone to now
37,737,098
<p>I have a string time coming from a third party (external to my python program), and I need to compare that time to right now. How long ago was that time?</p> <p>How can I do this?</p> <p>I've looked at the <code>datetime</code> and <code>time</code> libraries, as well as <code>pytz</code>, and can't find an obvio...
-2
2016-06-09T22:17:34Z
37,737,145
<p>Good question Zack! I've had this problem myself.</p> <p>Here's some code to do so:</p> <pre><code>from datetime import datetime import time import calendar import pytz def howLongAgo(thirdPartyString, timeFmt): # seconds since epoch thirdPartySeconds = calendar.timegm(time.strptime(thirdPartyString, timeFmt)...
0
2016-06-09T22:22:43Z
[ "python", "datetime", "timezone" ]
Compare time with timezone to now
37,737,098
<p>I have a string time coming from a third party (external to my python program), and I need to compare that time to right now. How long ago was that time?</p> <p>How can I do this?</p> <p>I've looked at the <code>datetime</code> and <code>time</code> libraries, as well as <code>pytz</code>, and can't find an obvio...
-2
2016-06-09T22:17:34Z
37,780,684
<blockquote> <p>TypeError: can't subtract offset-naive and offset-aware datetimes</p> </blockquote> <p>To fix the <code>TypeError</code>, use timezone aware datetime objects:</p> <pre><code>#!/usr/bin/env python from datetime import datetime import pytz # $ pip install pytz tz = pytz.timezone('US/Eastern') now = d...
0
2016-06-13T01:19:28Z
[ "python", "datetime", "timezone" ]
How can I delete the first 16 records on a List?
37,737,127
<p>I want to get just 16 records and if there more than 16, then delete the first 16 from the list.</p> <p>my code:</p> <pre><code>ItemList = { "items": [ [ [19,1],[19,2],[19,3],[19,4],[19,5],[19,6],[19,7],[19,8],[19,9],[19,10],[19,11],[19,12],[19,13],[19,14],[19,15],[19,16],[19,17],[19,18],[1...
2
2016-06-09T22:20:12Z
37,737,164
<p>You could just use slices:</p> <pre><code>&gt;&gt;&gt; ItemList['items'][0][16::] [[19, 17], [19, 18], [19, 19], [19, 20], [19, 21], [19, 22], [19, 23], [19, 24], [19, 25], [19, 26], [19, 27], [19, 28], [19, 29], [19, 30], [19, 31], [19, 32]] </code></pre>
0
2016-06-09T22:23:42Z
[ "python", "list" ]
How can I delete the first 16 records on a List?
37,737,127
<p>I want to get just 16 records and if there more than 16, then delete the first 16 from the list.</p> <p>my code:</p> <pre><code>ItemList = { "items": [ [ [19,1],[19,2],[19,3],[19,4],[19,5],[19,6],[19,7],[19,8],[19,9],[19,10],[19,11],[19,12],[19,13],[19,14],[19,15],[19,16],[19,17],[19,18],[1...
2
2016-06-09T22:20:12Z
37,737,259
<p>(Edit after comment)<br> May be this is what you are looking for:</p> <pre><code>if len(ItemList['items'][0]) &gt; 16: ItemList['items'][0] = ItemList['items'][0][-16:] </code></pre> <hr> <p>You can use this:</p> <pre><code>ItemList['items'][0] = ItemList['items'][0][16:] </code></pre>
2
2016-06-09T22:32:46Z
[ "python", "list" ]
How can I delete the first 16 records on a List?
37,737,127
<p>I want to get just 16 records and if there more than 16, then delete the first 16 from the list.</p> <p>my code:</p> <pre><code>ItemList = { "items": [ [ [19,1],[19,2],[19,3],[19,4],[19,5],[19,6],[19,7],[19,8],[19,9],[19,10],[19,11],[19,12],[19,13],[19,14],[19,15],[19,16],[19,17],[19,18],[1...
2
2016-06-09T22:20:12Z
37,737,273
<p>Just:</p> <pre><code>del ItemList["items"][0][:16] </code></pre>
1
2016-06-09T22:34:41Z
[ "python", "list" ]
Objective-C String Format by keyword
37,737,229
<p>In Objective C, is there a way to format a string similar to <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">python's</a> <code>str.format</code> method. I would like to be able to take a string with keywords <code>@"this is {keyword_1}, and this is {keyword_2}"</code> and replace...
3
2016-06-09T22:29:45Z
37,737,396
<p>Not in the standard first-party Apple libraries, no. I've never seen anything in a third-party library, either.</p>
0
2016-06-09T22:46:22Z
[ "python", "objective-c" ]
Objective-C String Format by keyword
37,737,229
<p>In Objective C, is there a way to format a string similar to <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="nofollow">python's</a> <code>str.format</code> method. I would like to be able to take a string with keywords <code>@"this is {keyword_1}, and this is {keyword_2}"</code> and replace...
3
2016-06-09T22:29:45Z
37,738,448
<p>It's fairly easy to write such a function, using the <code>NSScanner</code> class to parse the format string. </p> <p>Declare a category on <code>NSString</code> in a .h file:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface NSString (KeywordFormat) + (NSString *)stringWithKeywordFormat:(NSString...
2
2016-06-10T00:58:21Z
[ "python", "objective-c" ]
PySide2 signal not catched between threads with objects
37,737,238
<p>I've got an issue that I can't find an answer for.</p> <p>I'm working on a GUI application, developed in Python and its UI library : <code>PySide2</code> (Qt wrapper for Python)</p> <p>I have a heavy computation function I want to put on another thread in order to not freeze my UI. The Ui should show "Loading" and...
-1
2016-06-09T22:30:44Z
37,744,500
<p>You can't define signals dynamically on a class instance. They have to be defined as class attributes. You should be using the <a href="http://pyqt.sourceforge.net/Docs/PyQt4/new_style_signals_slots.html" rel="nofollow">new-style signals and slot syntax</a>.</p> <pre><code>class OtherThread(QThread): over = Q...
1
2016-06-10T09:19:15Z
[ "python", "multithreading", "pyside" ]
Random sample from list of lists
37,737,239
<p>In python, I have a list of lists, <code>x</code>, like so: <code>[[1, 2, 3],[4, 5, 6], [7, 8, 9]]</code></p> <p>I have another list, <code>y</code>, like so <code>[1, 2, 3, 4, 5, 6, 7, 8, 9]</code></p> <p>I need to get 2 random items from <code>y</code> that are not together in a list in <code>x</code>, so I can...
0
2016-06-09T22:30:55Z
37,737,372
<p>Why not randomly pick two distinct lists from <code>x</code> first and <em>then</em> swap a random choice of two elements between them?</p> <pre><code>lists = random.sample(x, 2) # now we swap two random elements between lists[0], lists[1] </code></pre>
2
2016-06-09T22:43:49Z
[ "python", "list", "random", "random-sample" ]
Overwriting all values while iterating a for loop- Python
37,737,352
<p>I'm new to python and have been working to parse an excel spreadsheet. I'm trying to determine the accumulated value associated with a particular zoning over a series of dates. </p> <p>I have a feeling that I'm not understanding the logic flow correctly, because no matter how I write it, I keep ending up with a dic...
0
2016-06-09T22:41:48Z
37,738,871
<p>I figured out the answer.</p> <p>The code immediately preceding this segment is:</p> <pre><code>#Set structure of hoursAllocationDict #Date: # Zoning1: 0 # Zoning2: 0 for date in uniqueDateList: hoursAllocationDict[date] = zoningsDict </code></pre> <p>Looking at how Python handles assignment (f...
0
2016-06-10T02:07:27Z
[ "python", "list", "python-2.7", "for-loop", "dictionary" ]
Python List of Lists vs numpy
37,737,368
<p>So, I have a snippet of a script:</p> <pre><code>lol = [] latv1 = 0 latv2 = 0 latv3 = 0 #Loop a for a in range(100): #Refresh latv2 after each iteration of loop a latv2 = 0 #Loop b for b in range(100): #Refresh latv3 after each iteration of loop b latv3 = 0 #Loop c ...
1
2016-06-09T22:43:25Z
37,737,470
<p><strong>Approach #1</strong></p> <p>To create the NumPy equivalent of the posted code and have NumPy array as output, you could additionally make use of <a href="https://docs.python.org/2/library/itertools.html" rel="nofollow"><code>itertools</code></a>, like so -</p> <pre><code>from itertools import product out ...
5
2016-06-09T22:54:27Z
[ "python", "arrays", "numpy" ]
How to recover lists that are saved in Series
37,737,480
<p>I have lists inside a Series, which are stored inside a Dataframe. Now i want to recreate these lists. How can I do that? I try to call them with a function. As example:</p> <pre><code> pd.Series([1, 2, 3], [4, 5, 6], ....) getList (df.ix[1,['column']]) </code></pre> <p>So how can it get now back aga...
2
2016-06-09T22:55:02Z
37,737,569
<p>If you want to get the original list back form a <code>Pandas Series' then 'totlist()</code> should work fine. If this is what you mean, because your question is not really clear. Also, your <code>pd.Series([1, 2, 3], [4, 5, 6], ....)</code> is not right, please see below:</p> <pre><code>s = pd.Series([[1, 2, 3], [...
1
2016-06-09T23:05:47Z
[ "python", "pandas", "series" ]
How to recover lists that are saved in Series
37,737,480
<p>I have lists inside a Series, which are stored inside a Dataframe. Now i want to recreate these lists. How can I do that? I try to call them with a function. As example:</p> <pre><code> pd.Series([1, 2, 3], [4, 5, 6], ....) getList (df.ix[1,['column']]) </code></pre> <p>So how can it get now back aga...
2
2016-06-09T22:55:02Z
37,737,631
<p><code>iloc[0]</code> gets you the first element of the series, which is a list. <code>[0]</code> gets the first element of that list.</p> <pre><code>pd.Series([[1, 2, 3]]).iloc[0][0] </code></pre> <p>Or:</p> <pre><code>pd.Series([[1, 2, 3]]).tolist()[0][0] </code></pre> <p>You can also do:</p> <pre><code>pd.Se...
1
2016-06-09T23:12:48Z
[ "python", "pandas", "series" ]
Filter pandas dataframe rows by multiple column values
37,737,494
<p>I have a pandas dataframe containing rows with numbered columns:</p> <pre><code> 1 2 3 4 5 a 0 0 0 0 1 b 1 1 2 1 9 c 2 2 2 2 2 d 5 5 5 5 5 e 8 9 9 9 9 </code></pre> <p>How can I filter out the rows where a subset of columns are all above or below a certain value?</...
3
2016-06-09T22:56:27Z
37,737,700
<p>I used <code>loc</code> and <code>all</code> in this function:</p> <pre><code>def filt(df, cols, thresh): return df.loc[(df[cols] &gt; thresh).all(axis=1)] filt(df, [1, 2, 3], 3) 1 2 3 4 5 d 5 5 5 5 5 e 8 9 9 9 9 </code></pre>
3
2016-06-09T23:21:44Z
[ "python", "pandas", "dataframe" ]
Filter pandas dataframe rows by multiple column values
37,737,494
<p>I have a pandas dataframe containing rows with numbered columns:</p> <pre><code> 1 2 3 4 5 a 0 0 0 0 1 b 1 1 2 1 9 c 2 2 2 2 2 d 5 5 5 5 5 e 8 9 9 9 9 </code></pre> <p>How can I filter out the rows where a subset of columns are all above or below a certain value?</...
3
2016-06-09T22:56:27Z
37,742,343
<p>You can achieve this without using <code>apply</code>:</p> <pre><code>In [73]: df[(df.ix[:,0:3] &gt; 3).all(axis=1)] Out[73]: 1 2 3 4 5 d 5 5 5 5 5 e 8 9 9 9 9 </code></pre> <p>So this slices the df to just the first 3 columns using <code>ix</code> and then we compare against the scalar <code>3</...
1
2016-06-10T07:27:03Z
[ "python", "pandas", "dataframe" ]
PyMySQL not found on windows
37,737,528
<p>I searched for a Python MySQL connector for Python3.4 on Windows, because I want to use SQLAlchemy as my MySQL ORM. People suggested <a href="https://github.com/PyMySQL/PyMySQL" rel="nofollow">PyMySQL</a> as connector, which I installed with pip. Now when I try to use sqlalchemy it says:</p> <pre><code>No module na...
0
2016-06-09T23:00:09Z
37,737,837
<p>Here you go if you have pip. </p> <pre><code>pip install MySQL-python </code></pre>
0
2016-06-09T23:38:02Z
[ "python", "pymysql", "mysql-connector-python" ]
Python - Subplots merging with shared x-axis, different y-scalings and figures
37,737,538
<p>I have two graphs to where both have the same x-axis, but with different y-axis scalings. </p> <p>The plot with regular axes is the data with a trend line depicting a decay while the y semi-log scaling depicts the accuracy of the fit.</p> <pre><code>fig1 = plt.figure(figsize=(15,6)) ax1 = fig1.add_subplot(111) # ...
1
2016-06-09T23:01:41Z
37,738,851
<p>Look at the code and comments in it:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np from matplotlib import gridspec # Simple data to display in various forms x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) fig = plt.figure() # set height ratios for sublots gs = gridspec.GridSpec(2, 1, hei...
2
2016-06-10T02:05:32Z
[ "python", "matplotlib", "subplot" ]
Trying to display text from web site using beautiful soup
37,737,567
<p>I am trying to obtain the number of team members from each team on the list, right now I get all the team links, but instead of obtain all the links I want to obtain the links to the teams with at least 5 team members. How would I go about doing so? I tried but nothing worked so far.</p> <pre><code> import time ...
1
2016-06-09T23:05:33Z
37,737,622
<p>Locate the <code>Members:</code> label which goes further in the tree after the team link. Then, get the team members value, convert to integer and check if it is less than 5:</p> <pre><code>for team_links in soup.select('div.details h3 a'): members = int(team_links.find_next("th", text="Members:").find_next_si...
1
2016-06-09T23:11:31Z
[ "python", "web-scraping", "beautifulsoup" ]
how to change the name of a file and the storage location on upload in django
37,737,587
<p>I want to change an image name and it's storage location on upload. </p> <p>I have </p> <pre><code>def name_func(instance, filename): blocks = filename.split('.') ext = blocks[-1] filename = "%s.%s" % (instance.id, ext) return filename class Restaurant(models.Model): id = models.UUIDField(prim...
1
2016-06-09T23:07:51Z
37,737,686
<p>I think your problem is that you need to prepend the subfolder onto your file name and return that. In your database the filename should be the relative path to your file from the <code>STATIC_URL</code> or <code>MEDIA_URL</code>.</p> <p>Here's an example I have where I generate a UUID for the filename and put it ...
1
2016-06-09T23:19:49Z
[ "python", "django", "file-upload", "django-models", "storage" ]
"type" command in python gives unexpected results
37,737,607
<p>I ran the following code in the Python interpreter:</p> <pre><code>&gt;&gt;&gt; s &lt;sqlalchemy.orm.session.Session object at 0x7f4fc8d69e10&gt; &gt;&gt;&gt; type(s) &lt;class 'sqlalchemy.orm.session.Session'&gt; &gt;&gt;&gt; type(s) == sqlalchemy.orm.session.Session False </code></pre> <p>(1) Why does the interp...
1
2016-06-09T23:10:29Z
37,737,888
<p>Your <code>s</code> is actually an instance of a subclass of <code>sqlalchemy.orm.session.Session</code>. The subclass is confusingly also named <code>sqlalchemy.orm.session.Session</code>.</p> <p>Looking at the SQLAlchemy source, it seems likely that this object was produced by a <code>sqlalchemy.orm.session.sessi...
2
2016-06-09T23:43:24Z
[ "python", "sqlalchemy" ]
Set pythonpath having two different versions
37,737,629
<p>Im working on a CentOS 6.5 which has Python 2.6.6 and I also have installed Python 2.7.5</p> <p>The problem is that I want to import qgis and works with Python 2.7.5.</p> <p>In python 2.6.6 if I write</p> <pre><code>from qgis.core import * </code></pre> <p>There is no problem, but when I tries with Python 2.7 by...
1
2016-06-09T23:12:38Z
37,737,660
<p>Please use Python virtual environments if you need to support multiple Pythons and multiple application on the same computer:</p> <p><a href="https://packaging.python.org/en/latest/installing/#creating-virtual-environments" rel="nofollow">https://packaging.python.org/en/latest/installing/#creating-virtual-environme...
0
2016-06-09T23:16:05Z
[ "python", "python-2.7", "unix", "qgis" ]
How to destroy an .exe file(not converted from py) by run as the same script
37,737,649
<p>I have a script that runs an .exe file via <code>subprocess.Popen()</code>, but I just realized, that .exe file keeps running even I close my script. Is there any way to stop running an .exe file via name of it or ID? That exe file is not converted from a py file, so I'm stuck.</p>
0
2016-06-09T23:14:29Z
37,776,347
<p>If you run <code>process = subprocess.Popen(...)</code> then you could terminate the process later using <code>process.terminate()</code>.</p> <p>If the subprocess may create its own children then <code>process.terminate()</code> and/or <code>process.kill()</code> might not be enough. On Windows, you might need to ...
0
2016-06-12T16:05:43Z
[ "python", "subprocess", "exe", "python-3.4" ]
weak object has gone away? - python/django
37,737,709
<p>I'm having this problem in my django project that I believe is related to caches. It appears once every 6 months or so and is "fixed" by restarting the app, only to come back some months later. Suddenly all views will fail with this exception.</p> <pre><code>TypeError: weak object has gone away </code></pre> <p>An...
0
2016-06-09T23:23:19Z
37,737,924
<p>Based on the traceback this looks more like a Python <code>weakrefset</code> issue to me which <code>collections.Iterator</code> relies on through the <code>abc</code> (Abstract Base Class) module.</p>
0
2016-06-09T23:47:18Z
[ "python", "django", "caching", "django-cache", "django-caching" ]
Bytecode optimization
37,737,740
<p>Here are 2 simple examples. In the first example <code>append</code> method produces LOAD_ATTR instruction inside the cycle, in the second it only produced once and result saved in variable (ie cached). <em>Reminder: I remember, that there <code>extend</code> method for this task which is much faster that this</em><...
9
2016-06-09T23:26:58Z
37,737,822
<p>In general Python optimises virtually nothing. It won't even optimise trivial things like <code>x = x</code>. Python is so dynamic that doing so correctly would be extremely hard. For example the <code>list.append</code> method can't be automatically cached in your first example because it could be changed in anothe...
2
2016-06-09T23:36:14Z
[ "python" ]
Bytecode optimization
37,737,740
<p>Here are 2 simple examples. In the first example <code>append</code> method produces LOAD_ATTR instruction inside the cycle, in the second it only produced once and result saved in variable (ie cached). <em>Reminder: I remember, that there <code>extend</code> method for this task which is much faster that this</em><...
9
2016-06-09T23:26:58Z
37,737,874
<p>Python is a dynamic language. This means that you have <em>a lot</em> of freedom in how you write code. Due to the crazy amounts of introspection that python exposes (which are incredibly useful BTW), many optimizations simply cannot be performed. For example, in your first example, python has no way of knowing w...
6
2016-06-09T23:41:47Z
[ "python" ]
Watching generation lists during a program run
37,737,753
<p><strong>The Story:</strong></p> <p>During <a href="https://www.youtube.com/watch?v=F6u5rhUQ6dU">Nina Zakharenko's PyCon talk</a> on Memory Management in Python, she explains the way the <em>generational garbage collection</em> works in Python noting that:</p> <blockquote> <p>Python maintains a list of every obje...
7
2016-06-09T23:28:32Z
37,847,256
<p>As we discussed in the comments, I don't think there is a way to access the generation lists directly from python, you can set some debug flags, in python2 you can use the following to report objects that can or cannot be collected:</p> <pre><code>import gc gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_COLLECTABL...
3
2016-06-15T23:04:18Z
[ "python", "debugging", "memory", "memory-management", "garbage-collection" ]
Splunk custom alert Python issue
37,737,831
<p>I am running the following code (called caa_fiel_write.py) to output my splunk results to a JSON file:</p> <pre><code>import sys, json, urllib2 def write_file(settings): f = open('myfile','w') f.write("%s"%json.dumps(settings)) f.close() if __name__ == "__main__": caa_config = json.l...
0
2016-06-09T23:37:10Z
37,737,994
<p><code>json.loads(sys.stdin.read())</code> is decoding standard input. Your input is not valid JSON.</p>
1
2016-06-09T23:56:53Z
[ "python", "python-2.7", "splunk" ]
What format does data input have to be for Python's json.loads?
37,737,861
<p>I'm trying to use <code>json.loads</code> to parse data in a Redshift database table. I've stripped out the function to test in a Python script and am having trouble understanding what's happening.</p> <p>The code I'm using is:</p> <pre><code>import json j="'['Bars', 'American (Traditional)', 'Nightlife', 'Restaur...
0
2016-06-09T23:40:38Z
37,737,914
<p>Your input string <code>j</code> is not valid JSON. JSON doesn't allow the use of single quotes (<code>'</code>) to denote string values.</p> <p>Try switching the quotes: <code>'["Bars", "American (Traditional)", "Nightlife", "Restaurants"]'</code></p> <p>The JSON specification is an excellent resource for determi...
1
2016-06-09T23:46:11Z
[ "python", "sql", "json", "amazon-redshift", "udf" ]
Is there an easier way to change the index values of a pandas dataframe?
37,737,865
<p>I am taking a dataframe, breaking it into two dataframes, and then I need to change the index values so that no number is greater than the total number of rows.</p> <p>Here's the code:</p> <pre><code>dataset = pd.read_csv("dataset.csv",usecols['row_id','x','y','time'],index_col=0) splitvalue = math.floor((0.9)*7...
2
2016-06-09T23:40:56Z
37,737,906
<p>try:</p> <pre><code>test = test.reset_index(drop=True).rename_axis('row_id') </code></pre>
3
2016-06-09T23:45:08Z
[ "python", "pandas", "dataframe", "reindex" ]
Is there an easier way to change the index values of a pandas dataframe?
37,737,865
<p>I am taking a dataframe, breaking it into two dataframes, and then I need to change the index values so that no number is greater than the total number of rows.</p> <p>Here's the code:</p> <pre><code>dataset = pd.read_csv("dataset.csv",usecols['row_id','x','y','time'],index_col=0) splitvalue = math.floor((0.9)*7...
2
2016-06-09T23:40:56Z
37,737,971
<p>You should shuffle your data before slicing.... </p> <pre><code>dataset.reindex(np.random.permutation(dataset.index)) </code></pre> <p>Otherwise your biasing your test/train sets. </p>
2
2016-06-09T23:53:49Z
[ "python", "pandas", "dataframe", "reindex" ]
Is there an easier way to change the index values of a pandas dataframe?
37,737,865
<p>I am taking a dataframe, breaking it into two dataframes, and then I need to change the index values so that no number is greater than the total number of rows.</p> <p>Here's the code:</p> <pre><code>dataset = pd.read_csv("dataset.csv",usecols['row_id','x','y','time'],index_col=0) splitvalue = math.floor((0.9)*7...
2
2016-06-09T23:40:56Z
37,742,242
<p>You can assign a new <code>Index</code> object directly to overwrite the index:</p> <pre><code>test.index = pd.Index(np.arange(len(df)), name='row_id') </code></pre>
2
2016-06-10T07:21:45Z
[ "python", "pandas", "dataframe", "reindex" ]
Timezone Conversion From UTC to new time zone
37,737,872
<p>I'm having a bunch of trouble converting UTC to a new time zone in python.</p> <p>The data is originally a string brought in and successfully to converted to UTC as such:</p> <pre><code>df['order delivery time'] = pd.to_datetime(df['order delivery time']) </code></pre> <p>Next I attempt to write a function like t...
0
2016-06-09T23:41:38Z
37,737,977
<p>I've had success using pytz and dateutil.parser in the past:</p> <pre><code>import pytz import dateutil.parser date_needed = dateutil.parser.parse(request.POST.get("date_needed")) item.date_needed = pytz.timezone("America/Phoenix").localize(date_needed, is_dst=None) </code></pre>
0
2016-06-09T23:54:54Z
[ "python", "timezone", "timestamp" ]
Timezone Conversion From UTC to new time zone
37,737,872
<p>I'm having a bunch of trouble converting UTC to a new time zone in python.</p> <p>The data is originally a string brought in and successfully to converted to UTC as such:</p> <pre><code>df['order delivery time'] = pd.to_datetime(df['order delivery time']) </code></pre> <p>Next I attempt to write a function like t...
0
2016-06-09T23:41:38Z
37,751,170
<blockquote> <p>AttributeError: ("'US/Central' object has no attribute 'upper'", u'occurred at index 0')</p> </blockquote> <p><code>central</code> is already a <code>pytz.timezone</code> object. Don't pass it to <code>pytz.timezone()</code>—use it directly.</p> <p>It is not clear what <code>time</code> variable i...
0
2016-06-10T14:47:31Z
[ "python", "timezone", "timestamp" ]
how to write queries using python and REST to retrieve data from JIRA
37,737,957
<p>I am trying to create a script using python and REST to get data from JIRA,currently am able to get data for each JIRA ticket using the code shown below,I want to be able to write queries to retrieve large data which I do currently from the UI as shown below,how can I update my current script to achieve this from t...
1
2016-06-09T23:51:48Z
37,738,906
<p>Try setting <code>jql</code> like this:</p> <pre><code>import urllib query = 'project = ITTICKETS AND "Build Info" ~ CI_-STD.INT-2' jql = '/rest/api/2/search?jql=%s' % urllib.quote(query) </code></pre>
1
2016-06-10T02:12:19Z
[ "python", "rest", "jira", "jql" ]
How does PyROOT change the python interpreter?
37,738,012
<p>If I try to run <code>.ls</code> in python, not surprisingly I get a SyntaxError</p> <pre><code>&gt;&gt;&gt; .ls File "&lt;stdin&gt;", line 1 .ls ^ SyntaxError: invalid syntax </code></pre> <p>But if I import PyROOT, it somehow makes this syntax legal (and behaves as it does in ROOT, listing the contents...
3
2016-06-09T23:58:51Z
37,746,002
<p>It can by found in lib/ROOT.py</p> <p>there is condition that if not ipython the sys.excepthook is redefined:</p> <pre><code>sys.excepthook = _excepthook </code></pre> <p>which in turn contains stuff like:</p> <pre><code>### RINT command emulation ------------------------------------------------------ def _...
3
2016-06-10T10:32:09Z
[ "python", "root-framework" ]
confused on use of abbreviations for LPTHW ex 39
37,738,019
<p>Here is the code for this example in Learn PYthon The Hard Way:</p> <pre><code>states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' } cities = { 'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville' } cities['NY'] = 'New York' cities['OR'] = 'Portland' print '...
-2
2016-06-10T00:00:17Z
37,738,152
<p>Firstly, <a href="http://sopython.com/wiki/LPTHW_Complaints" rel="nofollow">avoid LPTHW</a>.</p> <blockquote> <p>Lastly, why is worded states.items() and cities.items()? Why is the .items needed, couldn't it just be states() and cities()?</p> </blockquote> <p>Try running <code>print states.items()</code> and <co...
0
2016-06-10T00:19:31Z
[ "python" ]
django errno 104 Connection reset by peer
37,738,030
<p>I am trying to run my django server on an Ubuntu instance on AWS EC2. I am using gunicorn to run the server like this :</p> <p><code>gunicorn --workers 4 --bind 127.0.0.1:8000 woc.wsgi:application --name woc-server --log-level=info --worker-class=tornado --timeout=90 --graceful-timeout=10</code></p> <p>When I make...
0
2016-06-10T00:01:36Z
37,738,765
<p>Ok so your problem as far as I can tell is that your celery worker can't connect to the broker. You have some middleware trying to call a celery task, so it will fail on every request (unless that <code>analyse_urls.delay(**kw)</code> is conditional)</p> <p>I found <a href="http://stackoverflow.com/questions/246473...
0
2016-06-10T01:53:03Z
[ "python", "django", "amazon-ec2", "rabbitmq", "celery" ]
django errno 104 Connection reset by peer
37,738,030
<p>I am trying to run my django server on an Ubuntu instance on AWS EC2. I am using gunicorn to run the server like this :</p> <p><code>gunicorn --workers 4 --bind 127.0.0.1:8000 woc.wsgi:application --name woc-server --log-level=info --worker-class=tornado --timeout=90 --graceful-timeout=10</code></p> <p>When I make...
0
2016-06-10T00:01:36Z
37,774,003
<p>try setting the rabbitmq connection timeout to 30 seconds. this usually clears up the problem of being unable to connect to a server. </p> <p>you can add <code>connection_timeout</code> to your connection string:</p> <p><code>BROKER_URL = 'amqp://celeryuser:celerypassword@server.example.com:5672/MyVHost?connection...
0
2016-06-12T12:02:54Z
[ "python", "django", "amazon-ec2", "rabbitmq", "celery" ]
Python keyboard controls
37,738,070
<p>Here is my code I have trouble with, it's a basic side scroller game but I am having troubles with my keyboard control definitions, they don't seem to work, and I can't find the problem. </p> <pre><code>if keys[K_LEFT]: newmove= LEFT moveLeft(guy,10) climb(guy) if keys[K_RIGHT]: newmove=RIGHT ...
0
2016-06-10T00:08:34Z
37,756,224
<p>Have you tried using this? or something like this?</p> <pre><code> if event.type == pygame.KEYDOWN: if event.key == pygame.K_a or event.key == pygame.K_LEFT: xChange = -5 print("Left") if event.type == pygame.KEYDOWN: if ...
0
2016-06-10T19:56:28Z
[ "python", "keyboard", "pygame" ]
Python: Add Processing Time to Output CSV File
37,738,146
<p>The code below creates a pandas dataframe and outputs it into a csv file. It also clocks the processing time. How would I add the processing time to the csv file?</p> <p>Thank you for your time.</p> <pre><code>import pandas as pd import csv import time def procedure(): time.sleep(0) t0 = time.clock() y=pd.Data...
1
2016-06-10T00:19:17Z
37,738,186
<p>Open the file in append mode to add the time to the end:</p> <pre><code>... procedure() elapsed = time.clock()-t0 with open('temp1.csv', 'a') as f: f.write(str(elapsed)) </code></pre>
0
2016-06-10T00:25:32Z
[ "python", "csv", "time" ]
Python: Add Processing Time to Output CSV File
37,738,146
<p>The code below creates a pandas dataframe and outputs it into a csv file. It also clocks the processing time. How would I add the processing time to the csv file?</p> <p>Thank you for your time.</p> <pre><code>import pandas as pd import csv import time def procedure(): time.sleep(0) t0 = time.clock() y=pd.Data...
1
2016-06-10T00:19:17Z
37,738,232
<pre><code>import time start_time = time.time() finish_time = time.time() - start_time </code></pre> <p>To get the processing time you can use your code like that:</p> <pre><code>import pandas as pd import csv import time def procedure(): time.sleep(0) start_time = time.time() y=pd.DataFrame({'one':[1,2,3,4],'two...
0
2016-06-10T00:30:40Z
[ "python", "csv", "time" ]
Python: Add Processing Time to Output CSV File
37,738,146
<p>The code below creates a pandas dataframe and outputs it into a csv file. It also clocks the processing time. How would I add the processing time to the csv file?</p> <p>Thank you for your time.</p> <pre><code>import pandas as pd import csv import time def procedure(): time.sleep(0) t0 = time.clock() y=pd.Data...
1
2016-06-10T00:19:17Z
37,739,980
<p>Your indents are off:</p> <pre><code>import pandas as pd import csv import time def procedure(): time.sleep(0) y=pd.DataFrame({'one':[1,2,3,4],'two':[3,5,7,5],'three':[2,3,4,9],'four':[4,3,1,0],}) y.to_csv('temp1.csv') start_time = time.time() procedure() finish_time = time.time() - start_time pri...
0
2016-06-10T04:34:23Z
[ "python", "csv", "time" ]
Faster alternative to Pandas apply, text data
37,738,166
<p>I have a Pandas dataframe , two columns "text" and "status":</p> <pre><code>text,status Great!!, pos I dunno., neut Bad.,neg </code></pre> <p>There are about 6000 rows.</p> <p>Text field consists of short sentences. I did a </p> <pre><code>dataset["text"] = dataset["text"].apply(strip_punctuation) </code></pre> ...
-1
2016-06-10T00:22:01Z
37,738,271
<p>dataframe.apply essentially does a sequential scan of the entire dataframe and applies your function to each row. that is super slow if your dataframe is big. </p> <p>using vectorized methods like follows can increase performance. But you get a tradeoff of more complexity/less functionality.</p> <pre><code>df['tex...
2
2016-06-10T00:35:53Z
[ "python", "string", "pandas" ]
Creating a full nltk parse tree from a list of nltk subtrees in python 3.5
37,738,333
<p>I have list of subtrees which I derived from a parse history formatted as follows:</p> <p>The parse history:</p> <pre><code>parse = [('S', 0), ('NP', 1), ('Det', 0), ('N', 0), ('VP', 1), ('V', 4), ('NP', 2), ('NP', 0), ('PN', 1), ('NP', 1), ('Det', 0), ('N', 3)] </code></pre> <p>Each tuple in the list has a key t...
0
2016-06-10T00:44:14Z
37,738,709
<p>You need to recursively build the tree, but you need to distinguish between terminals and non-terminals. Btw. your parse sequence seems wrong. I hacked this up:</p> <pre><code>def build_tree(parse): assert(parse) rule_head = parse[0][0] rule_body = grammar[rule_head][parse[0][1]] tree_body = [] rest = par...
0
2016-06-10T01:42:40Z
[ "python", "parsing", "tree", "nltk", "subtree" ]
Get the status of a python process that was executed in another terminal
37,738,375
<p>I have a python program that will create and execute another python script in a new terminal. To do so, I'm using subprocess.Popen. I'm trying to get the PID of the new process using .pid. However, the value of this pid doesn't seem to match the real pid of the newly created process (the two values don't match). </p...
1
2016-06-10T00:50:08Z
37,738,400
<p>According to the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">documentation</a>.</p> <p>If you set the shell argument to <code>True</code>, this is the process ID of the spawned shell.</p> <p>So you'll need <code>shell=False</code></p>
0
2016-06-10T00:53:16Z
[ "python", "linux", "terminal", "subprocess", "popen" ]
Get the status of a python process that was executed in another terminal
37,738,375
<p>I have a python program that will create and execute another python script in a new terminal. To do so, I'm using subprocess.Popen. I'm trying to get the PID of the new process using .pid. However, the value of this pid doesn't seem to match the real pid of the newly created process (the two values don't match). </p...
1
2016-06-10T00:50:08Z
37,752,675
<blockquote> <p>However, the value of this pid doesn't seem to match the real pid of the newly created process (the two values don't match).</p> </blockquote> <p>There are three processes here: <code>shell=True</code> causes <code>/bin/sh</code> to run that runs <code>gnome-terminal</code> that runs <code>python</co...
0
2016-06-10T16:05:54Z
[ "python", "linux", "terminal", "subprocess", "popen" ]
Numpy 3darray matrix multiplication function
37,738,401
<p>Suppose I have an ndarray, W of shape (m,n,n) and a vector C of dimension (m,n). I need to multiply these two in the following way</p> <pre><code>result = np.empty(m,n) for i in range(m): result[i] = W[i] @ C[i] </code></pre> <p>How do I do this in a vectorized way without loops and all?</p>
1
2016-06-10T00:53:24Z
37,738,651
<p><code>np.dot</code> should be your friend. <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.dot.html" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.dot.html</a></p>
0
2016-06-10T01:33:17Z
[ "python", "numpy", "matrix", "vectorization", "multiplication" ]
Numpy 3darray matrix multiplication function
37,738,401
<p>Suppose I have an ndarray, W of shape (m,n,n) and a vector C of dimension (m,n). I need to multiply these two in the following way</p> <pre><code>result = np.empty(m,n) for i in range(m): result[i] = W[i] @ C[i] </code></pre> <p>How do I do this in a vectorized way without loops and all?</p>
1
2016-06-10T00:53:24Z
37,739,314
<p>It's done using np.tensordot</p> <pre><code>ans=np.tensordot(W,C,axes=[2,1])[np.arange(m),:,np.arange(m)] assert np.all(result==ans) </code></pre>
0
2016-06-10T03:11:06Z
[ "python", "numpy", "matrix", "vectorization", "multiplication" ]
Numpy 3darray matrix multiplication function
37,738,401
<p>Suppose I have an ndarray, W of shape (m,n,n) and a vector C of dimension (m,n). I need to multiply these two in the following way</p> <pre><code>result = np.empty(m,n) for i in range(m): result[i] = W[i] @ C[i] </code></pre> <p>How do I do this in a vectorized way without loops and all?</p>
1
2016-06-10T00:53:24Z
37,740,184
<p>Since, you need to keep the first axis from both <code>W</code> and <code>C</code> aligned, while loosing the last axis from them with the matrix-multiplication, I would suggest using <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> for ...
1
2016-06-10T04:56:38Z
[ "python", "numpy", "matrix", "vectorization", "multiplication" ]
Editing an attribute of a reference file without affecting its other attributes
37,738,404
<p>I am trying to edit this particular Camera's node - Film Gate in my scene. However while doing so, I was given the following error <code>The attribute 'main_camera01:main_cameraShape.horizontalFilmAperture' is locked or connected and cannot be modified</code> and <code>The attribute 'main_camera01:main_cameraShape.v...
0
2016-06-10T00:53:37Z
37,891,556
<p>Yellow means you have connection that means setAttr with lock won't work there. You need to use disconnectAttr. cmds.setAttr('your_source_object.attribute', 'camera01:cameraShape.horizontalFilmAperture'). But in this case I seriously think that you have a reference. In that case story will be different.</p>
0
2016-06-17T23:08:57Z
[ "python", "maya" ]
numpy stack rows of ndarray
37,738,483
<p>I have a ndarray A of shape (u,v,w) like this:</p> <pre><code> [[[ 1., 1., 0.], [ 1., 3., 0.]], [[ 0., 0., 0.], [ 0., 0., 0.]]] </code></pre> <p>I need to stack the rows (along dimension 0) together like so.</p> <pre><code>[[1., 1., 0., 0., 0., 0.], [1., 3., 0., 0., 0., 0...
0
2016-06-10T01:05:18Z
37,738,618
<p>This shoul work fine:</p> <pre><code>np.hstack(a) </code></pre> <p>Btw <code>a[0], a[1], ...</code> are the rows and not columns of <code>a</code>.</p>
4
2016-06-10T01:27:06Z
[ "python", "numpy", "theano" ]
numpy stack rows of ndarray
37,738,483
<p>I have a ndarray A of shape (u,v,w) like this:</p> <pre><code> [[[ 1., 1., 0.], [ 1., 3., 0.]], [[ 0., 0., 0.], [ 0., 0., 0.]]] </code></pre> <p>I need to stack the rows (along dimension 0) together like so.</p> <pre><code>[[1., 1., 0., 0., 0., 0.], [1., 3., 0., 0., 0., 0...
0
2016-06-10T01:05:18Z
37,738,711
<p>All the <code>concatenate</code> family of functions iterate over the argument, whether it's a list, tuple or array</p> <pre><code>In [318]: x=np.arange(12).reshape(2,2,3) In [319]: x Out[319]: array([[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7, 8], [ 9, 10, 11]]]) </code></pre> <p>These all ...
4
2016-06-10T01:43:07Z
[ "python", "numpy", "theano" ]
Flask-admin - multiple formats of same column in ModelView
37,738,505
<p>I am trying to modify this Flask-admin example code <a href="http://examples.flask-admin.org/forms/admin/image/" rel="nofollow">http://examples.flask-admin.org/forms/admin/image/</a> to display both the thumbnail of the image and the raw text of the file path as two separate columns. This is basically the same probl...
0
2016-06-10T01:10:26Z
37,745,135
<p>You are close. Define a "dummy" column in the view's <code>column_list</code> property, give it a nice label via the <code>column_label</code> property and now you can use the "dummy" column in <code>column_formatters</code> property.</p> <p>For example:</p> <pre><code>class ImageView(sqla.ModelView): # Add a...
1
2016-06-10T09:49:39Z
[ "python", "flask", "flask-sqlalchemy", "flask-admin" ]
Python import old version package instead of new one
37,738,530
<p>I install the library 'numpy1.11.0', 'pandas0.18.1', 'scipy0.17.1' with pip into the site-packages. The problem is that when I import numpy and scipy in my project, an old version which has also been installed is imported instead of the new version:</p> <pre><code> import numpy as np import pandas as pd import scip...
1
2016-06-10T01:13:37Z
37,738,584
<p>Uninstall all the above packages... Use brew to install the pandas. It should install dependencies as well. </p>
1
2016-06-10T01:21:44Z
[ "python", "pip" ]
Python import old version package instead of new one
37,738,530
<p>I install the library 'numpy1.11.0', 'pandas0.18.1', 'scipy0.17.1' with pip into the site-packages. The problem is that when I import numpy and scipy in my project, an old version which has also been installed is imported instead of the new version:</p> <pre><code> import numpy as np import pandas as pd import scip...
1
2016-06-10T01:13:37Z
37,738,631
<p>You can use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a>, install the libraries you want in the version you want.</p>
4
2016-06-10T01:29:35Z
[ "python", "pip" ]
Why doesn't flask sql alchemy update an attribute for a record?
37,738,574
<p>I have a class shown below:</p> <pre><code>class Account(db.Model, flask_login.UserMixin): __tablename__ = 'account' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(75)) username = db.Column(db.String(50)) password = db.Column(db.String(250)) admin = db.Column(db.Boo...
1
2016-06-10T01:20:16Z
37,740,273
<p>The change to the object is not added to the session. So correct way would be</p> <pre><code>account = Account.query.get(1) account.admin = True db.session.add(account) db.session.commit() </code></pre>
-1
2016-06-10T05:05:02Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Why doesn't flask sql alchemy update an attribute for a record?
37,738,574
<p>I have a class shown below:</p> <pre><code>class Account(db.Model, flask_login.UserMixin): __tablename__ = 'account' id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(75)) username = db.Column(db.String(50)) password = db.Column(db.String(250)) admin = db.Column(db.Boo...
1
2016-06-10T01:20:16Z
37,976,885
<p>Just do this:</p> <pre><code>account = Account.query.get(1) account.admin = True db.session.merge(account) db.session.commit() </code></pre> <p>The changes are going to be detected and sent to the database.</p> <p>The instance you have and the object in the session not necessarily are the same - despite they repr...
0
2016-06-22T19:40:30Z
[ "python", "flask", "sqlalchemy", "flask-sqlalchemy" ]
Can't use select.poll in OS X and already have MacPort installed
37,738,725
<p>so the title pretty much says it all, I couldn't run a project which used elect.poll(), since this is for college, I must use select.poll() and cannot switch it for kqueue, so I read in <a href="http://stackoverflow.com/questions/19740471/cannot-use-python-select-poll-in-mac-os">this</a> post that I could use MacPor...
1
2016-06-10T01:45:40Z
37,815,825
<p>Do you have any file named "select.py", "select.pyc", "select.pyo"? If there are, and you try to "import select", Python would be trying to recursively import that file instead of the standard library. </p> <p>To solve this, you must rename your script to something else and to make sure you remove any automatically...
0
2016-06-14T15:08:30Z
[ "python", "osx", "macports", "polling" ]
Require packages in my script
37,738,731
<p>I have a python script that makes use of the requests library. I was wondering if there was a more elegant way to go about displaying packages required to run my script other than exception handling on the import statements. Any insight would be greatly appreciated. Thank you!</p>
2
2016-06-10T01:47:42Z
37,738,793
<p>The packages required to run any python script mention in top of the script by <code>import moduleName</code>.</p> <p>you can get a list of installed packages in your python by this:</p> <pre><code>import pip installed_packages = pip.get_installed_distributions() for pack in installed_packages: print pack </co...
2
2016-06-10T01:57:08Z
[ "python", "python-import", "python-module" ]
Require packages in my script
37,738,731
<p>I have a python script that makes use of the requests library. I was wondering if there was a more elegant way to go about displaying packages required to run my script other than exception handling on the import statements. Any insight would be greatly appreciated. Thank you!</p>
2
2016-06-10T01:47:42Z
37,738,847
<p>You have some alternatives:</p> <p>1) You can write a README with the instructions to run your script;</p> <p>2) You can develop a Makefile to automate the setup;</p> <p>3) You can write a requirements.txt with the dependencies and versions;</p> <p>4) You can write the setup.py file using <a href="https://setupt...
2
2016-06-10T02:04:25Z
[ "python", "python-import", "python-module" ]
Editing Date in Dataframe to show Year in pandas
37,738,739
<p>I've got 2 datapanels loaded as df's in pandas :</p> <p><strong>df1:</strong></p> <p><a href="http://i.stack.imgur.com/r5V4v.png" rel="nofollow"><img src="http://i.stack.imgur.com/r5V4v.png" alt="enter image description here"></a></p> <p><strong>df2:</strong></p> <p><a href="http://i.stack.imgur.com/s7ii8.png" r...
2
2016-06-10T01:49:08Z
37,738,857
<p><code>educ['Year'] = educ['Year'].year</code> should get you the year in the data frame, provided the frame contains a date, if not you can convert them using the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">to_datetime</a> function, as follows:</p> <pre><c...
0
2016-06-10T02:06:05Z
[ "python", "date", "pandas", "merge", "panel-data" ]
Editing Date in Dataframe to show Year in pandas
37,738,739
<p>I've got 2 datapanels loaded as df's in pandas :</p> <p><strong>df1:</strong></p> <p><a href="http://i.stack.imgur.com/r5V4v.png" rel="nofollow"><img src="http://i.stack.imgur.com/r5V4v.png" alt="enter image description here"></a></p> <p><strong>df2:</strong></p> <p><a href="http://i.stack.imgur.com/s7ii8.png" r...
2
2016-06-10T01:49:08Z
37,738,964
<p>It looks like you need to splice in the century explicitly (to avoid it being parsed as 20XX):</p> <pre><code>In [11]: df = pd.DataFrame([["12/31/50", "Argentina"], ["12/31/51", "Argentina"], ["12/31/52", "Argentina"]], columns=["Year", "Country"]) In [12]: df Out[12]: Year Country 0 12/31/50 Argentina...
0
2016-06-10T02:21:11Z
[ "python", "date", "pandas", "merge", "panel-data" ]
Editing Date in Dataframe to show Year in pandas
37,738,739
<p>I've got 2 datapanels loaded as df's in pandas :</p> <p><strong>df1:</strong></p> <p><a href="http://i.stack.imgur.com/r5V4v.png" rel="nofollow"><img src="http://i.stack.imgur.com/r5V4v.png" alt="enter image description here"></a></p> <p><strong>df2:</strong></p> <p><a href="http://i.stack.imgur.com/s7ii8.png" r...
2
2016-06-10T01:49:08Z
37,757,789
<p>Maybe this can achieve what you wish in least amount of code:</p> <pre><code>df['Year'] = pd.to_datetime(df['Year']).dt.year - 100 </code></pre> <p>however bear in mind that changing the date to just 'year' will also change the column dtype to int</p> <pre><code>&gt;&gt;&gt; df.dtypes Year int64 Country ...
0
2016-06-10T22:09:10Z
[ "python", "date", "pandas", "merge", "panel-data" ]
Scrapy throttling and request scheduling only microservices
37,738,759
<p>I'm currently using python requests to download around 20,000 pages of json. I'm running into some bottlenecking due to rate limiting by the server I'm scraping, and maybe a lack of asynchronous calls/scheduling. I thought scrapy would be a good solution because I heard it has features to combat these problems assoc...
-1
2016-06-10T01:52:04Z
37,739,156
<p>if want you need is something to help you on rate limiting, I would recommend using a proxy rotation service, Scrapy won't be necessary if you already have your crawler ready.</p> <p>I would recommend <a href="http://crawlera.com/" rel="nofollow">Crawlera</a> or <a href="http://proxymesh.com/" rel="nofollow">proxym...
-1
2016-06-10T02:46:11Z
[ "python", "scrapy", "python-requests", "microservices", "grequests" ]
How Do I Fix My Code So It Can print() Out The Results I Want?
37,738,877
<p><strong>Note: I'm not looking for you to remake my code, I'm looking for tips and links to sites that will help me improve this code. If you want to fix the code I will also accept your answer.</strong></p> <p>I'm trying to understand how <code>class</code> works but, I'm having a really hard time doing so. I made ...
-1
2016-06-10T02:08:08Z
37,739,052
<p>I'm a little hesitant to post this because the code is a giant mess. But you said you didn't want a re-write you just wanted to see your code fixed, so here it is fixed. I've commented everything I changed</p> <pre><code>#renamed stat to player, the point of the object shouldn't be to hold just the stats, should ho...
2
2016-06-10T02:31:01Z
[ "python", "class", "init", "python-3.5" ]
How Do I Fix My Code So It Can print() Out The Results I Want?
37,738,877
<p><strong>Note: I'm not looking for you to remake my code, I'm looking for tips and links to sites that will help me improve this code. If you want to fix the code I will also accept your answer.</strong></p> <p>I'm trying to understand how <code>class</code> works but, I'm having a really hard time doing so. I made ...
-1
2016-06-10T02:08:08Z
37,758,802
<p>I revamped my code here it is:</p> <p>Code provider: Bradley Elko</p> <p>Update 1 [51 lines]</p> <p>Update 2 [97 lines]</p> <p>Update 3 [127 lines]</p> <p>Update 4 [148 lines]</p> <hr> <pre><code>class Char(): def __init__(self): self.name = "" self.role = "" self.health = 0 ...
0
2016-06-11T00:27:13Z
[ "python", "class", "init", "python-3.5" ]
Python: limit on string length when using isalpha
37,738,904
<p>First off - I am completely new to python and to programming so bear with me.</p> <p>Trying to solve the popular python challenge #2, I created the below code to parse a long string of mostly gibberish and extract the letters from it. I no it's not elegant and there are much more streamlined and efficient ways of d...
2
2016-06-10T02:11:59Z
37,738,959
<pre><code>''.join(ch for ch in get_input if ch.isalpha()) </code></pre> <p>Your code then can be reduced to following:</p> <pre><code>get_input = raw_input("input: ") alpha = ''.join(ch for ch in get_input if ch.isalpha()) print alpha </code></pre>
0
2016-06-10T02:20:33Z
[ "python", "string" ]
TypeError: expected string or buffer with BeautifulSoup
37,738,949
<p>I want to remove a few tags from some HTML:</p> <p><code>&lt;p class="mt-20" itemprop="description"&gt;</code> and <code>&lt;/p&gt;</code>. Everything else, such as <code>&lt;br&gt;</code> should remain.</p> <p>Code:</p> <pre><code>from bs4 import BeautifulSoup import requests import re url = 'https://www.tokoped...
0
2016-06-10T02:19:06Z
37,739,047
<p><code>re.sub</code> needs a <code>string</code> variable, your <code>v</code> variable is a <code>bs4 element tag</code>. You can change the bs4 element to string:</p> <pre><code>newv = str(v) result = re.sub('&lt;p class="mt-20" itemprop="description"&gt;', "", newv) </code></pre>
1
2016-06-10T02:30:37Z
[ "python", "regex", "beautifulsoup" ]
TypeError: expected string or buffer with BeautifulSoup
37,738,949
<p>I want to remove a few tags from some HTML:</p> <p><code>&lt;p class="mt-20" itemprop="description"&gt;</code> and <code>&lt;/p&gt;</code>. Everything else, such as <code>&lt;br&gt;</code> should remain.</p> <p>Code:</p> <pre><code>from bs4 import BeautifulSoup import requests import re url = 'https://www.tokoped...
0
2016-06-10T02:19:06Z
37,739,160
<p>On the other hand, you don't actually need regular expressions. You can <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#unwrap" rel="nofollow">unwrap</a> (this is what I think you are trying to achieve) an element with <code>BeautifulSoup</code> itself:</p> <pre><code>for elm in soup3.find_all("p", ...
0
2016-06-10T02:47:12Z
[ "python", "regex", "beautifulsoup" ]
TypeError. I don't understand what the error is
37,738,993
<p>I made a program that I designed to be able to read or write a file given that files directory. I made the read function and when I tested it out I was given this error</p> <pre class="lang-none prettyprint-override"><code>TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found </cod...
-1
2016-06-10T02:24:42Z
37,739,054
<p>You should read about <a href="http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules">scopes</a>. The problem is that the function <code>read</code> does not know about the variable <code>dir</code>. Usually, this would lead to a <code>NameError</code>, but in this case, <code>dir</code...
1
2016-06-10T02:31:13Z
[ "python", "typeerror" ]
TypeError. I don't understand what the error is
37,738,993
<p>I made a program that I designed to be able to read or write a file given that files directory. I made the read function and when I tested it out I was given this error</p> <pre class="lang-none prettyprint-override"><code>TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found </cod...
-1
2016-06-10T02:24:42Z
37,739,058
<p>You've got a few problems in your code, but the <code>TypeError</code> is because <code>dir</code> isn't what you think it is. <a href="https://docs.python.org/2/library/functions.html#dir" rel="nofollow"><code>dir</code></a> is a python builtin function.</p> <p>Presumably, you think that because <code>dir</code> ...
0
2016-06-10T02:31:40Z
[ "python", "typeerror" ]
TypeError. I don't understand what the error is
37,738,993
<p>I made a program that I designed to be able to read or write a file given that files directory. I made the read function and when I tested it out I was given this error</p> <pre class="lang-none prettyprint-override"><code>TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found </cod...
-1
2016-06-10T02:24:42Z
37,739,071
<p>Globals as suggseted by swstephe are a generally bad idea and should be avoided as much as possible. Prefer using arguments: </p> <pre><code>def file(): dir = raw_input("DIR : ") return dir def read(dir): f = open(dir, "r") for line in f: print line.strip("\n") f.close def main(): d...
1
2016-06-10T02:33:30Z
[ "python", "typeerror" ]
Swapping variables in a class without using a temporary variable
37,739,008
<p>This is the code. It's a standard Binary Tree class. </p> <pre><code>class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree...
1
2016-06-10T02:26:24Z
37,739,406
<p>No unfortunately you need to be able to keep track of the newly created <code>BinaryTree</code> instance and the previous <code>self.leftChild</code> value at the same time as you have it written, using simultaneous assignments will not work in this scenario.</p> <p>However if you allowed the <code>leftChild</code>...
1
2016-06-10T03:23:42Z
[ "python", "python-2.7" ]
Swapping variables in a class without using a temporary variable
37,739,008
<p>This is the code. It's a standard Binary Tree class. </p> <pre><code>class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insertLeft(self,newNode): if self.leftChild == None: self.leftChild = BinaryTree...
1
2016-06-10T02:26:24Z
37,739,484
<p>In a <code>BinaryTree</code> you must create a temporary variable, because use Object. if are a integer could be:</p> <pre><code>a = 5 b = 3 a += b # a = 8 b = a - b # b = 5 a -= b # a = 3 print(a) &gt;&gt;3 print(b) &gt;&gt;5 </code></pre>
0
2016-06-10T03:38:42Z
[ "python", "python-2.7" ]
Removing the upper corner part of the image
37,739,073
<p>I am using OpenCV and Python.</p> <p>I want to remove the upper corner part of the image.</p> <p>For example I have a image originally like this: <a href="http://i.stack.imgur.com/ys7Wd.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/ys7Wd.jpg" alt="enter image description here"></a></p> <p>Afterwards, I w...
1
2016-06-10T02:33:54Z
37,742,471
<p>Pedantically speaking, you cannot <em>remove</em> any part of an image except a stripe on either side, reducing it's width or height. For what <em>looks like "removal of the corner part"</em> you can draw a background-colored triangle over that corner part. Here, assuming your desired background color is white:</p> ...
1
2016-06-10T07:34:04Z
[ "python", "image", "opencv", "image-processing" ]
how to parse data from websocket with python?
37,739,270
<p>I want some data that send by websocket. and I can use python something like urllib How can I do this? sorry about my poor english and thanks for read my question</p>
-2
2016-06-10T03:05:09Z
37,739,385
<p>If it is just about parsing the data, it depends upon the format of the data. If you are receiving JSON as a response, you can do json.loads() and treat the retrieved value as a python dictionary.</p> <p>If you are looking at some python libraries/examples of dealing with websockets, take a look at: <a href="https:...
0
2016-06-10T03:21:31Z
[ "python", "websocket" ]
Python unorderable types: NoneType() > int()
37,739,288
<pre><code>class Solution(): def isHappy(self,n): t = n z = n while t&gt;0: t = self.cal(t) if t == 1: return True z = self.cal(self.cal(z)) if z == 1: return True if t == z: re...
0
2016-06-10T03:07:50Z
37,739,312
<p>The problem is self-explanatory: the value of <code>n</code> passed to <code>cal()</code> becomes <code>None</code>, which can not be compared. Make sure to return an appropriate value at the end of the <code>cal()</code> method, that's where the <code>None</code> is coming from. Add something like this at the end o...
2
2016-06-10T03:10:54Z
[ "python" ]
Python unorderable types: NoneType() > int()
37,739,288
<pre><code>class Solution(): def isHappy(self,n): t = n z = n while t&gt;0: t = self.cal(t) if t == 1: return True z = self.cal(self.cal(z)) if z == 1: return True if t == z: re...
0
2016-06-10T03:07:50Z
37,739,332
<p>You're <code>cal</code> function should return something.</p> <pre><code>t = self.cal(t) </code></pre> <p>here you use the result of <code>cal</code>, but <code>cal</code> doesn't have a <code>return</code> statement, thus returning the default of <code>None</code>. Fix it by returning the correct value.</p>
3
2016-06-10T03:13:01Z
[ "python" ]
Selenium Hover/Click event on ajax filled menu options
37,739,404
<p>Having serious issues here. Someone please help.</p> <p>I am trying to login to a website. - This Works!</p> <p>Redirect to the page I want after Login - This Works!</p> <p>Now once in, I have to <strong>hover over</strong> the <strong>settings icon</strong> so the dropdown shows, and then click on the <strong>"S...
1
2016-06-10T03:23:20Z
37,740,850
<p>To perform <code>mouse over</code> event on element you should try to use <code>.execute_script()</code> using following <code>java script</code> :-</p> <pre><code>wait = WebDriverWait(driver, 10) box = wait.until(EC.visibility_of_element_located((By.ID, "yucs-help_button"))) menuButton = driver.find_element_by_i...
0
2016-06-10T05:56:53Z
[ "python", "selenium", "selenium-webdriver" ]
Pandas: How to extract rows which are just within a time duration?
37,739,405
<p>I have a data-frame like this.</p> <pre><code> value estimated \ dttm_timezone 2011-12-31 20:10:00 10.7891 0 2011-12-31 20:15:00 11.2060 0 2011-12-31 20:20:00 19.9975 0 2011-12-31 20:25:00 15...
1
2016-06-10T03:23:29Z
37,740,361
<p>Let's use </p> <pre><code>import pandas as pd import numpy as np tidx = pd.date_range('2010-01-01', '2014-12-31', freq='H', name='dtime') np.random.seed([3,1415]) df = pd.DataFrame(np.random.rand(len(tidx)), tidx, ['value']) </code></pre> <p>You can limit to <code>'2010'</code> like this:</p> <pre><code>df['201...
3
2016-06-10T05:13:23Z
[ "python", "datetime", "pandas", "time-series" ]
Best way to restrict database insert based on another column in Weppy/pyDal?
37,739,540
<p>I'd like to restrict DB inserts for a particular table if the same user already has an item with the same name. </p> <pre><code>Table _____________ user | place | label | -------------------------------------------------------------------------- me | san francisco | work | you | san ...
0
2016-06-10T03:45:35Z
37,744,827
<p>The <em>complicated</em> thing about uniqueness is that you can't be sure it will be respected using just the application code in a concurrent environment like web applications. </p> <p>For instance, if the same user will produce two concurrent requests – maybe in this case is quite <em>unlikely</em>, but you sho...
2
2016-06-10T09:35:05Z
[ "python", "pydal" ]
How can I increment an attribute's Value through my method? (python)
37,739,576
<p>I am trying to add my <code>update_number_served</code> method to my <code>increment_number_served</code> method in my code. I'm pretty confused with classes in general at this point but after much googling I can't seem to find the answer here as I am very new to python and stackoverflow:</p> <pre><code>class resta...
0
2016-06-10T03:50:11Z
37,739,644
<p>Actually, you should print <code>self.number_served</code> instead of the <code>number</code>, <code>number</code> is the number incremented, here <code>self.number_served += number</code> is equivalent to <code>self.number_served = self.number_served + number</code>. </p> <pre><code>def increment_number_served(sel...
2
2016-06-10T03:59:03Z
[ "python", "class", "methods" ]
Slicing Pandas DataFrame with a Checkerboard Pattern
37,739,621
<p>If I have an m x n dataframe, how can I select only the values that make up the dark squares on a checkerboard pattern (note that m may not equal n and either could be bigger, smaller, or equal to the other)? I've tried to mask it by constructing a boolean mask but it isn't elegant. Also note that the values may not...
1
2016-06-10T03:55:35Z
37,740,368
<p>You can use ogrid to <a href="http://stackoverflow.com/a/2171883/1240268">create a "checkerboard"</a>:</p> <pre><code>In [11]: coords = np.ogrid[0:2, 0:3] In [12]: checkerboard = (coords[0] + coords[1]) % 2 == 0 # use != for an inverted board In [13]: checkerboard Out...
1
2016-06-10T05:13:52Z
[ "python", "pandas" ]
How to debug a scrapy pipeline?
37,739,622
<p>I am following <a href="https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/" rel="nofollow">this tutorial</a> to learn how to use scrapy and mongodb together. However, I keep getting these error messages:</p> <pre><code>[Anaconda2] C:\Users\Segovia\Dropbox\stack&gt;scrapy crawl stack Traceback ...
1
2016-06-10T03:56:04Z
37,740,311
<p>Let's look at the error:</p> <blockquote> <p>AttributeError: 'list' object has no attribute 'iteritems'</p> </blockquote> <p>At this part of your project settings:</p> <blockquote> <p><code>ITEM_PIPELINES = ['stack.pipelines.MongoDBPipeline', ]</code></p> </blockquote> <p>And at this <a href="http://doc.scra...
3
2016-06-10T05:08:03Z
[ "python", "mongodb", "debugging", "scrapy", "pipeline" ]
Pythonic way to break out of loop
37,739,756
<p>Total python beginner here.</p> <p>I have the following function, which checks if a string derived from certain inputs exists in a text file. It loops through each line of the text file, to see if an exact match is found.</p> <p>I have to break out of looping, immediately after the match is found, to avoid needles...
2
2016-06-10T04:12:17Z
37,739,835
<p>Just <code>return</code> instead of <code>break</code>:</p> <pre><code>def DateZoneCity_downloaded_previously(Order_Date,ZoneCity): """Check if a given DataZoneCity combination had already been downloaded.""" string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1] with ...
4
2016-06-10T04:20:25Z
[ "python", "loops", "python-3.x" ]
Pythonic way to break out of loop
37,739,756
<p>Total python beginner here.</p> <p>I have the following function, which checks if a string derived from certain inputs exists in a text file. It loops through each line of the text file, to see if an exact match is found.</p> <p>I have to break out of looping, immediately after the match is found, to avoid needles...
2
2016-06-10T04:12:17Z
37,739,856
<p>Depending on how big your text file is, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):</p> <pre><code>if string_to_match in open(Record_File).read(): return True </code></pre> <p>In your example:</p> <pre><code>def DateZoneCity_downloaded_pr...
3
2016-06-10T04:22:24Z
[ "python", "loops", "python-3.x" ]
Pythonic way to break out of loop
37,739,756
<p>Total python beginner here.</p> <p>I have the following function, which checks if a string derived from certain inputs exists in a text file. It loops through each line of the text file, to see if an exact match is found.</p> <p>I have to break out of looping, immediately after the match is found, to avoid needles...
2
2016-06-10T04:12:17Z
37,739,870
<p>You don't have to put a for loop here, See the updated code.</p> <pre><code>def DateZoneCity_downloaded_previously(Order_Date,ZoneCity): """Check if a given DataZoneCity combination had already been downloaded.""" string_to_match = Order_Date.strftime('%Y/%m/%d') + "-" + ZoneCity[0] + "-" + ZoneCity[1] ...
2
2016-06-10T04:23:27Z
[ "python", "loops", "python-3.x" ]
Pythonic way to break out of loop
37,739,756
<p>Total python beginner here.</p> <p>I have the following function, which checks if a string derived from certain inputs exists in a text file. It loops through each line of the text file, to see if an exact match is found.</p> <p>I have to break out of looping, immediately after the match is found, to avoid needles...
2
2016-06-10T04:12:17Z
37,739,926
<p>This feels like a situation where <code>any</code> would be the best solution:</p> <pre><code># Function to check if a given DateZoneCity def DateZoneCity_downloaded_previously(Order_Date, ZoneCity): # Combination had already been completely downloaded string_to_match = Order_Date.strftime('%Y/%m/%d') + "-"...
5
2016-06-10T04:28:33Z
[ "python", "loops", "python-3.x" ]
difference between python2 and python3 - int() and input()
37,739,765
<p>I wrote below python code. And I found that python2 and python3 has totally difference running result for input of 1.1. Why is there such difference between python2 and python3? For me, int(1.1) should be 1, then position is valid index 1 within range 0,1,2. So can you please explain why python3 has such result?</...
5
2016-06-10T04:13:17Z
37,739,823
<p>The issue is <code>intput()</code> converts the value to an number for python2 and a string for python 3.</p> <p><code>int()</code> of a non int string returns an error, while int() of a float does not.</p> <p>Convert the input value to a float using either:</p> <pre><code>value=float(input()) </code></pre> <p>o...
4
2016-06-10T04:18:57Z
[ "python", "python-3.4" ]
difference between python2 and python3 - int() and input()
37,739,765
<p>I wrote below python code. And I found that python2 and python3 has totally difference running result for input of 1.1. Why is there such difference between python2 and python3? For me, int(1.1) should be 1, then position is valid index 1 within range 0,1,2. So can you please explain why python3 has such result?</...
5
2016-06-10T04:13:17Z
37,740,502
<p>Please check the Python 3 release notes. In particular, the <code>input()</code> function (which is considered dangerous) was removed. In its stead, the safer <code>raw_input()</code> function was renamed to <code>input()</code>.</p> <p>In order to write code for both versions, only rely on <code>raw_input()</code>...
1
2016-06-10T05:26:55Z
[ "python", "python-3.4" ]