Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A hodgepodge of Py3 & style fixes.#10793

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
jklymak merged 1 commit intomatplotlib:masterfromanntzer:style3
Mar 15, 2018
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletionsexamples/user_interfaces/fourier_demo_wx_sgskip.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -180,8 +180,7 @@ def createPlots(self):
# This method creates the subplots, waveforms and labels.
# Later, when the waveforms or sliders are dragged, only the
# waveform data will be updated (not here, but below in setKnob).
if not hasattr(self, 'subplot1'):
self.subplot1, self.subplot2 = self.figure.subplots(2)
self.subplot1, self.subplot2 = self.figure.subplots(2)
x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value)
color = (1., 0., 0.)
self.lines += self.subplot1.plot(x1, y1, color=color, linewidth=2)
Expand Down
94 changes: 37 additions & 57 deletionslib/matplotlib/animation.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,22 +15,21 @@
# * Movies
# * Can blit be enabled for movies?
# * Need to consider event sources to allow clicking through multiple figures
from __future__ import (absolute_import, division, print_function,
unicode_literals)

import six
from six.moves import zip

import abc
import base64
import contextlib
from io import BytesIO
import itertools
import logging
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
from tempfile import TemporaryDirectory
import uuid

import numpy as np
Expand All@@ -39,11 +38,6 @@
JS_INCLUDE)
from matplotlib import cbook, rcParams, rcParamsDefault, rc_context

if six.PY2:
from base64 import encodestring as encodebytes
else:
from base64 import encodebytes


_log = logging.getLogger(__name__)

