Can't save figure as .eps [gswin32c is not recognized] - python-2.7

I'm using Enthought Canopy with PyLab(64-bit). For my report I need to use Latex (XeLaTex) and the plots are done with matplotlib.
To have an first idea I just copied the second example from http://matplotlib.org/users/usetex.html and compiled it. It looks fine and I can save it as a normal png without problems. However if i try to save it as .eps or.ps it does not work and an error appears:
invalid literal for int() with base 10: "
Additionaly in the Pylab shell it shows:
'gswin32c' is not recognized as an internal or external command, operable program or batch file'.
If I save it as .pdf I have no problems except the text is all black instead of being red and blue. This is a problem because in my plots I have two axes and I need them colorized for better readability.
If I then try to delete some lines from the example given (all text) I still cannot save it as .eps nor .ps. I can't figure out the problem and all the other topics related to this have not given me an insight. So I really need your help because I can't use .png for my report.
Thank you in advance!!!

I finally managed to solve this problem. It might look weird but maybe other people can benefit from it.
The solution might depend upon the software you use. I use Enthought Canopy (Python) and MikTeX 2.9 under W8 64bit.
If you want to output .ps and .eps files with matplotlib using the 'text.usetex': True option then you will encounter the problem posted above.
Solution:
Download and install Ghostscript (32bit) from http://www.ghostscript.com/download/gsdnld.html.
Download ps2eps-1.68.zip from http://www.tm.uka.de/~bless/ps2eps. The proceeding is given in the manual, however I like to point out the part with the environment variables. In this last step you need to go to Control Panel --> System --> Advanced system settings. Then click on the header 'Advanced' and on the bottom of the window you see 'Environment Variables' on which you click. Then you use the 'New'-Button for User Variables for USERNAME. Then you type in as variable name 'ps2eps' and for variable value you type in the actual path where you have saved the ps2eps.pl file. In my case this is 'C:\Program Files (x86)\ps2eps\bin\'. You can check if you type 'ps2eps' in the command-window.
Download xpdfbin-win-3.03.zip from http://www.foolabs.com/xpdf/download.html. You only need the file 'pdftops.exe'. However I could not assign a path like in step 2. I solved this by putting the 'pdftops.exe' in the MikTeX 2.9 folder. The exact location for me was 'C:\Program Files\MiKTeX 2.9\miktex\bin\x64'.
I was then able to save figures as .ps and have no more any error messages. Remember to use the settings proposed on http://matplotlib.org/users/usetex.html under 'postscript options'.
In myself used the following settings:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib as mpl
mpl.rc('font', **{'family':'serif', 'serif':['Computer Modern Roman'],
'monospace':['Computer Modern Typewriter']})
params = {'backend': 'ps',
'text.latex.preamble': [r"\usepackage{upgreek}",
r"\usepackage{siunitx}",
r"\usepackage{amsmath}",
r"\usepackage{amstext}",],
'axes.labelsize': 18,
#'axes.linewidth': 1,
#'text.fontsize':17,
'legend.fontsize': 10,
'xtick.labelsize': 13,
#'xtick.major.width' : 0.75,
'ytick.labelsize': 13,
'figure.figsize': [8.8,6.8],
#'figure.dpi': 120,
'text.usetex': True,
'axes.unicode_minus': True,
'ps.usedistiller' : 'xpdf'}
mpl.rcParams.update(params)
mpl.rcParams.update({'figure.autolayout':True})
(whereas many of the params are just for my own purpose later in the plots)
As a beginner I am not well informed about the dependence from the 'backend' used if you are running a script from your python console. I however used this without any --pylab settings in before and I do not know if one needs to switch the backend manually if he is working already in a console with a specific matplotlib backend.

I had the same problem and my problem was a font adjustment in the python code that is :
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
when I remove this iit works fine and now i can save eps.
So be sure that any shortest working example is working for you or not then check the font and other style edits in your code. This may help.

Related

Navigate to the file from output in the terminal - WebStorm

Is it possible to tune WebStorm so that when I have something like this in my terminal window, then I just click on the filename and jump to it.
Not possible using built-in terminal (please vote for IDEA-118566 and IDEA-154439).
Awesome Console plugin might be a solution; but it doesn't support built-in terminal (https://github.com/anthraxx/intellij-awesome-console/issues/23)
there is also Output Link Filter plugin that provides similar functionality, but it looks outdated and (also) doesn't work in built-in terminal
Update (2022): IDEA-118566 is already fixed, links should work. Please note that providing links for particular output needs adding specific logic handing such output. Thus, if you encounter missing links in a particular output, please file a separate issue request describing link output format and steps to reproduce such output.
Webstorm does in fact now have this functionality.
Note that the bug about this functionality being missing (linked in another answer) has been marked as fixed: https://youtrack.jetbrains.com/issue/IDEA-118566.
It's not quite a single click solution, but what I do, is double click the text so that it auto selects and copies the path, including line and char numbers to clipboard. Then use the shortcut for Goto File.... Hit paste (cmd+v) then Enter and it will take you to the exact location.
For me, the shortcut for Goto File... is cmd+shift+O - you can check your shortcut in the menu Navigate -> File...
You can use the following format to output text in the terminal via console.log and the path will be clickable:
at ($FILE_FULL_PATH:$LINE_NUMBER:$SYMBOL_NUMBER)
Example with the full path to the file:
at (/home/ubuntu/project/index.js:12:55)
However, if you're running WebStorm with exact file path's project's folder, you can use the following format:
at (./project/index.js:12:55)
I installed Awesome Console plugin and with this plugin, all files and links in the console and terminal will be highlighted and can be clicked. Source code files will be opened in the IDE, other links with the default viewer/browser for this type.
You can jump to files from the terminal with left click
Just select file path (dblclick) & press "shift" twice (search everywhere) & press "enter"...

PyCharm not doing full syntax coloring for a specific file name

In my Django projet, I have one models.py file that PyCharm is only partially syntax coloring: it's coloring the Python keywords and comments but not other things it normally does like coloring method names, keyword parameters. This is the only file in my project like this -- all other .py files are fully syntax colored.
It's the file name not contents that is the issue. I know this because when I rename the file, PyCharm immediately fully syntax colors it. When I rename it back to models.py, it goes back to partial coloring.
Note it's not just the syntax coloring that's off -- it's also other code analysis-related tools for this file.
What could be causing PyCharm to be treating this one file differently?
In the PyCharm status bar, there is a "Highlighting level" indicator. Clicking on it allows you to choose the highlighting level between "None", "Syntax" and "Inspections", and the selected value is persisted per file. Please try clicking on it and making sure that the level is set to "Inspections".

Testing a python recipe

I want to run a python recipe I found, but I don't know how as it imports from another one!
For example, I would like to test the code here.
I have downloaded it and also downloaded this one as it uses it.
So how can I test the this code by passing the needed parameter as below?!
>>> G = {'s':{'u':10, 'x':5}, 'u':{'v':1, 'x':2}, 'v':{'y':4}, 'x':{'u':3, 'v':9, 'y':2}, 'y':{'s':7, 'v':6}}
>>> Dijkstra.Dijkstra(G,'s','v')
I have added the two files in one of the python paths, and imported both but still get error
Could you please give me some advice on simple way to test this code?
You really should put the files in your current directory if you are just testing, instead of putting them in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ as that path is reserved for the Python standard library.
It seems that the second recipe, the Priority Dictionary, needs to be put in a file called priodict.py since the Dijkstra code imports from priodict. So, you should have the following files in your current directory: Dijkstra.py, priodict.py. Then you can just start Python and do import Dijkstra, and it should work.
Also, don't modify the Dijkstra code to remove the import as you apparently did...

How can I programmatically generate PDFs using LaTeX?

I'm trying to generate some LaTeX code which from thereon should generate PDF documents.
Currently, I'm using the Django templating system for dynamically creating the code, but I have no idea on as how to move on from here. I understand that I could save the code in a .tex file, and use subprocess to run pdflatex for generating the PDF. But I had so much trouble escaping the LaTeX code in "plain" Python that I decided to use the Django templating system. Is there a way that I could somehow maybe pipe the output produced by Django to pdflatex? The code produced is working properly, it's just that I do not know what to do with it.
Thanks in advance
I was tackling the same issue in a project I had previously worked on, and instead of piping the output, I created temporary files in a temporary folder, since I was worried about handling the intermediate files LaTeX produces. This is the code I used (note that it's a few years old, from when I was still new to Python/Django; I'm sure I could come up with something better if I was writing this today, but this definitely worked for me):
import os
from subprocess import call
from tempfile import mkdtemp, mkstemp
from django.template.loader import render_to_string
# In a temporary folder, make a temporary file
tmp_folder = mkdtemp()
os.chdir(tmp_folder)
texfile, texfilename = mkstemp(dir=tmp_folder)
# Pass the TeX template through Django templating engine and into the temp file
os.write(texfile, render_to_string('tex/base.tex', {'var': 'whatever'}))
os.close(texfile)
# Compile the TeX file with PDFLaTeX
call(['pdflatex', texfilename])
# Move resulting PDF to a more permanent location
os.rename(texfilename + '.pdf', dest_folder)
# Remove intermediate files
os.remove(texfilename)
os.remove(texfilename + '.aux')
os.remove(texfilename + '.log')
os.rmdir(tmp_folder)
return os.path.join(dest_folder, texfilename + '.pdf')
The dest_folder variable is usually set to somewhere in the media directory, so that the PDF can then be served statically. The value returned is the path to the file on disk. The logic of what its URL would be is handled by whatever function sets the dest_folder.

TextMate: Preview in Firefox without having to save document first?

Using TextMate:
Is it possible to assign a shortcut to preview/refresh the currently edited HTML document in, say, Firefox, without having to first hit Save?
I'm looking for the same functionality as TextMate's built-in Web Preview window, but I'd prefer an external browser instead of TextMate's. (Mainly in order to use a JavaScript console such as Firebug for instance).
Would it be possible to pipe the currently unsaved document through the shell and then preview in Firefox. And if so, is there anyone having a TextMate command for this, willing to share it?
Not trivially. The easiest way would be to write the current file to the temp dir, then launch that file.. but, this would break any relative links (images, scripts, CSS files)
Add a bundle:
Input: Entire Document
Output: Discard
Scope Selector: source.html
And the script:
#!/usr/bin/env python2.5
import os
import sys
import random
import tempfile
import subprocess
fname = os.environ.get("TM_FILEPATH", "Untitled %s.html" % random.randint(100, 1000))
fcontent = sys.stdin.read()
fd, name = tempfile.mkstemp()
print name
open(name, "w+").write(fcontent)
print subprocess.Popen(["open", "-a", "Firefox", name]).communicate()
As I said, that wont work with relative resource links, which is probably a big problem.. Another option is to modify the following line of code, from the exiting "Refresh Browsers" command:
osascript <<'APPLESCRIPT'
tell app "Firefox" to Get URL "JavaScript:window.location.reload();" inside window 1
APPLESCRIPT
Instead of having the javascript reload the page, it could clear it, and write the current document using a series of document.write() calls. The problem with this is you can't guarantee the current document is the one you want to replace.. Windows 1 could have changed to another site etc, especially with tabbed browsing..
Finally, an option that doesn't have a huge drawback: Use version control, particularly one of the "distributed" ones, where you don't have to send your changes to a remote server - git, mercurial, darcs, bazaar etc (all have TextMate integration also)
If your code is in version control, it doesn't matter if you save before previewing, you can also always go back to your last-commited version if you break something and lose the undo buffer.
Here's something that you can use and just replace "Safari" with "Firefox":
http://wiki.macromates.com/Main/Howtos#SafariPreview
Open the Bundle Editor (control + option + command + B)
Scroll to the HTML Bundle and expand the tree
Select "Open Document in Running Browser(s)"
Assign Activation Key Equivalent (shortcut)
Close the bundle editor
I don't think this is possible. You can however enable the 'atomic saves' option so every time you alt tab to Firefox your project is saved.
If you ever find a solution to have a proper Firefox live preview, let us know.