A pretty representation for Jupyter notebooks
487853
def _repr_html_(self):
        """"""
        fmt = ""
        fmt += "<table>"
        fmt += "<tr><th>Information</th><th>Blocks</th></tr>"
        fmt += "<tr><td>"
        fmt += "\n"
        fmt += "<table>\n"
        fmt += "<tr><th>{}</th><th>Values</th></tr>\n".format(type(self).__name__)
        row = "<tr><td>{}</td><td>{}</td></tr>\n"

        # now make a call on the object to get its attributes as a list of len 2 tuples
        for attr in self._get_attrs():
            try:
                fmt += row.format(attr[0], attr[2].format(*attr[1]))
            except:
                fmt += row.format(attr[0], attr[2].format(attr[1]))

        fmt += "</table>\n"
        fmt += "\n"
        fmt += "</td><td>"
        fmt += "\n"
        fmt += "<table>\n"
        row = "<tr><th>{}</th><th>{}</th><th>{}</th></tr>\n"
        fmt += row.format("Index", "Name", "Type")

        for i in range(self.n_blocks):
            data = self[i]
            fmt += row.format(i, self.get_block_name(i), type(data).__name__)

        fmt += "</table>\n"
        fmt += "\n"
        fmt += "</td></tr> </table>"
        return fmt
80276
def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
    """"""
    if root is None:
        root = {}
    root['vtkClass'] = 'vtkPolyData'
    container = root

    # Points
    points = dump_data_array(dataset_dir, data_dir,
                           dataset.GetPoints().GetData(), {}, compress)
    points['vtkClass'] = 'vtkPoints'
    container['points'] = points

    # Cells
    _cells = container

    # Verts
    if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
        _verts = dump_data_array(dataset_dir, data_dir,
                               dataset.GetVerts().GetData(), {}, compress)
        _cells['verts'] = _verts
        _cells['verts']['vtkClass'] = 'vtkCellArray'

    # Lines
    if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
        _lines = dump_data_array(dataset_dir, data_dir,
                               dataset.GetLines().GetData(), {}, compress)
        _cells['lines'] = _lines
        _cells['lines']['vtkClass'] = 'vtkCellArray'

    # Polys
    if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
        _polys = dump_data_array(dataset_dir, data_dir,
                               dataset.GetPolys().GetData(), {}, compress)
        _cells['polys'] = _polys
        _cells['polys']['vtkClass'] = 'vtkCellArray'

    # Strips
    if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
        _strips = dump_data_array(dataset_dir, data_dir,
                                dataset.GetStrips().GetData(), {}, compress)
        _cells['strips'] = _strips
        _cells['strips']['vtkClass'] = 'vtkCellArray'

    dump_color_array(dataset_dir, data_dir, color_array_info, container, compress)

    # PointData TCoords
    dump_t_coords(dataset_dir, data_dir, dataset, container, compress)
    # dump_normals(dataset_dir, data_dir, dataset, container, compress)

    return root
758545
def represent_list(self, data):
        
        node = super(Dumper, self).represent_list(data)
        length = len(data)
        if self.default_flow_style is None and length < 4:
            node.flow_style = True
        elif self.default_flow_style is None:
            node.flow_style = False
        return node
79514
def pretty_description(description, wrap_at=None, indent=0):
    
    if wrap_at is None or wrap_at < 0:
        width = console_width(default=79)
        if wrap_at is None:
            wrap_at = width
        else:
            wrap_at += width

    indent = ' ' * indent
    text_wrapper = textwrap.TextWrapper(
        width=wrap_at, replace_whitespace=False,
        initial_indent=indent, subsequent_indent=indent)
    new_desc = []
    for line in description.split('\n'):
        new_desc.append(line.replace('\n', '').strip())
    while not new_desc[0]:
        del new_desc[0]
    while not new_desc[-1]:
        del new_desc[-1]
    separators = [i for i, l in enumerate(new_desc) if not l]
    paragraphs = []
    if separators:
        start, end = 0, separators[0]
        paragraphs.append(new_desc[start:end])
        for i in range(len(separators) - 1):
            start = end + 1
            end = separators[i + 1]
            paragraphs.append(new_desc[start:end])
        paragraphs.append(new_desc[end + 1:])
        return '\n\n'.join(text_wrapper.fill(' '.join(p)) for p in paragraphs)
    return text_wrapper.fill(' '.join(new_desc))
173940
function prettyPrintVisitor (pp, spaces) {
  var visitor = {}
  visitor.pre = function (state) {
    state.result = ''
    state.depth = 0
  }
  visitor.visitor = {
    arrayEnter: function (val, state) {
      if (val.key !== undefined) {
        state.result += repeat(state.depth * spaces, ' ')
        if (val.parent.type === 'object') {
          state.result += "'" + val.key + "': "
        }
      }
      if (val.isCircularRef) {
        state.result += '[Circular]\n'
        return
      } else if (val.length === 0) {
        state.result += '[]\n'
        return
      }
      state.result += '[\n'
      state.depth += 1
    },
    arrayExit: function (val, state) {
      if (val.length === 0 || val.isCircularRef) { return }
      state.depth -= 1
      state.result += repeat(state.depth * spaces, ' ') + ']\n'
    },
    objectEnter: function (val, state) {
      if (val.key !== undefined) {
        state.result += repeat(state.depth * spaces, ' ')
        if (val.parent.type === 'object') {
          state.result += "'" + val.key + "': "
        }
      }
      if (val.isCircularRef) {
        state.result += '[Circular]\n'
        return
      } else if (val.length === 0) {
        state.result += '{}\n'
        return
      }
      state.result += '{\n'
      state.depth += 1
    },
    objectExit: function (val, state) {
      if (val.length === 0 || val.isCircularRef) { return }
      state.depth -= 1
      state.result += repeat(state.depth * spaces, ' ') + '}\n'
    },
    stringEnter: function (val, state) {
      if (val.parent === null) {
        state.result += pp(val.value).slice(1, -1)
        return
      }
      state.result += repeat(state.depth * spaces, ' ')
      if (val.parent.type === 'object') {
        state.result += "'" + val.key + "': "
      }
      state.result += pp(val.value) + '\n'
    },
    otherEnter: function (val, state) {
      state.result += repeat(state.depth * spaces, ' ')
      if (val.key !== undefined && val.parent.type === 'object') {
        state.result += "'" + val.key + "': "
      }
      state.result += pp(val.value) + '\n'
    }
  }
  visitor.post = function (state) {
    visitor.result = state.result.trim()
  }
  return visitor
}
60726
def separator(self):
        
        cells = dict([(column, "-" * self.column_widths[column]) for column in self.columns])
        return ColorRow(self, **cells)
869443
def as_html(self, max_rows=0):
        """"""
        if not max_rows or max_rows > self.num_rows:
            max_rows = self.num_rows
        omitted = max(0, self.num_rows - max_rows)
        labels = self.labels
        lines = [
            (0, '<table border="1" class="dataframe">'),
            (1, '<thead>'),
            (2, '<tr>'),
            (3, ' '.join('<th>' + label + '</th>' for label in labels)),
            (2, '</tr>'),
            (1, '</thead>'),
            (1, '<tbody>'),
        ]
        fmts = self._get_column_formatters(max_rows, True)
        for row in itertools.islice(self.rows, max_rows):
            lines += [
                (2, '<tr>'),
                (3, ' '.join('<td>' + fmt(v, label=False) + '</td>' for
                    v, fmt in zip(row, fmts))),
                (2, '</tr>'),
            ]
        lines.append((1, '</tbody>'))
        lines.append((0, '</table>'))
        if omitted:
            lines.append((0, '<p>... ({} rows omitted)</p>'.format(omitted)))
        return '\n'.join(4 * indent * ' ' + text for indent, text in lines)
478997
def _repr_html_(self):
        
        if self.size < 10:
            return np.ndarray.__repr__(self)
        attribs = self.__dict__.copy()

        # Header.
        row1 = '<tr><th style="text-align:center;" colspan="2">{} [{{}}]</th></tr>'
        rows = row1.format(attribs.pop('mnemonic'))
        rows = rows.format(attribs.pop('units', '&ndash;'))
        row2 = '<tr><td style="text-align:center;" colspan="2">{:.4f} : {:.4f} : {:.4f}</td></tr>'
        rows += row2.format(attribs.pop('start'), self.stop, attribs.pop('step'))

        # Curve attributes.
        s = '<tr><td><strong>{k}</strong></td><td>{v}</td></tr>'
        for k, v in attribs.items():
            rows += s.format(k=k, v=v)

        # Curve stats.
        rows += '<tr><th style="border-top: 2px solid #000; text-align:center;" colspan="2"><strong>Stats</strong></th></tr>'
        stats = self.get_stats()
        s = '<tr><td><strong>samples (NaNs)</strong></td><td>{samples} ({nulls})</td></tr>'
        s += '<tr><td><strong><sub>min</sub> mean <sup>max</sup></strong></td>'
        s += '<td><sub>{min:.2f}</sub> {mean:.3f} <sup>{max:.2f}</sup></td></tr>'
        rows += s.format(**stats)

        # Curve preview.
        s = '<tr><th style="border-top: 2px solid #000;">Depth</th><th style="border-top: 2px solid #000;">Value</th></tr>'
        rows += s.format(self.start, self[0])
        s = '<tr><td>{:.4f}</td><td>{:.4f}</td></tr>'
        for depth, value in zip(self.basis[:3], self[:3]):
            rows += s.format(depth, value)
        rows += '<tr><td>⋮</td><td>⋮</td></tr>'
        for depth, value in zip(self.basis[-3:], self[-3:]):
            rows += s.format(depth, value)

        # Footer.
        # ...

        # End.
        html = '<table>{}</table>'.format(rows)
        return html
772945
def pretty_view(graph, oriented=False, construction=False,
                graphviz_prog=DEFAULT_GRAPHVIZ_PROG):
    """"""
    layout = create_layout(graph, graphviz_prog=graphviz_prog)
    matrix_view = defaultdict(lambda: ' ')

    # Add the edge to the view

    # print('GRAPH EDGES:', tuple(graph.edges()))
    # print('LAYOUT:', layout)

    edges = ((layout[source], layout[target])
             for source, target in graph.edges())
    # print('EDGES:', tuple(edges))

    for source, target in edges:
        previous_edge_char = None
        previous_position = source
        while source != target:
            for is_dir, transform, edge_char in DIRECTIONS:
                first_loop = previous_edge_char is None
                if is_dir(source, target):
                    previous_source = source
                    source = transform(source)
                    if not first_loop:  # first loop: no previous char
                        char = CHARACTER[previous_edge_char, edge_char]
                        if not isinstance(char, str):
                            char = char.value
                        matrix_view[previous_source] = char
                        if construction:
                            old = defaultdict(lambda: ' ', matrix_view)
                            yield view.build(matrix_view)
                        assert isinstance(matrix_view[previous_source], str)
                    if source != target:
                        previous_edge_char = edge_char
                    previous_position = previous_source
                    break  # for loop ; don't test the remain directions

        if oriented:
            matrix_view[previous_position] = ORIENTATION[previous_edge_char, edge_char]
        if construction:
            yield view.build(matrix_view)

    # mark the place where nodes labels will be added
    # for node, coords in layout.items():
        # matrix_view[coords] = node[0]
    # Add the node labels to the view
    # matrix_view = view.clean(matrix_view)
    for node, (x, y) in layout.items():
        if len(node) == 1:
            matrix_view[x, y] = node
            continue
        row_min, row_max = (view.previous_unwrittable_on_row(matrix_view, (x, y)),
                            view.next_unwrittable_on_row(matrix_view, (x, y)))
        col_min, col_max = (view.previous_unwrittable_on_col(matrix_view, (x, y)),
                              view.next_unwrittable_on_col(matrix_view, (x, y)))
        # print('NODE ' + node + ':',
              # '→row: [{};{}]'.format(row_min, row_max).ljust(20),
              # '↓col: [{};{}]'.format(col_min, col_max))
        print_coords = [itertools.count(x), itertools.cycle((y,))]
        if row_min is None:  # write left to right, end at (x, y)
            if row_max is None or row_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords[0] = tuple(
                x - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            )
            # print('DEBUG 1:', y, len(node), print_coords[0])
        elif row_max is None:  # write left to right, beginning at (x, y)
            if row_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords[0] = tuple(
                x + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            )
            # print('DEBUG 2:', print_coords[0])
        elif (row_max - row_min) > len(node) + 1:  # write left to right, if enough place
            print_coords[0] = tuple(
                x + offset
                for offset in range(len(node))
            )
            # print('DEBUG 3:', print_coords[0])

        elif col_min is None:  # write up to down, end at (x, y)
            if col_max is None or col_max > (x + len(node) / 2):  # enough space at the right
                factor = 2
            else:
                factor = 1
            print_coords = (itertools.cycle((x,)), tuple(
                y - (len(node) // factor) + offset + 1
                for offset in range(len(node))
            ))
            # print('DEBUG 4:', y, len(node), print_coords[1])
        elif col_max is None:  # write up to down, beginning at (x, y)
            if col_min < (x - len(node) / 2):  # enough space at the left
                factor = 1
            else:
                factor = 0
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset - (len(node) // 2) * factor
                for offset in range(len(node))
            ))
            # print('DEBUG 5:', print_coords[1])
        elif (col_max - col_min) > len(node) + 1:  # write up to down, if enough place
            print_coords = (itertools.cycle((x,)), tuple(
                y + offset
                for offset in range(len(node))
            ))
            # print('DEBUG 6:', print_coords[1])
        else:  # not enough space
            if (row_max - row_min) > (col_max - col_min):
                # more space on Y axis
                node = node[:row_max - row_min]  # cut the node
                print_coords = (itertools.cycle((x,)), tuple(
                    x + offset
                    for offset in range(len(node))
                ))
                # print('DEBUG 7:', print_coords[1])
            else:
                # more space on X axis
                node = node[:col_max - col_min]  # cut the node
                print_coords[0] = tuple(
                    x + offset
                    for offset in range(len(node))
                )
                # print('DEBUG 8:', print_coords[0])

        for letter, i, j in zip(node, *print_coords):
            matrix_view[i, j] = letter




    if construction:
        yield view.build(matrix_view)
    else:
        yield from view.build(matrix_view)
1318701
def _repr_pretty_(self, p, cycle):
        
        if cycle:
            p.text('{...}')
        else:
            keys = self.keys()

            if keys:
                delim_start = '[{'
                delim_end = '}]'

                wid_max_max = self._repr_max_width
                wid_max = max([len(k) for k in keys])
                wid_max = min([wid_max, wid_max_max])
                key_template = '{{:{:d}s}}: '.format(wid_max)

                with p.group(len(delim_start), delim_start, delim_end):
                    # Loop over item keys
                    for idx, key in p._enumerate(keys):
                        if idx:
                            p.text(',')
                            p.breakable()

                        p.text(key_template.format(key))
                        p.pretty(self[key])
            else:
                p.text('{}')
1102653
def pretty_list(list)
      center = nil
      list.map.with_index do |c, idx|
        next center = Helper.color('[self]', sev: :bin) if c == @base

        color_c = Helper.color(format('%#x', c))
        fwd = fd_of(c)
        next "#{color_c}(invalid)" if fwd.nil? # invalid c

        bck = bk_of(c)
        if center.nil? # bk side
          format('%s%s', color_c, fwd == list[idx + 1] ? nil : Helper.color(format('(%#x)', fwd)))
        else # fd side
          format('%s%s', bck == list[idx - 1] ? nil : Helper.color(format('(%#x)', bck)), color_c)
        end
      end.join(' === ')
    end
91444
def pprint(self):
        """"""

        items = sorted(self.items())
        return u"\n".join(u"%s=%s" % (k, v.pprint()) for k, v in items)
1146384
def convert_notebook(self, name):
        """"""

        #subprocess.call(["jupyter","nbconvert","--to","python",
        #                self.get_path("%s.ipynb"%name)])
        exporter = nbconvert.exporters.python.PythonExporter()
        relative_path = self.convert_path(name)
        file_path = self.get_path("%s.ipynb"%relative_path)
        code = exporter.from_filename(file_path)[0]
        self.write_code(name, code)
        self.clean_code(name, [])
1012480
def _ipython_display_(self, **kwargs):
        """"""

        plaintext = repr(self)
        if len(plaintext) > 110:
            plaintext = plaintext[:110] + '…'
        data = {
            'text/plain': plaintext,
        }
        if self._view_name is not None:
            # The 'application/vnd.jupyter.widget-view+json' mimetype has not been registered yet.
            # See the registration process and naming convention at
            # http://tools.ietf.org/html/rfc6838
            # and the currently registered mimetypes at
            # http://www.iana.org/assignments/media-types/media-types.xhtml.
            data['application/vnd.jupyter.widget-view+json'] = {
                'version_major': 2,
                'version_minor': 0,
                'model_id': self._model_id
            }
        display(data, raw=True)

        if self._view_name is not None:
            self._handle_displayed(**kwargs)
370409
def pprint(data):
    
    pretty = json.dumps(data, sort_keys=True, indent=4, separators=(",", ": "))
    html = pretty.replace(" ", "&nbsp;").replace("\n", "<br>")
    return mark_safe("<code>%s</code>" % html)
1312992
def jupytext(args=None):
    """"""
    args = parse_jupytext_args(args)

    def log(text):
        if not args.quiet:
            sys.stdout.write(text + '\n')

    if args.version:
        log(__version__)
        return 0

    if args.pre_commit:
        if args.notebooks:
            raise ValueError('--pre-commit takes notebooks from the git index. Do not pass any notebook here.')
        args.notebooks = notebooks_in_git_index(args.input_format)
        log('[jupytext] Notebooks in git index are:')
        for nb_file in args.notebooks:
            log(nb_file)

    def writef_git_add(notebook_, nb_file_, fmt_):
        writef(notebook_, nb_file_, fmt_)
        if args.pre_commit:
            system('git', 'add', nb_file_)

    # Read notebook from stdin
    if not args.notebooks:
        if not args.pre_commit:
            args.notebooks = ['-']

    if args.set_formats is not None:
        # Replace empty string with None
        args.update_metadata = recursive_update(args.update_metadata,
                                                {'jupytext': {'formats': args.set_formats or None}})

    if args.paired_paths:
        if len(args.notebooks) != 1:
            raise ValueError('--paired-paths applies to a single notebook')
        print_paired_paths(args.notebooks[0], args.input_format)
        return 1

    if not args.to and not args.output and not args.sync \
            and not args.pipe and not args.check \
            and not args.test and not args.test_strict \
            and not args.update_metadata:
        raise ValueError('Please select an action')

    if args.output and len(args.notebooks) != 1:
        raise ValueError('Please input a single notebook when using --output')

    if args.input_format:
        args.input_format = long_form_one_format(args.input_format)

    if args.to:
        args.to = long_form_one_format(args.to)
        set_format_options(args.to, args.format_options)

    # Main loop
    round_trip_conversion_errors = 0

    # Wildcard extension on Windows #202
    notebooks = []
    for pattern in args.notebooks:
        if '*' in pattern or '?' in pattern:
            notebooks.extend(glob.glob(pattern))
        else:
            notebooks.append(pattern)

    for nb_file in notebooks:
        if nb_file == '-' and args.sync:
            raise ValueError('Cannot sync a notebook on stdin')

        nb_dest = args.output or (None if not args.to
                                  else ('-' if nb_file == '-' else
                                        full_path(base_path(nb_file, args.input_format), args.to)))

        # Just acting on metadata / pipe => save in place
        if not nb_dest and not args.sync:
            nb_dest = nb_file

        if nb_dest == '-':
            args.quiet = True

        # I. ### Read the notebook ###
        fmt = copy(args.input_format) or {}
        set_format_options(fmt, args.format_options)
        log('[jupytext] Reading {}{}'.format(
            nb_file if nb_file != '-' else 'stdin',
            ' in format {}'.format(short_form_one_format(fmt)) if 'extension' in fmt else ''))

        notebook = readf(nb_file, fmt)
        if not fmt:
            text_representation = notebook.metadata.get('jupytext', {}).get('text_representation', {})
            ext = os.path.splitext(nb_file)[1]
            if text_representation.get('extension') == ext:
                fmt = {key: text_representation[key] for key in text_representation if
                       key in ['extension', 'format_name']}
            elif ext:
                fmt = {'extension': ext}

        # Update the metadata
        if args.update_metadata:
            log('[jupytext] Updating notebook metadata with {}'.format(args.update_metadata))
            # Are we updating a text file that has a metadata filter? #212
            if fmt['extension'] != '.ipynb' and \
                    notebook.metadata.get('jupytext', {}).get('notebook_metadata_filter') == '-all':
                notebook.metadata.get('jupytext', {}).pop('notebook_metadata_filter')
            recursive_update(notebook.metadata, args.update_metadata)

        # Read paired notebooks
        if args.sync:
            set_prefix_and_suffix(fmt, notebook, nb_file)
            notebook, inputs_nb_file, outputs_nb_file = load_paired_notebook(notebook, fmt, nb_file, log)

        # II. ### Apply commands onto the notebook ###
        # Pipe the notebook into the desired commands
        for cmd in args.pipe or []:
            notebook = pipe_notebook(notebook, cmd, args.pipe_fmt)

        # and/or test the desired commands onto the notebook
        for cmd in args.check or []:
            pipe_notebook(notebook, cmd, args.pipe_fmt, update=False)

        # III. ### Possible actions ###
        modified = args.update_metadata or args.pipe
        # a. Test round trip conversion
        if args.test or args.test_strict:
            try:
                test_round_trip_conversion(notebook, args.to,
                                           update=args.update,
                                           allow_expected_differences=not args.test_strict,
                                           stop_on_first_error=args.stop_on_first_error)
            except NotebookDifference as err:
                round_trip_conversion_errors += 1
                sys.stdout.write('{}: {}'.format(nb_file, str(err)))
            continue

        # b. Output to the desired file or format
        if nb_dest:
            if nb_dest == nb_file and not args.to:
                args.to = fmt

            # Test consistency between dest name and output format
            if args.to and nb_dest != '-':
                base_path(nb_dest, args.to)

            # Describe what jupytext is doing
            if os.path.isfile(nb_dest) and args.update:
                if not nb_dest.endswith('.ipynb'):
                    raise ValueError('--update is only for ipynb files')
                action = ' (destination file updated)'
                check_file_version(notebook, nb_file, nb_dest)
                combine_inputs_with_outputs(notebook, readf(nb_dest), fmt)
            elif os.path.isfile(nb_dest):
                action = ' (destination file replaced)'
            else:
                action = ''

            log('[jupytext] Writing {nb_dest}{format}{action}'
                .format(nb_dest=nb_dest,
                        format=' in format ' + short_form_one_format(
                            args.to) if args.to and 'format_name' in args.to else '',
                        action=action))
            writef_git_add(notebook, nb_dest, args.to)

        # c. Synchronize paired notebooks
        if args.sync:
            # Also update the original notebook if the notebook was modified
            if modified:
                inputs_nb_file = outputs_nb_file = None
            formats = notebook.metadata['jupytext']['formats']

            for ipynb in [True, False]:
                # Write first format last so that it is the most recent file
                for alt_path, alt_fmt in paired_paths(nb_file, fmt, formats)[::-1]:
                    # Write ipynb first for compatibility with our contents manager
                    if alt_path.endswith('.ipynb') != ipynb:
                        continue
                    # Do not write the ipynb file if it was not modified
                    # But, always write text representations to make sure they are the most recent
                    if alt_path == inputs_nb_file and alt_path == outputs_nb_file:
                        continue
                    log("[jupytext] Updating '{}'".format(alt_path))
                    writef_git_add(notebook, alt_path, alt_fmt)

    return round_trip_conversion_errors
461130
def md_to_notebook(text):
    """"""
    tmp_file = tempfile.NamedTemporaryFile(delete=False)
    tmp_file.write(text.encode('utf-8'))
    tmp_file.close()

    pandoc(u'--from markdown --to ipynb -s --atx-headers --wrap=preserve --preserve-tabs', tmp_file.name, tmp_file.name)

    with open(tmp_file.name, encoding='utf-8') as opened_file:
        notebook = ipynb_reads(opened_file.read(), as_version=4)
    os.unlink(tmp_file.name)

    return notebook