Expand DownExpand Up@@ -383,8 +377,7 @@ def grab_frame(self, **savefig_kwargs):
dpi=self.dpi, **savefig_kwargs)
except (RuntimeError, IOError) as e:
out, err = self._proc.communicate()
_log.info('MovieWriter -- Error '
'running proc:\n%s\n%s' % (out, err))
_log.info('MovieWriter -- Error running proc:\n%s\n%s', out, err)
raise IOError('Error saving animation to file (cause: {0}) '
'Stdout: {1} StdError: {2}. It may help to re-run '
'with logging level set to '
Expand DownExpand Up@@ -537,8 +530,7 @@ def grab_frame(self, **savefig_kwargs):

except RuntimeError:
out, err = self._proc.communicate()
_log.info('MovieWriter -- Error '
'running proc:\n%s\n%s' % (out, err))
_log.info('MovieWriter -- Error running proc:\n%s\n%s', out, err)
raise

def finish(self):
Expand DownExpand Up@@ -669,7 +661,7 @@ def _args(self):
# Logging is quieted because subprocess.PIPE has limited buffer size.
# If you have a lot of frames in your animation and set logging to
# DEBUG, you will have a buffer overrun.
if(_log.getEffectiveLevel() > logging.DEBUG):
if _log.getEffectiveLevel() > logging.DEBUG:
args += ['-loglevel', 'quiet']
args += ['-i', 'pipe:'] + self.output_args
return args
Expand DownExpand Up@@ -903,7 +895,7 @@ def grab_frame(self, **savefig_kwargs):
f = BytesIO()
self.fig.savefig(f, format=self.frame_format,
dpi=self.dpi, **savefig_kwargs)
imgdata64 = encodebytes(f.getvalue()).decode('ascii')
imgdata64 =base64.encodebytes(f.getvalue()).decode('ascii')
self._total_bytes += len(imgdata64)
if self._total_bytes >= self._bytes_limit:
_log.warning(
Expand DownExpand Up@@ -1336,35 +1328,30 @@ def to_html5_video(self, embed_limit=None):
# Convert from MB to bytes
embed_limit *= 1024 * 1024

#First write the video to a tempfile. Set delete to False
#so we can re-open to read binary data.
withtempfile.NamedTemporaryFile(suffix='.m4v',
delete=False) as f:
#Can't open a NamedTemporaryFile twice on Windows, so use a
#TemporaryDirectory instead.
withTemporaryDirectory() as tmpdir:
path = Path(tmpdir, "temp.m4v")
# We create a writer manually so that we can get the
# appropriate size for the tag
Writer = writers[rcParams['animation.writer']]
writer = Writer(codec='h264',
bitrate=rcParams['animation.bitrate'],
fps=1000. / self._interval)
self.save(f.name, writer=writer)

# Now open and base64 encode
with open(f.name, 'rb') as video:
vid64 = encodebytes(video.read())
vid_len = len(vid64)
if vid_len >= embed_limit:
_log.warning(
"Animation movie is %s bytes, exceeding the limit of "
"%s. If you're sure you want a large animation "
"embedded, set the animation.embed_limit rc parameter "
"to a larger value (in MB).", vid_len, embed_limit)
else:
self._base64_video = vid64.decode('ascii')
self._video_size = 'width="{}" height="{}"'.format(
*writer.frame_size)

# Now we can remove
os.remove(f.name)
self.save(str(path), writer=writer)
# Now open and base64 encode.
vid64 = base64.encodebytes(path.read_bytes())

if len(vid64) >= embed_limit:
_log.warning(
"Animation movie is %s bytes, exceeding the limit of %s. "
"If you're sure you want a large animation embedded, set "
"the animation.embed_limit rc parameter to a larger value "
"(in MB).", vid_len, embed_limit)
else:
self._base64_video = vid64.decode('ascii')
self._video_size = 'width="{}" height="{}"'.format(
*writer.frame_size)

# If we exceeded the size, this attribute won't exist
if hasattr(self, '_base64_video'):
Expand DownExpand Up@@ -1392,25 +1379,18 @@ def to_jshtml(self, fps=None, embed_frames=True, default_mode=None):
if default_mode is None:
default_mode = 'loop' if self.repeat else 'once'

if hasattr(self, "_html_representation"):
return self._html_representation
else:
# Can't open a second time while opened on windows. So we avoid
# deleting when closed, and delete manually later.
with tempfile.NamedTemporaryFile(suffix='.html',
delete=False) as f:
self.save(f.name, writer=HTMLWriter(fps=fps,
embed_frames=embed_frames,
default_mode=default_mode))
# Re-open and get content
with open(f.name) as fobj:
html = fobj.read()

# Now we can delete
os.remove(f.name)

self._html_representation = html
return html
if not hasattr(self, "_html_representation"):
# Can't open a NamedTemporaryFile twice on Windows, so use a
# TemporaryDirectory instead.
with TemporaryDirectory() as tmpdir:
path = Path(tmpdir, "temp.html")
writer = HTMLWriter(fps=fps,
embed_frames=embed_frames,
default_mode=default_mode)
self.save(str(path), writer=writer)
self._html_representation = path.read_text()

return self._html_representation

def _repr_html_(self):
'''IPython display hook for rendering.'''
Expand Down
14 changes: 5 additions & 9 deletionslib/matplotlib/axes/_base.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
from __future__ import (absolute_import, division, print_function,
unicode_literals)

from collections import OrderedDict

import six
Expand DownExpand Up@@ -836,12 +833,11 @@ def _update_transScale(self):
self.transScale.set(
mtransforms.blended_transform_factory(
self.xaxis.get_transform(), self.yaxis.get_transform()))
if hasattr(self, "lines"):
for line in self.lines:
try:
line._transformed_path.invalidate()
except AttributeError:
pass
for line in getattr(self, "lines", []): # Not set during init.
try:
line._transformed_path.invalidate()
except AttributeError:
pass

def get_position(self, original=False):
"""
Expand Down
6 changes: 1 addition & 5 deletionslib/matplotlib/backend_bases.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -32,9 +32,6 @@
The base class for the messaging area.
"""

from __future__ import (absolute_import, division, print_function,
unicode_literals)

import six

from contextlib import contextmanager
Expand DownExpand Up@@ -2062,9 +2059,8 @@ def _get_output_canvas(self, fmt):
If necessary, this function will switch to a registered backend that
supports the format.
"""
method_name = 'print_%s' % fmt
# Return the current canvas if it supports the requested format.
if hasattr(self,method_name):
if hasattr(self,'print_{}'.format(fmt)):
return self
# Return a default canvas for the requested format, if it exists.
canvas_class = get_registered_canvas_class(fmt)
Expand Down
25 changes: 7 additions & 18 deletionslib/matplotlib/backends/backend_webagg.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
"""
Displays Agg images in the browser, with interactivity
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)

# The WebAgg backend is divided into two modules:
#
Expand All@@ -13,12 +11,12 @@
# - `backend_webagg.py` contains a concrete implementation of a basic
# application, implemented with tornado.

import six

from contextlib import contextmanager
import errno
from io import BytesIO
import json
import os
from pathlib import Path
import random
import sys
import signal
Expand DownExpand Up@@ -63,14 +61,9 @@ class WebAggApplication(tornado.web.Application):

class FavIcon(tornado.web.RequestHandler):
def get(self):
image_path = os.path.join(
os.path.dirname(os.path.dirname(__file__)),
'mpl-data', 'images')

self.set_header('Content-Type', 'image/png')
with open(os.path.join(image_path,
'matplotlib.png'), 'rb') as fd:
self.write(fd.read())
image_path = Path(rcParams["datapath"], "images", "matplotlib.png")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I'm a little confused about pathlib now. Will this work on 3.5? I wouldn't pick on it, but the test coverage of this PR is not good, so...

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Yes, pathlib is 3.4+ (https://docs.python.org/3/library/pathlib.html) ({read,write}_{text,bytes} is 3.5+,https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_bytes).

What changed in 3.6 is that a bunch of stdlib functions that were previously only accepting string paths (open, os.path.*, etc.) started to also accept Path objects (https://www.python.org/dev/peps/pep-0519/), thus greatly decreasing the friction when using Path objects. But that's not something we can rely on (yet).

There are quite a few places where we use the old idiom (e.g.)with open(...) as file: ... = file.read() which could trivially be replaced byPath(...).read_text(); I didn't change them (the gain is admittedly limited in that case), but only those where we also do path manipulations (because working on Path objects forthat is much nicer than using os.path, IMO) (or where we do this multiple times in a row).

jklymak reacted with thumbs up emoji
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

OK, and I take it nothing trivial can be done to increase the test coverage?

Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Probably not? If that makes you really uncomfortable I can revert that change, just let me know.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

No, I trust you, just asking in case you felt guilty about it...

self.write(image_path.read_bytes())

class SingleFigurePage(tornado.web.RequestHandler):
def __init__(self, application, request, **kwargs):
Expand DownExpand Up@@ -135,7 +128,7 @@ def get(self, fignum, fmt):

self.set_header('Content-Type', mimetypes.get(fmt, 'binary'))

buff =six.BytesIO()
buff = BytesIO()
manager.canvas.figure.savefig(buff, format=fmt)
self.write(buff.getvalue())

Expand DownExpand Up@@ -304,13 +297,9 @@ def ipython_inline_display(figure):
if not webagg_server_thread.is_alive():
webagg_server_thread.start()

with open(os.path.join(
core.FigureManagerWebAgg.get_static_file_path(),
'ipython_inline_figure.html')) as fd:
tpl = fd.read()

fignum = figure.number

tpl = Path(core.FigureManagerWebAgg.get_static_file_path(),
"ipython_inline_figure.html").read_text()
t = tornado.template.Template(tpl)
return t.generate(
prefix=WebAggApplication.url_prefix,
Expand Down
7 changes: 2 additions & 5 deletionslib/matplotlib/cbook/__init__.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,6 @@
it imports matplotlib only at runtime.
"""

from __future__ import absolute_import, division, print_function

import six
from six.moves import xrange, zip
import bz2
Expand DownExpand Up@@ -470,7 +468,7 @@ def to_filehandle(fname, flag='rU', return_opened=False, encoding=None):
files is automatic, if the filename ends in .gz. *flag* is a
read/write flag for :func:`file`
"""
ifhasattr(os, "PathLike") and isinstance(fname, os.PathLike):
ifisinstance(fname, getattr(os, "PathLike", ())):
return to_filehandle(
os.fspath(fname),
flag=flag, return_opened=return_opened, encoding=encoding)
Expand DownExpand Up@@ -547,8 +545,7 @@ def get_sample_data(fname, asfileobj=True):
path = os.path.join(root, fname)

if asfileobj:
if (os.path.splitext(fname)[-1].lower() in
('.csv', '.xrc', '.txt')):
if os.path.splitext(fname)[-1].lower() in ['.csv', '.xrc', '.txt']:
mode = 'r'
else:
mode = 'rb'
Expand Down
9 changes: 2 additions & 7 deletionslib/matplotlib/tests/test_artist.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
from __future__ import absolute_import, division, print_function

import io
import warnings
from itertools import chain
import warnings

import numpy as np

Expand DownExpand Up@@ -270,10 +268,7 @@ class TestArtist(martist.Artist):
def set_f(self):
pass

func = TestArtist.set_f
if hasattr(func, '__func__'):
func = func.__func__ # python 2 must write via __func__.__doc__
func.__doc__ = """
TestArtist.set_f.__doc__ = """
Some text.

%s
Expand Down
13 changes: 2 additions & 11 deletionslib/matplotlib/tests/test_simplification.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
from __future__ import absolute_import, division, print_function

import base64
import io

import numpy as np
Expand DownExpand Up@@ -265,15 +264,7 @@ def test_start_with_moveto():
AABHqP//ej8AAD6z//+FPwAANb7//48/AAAsyf//lz8AACPU//+ePwAAGt///6M/AAAR6v//pj8A
AAj1//+nPwAA/////w=="""

import base64
if hasattr(base64, 'encodebytes'):
# Python 3 case
decodebytes = base64.decodebytes
else:
# Python 2 case
decodebytes = base64.decodestring

verts = np.fromstring(decodebytes(data), dtype='<i4')
verts = np.fromstring(base64.decodebytes(data), dtype='<i4')
verts = verts.reshape((len(verts) // 2, 2))
path = Path(verts)
segs = path.iter_segments(transforms.IdentityTransform(),
Expand Down
9 changes: 2 additions & 7 deletionstools/triage_tests.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -24,9 +24,8 @@
R: Reject test. Copy the expected result to the source tree.
"""

from __future__ import unicode_literals

import os
from pathlib import Path
import shutil
import sys

Expand DownExpand Up@@ -272,11 +271,7 @@ def same(self, a, b):
"""
Returns True if two files have the same content.
"""
with open(a, 'rb') as fd:
a_content = fd.read()
with open(b, 'rb') as fd:
b_content = fd.read()
return a_content == b_content
return Path(a).read_bytes() == Path(b).read_bytes()

def copy_file(self, a, b):
"""
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp