Python IPython.display 模块,display() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用IPython.display.display()

项目:altair_widgets    作者:altair-viz    | 项目源码 | 文件源码
def interact_with(df, ndims=3, **kwargs):
    """
    Interactively view a DataFrame.

    Parameters
    ----------
    df : DataFrame
        The DataFrame to interact with

    ndims : int, optional
        The number of dimensions wished to encode at start (the number of rows
        with encoding/data/function/data_type).

    Notes
    -----
    In the Jupyter notebook, display a widget to allow you to selectively plot
    columns to plot/encode/etc.

    Use a smaller value if ndims if less dimensions and controls are desired.

    """
    return Interact(df, ndims=ndims, **kwargs)
项目:altair_widgets    作者:altair-viz    | 项目源码 | 文件源码
def __init__(self, df, ndims=3, show=True):
        if not isinstance(df, pd.core.frame.DataFrame):
            raise ValueError('Interact takes a DataFrame as input')
        columns = [None] + _get_columns(df)
        self.columns = columns
        encodings = _get_encodings()
        self.df = df
        encodings = [{'encoding': encoding}
                     for encoding in encodings[:ndims]]
        self.settings = {'mark': {'mark': 'mark_point'},
                         'encodings': encodings}

        self.controller = self._generate_controller(ndims)
        self.show = show
        if self.show:
            display(self.controller)

        self.plot(show=show)
项目:magenta    作者:tensorflow    | 项目源码 | 文件源码
def play_sequence(sequence,
                  synth=midi_synth.synthesize,
                  sample_rate=_DEFAULT_SAMPLE_RATE,
                  colab_ephemeral=True,
                  **synth_args):
  """Creates an interactive player for a synthesized note sequence.

  This function should only be called from a Jupyter or Colab notebook.

  Args:
    sequence: A music_pb2.NoteSequence to synthesize and play.
    synth: A synthesis function that takes a sequence and sample rate as input.
    sample_rate: The sample rate at which to synthesize.
    colab_ephemeral: If set to True, the widget will be ephemeral in Colab, and
      disappear on reload (and it won't be counted against realtime document
      size).
    **synth_args: Additional keyword arguments to pass to the synth function.
  """
  array_of_floats = synth(sequence, sample_rate=sample_rate, **synth_args)

  try:
    import google.colab  # pylint: disable=unused-import,unused-variable,g-import-not-at-top
    colab_play(array_of_floats, sample_rate, colab_ephemeral)
  except ImportError:
    display.display(display.Audio(array_of_floats, rate=sample_rate))
项目:Optimus    作者:ironmussa    | 项目源码 | 文件源码
def general_description(self):
        # General data description:
        # Filename:
        if self._path_file is None:
            file_name = "file with no path"
        else:
            file_name = self._path_file.split('/')[-1]
        # Counting the number of columns:
        row_number = self._df.count()
        # Counting the number of rows:
        col_number = len(self._df.columns)
        # Writting General Description table:
        temp_obj = GeneralDescripTable(file_name, col_number, row_number)
        display(temp_obj)

        data_types = len(set([x[1] for x in self._df.dtypes]))

        return self._create_dict(["filename", "size", "columns", "rows", "datatypes"],
                                 [file_name, 500, col_number, row_number, data_types])

    # Funtion to analize column datatypes, it also plot proportion datatypes and histograms:
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def __init__(self, mol, style=None, display=False, width='100%', height='400px',
                 **kwargs):
        kwargs.update(width=width, height=height)
        super().__init__(**kwargs)
        self.height = in_pixels(height)
        self.width = in_pixels(width)
        self.atom_colors = {}

        # current state
        self.atom_highlights = []
        self._axis_objects = None
        self._colored_as = {}

        self.add_molecule(mol)
        if style is None:
            self.autostyle()
        else:
            self.set_style(style)

        if display:
            dsp.display(self)
项目:notebook-molecular-visualization    作者:Autodesk    | 项目源码 | 文件源码
def set_positions(self, positions=None):
        """ Set positions of atoms in the 3D display

        Args:
            positions (Matrix[length, shape=(*,3)]): positions to set atoms to - optional.
               If not provided, positions are taken from current positions of the molecule.

        Returns:

        """
        if positions is None:
            pos = self.mol.positions
        else:
            pos = positions

        self.positions = pos.value_in(u.angstrom).tolist()
        self._update_clipping(np.abs(pos.value_in(self.DISTANCE_UNITS)).max())
