title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Python - Run function with parameters in command line
38,328,340
<p>Is it possible to run a python script with parameters in command line like this:</p> <pre><code>./hello(var=True) </code></pre> <p>or is it mandatory to do like this:</p> <pre><code>python -c "from hello import *;hello(var=True)" </code></pre> <p>The first way is shorter and simpler.</p>
0
2016-07-12T12:01:11Z
38,329,543
<p><code>./hello(var=True)</code> would be impossible from <a href="https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop" rel="nofollow">REPL</a> shell. In some case it could be useful to have python function available in your current shell session. Here a workaround to make your python functions availabl...
0
2016-07-12T12:55:59Z
[ "python", "command-line" ]
pandas dataframe: groupby by several columns, apply function and map back the result
38,328,397
<p>Here there is an example:</p> <pre class="lang-py prettyprint-override"><code>np.random.seed(1) df = pd.DataFrame({"x": np.random.random(size=10), "y": np.arange(10)}) df["z"] = np.where(df.x &lt; 0.5, 0, 1) print df </code></pre> <p>It gives the following result:</p> <pre><code> x y ...
0
2016-07-12T12:03:42Z
38,328,473
<p>use <code>transform</code> to add the result of your <code>groupby</code> operation back as a column, <code>transform</code> returns a <code>Series</code> with it's index aligned to the original df:</p> <pre><code>In [15]: df['mean'] = df.groupby(["y", "z"]).transform('mean') df Out[15]: x y z mea...
0
2016-07-12T12:07:16Z
[ "python", "pandas" ]
Obtain the value of a dictionary after select on of the combobox value
38,328,411
<p>I have created a dictionary for my combobox's value. I am trying to use <code>.get(keys)</code> to obtain the value that I set for the combobox. For example if I select A, it should print out <code>Haha What</code>, B should print out <code>Lala Sorry</code>, both of them are the values in my dictionary so how can I...
1
2016-07-12T12:04:18Z
38,329,640
<p>To display only the keys (<code>A</code>, <code>B</code> and <code>C</code>) in the Combobox widget, you need change <code>self.box_values=mydict.keys(</code>) to <code>self.box_values=list(self.mydict.keys())</code> and this line:</p> <pre><code>self.box = ttk.Combobox(self.parent, textvariable=self.box_value,valu...
3
2016-07-12T12:59:33Z
[ "python", "dictionary", "combobox", "tkinter", "interface" ]
Python: installation error
38,328,670
<p>I'm trying to install <code>Python 3.5.2</code> on my <code>Windows Vista Home Premium x32</code>. While installing it Windows pops up a window saying <code>"Python stops working"</code>. The installation continues, ends and it says it was successfull. Of course it wasn't because when I want to run python an error o...
-4
2016-07-12T12:16:23Z
38,329,765
<p>The <code>python 3.5.2</code> can't install because <code>api-ms-win-crt-runtime-|1-1-0.dll</code> is missing from your computer.You have to install <code>Windows Updates: Go to Start - Control Panel - Windows Update</code> Check for updates Install all available updates. After the updates are installed, restart you...
1
2016-07-12T13:05:03Z
[ "python", "python-3.x" ]
cant close last opened file
38,328,782
<p>Hello if i have following code:</p> <pre><code>n = len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))]) for i in range(0, n): dat_file = r'C1/C10000' + str(i).zfill(2) + '.dat' csv_file = r'C1_conv/C10000' + str(i).zfill(2) + '.csv' in_dat = csv.reader(open(dat_file, 'rb'),...
0
2016-07-12T12:21:56Z
38,329,172
<p>You need to track opened file in a separate variable, and close it after finishing write operation. A better convention is to use <code>with open(fname)</code> syntax, which close file for you.</p> <p>You may consult following code snippet to understand things in better way:</p> <pre><code>with open(infile, 'w') a...
2
2016-07-12T12:39:29Z
[ "python", "csv", "parsing" ]
Python Tkinter Run Checkbuttons
38,328,844
<p>I want to write a python script, where I have some Checkbuttons and a Button for Running my active checkbuttons. If a checkbutton is active and i click on "Run" the def run_app should check which checkbuttons are active. But if I run my code, the terminal says, that the global name "is_checked" is not defined.</p> ...
-1
2016-07-12T12:25:12Z
38,329,049
<p><code>is_checked</code> created locally which means there is no <code>is_checked</code> variable outside of your <code>__init__</code>. </p> <p>If you want to use that variable outside of where it is created, you need to either make it <code>global</code> or bind to a class. Since you already have class structure,...
1
2016-07-12T12:34:45Z
[ "python", "tkinter" ]
Why does '() is ()' return True when '[] is []' and '{} is {}' return False?
38,328,857
<p>From what I've been aware of, using <code>[], {}, ()</code> to instantiate objects returns a new instance of <code>list, dict, tuple</code> respectively; a new instance object with <strong><em>a new identity</em></strong><sup>*</sup>. </p> <p>This was pretty clear to me until I actually tested it where I noticed th...
44
2016-07-12T12:25:48Z
38,328,858
<h3>In short:</h3> <p>Python internally creates a <code>C</code> list of tuple objects whose first element contains the empty tuple. Every time <code>tuple()</code> or <code>()</code> is used, Python will return the existing object contained in the aforementioned <code>C</code> list and not create a new one.</p> <p>S...
48
2016-07-12T12:25:48Z
[ "python", "python-3.x", "tuples", "identity", "python-internals" ]
Newlines removed in POST request body? (Google App Engine)
38,328,864
<p>I am building a REST API on Google App Engine (not using Endpoints) that will allow users to upload a CSV or tab-delimited file and search for potential duplicates. Since it's an API, I cannot use <code>&lt;form&gt;</code>s or the BlobStore's <code>upload_url</code>. I also cannot rely on having a single web client ...
0
2016-07-12T12:26:00Z
38,330,965
<p>You are using the wrong <code>curl</code> command-line option to send your file data, and it is <em>this option</em> that is stripping the newlines.</p> <p>The <code>-d</code> option <em>parses out your data</em> and sends a <code>application/x-www-form-urlencoded</code> request, and it <strong>strips newlines</str...
1
2016-07-12T13:55:47Z
[ "python", "google-app-engine", "post", "newline" ]
How to write a list of values to text file with strings and numbers
38,328,870
<p>I have a 3 lists : </p> <pre><code>AList = ['name','name2'] BList = ['desg1','desg2'] InList = [1,2] </code></pre> <p>I am writing it to a text file using the follo code snippet:</p> <pre><code>fo = open(filepath, "w") for i in zip(AList,BList,InList): lines=fo.writelines(','.join(i) + '\n') </code></pre> <...
1
2016-07-12T12:26:16Z
38,329,109
<p><code>join</code> expects a sequence of <code>str</code> items as first argument, but your <code>InList</code> contains <code>int</code> values. Just convert them to a <code>str</code>:</p> <pre><code>lines=fo.writelines(','.join(map(str, i)) + '\n') </code></pre> <p>I'd suggest you to use <code>with</code> block ...
1
2016-07-12T12:37:01Z
[ "python", "python-3.x" ]
How to write a list of values to text file with strings and numbers
38,328,870
<p>I have a 3 lists : </p> <pre><code>AList = ['name','name2'] BList = ['desg1','desg2'] InList = [1,2] </code></pre> <p>I am writing it to a text file using the follo code snippet:</p> <pre><code>fo = open(filepath, "w") for i in zip(AList,BList,InList): lines=fo.writelines(','.join(i) + '\n') </code></pre> <...
1
2016-07-12T12:26:16Z
38,329,263
<p><code>join</code> expects string items but you've int in the InList. So either convert them to string before using join or you can do it like this :</p> <pre><code>AList = ['name','name2'] BList = ['desg1','desg2'] InList = ['1','2'] fo = open("a.txt", "w") for i in range(len(AList)): dataToWrite = ",".join((A...
1
2016-07-12T12:43:50Z
[ "python", "python-3.x" ]
fail to login to website with request
38,328,934
<p>At first here is my code:</p> <pre><code>import requests payload = {'name':'loginname', 'password': 'loginpassword'} requests.post('http://myurl/auth',data=payload,verify=False) rl = requests.get('http://myurl/dashboard',verify=False) print(rl.text) </code></pre> <p>My problem:</p> <p>I get the status ...
1
2016-07-12T12:29:12Z
38,329,443
<p>You need to use a <a href="http://docs.python-requests.org/en/master/user/advanced/#session-objects" rel="nofollow"><code>Session</code></a> object to have <code>requests</code> maintain track of your cookies, such as the login cookie which would get set after your <code>requests.post</code> login action. Quoting th...
1
2016-07-12T12:51:27Z
[ "python", "python-3.x", "python-requests" ]
Need to install pip for python 3
38,328,976
<p>I have installed python 2.7 and python 3.3 on server and now my need is to install pip for python 3.</p> <p>Here what I have tried so far.</p> <pre><code>sudo apt-get install python3-setuptools sudo easy_install3 pip </code></pre> <p>This will install pip for python 3.2 ( I don't have installed python 3.2),</p> ...
0
2016-07-12T12:31:09Z
38,329,132
<p>After:</p> <pre><code>sudo apt install python3-pip </code></pre> <p>you should be able to install packages with pip3 command. Try:</p> <pre><code>pip --version pip3 --version </code></pre>
1
2016-07-12T12:37:49Z
[ "python", "ubuntu", "python-3.3" ]
Import Error: No module named numpy Anaconda
38,328,987
<p>I have a very similar question to this question. I have only one version of python 3.5 installed on my Windows 7 64-bit system. I installed Anaconda3.4 via official website - as suggested in the question. The installation went fine but when I want to import(I just typing python from the command line )</p> <pre><cod...
0
2016-07-12T12:31:54Z
38,329,105
<p>You need to install <code>numpy</code> using <code>pip3</code></p> <p>install <code>pip3</code> :</p> <pre><code>sudo apt-get install python-pip python3-pip </code></pre> <p>Then install <code>numpy</code> using <code>pip3</code></p> <pre><code>sudo pip3 install -U numpy </code></pre>
3
2016-07-12T12:36:52Z
[ "python", "numpy", "anaconda", "conda" ]
Import Error: No module named numpy Anaconda
38,328,987
<p>I have a very similar question to this question. I have only one version of python 3.5 installed on my Windows 7 64-bit system. I installed Anaconda3.4 via official website - as suggested in the question. The installation went fine but when I want to import(I just typing python from the command line )</p> <pre><cod...
0
2016-07-12T12:31:54Z
38,330,088
<p>If you are using Anaconda3 then you should already have numpy installed. There is no reason to use <code>pip</code>. My guess is that the Anaconda distribution is possibly not on your path and you are picking up some other system python.</p> <p>You should run <code>where python</code> (or <code>where python3</code>...
0
2016-07-12T13:19:13Z
[ "python", "numpy", "anaconda", "conda" ]
Tying values to keys in a dictionary and then printing
38,329,014
<p>This is a smaller portion of the main code I have been writing. Depending on user selection they can add player informationa and then print the information from the dictionary player roster. I want to store the information and then print in this format but I havent been able to figure out how to do this. ...
0
2016-07-12T12:33:26Z
38,329,467
<p>You're pretty much there. The below modification would allow you to print as you need (and is slightly more readable):</p> <pre><code>class PlayerDictionary(): def __init__(self): pass player_roster = {} def display_roster(self): #Print Roster if len(self.player_r...
0
2016-07-12T12:52:11Z
[ "python", "dictionary", "printing", "storing-data" ]
Tying values to keys in a dictionary and then printing
38,329,014
<p>This is a smaller portion of the main code I have been writing. Depending on user selection they can add player informationa and then print the information from the dictionary player roster. I want to store the information and then print in this format but I havent been able to figure out how to do this. ...
0
2016-07-12T12:33:26Z
38,329,525
<p>I would propose that you replace the print statement to this:</p> <pre><code>print(" Name: %s \n Phone Number: %s \n Jersey Number: %d") % player_roster[x] </code></pre>
0
2016-07-12T12:55:12Z
[ "python", "dictionary", "printing", "storing-data" ]
Tying values to keys in a dictionary and then printing
38,329,014
<p>This is a smaller portion of the main code I have been writing. Depending on user selection they can add player informationa and then print the information from the dictionary player roster. I want to store the information and then print in this format but I havent been able to figure out how to do this. ...
0
2016-07-12T12:33:26Z
38,329,708
<p>There are some things i would change in your code but to keep this close to what you asked for take a look at this:</p> <pre><code>def display_roster(): if len(player_roster) != 0: for x in player_roster.keys(): print('Name:', x) print('Phone Number:', player_roster[x][0]) ...
1
2016-07-12T13:02:43Z
[ "python", "dictionary", "printing", "storing-data" ]
I need to calculate the range of the max overlapping occurances not the max number of them
38,329,152
<p>Assume that I have a dataset with numbers (start, stop):</p> <pre><code>4556745 , 4556749 4556749 , 5078554 </code></pre> <p>… and so on</p> <p>I want to make a chunk of code in order to print the range (start, stop) in which the max overlapping is occurred. Till now I have managed to calculate the max numb...
0
2016-07-12T12:38:32Z
38,330,991
<p>The maximum overlapping range is maybe (quase surely) not a whole tuple (start, stop) of input data. </p> <p>So I'd transform you all your tuple (start, stop) in range containing all the range between start and stop:</p> <pre><code>(4556745, 4556749) → range(4556745, 4556749) </code></pre> <p>and then I'll pro...
0
2016-07-12T13:57:02Z
[ "python", "pseudocode" ]
How to change the convert command to python code
38,329,195
<p>I'm using Imagemagick for image enhancement in my project. As I'm a newbie to Imagemagick, I have started it with using command line argument for this package. For further processing, I need to change the below command into python code.</p> <pre><code>convert sample.jpg -blur 2x1 -sharpen 0x3 -sharpen 0x3 -quality ...
0
2016-07-12T12:40:26Z
38,329,265
<p>You can use <a href="https://docs.python.org/3/library/os.html" rel="nofollow"><code>os.system()</code></a> to run terminal commands from Python.</p> <pre><code>import os command = 'convert sample.jpg -blur 2x1 -sharpen 0x3 -sharpen 0x3 -quality 100 -morphology erode diamond -auto-orient -enhance -contrast -contra...
2
2016-07-12T12:43:58Z
[ "python", "python-2.7", "imagemagick-convert", "wand" ]
How to change the convert command to python code
38,329,195
<p>I'm using Imagemagick for image enhancement in my project. As I'm a newbie to Imagemagick, I have started it with using command line argument for this package. For further processing, I need to change the below command into python code.</p> <pre><code>convert sample.jpg -blur 2x1 -sharpen 0x3 -sharpen 0x3 -quality ...
0
2016-07-12T12:40:26Z
39,771,854
<p>Another option is <strong>Wand, an ImageMagick binding for python</strong> to convert the command mentioned above. Please refer the below link for more details:</p> <p><a href="http://docs.wand-py.org/en/0.4.3/" rel="nofollow">wand docs</a></p>
0
2016-09-29T13:36:01Z
[ "python", "python-2.7", "imagemagick-convert", "wand" ]
Flask SQLalchemy order_by value joined from two Tables
38,329,289
<p>Currently I cant figure out how to perform a proper join in SQLalchemy, I have two tables <code>User</code> and <code>Room</code>each room is submited by a user and that is why each room has a <code>users_id</code> as <code>foreign key</code>.</p> <p>User has an attribute <code>has_payed</code>.</p> <p>What I want...
0
2016-07-12T12:44:57Z
38,329,514
<p>It seems that this solved the issue, but I dont know how it knows that it has to join on <code>Room.users_id == User.id</code></p> <pre><code>Room.query.join(User).order_by(desc(User.has_payed)) </code></pre>
0
2016-07-12T12:54:44Z
[ "python", "python-2.7", "flask", "sqlalchemy" ]
Changing the format of a column of Data frame from Str to Date in specific format
38,329,428
<p>I have two data frames which I have to merge on Date. but the type of data isn't same. They are Date and of str format.</p> <pre><code>print(visit_data.iloc[0]['visit_date']) 2016-05-22 type(visit_data.iloc[0]['visit_date']) Out[40]: datetime.date print(holiday_data.iloc[0]['visit_date']) 1/1/2016 type(holiday_d...
0
2016-07-12T12:50:29Z
38,330,165
<p>If you want it to return as a <code>datetime</code> object, you could do this:</p> <pre><code>import datetime holiday_data['visit_date'] = holiday_data['visit_date'].apply(lambda x: datetime.datetime.strptime(x,'%m/%d/%Y')) </code></pre> <p><strong>EDIT :</strong></p> <p>To ...
1
2016-07-12T13:22:37Z
[ "python", "python-2.7", "pandas", "merge" ]
python script to carve up csv data
38,329,480
<p>I have some csv data that looks like this: </p> <pre><code>724 "Overall evaluation: 2 Invite to interview: 2 Strength or novelty of the idea (1): 3 Strength or novelty of the idea (2): 3 Strength or novelty of the idea (3): 2 Use or provision of open data (1): 3 Use or provision of open data (2): 3 ""Open by defaul...
1
2016-07-12T12:52:45Z
38,329,612
<p>That should do the work:</p> <pre><code>lines=open("1.txt",'r').read().splitlines() for l in lines: data = l.split(' "Overall evaluation: ') if len(data) == 2: print(data[0] + ", " + data[1]) </code></pre> <p>The split function use the string <code>"Overall evaluation:</code> as a seperator</p>
4
2016-07-12T12:58:26Z
[ "python", "regex", "csv" ]
Error creating pytheapp for Ethereum on OSX
38,329,565
<p>I am trying to install pyethapp on OSX but get an error right at the end ""python setup.py egg_info"". Any suggestions?</p> <pre><code> c233:json-server-api justinstaines$ pip install pyethapp Collecting pyethapp Downloading pyethapp-1.3.0-py2.py3-none-any.whl (334kB) 100% |███████████â...
0
2016-07-12T12:57:02Z
38,329,566
<p>Doh just realised </p> <p>Your setuptools version (1.1.6) is too old to correctly install this package. Please upgrade to a newer version (>= 3.3).</p>
1
2016-07-12T12:57:02Z
[ "python", "json-rpc", "ethereum" ]
adding simple mathematical operation to python script
38,329,752
<p>I have a program that operates on a csv file to create output that looks like this:</p> <pre><code>724, 2 724, 1 725, 3 725, 3 726, 1 726, 0 </code></pre> <p>I would like to modify the script with some simple math operations such that it would render the output: </p> <pre><code>724, 1.5 725, 3 726, 0.5 </code></p...
-2
2016-07-12T13:04:24Z
38,330,021
<p>You can use a dictionary that map the key to the total and count and then print it:</p> <pre><code>map = {} lines=open("1.txt",'r').read().splitlines() for l in lines: data = l.split('"Overall evaluation:') if len(data) == 2: if data[0] not in map.keys(): map[data[0]] = (0,0) map...
1
2016-07-12T13:16:46Z
[ "python" ]
adding simple mathematical operation to python script
38,329,752
<p>I have a program that operates on a csv file to create output that looks like this:</p> <pre><code>724, 2 724, 1 725, 3 725, 3 726, 1 726, 0 </code></pre> <p>I would like to modify the script with some simple math operations such that it would render the output: </p> <pre><code>724, 1.5 725, 3 726, 0.5 </code></p...
-2
2016-07-12T13:04:24Z
38,330,029
<p>I would just store an list of values with the key. Then take the average when file is read.</p> <pre><code>lines=open("1.txt",'r').read().splitlines() results = {} for l in lines: data = l.split('"Overall evaluation:') if len(data) == 2: if data[0] in results: results[data[0]].append(da...
1
2016-07-12T13:17:10Z
[ "python" ]
adding simple mathematical operation to python script
38,329,752
<p>I have a program that operates on a csv file to create output that looks like this:</p> <pre><code>724, 2 724, 1 725, 3 725, 3 726, 1 726, 0 </code></pre> <p>I would like to modify the script with some simple math operations such that it would render the output: </p> <pre><code>724, 1.5 725, 3 726, 0.5 </code></p...
-2
2016-07-12T13:04:24Z
38,330,189
<p>(Edited to avoid storing of values)</p> <p>I love <code>defaultdict</code>:</p> <pre><code>from collections import defaultdict average = defaultdict(lambda: (0,0)) with open("1.txt") as input: for line in input.readlines(): data = line.split('"Overall evaluation:') if len(data) != 2: ...
1
2016-07-12T13:23:48Z
[ "python" ]
adding simple mathematical operation to python script
38,329,752
<p>I have a program that operates on a csv file to create output that looks like this:</p> <pre><code>724, 2 724, 1 725, 3 725, 3 726, 1 726, 0 </code></pre> <p>I would like to modify the script with some simple math operations such that it would render the output: </p> <pre><code>724, 1.5 725, 3 726, 0.5 </code></p...
-2
2016-07-12T13:04:24Z
38,330,556
<p>A simple way is to keep a state storing current number, current sum and number of items, and only print it when current number changes (do not forget to print last state!). Code could be:</p> <pre><code>lines=open("1.txt",'r') # .read().splitlines() is useless and only force a full load in memory state = [None] fo...
1
2016-07-12T13:39:09Z
[ "python" ]
Do we have to open excel file EVERYTIME we write in it with Python?
38,329,760
<p>I have to write on an Excel file using Python. I use win32com to do it.</p> <p>I want to open it first do some stuff then write in my file do more stuff and write again in the file.</p> <p>but I if I don't open the file everytime before writing, i have this error message:</p> <p>pywintypes.com_error: (-2146827864...
1
2016-07-12T13:04:49Z
38,329,836
<p>Because you are opening the file every iteration of the loop.</p> <p>You should move the lines </p> <pre><code>excel = win32.gencache.EnsureDispatch('Excel.Application') wb = excel.Workbooks.Open('//Srvaktct-bur02/Copie de vide.xlsx') ws = wb.Worksheets(date_onglet) </code></pre> <p>to before the loop, so you don...
2
2016-07-12T13:08:14Z
[ "python", "excel", "pyodbc", "pywin32" ]
Do we have to open excel file EVERYTIME we write in it with Python?
38,329,760
<p>I have to write on an Excel file using Python. I use win32com to do it.</p> <p>I want to open it first do some stuff then write in my file do more stuff and write again in the file.</p> <p>but I if I don't open the file everytime before writing, i have this error message:</p> <p>pywintypes.com_error: (-2146827864...
1
2016-07-12T13:04:49Z
38,330,143
<blockquote> <p>if I don't open the file everytime before writing, i have this error message:</p> </blockquote> <p>Well yeah, because if you don't have a file object to write <em>to</em>, what else would you expect to happen? </p> <p>You're doing a <code>wb.Close()</code> call within the loop, so, because you close...
1
2016-07-12T13:21:54Z
[ "python", "excel", "pyodbc", "pywin32" ]
Round columns based on second level of MultiColumn
38,329,777
<p>I have a table which looks like this:</p> <pre><code>&gt;&gt;&gt; df.head() Out[13]: v u init change integral init change foo bar ba...
2
2016-07-12T13:05:51Z
38,332,032
<p>consider the dataframe:</p> <pre><code>df = pd.DataFrame(np.arange(8).reshape(2, 4), ['a', 'b'], pd.MultiIndex.from_product([['A', 'B'], ['One', 'Two']])) df </code></pre> <p><a href="http://i.stack.imgur.com/8E6I9.png" rel="nofollow"><img src="http://i.stack.imgur.com/8E6I9.pn...
3
2016-07-12T14:41:53Z
[ "python", "pandas", "multi-index" ]
pdfkit not converting image to pdf
38,329,909
<p>I am using PDFkit with python to convert an html page to pdf. In the html there is only one image tag in body with src pointing to a complete url like:</p> <pre><code>&lt;html&gt; &lt;body style="margin: 0px;"&gt; &lt;img style="-webkit-user-select: none; cursor: -webkit-zoom-in;" src="https://blah.blah...
0
2016-07-12T13:11:04Z
38,942,848
<p>I use the file path instead of the file url in image src, like:</p> <pre><code>&lt;img src="D:/image/path/pircure.png"&gt; </code></pre> <p>and it work, maybe you can try it.</p>
0
2016-08-14T13:46:11Z
[ "python", "pdfkit" ]
instagram api keep raise 'You must provide a client_id' exception when I use python-instagram library
38,329,960
<p>I registered my app in instagram developer dashboard and tried to use python-instagram library made by Facebook.</p> <p>After I ran sample_app.py code, I accessed my test website(localhost:8515) and successfully logged in using my instagram id. However, I can't get access code because of this exception "You must pr...
1
2016-07-12T13:13:21Z
38,342,567
<p>Had the same problem, obviously due instagram api or httplib2 update. Fixed for me <a href="https://github.com/vgavro/python-instagram/commit/9dfc264571ad7c343af3899445d13afedf23e3aa" rel="nofollow">https://github.com/vgavro/python-instagram/commit/9dfc264571ad7c343af3899445d13afedf23e3aa</a> (link to my fork of pyt...
4
2016-07-13T04:12:16Z
[ "python", "oauth-2.0", "instagram-api" ]
instagram api keep raise 'You must provide a client_id' exception when I use python-instagram library
38,329,960
<p>I registered my app in instagram developer dashboard and tried to use python-instagram library made by Facebook.</p> <p>After I ran sample_app.py code, I accessed my test website(localhost:8515) and successfully logged in using my instagram id. However, I can't get access code because of this exception "You must pr...
1
2016-07-12T13:13:21Z
38,377,928
<p>I've resorted to doing it myself; couldn't get python-instagram to work. Will probably ditch the entire library. Way too many bugs lately, and it's not being maintained, I think.</p> <pre><code>@classmethod def exchange_code_for_access_token(cls, code, redirect_uri, **kwargs): url = u'https://api.instagram.com/...
4
2016-07-14T15:11:56Z
[ "python", "oauth-2.0", "instagram-api" ]
Qt5 / PyQt5 : Custom QML components with QML frontend and Python backend
38,329,988
<p>I want to create a QML Module with a python "backend" if that makes sense. Basically, I want to use QML do define how the component looks, and then implement specific behavior in a python class, which should extend this QML-Type and - in my imagination - somehow must be linkable to the QML component.</p> <p>I under...
1
2016-07-12T13:15:18Z
38,363,722
<p>If you inherit from the <code>QQuickItem</code> and register it - it will obviously act like <code>Item {}</code>.</p> <p>If you add some properties on the C++/python side - it'll be an <code>Item</code> with properties.</p> <p><code>ColorWheelImpl.h</code> (make a python equivalent):</p> <pre><code>class ColorWh...
0
2016-07-14T00:26:58Z
[ "python", "qt", "qml", "qt5", "pyqt5" ]
Permissions to Django admin actions
38,329,999
<p>I have written some custom actions for my django project, however cannot work out how to make them available to only superusers. I have tried putting an if statement round the actions line with Users.is_superuser but it keeps giving me an error saying there is no attribute called is_superuser.</p> <p>Here is my adm...
1
2016-07-12T13:15:59Z
38,330,258
<p>You can override your ModelAdmin's <code>get_actions</code> method like this:</p> <pre><code>def get_actions(self, request): actions = super(MyModelAdmin, self).get_actions(request) if request.user.is_superuser: actions.update(dict(youraction=youraction)) return actions </code></pre> <p>Her...
0
2016-07-12T13:26:56Z
[ "python", "django" ]
Permissions to Django admin actions
38,329,999
<p>I have written some custom actions for my django project, however cannot work out how to make them available to only superusers. I have tried putting an if statement round the actions line with Users.is_superuser but it keeps giving me an error saying there is no attribute called is_superuser.</p> <p>Here is my adm...
1
2016-07-12T13:15:59Z
38,330,275
<p>Try this: </p> <pre><code>class ArtAdmin(ImportExportModelAdmin): list_display = ['id', 'identification', 'name', 'artist', 'category', 'type', 'agent', 'authenticate', ] search_fields = ('name', 'category', 'artist', 'id', 'authenticate', ) list_filter = ["authenticate"] actions ...
0
2016-07-12T13:27:35Z
[ "python", "django" ]
Permissions to Django admin actions
38,329,999
<p>I have written some custom actions for my django project, however cannot work out how to make them available to only superusers. I have tried putting an if statement round the actions line with Users.is_superuser but it keeps giving me an error saying there is no attribute called is_superuser.</p> <p>Here is my adm...
1
2016-07-12T13:15:59Z
38,333,289
<p>Considering that an action is not <code>ModelAdmin</code>-dependant, the best way to prevent it from being run by an non-authorized user remains to check it inside the action:</p> <pre><code>from django.core.exceptions import PermissionDenied def approve_art(modeladmin, request, queryset): if not request.user....
0
2016-07-12T15:35:17Z
[ "python", "django" ]
Can I create a class which can be unpacked?
38,330,001
<p>For example:</p> <pre><code>x = (1, 2) a,b = x </code></pre> <p>Now I'd like to accomplish this in the case of <code>x</code> being an instance of some class that isn't a list or tuple. Simply overriding <code>__getitem__</code> or <code>__getslice__</code> doesn't work:</p> <pre><code>class Test(object): def...
3
2016-07-12T13:16:00Z
38,330,055
<p>You need to override <code>__iter__</code> or <code>__getitem__</code>. Here's an example using <code>__iter__</code>:</p> <pre><code>class Test(object): def __iter__(self): return iter([1, 2]) a,b = Test() </code></pre> <p>Be careful, <code>__iter__</code> needs to return an iterator. The easiest way...
4
2016-07-12T13:18:25Z
[ "python", "python-2.7", "iterator" ]
Can I create a class which can be unpacked?
38,330,001
<p>For example:</p> <pre><code>x = (1, 2) a,b = x </code></pre> <p>Now I'd like to accomplish this in the case of <code>x</code> being an instance of some class that isn't a list or tuple. Simply overriding <code>__getitem__</code> or <code>__getslice__</code> doesn't work:</p> <pre><code>class Test(object): def...
3
2016-07-12T13:16:00Z
38,330,349
<p>Per <a href="https://www.python.org/dev/peps/pep-0234/" rel="nofollow">PEP-234</a>, which defines iterators (emphasis mine):</p> <blockquote> <p>An object can be iterated over with "for" if it implements <code>__iter__()</code> <strong>or <code>__getitem__()</code></strong>.</p> </blockquote> <p>You <em>can</e...
4
2016-07-12T13:30:50Z
[ "python", "python-2.7", "iterator" ]
How to run GDB with the results of a script?
38,330,027
<p>Simple, maybe not so simple issue. How can I run GDB with the results of a script?</p> <p>What I mean is that instead of saying:</p> <pre><code>run arg1 </code></pre> <p>You would say:</p> <pre><code>run "python generatingscript.py" </code></pre> <p>which would output the args. I'm aware I could find a way to...
0
2016-07-12T13:17:05Z
38,347,755
<p>You can use gdb with the <code>--args</code> option like this: <code>gdb --args your_program $(python generatingscript.py</code>.</p>
1
2016-07-13T09:30:34Z
[ "python", "debugging", "gdb" ]
DJango REST Framework - how to pass parameter to serializer __init__
38,330,147
<p>I've been reading the django rest framework doc and I couldn't find how to pass parameter to the <strong>init</strong> method of a serializer. In a regular view I do like this:</p> <pre><code>def get_form_kwargs(self, *args, **kwargs): form_kwargs = super(ContentCreateView, self).get_form_kwargs(*args, **kwargs...
1
2016-07-12T13:22:02Z
38,347,114
<p>DRF has solutions around this.</p> <p>Either you need delivery_id to save your instance, in which case you'll pass it directly to <a href="http://www.django-rest-framework.org/api-guide/serializers/#passing-additional-attributes-to-save" rel="nofollow">the serializer's save</a> and get it in the <code>create</code>...
0
2016-07-13T09:01:20Z
[ "python", "django", "django-rest-framework" ]
flask_mail, mails are stuck on thread and are never send
38,330,151
<p>I'm using flask + socketio with ssl, and I'm trying to send mail, but for some reason, sending mail are not working.</p> <p>Here is my configuration:</p> <pre><code>app.config['MAIL_SERVER']='smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USERNAME'] = 'xxx@gmail.com' app.config['MAIL_PASSWORD'] = '...
0
2016-07-12T13:22:09Z
38,334,433
<p>I had the same issue, if your are working in a virtual machine check the network connection for the <code>ssh</code> port, in my case i work with <code>vagrant</code>, I enabled connection for the <code>ssh</code> port, this code works to me:</p> <pre><code>from flask import Flask from flask_mail import Mail, Mess...
0
2016-07-12T16:28:56Z
[ "python", "ssl", "socket.io", "flask-mail" ]
How to edit the order of LastName, FirstName in pandas without losing the dataframe
38,330,278
<p>I have a dataset in which two columns have strings values "LastName, FirstName". I would love to replace them with "FirstName Last Name". They are like these:</p> <pre><code> conductorName composerName conduct_count 0 Abbado, Claudio Berg, Alban 2 1 Abbado, Claudio Berlioz...
1
2016-07-12T13:27:37Z
38,330,529
<p>You can use the vectorised <code>str.split</code> to split on the separator, then reverse the list contents using slicing semantics and then join again using <code>str.join</code>:</p> <pre><code>In [35]: df['ComposerFirstLastName'] = df['composerName'].str.split(', ').str[::-1].str.join(' ') df['ConductorFirstLast...
2
2016-07-12T13:38:09Z
[ "python", "pandas" ]
How to edit the order of LastName, FirstName in pandas without losing the dataframe
38,330,278
<p>I have a dataset in which two columns have strings values "LastName, FirstName". I would love to replace them with "FirstName Last Name". They are like these:</p> <pre><code> conductorName composerName conduct_count 0 Abbado, Claudio Berg, Alban 2 1 Abbado, Claudio Berlioz...
1
2016-07-12T13:27:37Z
38,330,551
<p>You rewrote over the the entire dataframe:</p> <pre><code>data = [" ".join(n.split(", ")[::-1]) for n in data["composerName"]] </code></pre> <p>This is what it <em>should</em> say:</p> <pre><code>data["composerName"] = [" ".join(n.split(", ")[::-1]) for n in data["composerName"]] </code></pre>
1
2016-07-12T13:38:55Z
[ "python", "pandas" ]
How can I rearrange the index level with Pandas?
38,330,298
<p>The purpose of this post is to try to understand how best to manipulate dataframes with multilevels.</p> <p><strong>Create the dataframe</strong></p> <pre><code>import numpy as np dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('WXYZ')) df['Portfolio']...
1
2016-07-12T13:28:45Z
38,330,410
<p>To swap the order of the MultiIndex levels, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.swaplevel.html" rel="nofollow"><code>DataFrame.swaplevel</code></a>:</p> <pre><code>import numpy as np import pandas as pd dates = pd.date_range('20130101', periods=6) df = pd.DataFrame(np...
4
2016-07-12T13:33:32Z
[ "python", "pandas" ]
string.decode() function in python2
38,330,354
<p>So I am converting some code from python2 to python3. I don't understand the python2 encode/decode functionality enough to even determine what I should be doing in python3</p> <p>In python2, I can do the following things:</p> <pre><code>&gt;&gt;&gt; c = '\xe5\xb8\x90\xe6\x88\xb7' &gt;&gt;&gt; print c 帐户 &gt;&g...
0
2016-07-12T13:31:06Z
38,330,682
<p>Your variable c was not declared as a unicode (with prefix 'u'). If you decode it using the 'latin1' encoding you will get the same result:</p> <pre><code>&gt;&gt;&gt; c.decode('latin1') u'\xe5\xb8\x90\xe6\x88\xb7' </code></pre> <p>Note that the result of <code>decode</code> is a unicode string:</p> <pre><code>&g...
1
2016-07-12T13:44:15Z
[ "python", "python-2.7" ]
Decompressing a text file
38,330,383
<p>So I have already compressed my text now I need to decompress it to be able to recreate the text.</p> <p>The compression is :</p> <pre><code>import zlib, base64 text = raw_input("Enter a sentence: ")#Asks the user to input text text = text.split()#Splits the sentence uniquewords = [] #Creates an empty array for...
0
2016-07-12T13:32:25Z
38,330,988
<p>There are a few things going on here. Let me start by giving you a working sample:</p> <pre><code>import zlib, base64 rawtext = raw_input("Enter a sentence: ") # Asks the user to input text text = rawtext.split() # Splits the sentence uniquewords = [] # Creates an empty array for word in text: # Loop to do th...
2
2016-07-12T13:56:51Z
[ "python" ]
How to prevent multiple catching of exception
38,330,393
<p>Is there a way to prevent multiple catching of exceptions while they ride up the stack to the top level of the program?</p> <p>Here is a <strong>very</strong> simplified code example that illustrate the phenomenon:</p> <pre><code>def try_except_block(smthg): try: smthg.run() except Exception as e: ...
1
2016-07-12T13:32:57Z
38,330,517
<p>I don't fully understand why your code does what it does, but a thing you could do that <em>might</em> suit is to mark exception objects as already-seen, rather than setting a global flag. Like so:</p> <pre><code>def try_except_block(smthg): try: smthg.run() except Exception as e: if not ha...
2
2016-07-12T13:37:35Z
[ "python", "oop", "exception", "exception-handling" ]
Trying to pass filename to ExcelWriter
38,330,416
<p>I am trying to pass a customized filename variable to ExcelWriter but cannot get the ExcelWriter portion of this to work for some reason. If I replace "Sheetname" with "Temp.xlsx" in the ExcelWriter function this works, but i'm not able to pass my variable to the function. I need to be able to store today's date i...
1
2016-07-12T13:33:45Z
38,332,253
<p>When I run your program I get the following error:</p> <pre><code>IOError: [Errno 2] No such file or directory: 'Makino Machine Metrics 07/12/2016.xlsx' </code></pre> <p>You can fix it by removing the forward slashes from the date part:</p> <pre><code>import pandas import time Spreadsheet = pandas.Data...
0
2016-07-12T14:50:54Z
[ "python", "pandas", "time", "xlsxwriter" ]
How to change which axis a colormap acts on
38,330,426
<p>When plotting a 3D figure in matplotlib, how can I set the colormap to act over the y-values instead of over the z-values which it does by default?</p> <p>For example, at the moment when I am plotting, the color map acts across the z axis, however I would like it to use the y axis instead, how can I do this?<a href...
0
2016-07-12T13:34:05Z
38,332,859
<p>As a workaround you can switch the axis and set the view accordingly:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np fig = plt.figure() ax = fig.gca(projection='3d') X = np.arange(-5, 5, 0.25) Y = np.arange(-5, 5, 0.25) X, Y = np.meshgrid(X, Y) Z = np.sin...
0
2016-07-12T15:15:16Z
[ "python", "matplotlib" ]
speed up the process of import multiple csv into python dataframe
38,330,524
<p>I would like to read multiple CSV files (hundreds of files,hundreds of lines each but with the same number of columns) from a target directory into a single Python Pandas DataFrame.</p> <p>The code below I wrote works but too slow.It takes minutes to run 30 files(so how long should I wait if I load all of my files)...
2
2016-07-12T13:37:52Z
38,332,726
<p>you may try the following - read only those columns that really need, use list comprehension and call <code>pd.concat([ ... ], ignore_index=True)</code> once, because it's pretty slow:</p> <pre><code># there is no sense to read columns that you don't need # specify the column list (EXCLUDING: 'aPaye','MethodePaieme...
1
2016-07-12T15:08:50Z
[ "python", "csv", "pandas", "encoding", "dataframe" ]
Can someone help me solve this string index error in python?
38,330,562
<p>This is some code that I need for a schools CAU, I thought I had solved it but I keep getting a string index error, just wondering if anybody could tell me why<a href="http://i.stack.imgur.com/CNpUd.png" rel="nofollow">Error message</a></p> <pre><code>Letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k"...
-5
2016-07-12T13:39:16Z
38,330,885
<p>Your code is wrong in the <code>while totalnum &lt;= len(forename):</code></p> <p>The len of an array returns the lenght of an array starting from 1 not from 0.</p> <p>If you have [1,2,3] the len is 3 but the last position is 2.</p> <p>So to solve your problem change to this:</p> <p><code>while totalnum &lt; len...
1
2016-07-12T13:52:34Z
[ "python", "python-3.x" ]
Python: Certain unicode characters do not display correctly
38,330,713
<p>I am trying to set the label of a GUI-element to display a greek letter with Python.</p> <p><code>str(u'\u0054'.encode('utf8'))</code> will correctly produce the unicode character 'T', as its unicode number is 0054.</p> <p>Writing <code>str(u'\u03B6'.encode('utf8'))</code> will not display the Greek letter small z...
0
2016-07-12T13:45:27Z
38,331,115
<p>Your output encoding is wrong. Make sure your terminal is correctly configured for UTF-8 output.</p> <p>If I interpret your (rather muddy) image correctly, CE B6 is being displayed as Î‎¶‎ which is consistent with any one of a number of common Western <a href="https://rawgit.com/tripleee/8bit/master/encoding...
0
2016-07-12T14:01:45Z
[ "python", "unicode", "utf-8", "fonts" ]
Sublime Text: How do you exit the multiple row layout
38,330,752
<p>I was wondering how you exit the multiple row layout on Sublime Text. I switched to a 3 row layout when editing one of my Django projects, but how do I exit from it (remove the extra rows I have added).</p> <p>Thanks, Henry</p>
0
2016-07-12T13:47:03Z
38,330,833
<p>Use View -> Layout menu. If you choose View -> Layout -> Single, other rows will be removed. Short keys depends on OS.</p>
2
2016-07-12T13:50:01Z
[ "python", "sublimetext2", "sublimetext3", "sublimetext", "text-editor" ]
Sublime Text: How do you exit the multiple row layout
38,330,752
<p>I was wondering how you exit the multiple row layout on Sublime Text. I switched to a 3 row layout when editing one of my Django projects, but how do I exit from it (remove the extra rows I have added).</p> <p>Thanks, Henry</p>
0
2016-07-12T13:47:03Z
38,330,853
<p>In the menu bar: View > Layout > Single</p> <p>Or from the keyboard (on Windows): Alt + Shift + 1</p> <p>To find your default shortcuts, Preferences > Key Bindings - Default, and search for <code>"set_layout"</code>.</p>
2
2016-07-12T13:50:59Z
[ "python", "sublimetext2", "sublimetext3", "sublimetext", "text-editor" ]
MariaDB query from python code
38,330,796
<p>I'm writing a python script that connects to a MariaDB server (V 10.1.12) and saves to file the results of some queries. However, when sending the following query:</p> <pre><code>sql = 'SELECT * FROM Monitor_Run_Tracking WHERE Entry IN (SELECT MAX(Entry) ' \ 'FROM Monitor_Run_Tracking WHERE Run in ({0}) '...
0
2016-07-12T13:48:49Z
38,331,217
<p>You didn't close the parenthesis around the nested select. It should be</p> <pre><code>SELECT * FROM Monitor_Run_Tracking WHERE Entry IN ( SELECT MAX(Entry) FROM Monitor_Run_Tracking WHERE Run in ({0}) AND WhenEntered&lt;'{1}') GROUP BY Run </code></pre> <p>or</p> <pre><code>SELECT * FROM ...
1
2016-07-12T14:06:44Z
[ "python", "mariadb", "mysql-python" ]
Passing command line arguments in django runscript
38,330,829
<p>Is there a way to pass command line arguments to a script using <code>django runscript</code> ? The script I am trying to run uses <code>argparse</code> to accept command line arguments.</p> <p><strong>Command line execution of the script:</strong></p> <pre><code>./consumer --arg1 arg1 --arg2 arg2 </code></pre> <...
0
2016-07-12T13:49:46Z
39,405,658
<p>Take a look at Django's <a href="https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/" rel="nofollow">Commands</a></p> <pre><code>class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--arg1', help="Something helpful") def handle(self, *args, **option...
0
2016-09-09T07:03:31Z
[ "python", "django", "python-2.7", "django-extensions" ]
handle duplicates fields in psycopg2
38,330,841
<p>I am writing web app using Flask(Python3.4) &amp; psycopg2 to connect to postgres 9.4 database.</p> <p>I have option in my web app where user can write their own query and execute it using web app and get output in html table in response.</p> <p>I'm using cursor as <strong>conn.cursor(cursor_factory=psycopg2.extra...
0
2016-07-12T13:50:20Z
38,342,088
<p>The basic problem is that dictionary entries have to have unique keys. Column name can't be used as a key if there's going to be more than one column with the same name. However you could check for that and if there is a duplicate column name, make it unique somehow:</p> <pre><code># Fetch the column info if cur.d...
1
2016-07-13T03:14:06Z
[ "python", "psycopg2" ]
How to find element with specific class attributes in selenium (python)?
38,331,009
<p>On Windows Server 2012 I am using selenium 2.53.6, and I want to check if the <code>class</code> contains the element <code>lock-icon</code> for the following html element:</p> <pre><code>&lt;a href="http://my.page/link/somewhere" class="more-link lock-icon" target="_blank"&gt; Selenium Proje...
0
2016-07-12T13:57:54Z
38,331,091
<p>try:</p> <pre><code>find_element(by=By.CSS_SELECTOR, value="a.more-link") </code></pre>
1
2016-07-12T14:00:46Z
[ "python", "selenium" ]
How to find element with specific class attributes in selenium (python)?
38,331,009
<p>On Windows Server 2012 I am using selenium 2.53.6, and I want to check if the <code>class</code> contains the element <code>lock-icon</code> for the following html element:</p> <pre><code>&lt;a href="http://my.page/link/somewhere" class="more-link lock-icon" target="_blank"&gt; Selenium Proje...
0
2016-07-12T13:57:54Z
38,331,110
<p>You should try as below :-</p> <pre><code>driver.find_element(by=By.CSS_SELECTOR, value="a.lock-icon") </code></pre> <p>or</p> <pre><code>driver.find_element_by_css_selector("a.lock-icon") </code></pre> <p>Hope it will work..:)</p>
1
2016-07-12T14:01:37Z
[ "python", "selenium" ]
How to find element with specific class attributes in selenium (python)?
38,331,009
<p>On Windows Server 2012 I am using selenium 2.53.6, and I want to check if the <code>class</code> contains the element <code>lock-icon</code> for the following html element:</p> <pre><code>&lt;a href="http://my.page/link/somewhere" class="more-link lock-icon" target="_blank"&gt; Selenium Proje...
0
2016-07-12T13:57:54Z
38,331,230
<p>Since <code>more-link</code> is also class name you should call it like <code>.more-link.lock-icon</code>. See the following:</p> <pre><code>find_element(by=By.CSS_SELECTOR, value=".more-link.lock-icon") </code></pre>
0
2016-07-12T14:07:11Z
[ "python", "selenium" ]
Python, Subclass inheritance
38,331,023
<p>Disclaimer, really new at this. Goal, learn more about OOP and Python Stuck, trying to create the instance "pone" that has the attributes of both Person and Station in life. Q1, how do i add the StationInLife values to the instance, without loosing the values given in Person</p> <pre><code>class Person(object): ...
-2
2016-07-12T13:58:27Z
38,331,254
<p>The line:</p> <pre><code>pone= Person(fname='Simon', lname='Dahl', age= 10) </code></pre> <p>creates an object of class <code>Person</code> and it is referenced by name <code>pone</code>.</p> <p>The line:</p> <pre><code>pone = StationInLife(company='Inpay', title = 'HOP', wage = 100) </code></pre> <p>creates an...
2
2016-07-12T14:08:21Z
[ "python", "class", "subclass" ]
Read parameters like eta from youtube-dl
38,331,131
<p>Hi I would like to read the output from youtube dl on cmd and put in my wxpython program. This is the function I used. </p> <pre><code> def execute(self,command,textctrl): process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output ...
0
2016-07-12T14:02:32Z
38,342,330
<p>As long as you are blocked in this function and are not letting control return to the event loop, then there can be no events dispatched to handlers. With no events being sent and processed, there can be no repainting of the contents of the widgets, no interaction with with the mouse and keyboard, nothing. Basical...
0
2016-07-13T03:45:18Z
[ "python", "wxpython", "youtube-dl" ]
PyCharm Directly Open Python File
38,331,175
<p>I switched to PyCharm a couple of months ago, but I can't figure out how to get rid of the welcome screen when I open files.</p> <p>More specifically, I've set up my mac to open all .py files using PyCharm. However, when I double click on a .py file, it's the Welcome screen that opens up and not the .py file.</p> ...
0
2016-07-12T14:04:29Z
38,331,228
<p>PyCharm displays the Welcome screen when no project is open. From this screen, you can quickly access the major starting points of PyCharm. The Welcome screen appears when you close the current project in the only instance of PyCharm. If you are working with multiple projects, usually closing a project results in cl...
0
2016-07-12T14:07:07Z
[ "python", "ide", "pycharm" ]
Loading a pickeld file using pickle.load() fails after some successful attempts
38,331,207
<p>I saved a np.array using </p> <pre><code> pickle.dump(np.array(freq_timeseries), open( "fname.p","wb")) </code></pre> <p>This works fine and after that I can access this file by using <code>pickle.load()</code>. After some time (meaning after some successful <code>pickle.load()</code> uses) the attempt to load...
0
2016-07-12T14:06:20Z
38,331,470
<p>If it is as Kevin commented, that you're not closing the files, consider re-writing using the <code>with</code> statement and it'll auto-close.</p>
0
2016-07-12T14:17:44Z
[ "python", "python-3.x", "pickle" ]
ElementTree cannot find element
38,331,276
<p>I have an XML document, for which I'm including a sufficient subset in the reproducer below, for which <code>tree.find()</code> returns no results:</p> <pre><code>import xml.etree.ElementTree as ET xml_str = ''' &lt;Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"&gt; &lt;System/&gt; &lt;/Eve...
1
2016-07-12T14:09:16Z
38,331,355
<p>Use the namespace in your search:</p> <pre><code>&gt;&gt;&gt; doc.find('{http://schemas.microsoft.com/win/2004/08/events/event}System') &lt;Element {http://schemas.microsoft.com/win/2004/08/events/event}System at 0x10167e5a8&gt; </code></pre>
2
2016-07-12T14:12:54Z
[ "python", "elementtree" ]
Move scientific notation exponential to right side of y axis in matplotlib
38,331,332
<p>I have plotted a figure like this<a href="http://i.stack.imgur.com/Lpx8s.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Lpx8s.jpg" alt="enter image description here"></a></p> <p>Now I want to move the scientific notation offset <code>1e4</code> to the right of the right y axis, best move it to the upper rig...
0
2016-07-12T14:11:49Z
38,332,577
<p>This should work:</p> <pre><code>t = ax.yaxis.get_offset_text() t.set_x(1.1) </code></pre> <p>with <code>ax</code> your right axis. However, you cannot change the y position, so if you are not satisfied with it, you can hide the offset text and create it manually at the right position (x,y):</p> <pre><code>ax.yax...
1
2016-07-12T15:02:19Z
[ "python", "matplotlib" ]
python script to increment value of naive spreadsheet macro
38,331,340
<p>I have a simple macro function in a spreadsheet, looks like this: </p> <pre><code>=LOOKUP(B2, eligible.submissions!A1:A158,eligible.submissions!B1:B158) </code></pre> <p>I want to increment it as so: </p> <pre><code>=LOOKUP(B2, eligible.submissions!A1:A158,eligible.submissions!B1:B158) =LOOKUP(B3, eligible.submis...
0
2016-07-12T14:12:13Z
38,331,493
<p>I don't see what does this have anything to do with Python, but try putting a <code>$</code> sign in front of references that you don't want to change, ie:</p> <pre><code>=LOOKUP($B2, eligible.submissions!$A$1:$A$158,eligible.submissions!$B$1:$B$158) </code></pre> <p>See <a href="https://support.office.com/en-us/a...
1
2016-07-12T14:18:54Z
[ "python", "excel", "macros", "spreadsheet" ]
python reports missing parameter
38,331,364
<p>I have a function in an object which requires 5 params. I create an instance of that object and run the function, define(param1,2,3,4,5) and it gives me a response of missing the fifth parameter. </p> <p>Here is part of my code:</p> <pre><code> class KeyProperties: #Object path = None keytype = None image = N...
1
2016-07-12T14:13:07Z
38,331,409
<p>Your current <code>key</code> is not an instance of <code>KeyProperties</code> but the class itself. Hence <code>define</code> will require 6 parameters (which includes <code>self</code>):</p> <p>To fix this, instantiate the class:</p> <pre><code>key = KeyProperties() # ^^ </code></pre> <p>The fi...
8
2016-07-12T14:14:43Z
[ "python", "object", "self" ]
Creating a list/removing a row from a list if a string exist in the list
38,331,379
<p>I have a 2d list of strings in the form</p> <pre><code>data = [['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 40162.0, 'CFSAN', 'Pesticides and Chemical Contaminants'], ['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 41033.0, 'CFSAN', 'Foodborne Hazards']] </code></pre> <p>If a row in my list ...
0
2016-07-12T14:13:38Z
38,331,483
<pre><code>thelist[:] = [x for x in thelist if 'Food' not in str(x)] </code></pre> <p>u may use this while u iterate over the list - u'd never get out of index error</p> <p>adding info for two nested lists- your case :</p> <pre><code>for singlelist in data: singlelist[:] = [x for x in singlelist if 'Food' not in...
1
2016-07-12T14:18:22Z
[ "python", "list" ]
Creating a list/removing a row from a list if a string exist in the list
38,331,379
<p>I have a 2d list of strings in the form</p> <pre><code>data = [['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 40162.0, 'CFSAN', 'Pesticides and Chemical Contaminants'], ['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 41033.0, 'CFSAN', 'Foodborne Hazards']] </code></pre> <p>If a row in my list ...
0
2016-07-12T14:13:38Z
38,331,782
<p>This is a job for <code>filter</code>. Comprehensions could do the same trick but I find that <code>map/filter/reduce</code> always make easier to read code:</p> <pre><code>def my_food_filter(inner_list): return not any(['Food' in str(p) for p in inner_list]) foodless_list = filter(my_food_filter, data) </code...
3
2016-07-12T14:31:04Z
[ "python", "list" ]
Creating a list/removing a row from a list if a string exist in the list
38,331,379
<p>I have a 2d list of strings in the form</p> <pre><code>data = [['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 40162.0, 'CFSAN', 'Pesticides and Chemical Contaminants'], ['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 41033.0, 'CFSAN', 'Foodborne Hazards']] </code></pre> <p>If a row in my list ...
0
2016-07-12T14:13:38Z
38,331,917
<pre><code>[[y for y in x if 'Food' not in str(y)] for x in data] </code></pre> <p>Input : data Output :</p> <pre><code>[['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 40162.0, 'CFSAN', 'Pesticides and Chemical Contaminants'], ['DAL', "Luna's", 'Dallas', 'TX', '75235-3013', 'US', 41033.0, 'CFSAN']] </code></pr...
2
2016-07-12T14:36:45Z
[ "python", "list" ]
How to install libjpeg on OSX?
38,331,388
<p>libjpeg or libjpeg-turbo are requirements for installing <a href="https://pypi.python.org/pypi/Pillow" rel="nofollow">Pillow</a>, which is <a href="https://docs.djangoproject.com/en/1.9/_modules/django/core/files/images/" rel="nofollow">a new requirement for storing images on django</a>. So I need to install Pillow...
1
2016-07-12T14:13:57Z
38,331,481
<p><a href="http://brew.sh" rel="nofollow">Homebrew</a>:</p> <pre><code>brew install libjpeg </code></pre>
1
2016-07-12T14:18:15Z
[ "python", "osx", "libjpeg", "libjpeg-turbo" ]
Close a scrapy spider when a condition is met and return the output object
38,331,428
<p>I have made a spider to get reviews from a page like this <a href="http://www.flipkart.com/moto-x-play/product-reviews/ITMEAJTQYHRNKWRZ?pid=MOBEAJTQGSBHEFHA&amp;type=all&amp;sort=most_recent" rel="nofollow">here</a> using scrapy. I want product reviews only till a certain date(2nd July 2016 in this case). I want to ...
0
2016-07-12T14:15:53Z
38,331,733
<p>To force spider to close you can use raise <code>CloseSpider</code> exception as described <a href="http://doc.scrapy.org/en/latest/faq.html?#how-can-i-instruct-a-spider-to-stop-itself" rel="nofollow">here in scrapy docs</a>. Just be sure to return/yield your items before you raise the exception.</p>
1
2016-07-12T14:28:40Z
[ "python", "scrapy", "web-crawler", "screen-scraping" ]
Replcae inner space in Python
38,331,509
<p>Iam new to Python, And I need to remove space between string and a digit only not between two strings.</p> <p>eg: </p> <p>Input : Paragraph 25 is in documents and paragraph number in another file.</p> <p>Output : Paragraph25 is in documents and paragraph number in another file.</p> <p>How this can be done in Pyt...
-2
2016-07-12T14:19:50Z
38,331,904
<pre><code> &gt;&gt;&gt; re.sub(r'\s+(\d+)', r'\1', 'Program 25 is fun') 'Program25 is fun' </code></pre> <p>That might work in a pinch. I'm not the most familiar with regexes, so hopefully someone who is can chime in with something more robust.</p> <p>Basically we match on whitespace succeeded by numbers and remove ...
1
2016-07-12T14:36:10Z
[ "python" ]
NumPy array format (cut fractional part)
38,331,562
<p>I get the infinite fractional and I want to reduce it to 4-6 signs after mantissa:</p> <pre><code>[[ 0.43209877 0. 0.11111111 0. 0.45679012 0. 0. 0. 0. ]] </code></pre> <p>must be formatted to something like this:</p> <pre><code>[[ 0.432 0. 0.1111 0. 0.4567 0. ...
-2
2016-07-12T14:21:45Z
38,331,629
<p>I am not sure whether I did understand your question correctly, but it seems to me that you are looking for something like this:</p> <p>code</p> <pre><code>import numpy as np a = np.array([ 0.43209877, 0.,0.11111111, 0., 0.45679012,0.,0.,0.,0.]) np.round(a,3) </code></pre> <p>result</p> <pre><code>array([ 0.4...
1
2016-07-12T14:24:26Z
[ "python", "arrays", "numpy", "fractions" ]
NumPy array format (cut fractional part)
38,331,562
<p>I get the infinite fractional and I want to reduce it to 4-6 signs after mantissa:</p> <pre><code>[[ 0.43209877 0. 0.11111111 0. 0.45679012 0. 0. 0. 0. ]] </code></pre> <p>must be formatted to something like this:</p> <pre><code>[[ 0.432 0. 0.1111 0. 0.4567 0. ...
-2
2016-07-12T14:21:45Z
38,331,890
<p>You can set the print settings for numpy arrays by using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html" rel="nofollow"><code>set_printoptions</code></a>:</p> <pre><code>numpy.set_printoptions(precision=4) </code></pre> <p>appears to be what you want.</p>
1
2016-07-12T14:35:37Z
[ "python", "arrays", "numpy", "fractions" ]
Return the column name(s) for a specific value in a pandas dataframe
38,331,568
<p>where I have found this option in other languages such as R or SQL but I am not quite sure how to go about this in Pandas.</p> <p>So I have a file with 1262 columns and 1 row and need the column headers to return for every time that a specific value appears. </p> <p>Say for example this test dataframe:</p> <pre><...
4
2016-07-12T14:21:56Z
38,331,709
<p>Seeing as you only have a single row then you can call <code>iloc[0]</code> on the result and use this to mask the columns:</p> <pre><code>In [47]: df.columns[(df == 38.15).iloc[0]] Out[47]: Index(['col7'], dtype='object') </code></pre> <p>Breaking down the above:</p> <pre><code>In [48]: df == 38.15 Out[48]: ...
5
2016-07-12T14:27:31Z
[ "python", "pandas" ]
Return the column name(s) for a specific value in a pandas dataframe
38,331,568
<p>where I have found this option in other languages such as R or SQL but I am not quite sure how to go about this in Pandas.</p> <p>So I have a file with 1262 columns and 1 row and need the column headers to return for every time that a specific value appears. </p> <p>Say for example this test dataframe:</p> <pre><...
4
2016-07-12T14:21:56Z
38,331,713
<p>You can use data frame slicing and then get the columns names:</p> <pre><code>df.ix[:,df.loc[0] == 38.15].columns </code></pre> <p>output:</p> <pre><code>Index([u'col7'], dtype='object') </code></pre>
1
2016-07-12T14:27:40Z
[ "python", "pandas" ]
Return the column name(s) for a specific value in a pandas dataframe
38,331,568
<p>where I have found this option in other languages such as R or SQL but I am not quite sure how to go about this in Pandas.</p> <p>So I have a file with 1262 columns and 1 row and need the column headers to return for every time that a specific value appears. </p> <p>Say for example this test dataframe:</p> <pre><...
4
2016-07-12T14:21:56Z
38,332,216
<p>just for the sake of throwing something a bit different into the ring:</p> <pre><code>row = df.iloc[0] row.reset_index().set_index(0).loc[38.15] </code></pre>
1
2016-07-12T14:49:28Z
[ "python", "pandas" ]
How do I allow a function to be redefined in Django?
38,331,669
<p>I have a 'core' Django product that includes default implementations of common tasks, but I want to allow that implementation to be redefined (or customised if that makes it easier).</p> <p>For example in the core product, I might have a view which allows a user to click a button to resend 'all notifications':</p> ...
0
2016-07-12T14:26:05Z
38,339,470
<p>In a similar situation I ended up going for a solution like so – I put this on my <code>Organization</code> model in the application (equiv of a GitHub organization).</p> <pre><code>@property def forms(self): if self.ldap: from portal.ldap import forms else: from portal.users import forms ...
0
2016-07-12T21:54:20Z
[ "python", "django", "celery" ]
How do I allow a function to be redefined in Django?
38,331,669
<p>I have a 'core' Django product that includes default implementations of common tasks, but I want to allow that implementation to be redefined (or customised if that makes it easier).</p> <p>For example in the core product, I might have a view which allows a user to click a button to resend 'all notifications':</p> ...
0
2016-07-12T14:26:05Z
39,621,445
<p>This ended up being solved via a Django settings object that can be reconfigured by the deployment config. It was largely inspired by the technique here: <a href="https://github.com/tomchristie/django-rest-framework/blob/8385ae42c06b8e68a714cb67b7f0766afe316883/rest_framework/settings.py" rel="nofollow">settings.py ...
0
2016-09-21T16:03:09Z
[ "python", "django", "celery" ]
Why does numpy's broadcasting sometimes allow comparing arrays of different lengths?
38,331,703
<p>I'm trying to understand how numpy's broadcasting affects the output of <code>np.allclose</code>.</p> <pre><code>&gt;&gt;&gt; np.allclose([], [1.]) True </code></pre> <p>I don't see why that works, but this does not:</p> <pre><code>&gt;&gt;&gt; np.allclose([], [1., 2.]) ValueError: operands could not be broadcast...
2
2016-07-12T14:27:09Z
38,333,159
<p>Broadcasting doesn't affect <code>np.allclose</code> in any other way than it affects any other function.</p> <p>As in the comment by @cel, <code>[1.]</code> is of dimension 1 and so can be broadcasted to any other dimension, including 0. On the other hand <code>[1., 2.]</code> is of dimension 2 and thus cannot be ...
1
2016-07-12T15:28:49Z
[ "python", "numpy", "numpy-broadcasting" ]
Why does numpy's broadcasting sometimes allow comparing arrays of different lengths?
38,331,703
<p>I'm trying to understand how numpy's broadcasting affects the output of <code>np.allclose</code>.</p> <pre><code>&gt;&gt;&gt; np.allclose([], [1.]) True </code></pre> <p>I don't see why that works, but this does not:</p> <pre><code>&gt;&gt;&gt; np.allclose([], [1., 2.]) ValueError: operands could not be broadcast...
2
2016-07-12T14:27:09Z
38,335,733
<p>Broadcasting rules apply to addition as well, </p> <pre><code>In [7]: np.array([])+np.array([1.]) Out[7]: array([], dtype=float64) In [8]: np.array([])+np.array([1.,2.]) .... ValueError: operands could not be broadcast together with shapes (0,) (2,) </code></pre> <p>Let's look at the shapes.</p> <pre><code>In [...
1
2016-07-12T17:45:25Z
[ "python", "numpy", "numpy-broadcasting" ]
Converting string.decode('utf8') from python2 to python3
38,331,819
<p>I am converting some code from python2 to python3. </p> <p>In python2, I can do the following things:</p> <pre><code>&gt;&gt;&gt; c = '\xe5\xb8\x90\xe6\x88\xb7' &gt;&gt;&gt; print c 帐户 &gt;&gt;&gt; c.decode('utf8') u'\u5e10\u6237' </code></pre> <p>How can I get that same output (u'\u5e10\u6237') in python3?</...
3
2016-07-12T14:32:26Z
38,333,224
<p>Returning the same unicode as in python2 is not possible : I have not seen unicode object like there was in python2, in python3. But it is possible to get the value of the unicode object. </p> <p>To do this, you need to do several things :<br> - Create a byte element with value '\xe5\xb8\x90\xe6\x88\xb7' - Tran...
1
2016-07-12T15:32:01Z
[ "python", "python-2.7", "python-3.x" ]
Converting string.decode('utf8') from python2 to python3
38,331,819
<p>I am converting some code from python2 to python3. </p> <p>In python2, I can do the following things:</p> <pre><code>&gt;&gt;&gt; c = '\xe5\xb8\x90\xe6\x88\xb7' &gt;&gt;&gt; print c 帐户 &gt;&gt;&gt; c.decode('utf8') u'\u5e10\u6237' </code></pre> <p>How can I get that same output (u'\u5e10\u6237') in python3?</...
3
2016-07-12T14:32:26Z
38,333,324
<p>This is called "unicode-escape" encoding. Here is an example of how one would achieve this behavior in python3:</p> <pre><code>In [11]: c = b'\xe5\xb8\x90\xe6\x88\xb7' In [12]: d = c.decode('utf8') In [13]: print(d) 帐户 In [14]: print(d.encode('unicode-escape').decode('ascii')) \u5e10\u6237 </code></pre> <p>...
3
2016-07-12T15:36:54Z
[ "python", "python-2.7", "python-3.x" ]
arc lint command fails with error #1
38,331,830
<p>I've configured <a href="https://secure.phabricator.com/book/phabricator/article/arcanist_lint/" rel="nofollow">arc lint</a> to use <a href="https://www.google.com.ua/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwixo6qxxPLNAhVBOpQKHdjxCasQFggcMAA&amp;url=https%3A%...
1
2016-07-12T14:33:07Z
38,437,270
<p>In my case the issue was related to ValueError: unknown locale: UTF-8.</p> <p>If you have faced the same error on MacOS here's the quick fix (export in bash):</p> <pre><code>export LC_ALL=en_US.UTF-8 export LANG=en_US.UTF-8 </code></pre> <p>How to fix :</p> <p>Please use test.php script to reproduce issue (provi...
2
2016-07-18T12:55:01Z
[ "php", "python", "pylint", "phabricator", "arcanist" ]
Python - manually removing a specific letter from a string
38,331,921
<p>I'm aware of the <code>string.replace("x", "y")</code> method, but I'm trying to manually remove a character from a string to help me better understand Python and programming in general. The method I currently have is detailed below, but I can't understand why for "Dee" and removing "e" it will return "De", but for ...
3
2016-07-12T14:37:00Z
38,332,113
<p>The problem oyu have is that you change the size of the string you want to remove the letter from, while removing the letter :<br> When you remove the first 'e' in Dee, you have location = 1, corresponding to the first 'e, but is now that of the second 'e'. After removing the e, at the end of the current loop, you h...
3
2016-07-12T14:45:21Z
[ "python", "string" ]
Python - manually removing a specific letter from a string
38,331,921
<p>I'm aware of the <code>string.replace("x", "y")</code> method, but I'm trying to manually remove a character from a string to help me better understand Python and programming in general. The method I currently have is detailed below, but I can't understand why for "Dee" and removing "e" it will return "De", but for ...
3
2016-07-12T14:37:00Z
38,332,195
<p>Considering what khelwood and HolyDanna said, this might be a viable approach:</p> <pre><code>def removeletter(string, letter): out = '' for i in string: if not i == letter: out += i return out altered_string = removeletter(string, letter) </code></pre> <p>EDIT - You could also eas...
2
2016-07-12T14:48:54Z
[ "python", "string" ]
Connect to a different database in django shell
38,331,941
<p>How can I connect to a different database when in a Django shell?</p> <p>Something like:</p> <pre><code>python manage.py shell --database=slave </code></pre> <p>I tried googling all around, but couldn't find anything useful on this.</p> <p>This is what my settings looks like:</p> <pre><code>DATABASES = { 'd...
3
2016-07-12T14:38:01Z
38,332,185
<p>You could select database in your query with <a href="https://docs.djangoproject.com/en/1.9/topics/db/multi-db/#manually-selecting-a-database-for-a-queryset" rel="nofollow"><code>using()</code></a> ORM's method:</p> <pre><code># This will hit a model in your default DB: Model.objects.using('default').all() # And t...
4
2016-07-12T14:48:19Z
[ "python", "django", "shell" ]
Connect to a different database in django shell
38,331,941
<p>How can I connect to a different database when in a Django shell?</p> <p>Something like:</p> <pre><code>python manage.py shell --database=slave </code></pre> <p>I tried googling all around, but couldn't find anything useful on this.</p> <p>This is what my settings looks like:</p> <pre><code>DATABASES = { 'd...
3
2016-07-12T14:38:01Z
38,332,388
<p>You can split your settings module into submodules. For instance:</p> <pre><code>project/ settings/ __init__.py base.py dev.py prod.py shell.py </code></pre> <p>Your main/common settings are located in <code>project/settings/base.py</code></p> <p>In development, set <co...
1
2016-07-12T14:56:19Z
[ "python", "django", "shell" ]
optional argument with ternary operator
38,332,054
<p>I have a function <code>f</code> that may take a variable number of arguments, like this:</p> <pre><code>f = f_5_args if five else f_4_args </code></pre> <p>To call <code>f</code>, I'm currently doing this:</p> <pre><code>if five: result = f(x1, x2, x3, x4, x5) else: result = f(x1, x2, x3, x4) </code></pre> ...
1
2016-07-12T14:42:51Z
38,332,221
<p>You can do the following:</p> <pre><code>result = f(*(filter(None, (x1, x2, x3, x4, x5 if five else None)))) </code></pre> <p>Note that this solution eliminates all the False and zero values together with <code>None</code>s, so use it if it suits your use case.</p>
0
2016-07-12T14:49:39Z
[ "python", "arguments", "optional", "ternary-operator" ]
optional argument with ternary operator
38,332,054
<p>I have a function <code>f</code> that may take a variable number of arguments, like this:</p> <pre><code>f = f_5_args if five else f_4_args </code></pre> <p>To call <code>f</code>, I'm currently doing this:</p> <pre><code>if five: result = f(x1, x2, x3, x4, x5) else: result = f(x1, x2, x3, x4) </code></pre> ...
1
2016-07-12T14:42:51Z
38,332,341
<p>You could do something like this:</p> <pre><code>fargs = [x1, x2, x3, x4] if five: fargs.append(x5) result = f_5_args(*fargs) else: result = f_4_args(*fargs) </code></pre> <p>That avoids having to write out all your function arguments twice.</p>
0
2016-07-12T14:54:12Z
[ "python", "arguments", "optional", "ternary-operator" ]
optional argument with ternary operator
38,332,054
<p>I have a function <code>f</code> that may take a variable number of arguments, like this:</p> <pre><code>f = f_5_args if five else f_4_args </code></pre> <p>To call <code>f</code>, I'm currently doing this:</p> <pre><code>if five: result = f(x1, x2, x3, x4, x5) else: result = f(x1, x2, x3, x4) </code></pre> ...
1
2016-07-12T14:42:51Z
38,332,350
<p>If you have the list of arguments, you could make it more concise by using slicing:</p> <pre><code>args = [x1, x2, x3, x4, x5] result = f(*args) if five else f(*args[:4]) </code></pre> <p>But it would probably be easier to use a function that accepts an arbitrary number of positional arguments:</p> <pre><code>def...
2
2016-07-12T14:54:28Z
[ "python", "arguments", "optional", "ternary-operator" ]
Python & Matplotlib: Simplify plot configuration (xlabel, title, legend...)?
38,332,149
<p>When I make plots, I always need to set x,ylabels, titles, legend etc. Setting them one by one is tedious, so I tried to put them into a single helper method:</p> <pre><code>def plt_configure(ax=None, xlabel='', ylabel='', title='', legend=False, tight=False, figsize=False): if ax == None : ax=plt.gca()...
1
2016-07-12T14:46:39Z
38,332,580
<p>Similarly, I am also used to set up a helper function for <code>plt</code> setup. I feel like only setting the very basics in such kind of a function is sufficient, as the rest is always plot-dependent.</p> <p>You only run into the high complexity of your "helper", because you try to put too much options into it, e...
1
2016-07-12T15:02:30Z
[ "python", "matplotlib" ]
Python & Matplotlib: Simplify plot configuration (xlabel, title, legend...)?
38,332,149
<p>When I make plots, I always need to set x,ylabels, titles, legend etc. Setting them one by one is tedious, so I tried to put them into a single helper method:</p> <pre><code>def plt_configure(ax=None, xlabel='', ylabel='', title='', legend=False, tight=False, figsize=False): if ax == None : ax=plt.gca()...
1
2016-07-12T14:46:39Z
38,332,604
<p>You can use a <code>for</code> loop to achieve the above. </p> <p>For example, let's say we have 3 subplots and we need to have common legends, labels, <code>xscale</code> or <code>yscale</code> etc.</p> <pre><code>fig2 = plt.figure(figsize=(9,10)) ax1 = fig2.add_subplot(131) ax1.scatter(data_z,data_zphot1,s=3,ma...
0
2016-07-12T15:03:30Z
[ "python", "matplotlib" ]
How to wrap a static class (from .NET) in a 'with' statement
38,332,166
<p>I am trying to wrap a .NET library in nice pythonic wrappers for use in IronPython. </p> <p>A pattern used often in this library is a PersistenceBlock to make database CRUD operations clean and 'all or nothing':</p> <pre><code>try: Persistence.BeginNewTransaction() # do stuff here Persistence.CommitTransacti...
2
2016-07-12T14:47:11Z
38,332,941
<p>You can find the docs via searching for <code>context manager</code> protocol - that's the protocol all objects supposed to work with the <code>with</code> statement should implement.</p> <p>Context managers (i.e. the <code>__enter__</code> method) does not need to return anything - only if you want to use the <cod...
4
2016-07-12T15:18:47Z
[ "python", "ironpython" ]
Catching the same expection in every method of a class
38,332,356
<p>I, a beginner, am working on a simple card-based GUI. written in Python. There is a base class that, among other things, consists a vocabulary of all the cards, like <code>_cards = {'card1_ID': card1, 'card2_ID': card2}</code>. The cards on the GUI are referenced by their unique IDs. </p> <p>As I plan to make the c...
4
2016-07-12T14:54:40Z
38,332,482
<p>Extract the actual getting of the card from the id into a separate method, with a try/except there, and call that method from everywhere else.</p> <pre><code>def get_card(self, card_id): try: return self._cards[card_ID] except KeyError: raise ValueError("Invaild card ID") def invert(self, c...
7
2016-07-12T14:59:06Z
[ "python", "python-3.x", "exception", "exception-handling" ]
Catching the same expection in every method of a class
38,332,356
<p>I, a beginner, am working on a simple card-based GUI. written in Python. There is a base class that, among other things, consists a vocabulary of all the cards, like <code>_cards = {'card1_ID': card1, 'card2_ID': card2}</code>. The cards on the GUI are referenced by their unique IDs. </p> <p>As I plan to make the c...
4
2016-07-12T14:54:40Z
38,332,633
<p>You could use a decorator to remove some of that repetitive boiler plate.</p> <pre><code>from functools import wraps def replace_keyerror(func): """Catches KeyError and replaces it with ValueError""" @wraps(func) def inner(*args, **kwargs): try: func(*args, **kwargs) except...
6
2016-07-12T15:04:43Z
[ "python", "python-3.x", "exception", "exception-handling" ]