项目:ipython-IDV    作者:Unidata    | 项目源码 | 文件源码
def make_movie(line, cell=None):
    toks = shlex.split(line)
    skip = 0
    publish = False
    display_id = None
    caption = None
    cptr = None;
    for i in range(len(toks)):
        if skip > 0:
            skip = skip-1
            continue
        tok = toks[i]
        if tok == "-publish":
            publish = True
        elif tok == "-caption":
            skip = 1
            caption = toks[i+1]
        elif tok == "-capture":
            skip = 1
            cptr = toks[i+1]
        elif tok == "-display":
            skip = 1
            display_id = toks[i+1]

    return Idv.make_movie(publish, caption, display_id=display_id, capture=cptr)
项目:ipython-IDV    作者:Unidata    | 项目源码 | 文件源码
def view_url_clicked(b):
        DrilsdownUI.do_display(HTML("<a target=ramadda href=" + b.url + ">" + b.name + "</a>"))
        display(IFrame(src=b.url, width=800, height=400))
项目:ipython-IDV    作者:Unidata    | 项目源码 | 文件源码
def publish_notebook(extra=None):
        # If we do this then the Javascript object shows up in the notebook
        # js = Javascript('IPython.notebook.save_checkpoint();')
        # display(js)
        file = Idv.getname()
        if file is None:
            return
        isl = '<isl><publish file="' + file + '"/></isl>'
        DrilsdownUI.status("Make sure you do 'File->Save and Checkpoint'. Check your IDV to publish the file")
        result = Idv.run_isl(isl);
        if not result.ok():
            print("Publication failed")
            return
        if result.get_results().strip()!="":
            print("Publication successful")
            print("URL: " + result.get_results())
            return
        print("Publication failed")
项目:ipython-IDV    作者:Unidata    | 项目源码 | 文件源码
def export_data(filename=None, display_id=None, load_data = False):
        DrilsdownUI.status("Exporting data ...")
        extra = ""
        if display_id is not None:
            extra += ' display="' + display_id + '" '
        if filename is  None:
            f = NamedTemporaryFile(suffix='.gif', delete=False) 
            filename = f.name;
        isl = '<isl><export file="' + f.name + '"' \
            + extra + '/></isl>'
        result = Idv.run_isl(isl)
        if not result.ok():
            return;
        if load_data:
            placeholder = false;
            #                return load_data(filename);
            # img = '<img src="data:image/gif;base64,{0}">'
        DrilsdownUI.status("data exported to: " + filename)
项目:ipython-IDV    作者:Unidata    | 项目源码 | 文件源码
def do_list(self, dir=None, display=False, label="Entries"):
        """make a list of RamaddaEntry objects that are children of the given entryId"""
        if dir is None:
            dir = self.dir
        files = os.listdir(dir)
        entries = []
        prefix = dir+"/"
        if prefix == "./":
            prefix = ""
        for i in range(len(files)):
            if files[i].startswith(".") is not True:
                entries.append(FileEntry(self, prefix + files[i]))

        if display:
            self.display_entries(label, entries)
        else:
            return entries
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def update_display(obj, *, display_id, **kwargs):
    """Update an existing display by id

    Parameters
    ----------

    obj:
        The object with which to update the display
    display_id: keyword-only
        The id of the display to update

    See Also
    --------

    :func:`display`
    """
    kwargs['update'] = True
    display(obj, display_id=display_id, **kwargs)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def display_markdown(*objs, **kwargs):
    """Displays the Markdown representation of an object.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display, or if raw=True raw markdown data to
        display.
    raw : bool
        Are the data objects raw data or Python objects that need to be
        formatted before display? [default: False]
    metadata : dict (optional)
        Metadata to be associated with the specific mimetype output.
    """

    _display_mimetype('text/markdown', objs, **kwargs)
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def display_pdf(*objs, **kwargs):
    """Display the PDF representation of an object.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display, or if raw=True raw javascript data to
        display.
    raw : bool
        Are the data objects raw data or Python objects that need to be
        formatted before display? [default: False]
    metadata : dict (optional)
        Metadata to be associated with the specific mimetype output.
    """
    _display_mimetype('application/pdf', objs, **kwargs)


#-----------------------------------------------------------------------------
# Smart classes
#-----------------------------------------------------------------------------
项目:leetcode    作者:thomasyimgit    | 项目源码 | 文件源码
def __init__(self, data=None, url=None, filename=None, expanded=False, metadata=None, **kwargs):
        """Create a JSON display object given raw data.

        Parameters
        ----------
        data : dict or list
            JSON data to display. Not an already-serialized JSON string.
            Scalar types (None, number, string) are not allowed, only dict
            or list containers.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        expanded : boolean
            Metadata to control whether a JSON display component is expanded.
        metadata: dict
            Specify extra metadata to attach to the json display object.
        """
        self.metadata = {'expanded': expanded}
        if metadata:
            self.metadata.update(metadata)
        if kwargs:
            self.metadata.update(kwargs)
        super(JSON, self).__init__(data=data, url=url, filename=filename)
项目:chxanalys    作者:yugangzhang    | 项目源码 | 文件源码
def displayResult(self):
        fig = plt.figure(101)
        plt.subplot(221)
        plt.imshow(np.abs(self.reconstruction),origin='lower')
        plt.draw()
        plt.title('Reconstruction Magnitude')
        plt.subplot(222)
        plt.imshow(np.angle(self.reconstruction),origin='lower')
        plt.draw()
        plt.title('Reconstruction Phase')
        plt.subplot(223)
        plt.imshow(np.abs(self.aperture),origin='lower')
        plt.title("Aperture Magnitude")
        plt.draw()
        plt.subplot(224)
        plt.imshow(np.angle(self.aperture),origin='lower')
        plt.title("Aperture Phase")
        plt.draw()
        fig.canvas.draw()


        #fig.tight_layout()
        # display.display(fig)
        # display.clear_output(wait=True)
        # time.sleep(.00001)
项目:paramnb    作者:ioam    | 项目源码 | 文件源码
def run_next_cells(n):
    if n=='all':
        n = 'NaN'
    elif n<1:
        return

    js_code = """
       var num = {0};
       var run = false;
       var current = $(this)[0];
       $.each(IPython.notebook.get_cells(), function (idx, cell) {{
          if ((cell.output_area === current) && !run) {{
             run = true;
          }} else if ((cell.cell_type == 'code') && !(num < 1) && run) {{
             cell.execute();
             num = num - 1;
          }}
       }});
    """.format(n)

    display(Javascript(js_code))
项目:berrl    作者:murphy214    | 项目源码 | 文件源码
def make_legend(title,colors,labels):
    colorhashs=[]
    for row in colors:
        colorhashs.append(get_colors(row))
    return '''
<div id='legend' style='display:none;'>
  <strong>%s</strong>
  <nav class='legend clearfix'>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <span style='background:%s;'></span>
    <label>%s</label>
    <label>%s</label>
    <label>%s</label>
    <label>%s</label>
    <label>%s</label>
    <small>Source: <a href="https://github.com/murphy214/berrl">Made using Berrl</a></small>
</div>
''' % (title,colorhashs[0],colorhashs[1],colorhashs[2],colorhashs[3],colorhashs[4],labels[0],labels[1],labels[2],labels[3],labels[4])


# returns the blocks of color backgrounds for a given list of colors
项目:berrl    作者:murphy214    | 项目源码 | 文件源码
def make_top2(rangelist):
    widthpercentage = 100.0 / float(len(rangelist))
    return '''<style>
.legend label,
.legend span {
  display:block;
  float:left;
  height:15px;
  width:xx%;
  text-align:center;
  font-size:9px;
  color:#808080;
  }
</style>'''.replace('xx',str(widthpercentage))



# generates 5 labels and then inserts dummy spaces in each label value not used
# may eventually accept a number of labels right now assumes 5 and returns adequate dummy labels for inbetween values
项目:berrl    作者:murphy214    | 项目源码 | 文件源码
def make_top2(rangelist):
    widthpercentage = 100.0 / float(len(rangelist))
    return '''<style>
.legend label,
.legend span {
  display:block;
  float:left;
  height:15px;
  width:xx%;
  text-align:center;
  font-size:9px;
  color:#808080;
  }
</style>'''.replace('xx',str(widthpercentage))



# generates 5 labels and then inserts dummy spaces in each label value not used
# may eventually accept a number of labels right now assumes 5 and returns adequate dummy labels for inbetween values
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def show(self):
        r"""This will send any existing plots to the IPython notebook.

        If yt is being run from within an IPython session, and it is able to
        determine this, this function will send any existing plots to the
        notebook for display.

        If yt can't determine if it's inside an IPython session, it will raise
        YTNotInsideNotebook.

        Examples
        --------

        >>> import yt
        >>> ds = yt.load('IsolatedGalaxy/galaxy0030/galaxy0030')
        >>> pp = ProfilePlot(ds.all_data(), 'density', 'temperature')
        >>> pp.show()

        """
        if "__IPYTHON__" in dir(builtins):
            from IPython.display import display
            display(self)
        else:
            raise YTNotInsideNotebook
项目:yt    作者:yt-project    | 项目源码 | 文件源码
def _repr_html_(self):
        """Return an html representation of the plot object. Will display as a
        png for each WindowPlotMPL instance in self.plots"""
        ret = ''
        unique = set(self.plots.values())
        if len(unique) < len(self.plots):
            iters = izip(range(len(unique)), sorted(unique))
        else:
            iters = iteritems(self.plots)
        for uid, plot in iters:
            with matplotlib_style_context():
                img = plot._repr_png_()
            img = base64.b64encode(img).decode()
            ret += r'<img style="max-width:100%%;max-height:100%%;" ' \
                   r'src="data:image/png;base64,{0}"><br>'.format(img)
        return ret
项目:lddmm-ot    作者:jeanfeydy    | 项目源码 | 文件源码
def __init__(self, mode = 'whole sphere', resolution = (45, 90) ):
        "mode = 'whole sphere' | 'spherical blackboard'"
        self.mode = mode
        if self.mode == 'whole sphere' :
            thetas = linspace(0,   pi, resolution[0] + 1)
            phis   = linspace(-pi, pi, resolution[1] + 1)
        elif self.mode == 'spherical blackboard' :
            thetas = linspace(0,.5*pi, resolution[0] + 1)
            phis   = linspace(-pi/3, 0, resolution[1] + 1)

        (self.theta_grid, self.phi_grid) = meshgrid(thetas, phis)
        self.theta_centers = (self.theta_grid[0:-1,0:-1] + self.theta_grid[0:-1,1:] + self.theta_grid[1:,0:-1] + self.theta_grid[1:,1:]) / 4.
        self.phi_centers   = (self.phi_grid[0:-1,0:-1]   + self.phi_grid[0:-1,1:]   + self.phi_grid[1:,0:-1]   + self.phi_grid[1:,1:] ) / 4.

        areas_thetas = (phis[1]-phis[0]) * ( -cos(thetas[1:]) + cos(thetas[0:-1]))
        self.cell_areas = vstack( (areas_thetas,)*(resolution[1]) ).T

        # Setup routines for the interactive "Plot.ly" display
        self.setup_layout()
        self.current_axis = []
项目:LIE    作者:EmbraceLife    | 项目源码 | 文件源码
def plot_image(image):
    # Assume the pixel-values are scaled between 0 and 255.

    if False:
        # Convert the pixel-values to the range between 0.0 and 1.0
        image = np.clip(image/255.0, 0.0, 1.0)

        # Plot using matplotlib.
        plt.imshow(image, interpolation='lanczos')
        plt.show()
    else:
        # Ensure the pixel-values are between 0 and 255.
        image = np.clip(image, 0.0, 255.0)

        # Convert pixels to bytes.
        image = image.astype(np.uint8)

        # Convert to a PIL-image and display it.
        display(PIL.Image.fromarray(image))


# Normalize an image so its values are between 0.0 and 1.0. This is useful for plotting the gradient.

# In[13]:
项目:jupyter_vega    作者:altair-viz    | 项目源码 | 文件源码
def __init__(self, spec=None, data=None, url=None, filename=None, metadata=None):
        """Create a VegaLite display object given raw data.

        Parameters
        ----------
        spec : dict
            VegaLite spec. Not an already-serialized JSON string.
        data : dict or list
            VegaLite data. Not an already-serialized JSON string.
            Scalar types (None, number, string) are not allowed, only dict
            or list containers.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        metadata: dict
            Specify extra metadata to attach to the json display object.
        """

        super(VegaLite, self).__init__(spec=spec, data=data, url=url, filename=filename)
项目:jupyter_vega    作者:altair-viz    | 项目源码 | 文件源码
def __init__(self, spec=None, data=None, url=None, filename=None, metadata=None):
        """Create a VegaLite display object given raw data.

        Parameters
        ----------
        spec : dict
            VegaLite spec. Not an already-serialized JSON string.
        data : dict or list
            VegaLite data. Not an already-serialized JSON string.
            Scalar types (None, number, string) are not allowed, only dict
            or list containers.
        url : unicode
            A URL to download the data from.
        filename : unicode
            Path to a local file to load the data from.
        metadata: dict
            Specify extra metadata to attach to the json display object.
        """

        super(VegaLite, self).__init__(spec=spec, data=data, url=url, filename=filename)
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def show_site(self, article, nwork, info):
        """Display site citation"""
        text = "# Temp\n"
        text += "insert('''"
        text += citation_text(
            self.citation_var, info,
            ref=article.get('citation_id', ''),
            backward=self.backward
        ) + "\n"
        text += "''', citations='{}');".format(self.citation_file)
        display_cell(text)
        self.output_widget.clear_output()
        with self.output_widget:
            if self.to_display:
                display("\n".join(self.to_display))
            if 'div' in article:
                display(HTML(repr(article['div'])))
            elif 'name' in article:
                print(article['name'])
        self.to_display = []
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def update_r_widget(self, *args):
        """Callback for updating r_widget value"""
        self._display_stack += 1
        r_value = self.r_widget.value
        dist_min = 2 * r_value + 2
        letters_max = int(r_value / 3.6)
        self.margin_left_widget.min = -1
        self.margin_left_widget.value = max(r_value, self.margin_left_widget.value)
        self.margin_left_widget.min = r_value
        self.dist_x_widget.min = -1
        self.dist_x_widget.value = max(dist_min, self.dist_x_widget.value)
        self.dist_x_widget.min = dist_min
        self.dist_y_widget.min = -1
        self.dist_y_widget.value = max(dist_min, self.dist_y_widget.value)
        self.dist_y_widget.min = dist_min
        self.letters_widget.max = 5000
        self.letters_widget.value = min(letters_max, self.letters_widget.value)
        self.letters_widget.max = letters_max
        self.display()
项目:snowballing    作者:JoaoFelipe    | 项目源码 | 文件源码
def create_category(self, name, attr, value, color, font_color):
        """Create category widget"""
        VIS = ['none', '']
        widget = self.toggle_widgets[attr] = ToggleButton(value=value, description=name)
        wcolor = self.color_widgets[attr] = ColorPicker(value=color, description=name, width="180px")
        wfont_color = self.font_color_widgets[attr] = ColorPicker(value=font_color, width="110px")
        def visibility(*args):
            """" Toggles visibility of category """
            self._display_stack += 1
            wcolor.layout.display = VIS[int(widget.value)]
            wfont_color.layout.display = VIS[int(widget.value)]
            self.display()
        widget.observe(visibility, "value")
        wcolor.observe(self.update_widget, "value")
        wfont_color.observe(self.update_widget, "value")
        visibility()
项目:Kaggle_Buddy    作者:NickYi1990    | 项目源码 | 文件源码
def ka_display_muti_tables_summary(tables, table_names, n=5):
    '''display multi tables' summary

        Parameters
        ----------
        tables: list_like
                Pandas dataframes
        table_names: list_like
                     names of each dataframe

        Return
        ------
        1. show head of data
        2. show column types of data
        3. show summary of data
    '''
    for t, t_name in zip(tables, table_names):
        print(t_name + ":", t.shape)
        ka_display_side_by_side(t.head(n=n), _ka_display_col_type(t), DataFrameSummary(t).summary())
项目:Kaggle_Buddy    作者:NickYi1990    | 项目源码 | 文件源码
def ka_C_Binary_ratio(y, positive=1):
    '''Find the positive ration of dependent variable

        Parameters
        ----------
        y: pandas series
           binary dependent variable
        positive: 1 or 0
                  identify which value is positive

        Return
        ------
        float value display positive rate
    '''
    return y.value_counts()[positive] / (y.value_counts().sum())

####################################################################################
##                              NUMERICAL BLOCK
####################################################################################
项目:CatchGame-QLearningExample-TensorFlow    作者:solaris33    | 项目源码 | 文件源码
def drawState(fruitRow, fruitColumn, basket):
  global gridSize
  # column is the x axis
  fruitX = fruitColumn 
  # Invert matrix style points to coordinates
  fruitY = (gridSize - fruitRow + 1)
  statusTitle = "Wins: " + str(winCount) + "  Losses: " + str(loseCount) + "  TotalGame: " + str(numberOfGames)
  axis.set_title(statusTitle, fontsize=30)
  for p in [
    patches.Rectangle(
        ((ground - 1), (ground)), 11, 10,
        facecolor="#000000"      # Black
    ),
    patches.Rectangle(
        (basket - 1, ground), 2, 0.5,
        facecolor="#FF0000"     # No background
    ),
    patches.Rectangle(
        (fruitX - 0.5, fruitY - 0.5), 1, 1,
        facecolor="#FF0000"       # red 
    ),   
    ]:
      axis.add_patch(p)
  display.clear_output(wait=True)
  display.display(pl.gcf())
项目:ray    作者:ray-project    | 项目源码 | 文件源码
def task_search_bar():
    task_search = widgets.Text(
        value="",
        placeholder="Task ID",
        description="Search for a task:",
        disabled=False
        )
    display(task_search)

    def handle_submit(sender):
        pp = pprint.PrettyPrinter()
        pp.pprint(ray.global_state.task_table(task_search.value))

    task_search.on_submit(handle_submit)


# Hard limit on the number of tasks to return to the UI client at once
项目:tap    作者:mfouesneau    | 项目源码 | 文件源码
def add_input_toggle():
    from IPython.display import HTML, display

    r = HTML('''
    <script>

    $( document ).ready(function () {
        IPython.CodeCell.options_default['cm_config']['lineWrapping'] = true;
        IPython.notebook.get_selected_cell()

        IPython.toolbar.add_buttons_group([
                {
                    'label'   : 'toggle all input cells',
                    'icon'    : 'fa-eye-slash',
                    'callback': function(){ $('div.input').slideToggle(); }
                }
            ]);
    });
    </script>
    ''')
    display(r)
    return r
项目:scikit-discovery    作者:MITHaystack    | 项目源码 | 文件源码
def drawGUI():
    '''
    Draw the GUI on the screen
    '''
    display(widget_dict['aws_id_widget'])
    display(widget_dict['aws_secret_widget'])
    display(widget_dict['aws_region_widget'])
    display(widget_dict['aws_security_widget'])
    display(widget_dict['aws_keyname_widget'])
    display(widget_dict['aws_pem_widget'])
    display(widget_dict['aws_image_id'])    
    display(widget_dict['instance_type_widget'])
    display(widgets.HBox([widget_dict['initialize_button'], widget_dict['cache_button'],widget_dict['restore_button']]))

    # display(widgets.HBox([widget_dict['label_num_instances'], widget_dict['new_num_instances_widget']]))
    # display(widgets.HBox([widget_dict['run_label'], widget_dict['aws_status_widget']]))

    display(widget_dict['new_num_instances_widget'])
    display(widget_dict['aws_status_widget'])
    display(widget_dict['execute_instances_button'])
项目:TensorFlow_Examples    作者:solaris33    | 项目源码 | 文件源码
def drawState(fruitRow, fruitColumn, basket):
  global gridSize
  # column is the x axis
  fruitX = fruitColumn 
  # Invert matrix style points to coordinates
  fruitY = (gridSize - fruitRow + 1)
  statusTitle = "Wins: " + str(winCount) + "  Losses: " + str(loseCount) + "  TotalGame: " + str(numberOfGames)
  axis.set_title(statusTitle, fontsize=30)
  for p in [
    patches.Rectangle(
        ((ground - 1), (ground)), 11, 10,
        facecolor="#000000"      # Black
    ),
    patches.Rectangle(
        (basket - 1, ground), 2, 0.5,
        facecolor="#FF0000"     # No background
    ),
    patches.Rectangle(
        (fruitX - 0.5, fruitY - 0.5), 1, 1,
        facecolor="#FF0000"       # red 
    ),   
    ]:
      axis.add_patch(p)
  display.clear_output(wait=True)
  display.display(pl.gcf())
项目:ro_sgns    作者:AlexGrinch    | 项目源码 | 文件源码
def plot_dynamics(vecs, vec2, n=5, MAX_ITER=100):
    """
    Plot how the distances between pairs change with each n
    iterations of the optimization method.
    """

    for i in xrange(MAX_ITER):
        if (i%n==0):
            plt.clf()
            plt.xlim([-0.01, 1.2])
            plt.plot(vecs[i], vec2, 'ro', color='blue')
            plt.grid()
            display.clear_output(wait=True)
            display.display(plt.gcf())
    plt.clf()

    fig, ax = plt.subplots(1, 2, figsize=(13, 4))
    for i in xrange(2):
        ax[i].set_xlim([-0.01, 1.2])
        ax[i].plot(vecs[-i], vec2, 'ro', color='blue')
        ax[i].set_title(str(i*MAX_ITER)+' iterations')
        ax[i].set_xlabel('Cosine distance', fontsize=14)
        ax[i].set_ylabel('Assesor grade', fontsize=14)
        ax[i].grid()
项目:jupyterlib    作者:cybergis    | 项目源码 | 文件源码
def __init__(self):
        #user=widgets.Text(value=USERNAME,placeholder='Your ROGER Account name', description='Username',disabled=False)
        #display(user)
        #pw=getpass(prompt='Password')

        #paramiko.util.log_to_file("ssh.log")
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.homeDir = '%s/%s'%(JUPYTER_HOME,USERNAME)
        self.jobDir = self.homeDir + '/.jobs'
        if not os.path.exists(self.jobDir):
            os.makedirs(self.jobDir)
        self.userName = USERNAME
        self.rogerRoot = '%s/%s'%(ROGER_PRJ, self.userName)
        self.rogerJobDir = self.rogerRoot + '/.jobs'
        self.relPath = os.path.relpath(os.getcwd(), self.homeDir)
        self.rogerPath = self.rogerRoot + '/' + self.relPath
        self.editMode = True
        self.jobId = None
        with open(os.path.dirname(__file__)+'/qsub.template') as input:
            self.job_template=Template(input.read())
        self.login()
项目:tutorials    作者:pytorch    | 项目源码 | 文件源码
def forward(self, x):
        x = F.relu(self.bn1(self.conv1(x)))
        x = F.relu(self.bn2(self.conv2(x)))
        x = F.relu(self.bn3(self.conv3(x)))
        return self.head(x.view(x.size(0), -1))


######################################################################
# Input extraction
# ^^^^^^^^^^^^^^^^
#
# The code below are utilities for extracting and processing rendered
# images from the environment. It uses the ``torchvision`` package, which
# makes it easy to compose image transforms. Once you run the cell it will
# display an example patch that it extracted.
#
项目:CheTo    作者:rdkit    | 项目源码 | 文件源码
def drawMolsByLabel(topicModel, label, idLabelToMatch=0, baseRad=0.5, molSize=(250,150),\
                    numRowsShown=3, tableHeader='', maxMols=100):

    result = generateMoleculeSVGsbyLabel(topicModel, label, idLabelToMatch=idLabelToMatch,baseRad=baseRad,\
                                                              molSize=molSize, maxMols=maxMols)
    if len(result)  == 1:
        print(result)
        return

    svgs, namesSVGs = result
    finalsvgs = []
    for svg in svgs:
        # make the svg scalable
        finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
                                     +' '+str(molSize[1])+'"'))

    return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader='Molecules of '+str(label),
                                                 namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))

# produces a svg grid of the molecules of a certain label and highlights the most probable topic
项目:CheTo    作者:rdkit    | 项目源码 | 文件源码
def drawMolsByTopic(topicModel, topicIdx, idsLabelToShow=[0], topicProbThreshold = 0.5, baseRad=0.5, molSize=(250,150),\
                    numRowsShown=3, color=(.0,.0, 1.), maxMols=100):
    result = generateMoleculeSVGsbyTopicIdx(topicModel, topicIdx, idsLabelToShow=idsLabelToShow, \
                                             topicProbThreshold = topicProbThreshold, baseRad=baseRad,\
                                             molSize=molSize,color=color, maxMols=maxMols)
    if len(result)  == 1:
        print(result)
        return

    svgs, namesSVGs = result
    finalsvgs = []
    for svg in svgs:
        # make the svg scalable
        finalsvgs.append(svg.replace('<svg','<svg preserveAspectRatio="xMinYMin meet" viewBox="0 0 '+str(molSize[0])\
                                     +' '+str(molSize[1])+'"'))

    tableHeader = 'Molecules in topic '+str(topicIdx)+' (sorted by decending probability)'

    return display(HTML(utilsDrawing.drawSVGsToHTMLGrid(finalsvgs[:maxMols],cssTableName='overviewTab',tableHeader=tableHeader,\
                                                 namesSVGs=namesSVGs[:maxMols], size=molSize, numRowsShown=numRowsShown, numColumns=4)))

# produces a svg grid of the molecules belonging to a certain topic and highlights this topic within the molecules
项目:blender    作者:gastrodia    | 项目源码 | 文件源码
def __enter__(self):
        from IPython.core.getipython import get_ipython
        from IPython.core.displaypub import CapturingDisplayPublisher

        self.sys_stdout = sys.stdout
        self.sys_stderr = sys.stderr

        if self.display:
            self.shell = get_ipython()
            if self.shell is None:
                self.save_display_pub = None
                self.display = False

        stdout = stderr = outputs = None
        if self.stdout:
            stdout = sys.stdout = StringIO()
        if self.stderr:
            stderr = sys.stderr = StringIO()
        if self.display:
            self.save_display_pub = self.shell.display_pub
            self.shell.display_pub = CapturingDisplayPublisher()
            outputs = self.shell.display_pub.outputs


        return CapturedIO(stdout, stderr, outputs)
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def update_display(obj, *, display_id, **kwargs):
    """Update an existing display by id

    Parameters
    ----------

    obj:
        The object with which to update the display
    display_id: keyword-only
        The id of the display to update

    See Also
    --------

    :func:`display`
    """
    kwargs['update'] = True
    display(obj, display_id=display_id, **kwargs)
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def display_markdown(*objs, **kwargs):
    """Displays the Markdown representation of an object.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display, or if raw=True raw markdown data to
        display.
    raw : bool
        Are the data objects raw data or Python objects that need to be
        formatted before display? [default: False]
    metadata : dict (optional)
        Metadata to be associated with the specific mimetype output.
    """

    _display_mimetype('text/markdown', objs, **kwargs)
项目:yatta_reader    作者:sound88    | 项目源码 | 文件源码
def display_pdf(*objs, **kwargs):
    """Display the PDF representation of an object.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display, or if raw=True raw javascript data to
        display.
    raw : bool
        Are the data objects raw data or Python objects that need to be
        formatted before display? [default: False]
    metadata : dict (optional)
        Metadata to be associated with the specific mimetype output.
    """
    _display_mimetype('application/pdf', objs, **kwargs)


#-----------------------------------------------------------------------------
# Smart classes
#-----------------------------------------------------------------------------
项目:altair_widgets    作者:altair-viz    | 项目源码 | 文件源码
def plot(self, show=True):
        """ Assumes nothing in self.settings is None (i.e., there are no keys
        in settings such that settings[key] == None"""

        kwargs = {e['encoding']: _get_plot_command(e)
                  for e in self.settings['encodings']}

        mark_opts = {k: v for k, v in self.settings['mark'].items()}
        mark = mark_opts.pop('mark')
        Chart_mark = getattr(altair.Chart(self.df), mark)
        self.chart = Chart_mark(**mark_opts).encode(**kwargs)
        if show and self.show:
            clear_output()
            display(self.chart)
项目:altair_widgets    作者:altair-viz    | 项目源码 | 文件源码
def _add_dim(self, button):
        i = len(self.controller.children) - 1
        encoding = _get_encodings()[i]
        shelf = self._create_shelf(i=i)
        kids = self.controller.children
        teens = list(kids)[:-1] + [shelf] + [list(kids)[-1]]
        self.controller.children = teens

        # clear_output()
        # display(self.controller)
        self.settings['encodings'] += [{'encoding': encoding}]
        self.plot(self.settings)
项目:SQLCell    作者:tmthyjames    | 项目源码 | 文件源码
def display(self, columns=[], msg=None):
        data = self.data if len(self.data) <= 100 else self.data[:49] + [['...'] * (len(self.data[0]))] + self.data[-49:]
        table_str = HTMLTable([columns] + data, self.id_)._repr_html_(n_rows=100, length=len(self.data))
        table_str = table_str.replace('<table', '<table class="table-striped table-hover table-bordered"').replace("'", "\\'").replace('\n','')
        display(
            HTML(
                """
                <script type="text/Javascript">
                $('#dbinfo{id}').append('{msg}');
                $('#table{id}').append('{table}');
                </script>
                """.format(msg=str(msg), table=table_str, id=self.id_)
            )
        )
项目:SQLCell    作者:tmthyjames    | 项目源码 | 文件源码
def build_node(id_, node, xPos):
        _node = {
            'name': id_,
            'nodetype': node.get('Plan', node).get('Node Type'),
            'starttime': node.get('Plan', node).get('Actual Startup Time'),
            'endtime': node.get('Plan', node).get('Actual Total Time'),
            'subplan': node.get('Plan', node).get('Subplan Name'),
            'display': str(node.get('Plan', node).get('Join Filter', 
                                                  node.get('Filter', 
                                                           node.get('Index Cond', 
                                                                    node.get('Hash Cond', 
                                                                             node.get('One-Time Filter',
                                                                                     node.get('Recheck Cond',
                                                                                             node.get('Group Key')
                                                                                             )
                                                                                     )
                                                                            )
                                                                   )
                                                          )
                                                 ) or '') + (' using ' 
                                            + str(node.get('Index Name', 
                                                           node.get('Relation Name',
                                                                   node.get('Schema')))) + ' ' + str(node.get('Alias')or'')
                                                if node.get('Index Name', 
                                                            node.get('Relation Name',
                                                                    node.get('Schema'))) 
                                                else ''),
            'rows': node.get('Plan', node).get('Plan Rows'),
            'xPos': xPos
        }
        return _node
项目:SQLCell    作者:tmthyjames    | 项目源码 | 文件源码
def load_js_files():
    display(Javascript(
        load_js_scripts()
    ))
    return None