All
Python
Javascript
1.
bloomberg/bqplot · pyplot.py
Match rating: 66.63% · See similar code snippets
python logo
def scatter(x, y, **kwargs):
    """Draw a scatter in the current context figure.

    Parameters
    ----------

    x: numpy.ndarray, 1d
        The x-coordinates of the data points.
    y: numpy.ndarray, 1d
        The y-coordinates of the data points.
    options: dict (default: {})
        Options for the scales to be created. If a scale labeled 'x' is
        required for that mark, options['x'] contains optional keyword
        arguments for the constructor of the corresponding scale type.
    axes_options: dict (default: {})
        Options for the axes to be created. If an axis labeled 'x' is required
        for that mark, axes_options['x'] contains optional keyword arguments
        for the constructor of the corresponding axis type.
    """
    kwargs['x'] = x
    kwargs['y'] = y
    return _draw_mark(Scatter, **kwargs)
2.
SheffieldML/GPy · plot_definitions.py
Match rating: 62.52% · See similar code snippets
python logo
def scatter(self, ax, X, Y, Z=None, color=Tango.colorsHex['mediumBlue'], label=None, marker='o', **kwargs):
        if Z is not None:
            return ax.scatter(X, Y, c=color, zs=Z, label=label, marker=marker, **kwargs)
        return ax.scatter(X, Y, c=color, label=label, marker=marker, **kwargs)
3.
atarashansky/self-assembling-manifold · SAM.py
Match rating: 59.86% · See similar code snippets
python logo
def scatter(self, projection=None, c=None, cmap='rainbow', linewidth=0.0,
                edgecolor='k', axes=None, colorbar=True, s=10, **kwargs):
        """Display a scatter plot.

        Displays a scatter plot using the SAM projection or another input
        projection with or without annotations.

        Parameters
        ----------

        projection - ndarray of floats, optional, default None
            An N x 2 matrix, where N is the number of data points. If None,
            use an existing SAM projection (default t-SNE). Can take on values
            'umap' or 'tsne' to specify either the SAM UMAP embedding or
            SAM t-SNE embedding.

        c - ndarray or str, optional, default None
            Colors for each cell in the scatter plot. Can be a vector of
            floats or strings for cell annotations. Can also be a key
            for sam.adata.obs (i.e. 'louvain_clusters').

        axes - matplotlib axis, optional, default None
            Plot output to the specified, existing axes. If None, create new
            figure window.

        cmap - string, optional, default 'rainbow'
            The colormap to use for the input color values.

        colorbar - bool, optional default True
            If True, display a colorbar indicating which values / annotations
            correspond to which color in the scatter plot.

        Keyword arguments -
            All other keyword arguments that can be passed into
            matplotlib.pyplot.scatter can be used.
        """

        if (not PLOTTING):
            print("matplotlib not installed!")
        else:
            if(isinstance(projection, str)):
                try:
                    dt = self.adata.obsm[projection]
                except KeyError:
                    print('Please create a projection first using run_umap or'
                          'run_tsne')

            elif(projection is None):
                try:
                    dt = self.adata.obsm['X_umap']
                except KeyError:
                    try:
                        dt = self.adata.obsm['X_tsne']
                    except KeyError:
                        print("Please create either a t-SNE or UMAP projection"
                              "first.")
                        return
            else:
                dt = projection

            if(axes is None):
                plt.figure()
                axes = plt.gca()

            if(c is None):
                plt.scatter(dt[:, 0], dt[:, 1], s=s,
                            linewidth=linewidth, edgecolor=edgecolor, **kwargs)
            else:

                if isinstance(c, str):
                    try:
                        c = self.adata.obs[c].get_values()
                    except KeyError:
                        0  # do nothing

                if((isinstance(c[0], str) or isinstance(c[0], np.str_)) and
                   (isinstance(c, np.ndarray) or isinstance(c, list))):
                    i = ut.convert_annotations(c)
                    ui, ai = np.unique(i, return_index=True)
                    cax = axes.scatter(dt[:,0], dt[:,1], c=i, cmap=cmap, s=s,
                                       linewidth=linewidth,
                                       edgecolor=edgecolor,
                                       **kwargs)

                    if(colorbar):
                        cbar = plt.colorbar(cax, ax=axes, ticks=ui)
                        cbar.ax.set_yticklabels(c[ai])
                else:
                    if not (isinstance(c, np.ndarray) or isinstance(c, list)):
                        colorbar = False
                    i = c

                    cax = axes.scatter(dt[:,0], dt[:,1], c=i, cmap=cmap, s=s,
                                       linewidth=linewidth,
                                       edgecolor=edgecolor,
                                       **kwargs)

                    if(colorbar):
                        plt.colorbar(cax, ax=axes)
4.
pyecharts/pyecharts · scatter_example.py
Match rating: 59.43% · See similar code snippets
python logo
def scatter_base() -> Scatter:
    c = (
        Scatter()
        .add_xaxis(Faker.choose())
        .add_yaxis("商家A", Faker.values())
        .set_global_opts(title_opts=opts.TitleOpts(title="Scatter-基本示例"))
    )
    return c
5.
theislab/scvelo · scatter.py
Match rating: 59.01% · See similar code snippets
python logo
def scatter(adata=None, x=None, y=None, basis=None, vkey=None, color=None, use_raw=None, layer=None, color_map=None,
            colorbar=True, palette=None, size=None, alpha=None, linewidth=None, perc=None, sort_order=True, groups=None,
            components=None, projection='2d', legend_loc='none', legend_fontsize=None, legend_fontweight=None,
            right_margin=None, left_margin=None, xlabel=None, ylabel=None, title=None, fontsize=None, figsize=None,
            dpi=None, frameon=None, show=True, save=None, ax=None, zorder=None, ncols=None, **kwargs):
    """\
    Scatter plot along observations or variables axes.

    Arguments
    ---------
    adata: :class:`~anndata.AnnData`
        Annotated data matrix.
    x: `str`, `np.ndarray` or `None` (default: `None`)
        x coordinate
    y: `str`, `np.ndarray` or `None` (default: `None`)
        y coordinate
    {scatter}

    Returns
    -------
        If `show==False` a `matplotlib.Axis`
    """
    scatter_kwargs = {"use_raw": use_raw, "sort_order": sort_order, "alpha": alpha, "components": components,
                      "projection": projection, "legend_loc": legend_loc, "groups": groups, "palette": palette,
                      "legend_fontsize": legend_fontsize, "legend_fontweight": legend_fontweight,
                      "right_margin": right_margin, "left_margin": left_margin, "show": False, "save": None}

    adata = AnnData(np.stack([x, y]).T) if adata is None and (x is not None and y is not None) else adata
    colors, layers, bases = make_unique_list(color, allow_array=True), make_unique_list(layer), make_unique_list(basis)
    multikey = colors if len(colors) > 1 else layers if len(layers) > 1 else bases if len(bases) > 1 else None
    if multikey is not None:
        if isinstance(title, (list, tuple)): title *= int(np.ceil(len(multikey) / len(title)))
        ncols = len(multikey) if ncols is None else min(len(multikey), ncols)
        nrows = int(np.ceil(len(multikey) / ncols))
        figsize = rcParams['figure.figsize'] if figsize is None else figsize
        for i, gs in enumerate(
                pl.GridSpec(nrows, ncols, pl.figure(None, (figsize[0] * ncols, figsize[1] * nrows), dpi=dpi))):
            if i < len(multikey):
                scatter(adata, x=x, y=y, size=size, linewidth=linewidth, xlabel=xlabel, ylabel=ylabel, vkey=vkey,
                        color_map=color_map, colorbar=colorbar, perc=perc, frameon=frameon, ax=pl.subplot(gs), zorder=zorder,
                        color=colors[i] if len(colors) > 1 else color,
                        layer=layers[i] if len(layers) > 1 else layer,
                        basis=bases[i] if len(bases) > 1 else basis,
                        title=title[i] if isinstance(title, (list, tuple)) else title, **scatter_kwargs, **kwargs)
        savefig_or_show('' if basis is None else basis, dpi=dpi, save=save, show=show)
        if not show: return ax

    else:
        color, layer, basis = colors[0], layers[0], bases[0]
        color = default_color(adata) if color is None else color
        color_map = default_color_map(adata, color) if color_map is None else color_map

        is_embedding = ((x is None) | (y is None)) and basis not in adata.var_names
        basis = default_basis(adata) if basis is None and is_embedding else basis
        size = default_size(adata) if size is None else size
        linewidth = 1 if linewidth is None else linewidth
        frameon = frameon if frameon is not None else True if not is_embedding else settings._frameon

        if projection == '3d':
            from mpl_toolkits.mplot3d import Axes3D
            ax = pl.figure(None, figsize, dpi=dpi).gca(projection=projection) if ax is None else ax
        else:
            ax = pl.figure(None, figsize, dpi=dpi).gca() if ax is None else ax

        if is_categorical(adata, color) and is_embedding:
            from scanpy.api.pl import scatter as scatter_
            ax = scatter_(adata, basis=basis, color=color, color_map=color_map, size=size, frameon=frameon, ax=ax,
                          title=title, **scatter_kwargs, **kwargs)

        else:
            if basis in adata.var_names:
                xkey, ykey = ('spliced', 'unspliced') if use_raw or 'Ms' not in adata.layers.keys() else ('Ms', 'Mu')
                x = make_dense(adata[:, basis].layers[xkey])
                y = make_dense(adata[:, basis].layers[ykey])
                xlabel, ylabel = 'spliced', 'unspliced'
                title = basis if title is None else title

            elif is_embedding:
                X_emb = adata.obsm['X_' + basis][:, get_components(components, basis)]
                x, y = X_emb[:, 0], X_emb[:, 1]

            elif isinstance(x, str) and isinstance(y, str) and x in adata.var_names and y in adata.var_names:
                x = adata[:, x].layers[layer] if layer in adata.layers.keys() else adata[:, x].X
                y = adata[:, y].layers[layer] if layer in adata.layers.keys() else adata[:, y].X

            if basis in adata.var_names and isinstance(color, str) and color in adata.layers.keys():
                c = interpret_colorkey(adata, basis, color, perc)
            else:
                c = interpret_colorkey(adata, color, layer, perc)

            if layer is not None and 'velocity' in layer and isinstance(color, str) and color in adata.var_names:
                ub = np.percentile(np.abs(c), 98)
                kwargs.update({"vmin": -ub, "vmax": ub})
            if layer is not None and ('spliced' in layer or 'Ms' in layer or 'Mu' in layer) \
                    and isinstance(color, str) and color in adata.var_names:
                ub = np.percentile(c, 98)
                kwargs.update({"vmax": ub})

            if groups is not None or np.any(pd.isnull(c)):
                zorder = 0 if zorder is None else zorder
                ax = scatter(adata, basis=basis, color='lightgrey', ax=ax, zorder=zorder, **scatter_kwargs)
                zorder += 1

            if basis in adata.var_names:
                fits = show_linear_fit(adata, basis, vkey, xkey, linewidth)
                from .simulation import show_full_dynamics
                if 'true_alpha' in adata.var.keys():
                    fit = show_full_dynamics(adata, basis, 'true', use_raw, linewidth)
                    fits.append(fit)
                if 'fit_alpha' in adata.var.keys() and (vkey is None or 'dynamics' in vkey):
                    fit = show_full_dynamics(adata, basis, 'fit', use_raw, linewidth,
                                             show_assigments=vkey is not None and 'assignment' in vkey)
                    fits.append(fit)
                if vkey is not None and 'density' in vkey:
                    show_density(x, y)

                if len(fits) > 0 and legend_loc is not None:
                    pl.legend(fits, loc=legend_loc if legend_loc is not 'none' else 'lower right')
                if use_raw and perc is not None:
                    pl.xlim(right=np.percentile(x, 99.9 if not isinstance(perc, int) else perc) * 1.05)
                    pl.ylim(top=np.percentile(y, 99.9 if not isinstance(perc, int) else perc) * 1.05)

            pl.scatter(x, y, c=c, cmap=color_map, s=size, alpha=alpha, edgecolors='none', marker='.', zorder=zorder, **kwargs)

            set_label(xlabel, ylabel, fontsize, basis)
            set_title(title, layer, color, fontsize)
            ax = update_axes(ax, fontsize, is_embedding, frameon)
            if colorbar and not is_categorical(adata, color): set_colorbar(ax)

        savefig_or_show('' if basis is None else basis, dpi=dpi, save=save, show=show)
        if not show: return ax
6.
astrofrog/mpl-scatter-density · scatter_density_axes.py
Match rating: 58.92% · See similar code snippets
python logo
def scatter_density(self, x, y, dpi=72, downres_factor=4, color=None, cmap=None,
                        alpha=1.0, norm=None, **kwargs):
        """
        Make a density plot of the (x, y) scatter data.

        Parameters
        ----------
        x, y : iterable
            The data to plot
        dpi : int or `None`
            The number of dots per inch to include in the density map. To use
            the native resolution of the drawing device, set this to None.
        downres_factor : int
            For interactive devices, when panning, the density map will
            automatically be made at a lower resolution and including only a
            subset of the points. The new dpi of the figure when panning will
            then be dpi / downres_factor, and the number of elements in the
            arrays will be reduced by downres_factor**2.
        cmap : `matplotlib.colors.Colormap`
            The colormap to use for the density map.
        color : str or tuple
            The color to use for the density map. This can be any valid
            Matplotlib color. If specified, this takes precedence over the
            colormap.
        alpha : float
            Transparency of the density map
        norm : `matplotlib.colors.Normalize`
            The normalization class for the density map.
        """

        self.set_xlim(np.min(x), np.max(x))
        self.set_ylim(np.min(y), np.max(y))

        scatter = ScatterDensityArtist(self, x, y, dpi=dpi, downres_factor=downres_factor,
                                       color=color, cmap=cmap,
                                       alpha=alpha, norm=norm, **kwargs)
        self.add_artist(scatter)

        return scatter
7.
newville/wxmplot · plotframe.py
Match rating: 58.65% · See similar code snippets
python logo
def scatterplot(self, x, y, **kw):
        """plot after clearing current plot """
        self.panel.scatterplot(x, y, **kw)
8.
yjzhang/uncurl_python · vis.py
Match rating: 58.29% · See similar code snippets
python logo
def visualize_dim_red(r, labels, filename=None, figsize=(18,10), title='', legend=True, label_map=None, label_scale=False, label_color_map=None, **scatter_options):
    """
    Saves a scatter plot of a (2,n) matrix r, where each column is a cell.

    Args:
        r (array): (2,n) matrix
        labels (array): (n,) array of ints/strings or floats. Can be None.
        filename (string): string to save the output graph. If None, then this just displays the plot.
        figsize (tuple): Default: (18, 10)
        title (string): graph title
        legend (bool): Default: True
        label_map (dict): map of labels to label names. Default: None
        label_scale (bool): True if labels is should be treated as floats. Default: False
        label_color_map (array): (n,) array or list of colors for each label.
    """
    fig = plt.figure(figsize=figsize)
    plt.cla()
    if not label_scale:
        for i in set(labels):
            label = i
            if label_map is not None:
                label = label_map[i]
            if label_color_map is not None:
                c = label_color_map[i]
                plt.scatter(r[0, labels==i], r[1, labels==i], label=label, c=c, **scatter_options)
            else:
                plt.scatter(r[0, labels==i], r[1, labels==i], label=label, **scatter_options)
    else:
        if labels is None:
            plt.scatter(r[0,:], r[1,:], **scatter_options)
        else:
            plt.scatter(r[0,:], r[1,:], c=labels/labels.max(), **scatter_options)
    plt.title(title)
    if legend:
        plt.legend()
    if filename is not None:
        plt.savefig(filename, dpi=100)
        plt.close()
    return fig
9.
pandas-dev/pandas · _core.py
Match rating: 58.15% · See similar code snippets
python logo
def scatter(self, x, y, s=None, c=None, **kwds):
        """
        Create a scatter plot with varying marker point size and color.

        The coordinates of each point are defined by two dataframe columns and
        filled circles are used to represent each point. This kind of plot is
        useful to see complex correlations between two variables. Points could
        be for instance natural 2D coordinates like longitude and latitude in
        a map or, in general, any pair of metrics that can be plotted against
        each other.

        Parameters
        ----------
        x : int or str
            The column name or column position to be used as horizontal
            coordinates for each point.
        y : int or str
            The column name or column position to be used as vertical
            coordinates for each point.
        s : scalar or array_like, optional
            The size of each point. Possible values are:

            - A single scalar so all points have the same size.

            - A sequence of scalars, which will be used for each point's size
              recursively. For instance, when passing [2,14] all points size
              will be either 2 or 14, alternatively.

        c : str, int or array_like, optional
            The color of each point. Possible values are:

            - A single color string referred to by name, RGB or RGBA code,
              for instance 'red' or '#a98d19'.

            - A sequence of color strings referred to by name, RGB or RGBA
              code, which will be used for each point's color recursively. For
              instance ['green','yellow'] all points will be filled in green or
              yellow, alternatively.

            - A column name or position whose values will be used to color the
              marker points according to a colormap.

        **kwds
            Keyword arguments to pass on to :meth:`DataFrame.plot`.

        Returns
        -------
        :class:`matplotlib.axes.Axes` or numpy.ndarray of them

        See Also
        --------
        matplotlib.pyplot.scatter : Scatter plot using multiple input data
            formats.

        Examples
        --------
        Let's see how to draw a scatter plot using coordinates from the values
        in a DataFrame's columns.

        .. plot::
            :context: close-figs

            >>> df = pd.DataFrame([[5.1, 3.5, 0], [4.9, 3.0, 0], [7.0, 3.2, 1],
            ...                    [6.4, 3.2, 1], [5.9, 3.0, 2]],
            ...                   columns=['length', 'width', 'species'])
            >>> ax1 = df.plot.scatter(x='length',
            ...                       y='width',
            ...                       c='DarkBlue')

        And now with the color determined by a column as well.

        .. plot::
            :context: close-figs

            >>> ax2 = df.plot.scatter(x='length',
            ...                       y='width',
            ...                       c='species',
            ...                       colormap='viridis')
        """
        return self(kind='scatter', x=x, y=y, c=c, s=s, **kwds)
10.
Match rating: 58.11% · See similar code snippets
python logo
def sentiment_scatter(sms=sms):
    plt.figure(figsize=(10, 7.5))
    ax = plt.subplot(1, 1, 1)
    ax = sms.plot.scatter(x='topic4', y='line', ax=ax, color='g', marker='+', alpha=.6)
    ax = sms.plot.scatter(x='topic4', y='sgd', ax=ax, color='r', marker='x', alpha=.4)
    ax = sms.plot.scatter(x='topic4', y='vader', ax=ax, color='k', marker='.', alpha=.3)
    ax = sms.plot.scatter(x='topic4', y='sgd', ax=ax, color='c', marker='s', alpha=.6)
    ax = sms.plot.scatter(x='topic4', y='pca_lda_spaminess', ax=ax, color='b', marker='o', alpha=.6)
    plt.ylabel('Sentiment')
    plt.xlabel('Topic 4')
    plt.legend(['LinearRegressor', 'SGDRegressor', 'Vader', 'OneNeuronRegresor', 'PCA->LDA->spaminess'])
    plt.tight_layout()
    plt.show()
11.
gl-vis/regl-scatter2d · index.js
Match rating: 42.41% · See similar code snippets
javascript logo
function (regl, options) {
	var scatter = new Scatter(regl, options)

	var render = scatter.render.bind(scatter)

	// expose API
	extend(render, {
		render: render,
		update: scatter.update.bind(scatter),
		draw: scatter.draw.bind(scatter),
		destroy: scatter.destroy.bind(scatter),
		regl: scatter.regl,
		gl: scatter.gl,
		canvas: scatter.gl.canvas,
		groups: scatter.groups,
		markers: scatter.markerCache,
		palette: scatter.palette
	})

	return render
}
12.
MakerCollider/node-red-contrib-smartnode-hook · highcharts-more.src.js
Match rating: 39.39% · See similar code snippets
javascript logo
function (config) {
				var backgroundColor = config.backgroundColor,  // if defined, replace the old one (specific for gradients)
					axisUserOptions = firstAxis.userOptions;
				config = merge(pane.defaultBackgroundOptions, config);
				if (backgroundColor) {
					config.backgroundColor = backgroundColor;
				}
				config.color = config.backgroundColor; // due to naming in plotBands
				firstAxis.options.plotBands.unshift(config);
				axisUserOptions.plotBands = axisUserOptions.plotBands || []; // #3176
				axisUserOptions.plotBands.unshift(config);
			}
13.
stellarterm/stellarterm · highstock.js
Match rating: 39.18% · See similar code snippets
javascript logo
function(){var a=
this.baseSeries||[];this.navigatorEnabled&&a[0]&&!1!==this.navigatorOptions.adaptToUpdatedData&&(t(a,function(a){H(a,"updatedData",this.updatedDataHandler)},this),a[0].xAxis&&H(a[0].xAxis,"foundExtremes",this.modifyBaseAxisExtremes))}
14.
hl198181/neptune · jquery.plupload.queue.js
Match rating: 38.63% · See similar code snippets
javascript logo
function(i, file) {
						inputHTML = '';

						if (file.status == plupload.DONE) {
							if (file.target_name) {
								inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_tmpname" value="' + plupload.xmlEncode(file.target_name) + '" />';
							}

							inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_name" value="' + plupload.xmlEncode(file.name) + '" />';
							inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_status" value="' + (file.status == plupload.DONE ? 'done' : 'failed') + '" />';
	
							inputCount++;

							$('#' + id + '_count').val(inputCount);
						}

						fileList.append(
							'<li id="' + file.id + '">' +
								'<div class="plupload_file_name"><span>' + file.name + '</span></div>' +
								'<div class="plupload_file_action"><a href="#"></a></div>' +
								'<div class="plupload_file_status">' + file.percent + '%</div>' +
								'<div class="plupload_file_size">' + plupload.formatSize(file.size) + '</div>' +
								'<div class="plupload_clearer">&nbsp;</div>' +
								inputHTML +
							'</li>'
						);

						handleStatus(file);

						$('#' + file.id + '.plupload_delete a').click(function(e) {
							$('#' + file.id).remove();
							uploader.removeFile(file);

							e.preventDefault();
						});
					}
15.
vigour-io/api-promise · index.js
Match rating: 38.08% · See similar code snippets
javascript logo
function lookup (host, options, cb) {
  if (!cb) {
    cb = options
    options = null
  }
  if (dnsCache[host] && dnsCache[host][2] > +new Date() - 6e4) {
    clearTimeout(dnsCache[host][3])
    dnsCache[host][3] = setTimeout(() => { delete dnsCache[host] }, 500)
    cb(null, dnsCache[host][0], dnsCache[host][1])
  } else {
    if (dnsCache[host]) {
      clearTimeout(dnsCache[host][3])
      delete dnsCache[host]
    }
    dns.lookup(host, options, (err, ip, type) => {
      if (err) {
        cb(err)
      } else {
        dnsCache[host] = [ip, type, +new Date()]
        dnsCache[host][3] = setTimeout(() => { delete dnsCache[host] }, 500)
        cb(null, dnsCache[host][0], dnsCache[host][1])
      }
    })
  }
}
16.
medialab/sandcrawler · spawn.js
Match rating: 38.06% · See similar code snippets
javascript logo
function(spider, callback) {
  var self = this;

  if (!types.check(spider, 'spider'))
    throw Error('sandcrawler.spawn.run: given argument is not a valid spider.');

  if (spider.state.fulfilled)
    throw Error('sandcrawler.spawn.run: given spider has already been fulfilled.');

  if (spider.state.running)
    throw Error('sandcrawler.spawn.run: given spider has already running.');

  // Registering
  this.spiders.push(spider.id);

  // Running given spider
  spider.engine.phantom = this.spy;
  spider._start(function(err, remains) {

    // Removing spiders from list
    _.pullAt(self.spiders, self.spiders.indexOf(spider.id));

    // Autoclosing the spawn?
    if (self.params.autoClose && !self.spiders.length)
      self.close();

    if (typeof callback !== 'function')
      return;

    if (err)
      return callback(err, remains);

    callback(null, remains);
  });
}
17.
chrisJohn404/ljswitchboard-device_scanner · open_all_device_scanner.js
Match rating: 38.0% · See similar code snippets
javascript logo
function closeInactiveDevices(bundle) {
        debugSS('in closeInactiveDevices');
        var defered = q.defer();

        self.deviceManager.closeDevicesOpenedByScanner()
        .then(function() {
            defered.resolve(bundle);
        })
        .catch(function() {
            defered.resolve(bundle);
        });
        return defered.promise;
    }
18.
hl198181/neptune · jquery.plupload.queue.js
Match rating: 37.92% · See similar code snippets
javascript logo
function updateList() {
					var fileList = $('ul.plupload_filelist', target).html(''), inputCount = 0, inputHTML;

					$.each(uploader.files, function(i, file) {
						inputHTML = '';

						if (file.status == plupload.DONE) {
							if (file.target_name) {
								inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_tmpname" value="' + plupload.xmlEncode(file.target_name) + '" />';
							}

							inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_name" value="' + plupload.xmlEncode(file.name) + '" />';
							inputHTML += '<input type="hidden" name="' + id + '_' + inputCount + '_status" value="' + (file.status == plupload.DONE ? 'done' : 'failed') + '" />';
	
							inputCount++;

							$('#' + id + '_count').val(inputCount);
						}

						fileList.append(
							'<li id="' + file.id + '">' +
								'<div class="plupload_file_name"><span>' + file.name + '</span></div>' +
								'<div class="plupload_file_action"><a href="#"></a></div>' +
								'<div class="plupload_file_status">' + file.percent + '%</div>' +
								'<div class="plupload_file_size">' + plupload.formatSize(file.size) + '</div>' +
								'<div class="plupload_clearer">&nbsp;</div>' +
								inputHTML +
							'</li>'
						);

						handleStatus(file);

						$('#' + file.id + '.plupload_delete a').click(function(e) {
							$('#' + file.id).remove();
							uploader.removeFile(file);

							e.preventDefault();
						});
					});

					$('span.plupload_total_file_size', target).html(plupload.formatSize(uploader.total.size));

					if (uploader.total.queued === 0) {
						$('span.plupload_add_text', target).html(_('Add Files'));
					} else {
						$('span.plupload_add_text', target).html(o.sprintf(_('%d files queued'), uploader.total.queued));
					}

					$('a.plupload_start', target).toggleClass('plupload_disabled', uploader.files.length == (uploader.total.uploaded + uploader.total.failed));

					// Scroll to end of file list
					fileList[0].scrollTop = fileList[0].scrollHeight;

					updateTotalProgress();

					// Re-add drag message if there is no files
					if (!uploader.files.length && uploader.features.dragdrop && uploader.settings.dragdrop) {
						$('#' + id + '_filelist').append('<li class="plupload_droptext">' + _("Drag files here.") + '</li>');
					}
				}
19.
jsbin/jsbin · file-drop.js
Match rating: 37.59% · See similar code snippets
javascript logo
function uploadAsset(file) {
    var loading = document.createElement('div');
    loading.className = 'assetLoading';
    loading.innerHTML = '0% uploading...';
    var currentStatus = 0;

    var progress = function progress(percent, status) {
      if (percent - currentStatus < 10) {
        currentStatus = percent;
      } else {
        currentStatus += 10;
        requestAnimationFrame(function () {
          progress(percent, status);
        });
      }

      if (loading && currentStatus > 0) {
        if (currentStatus > 97) {
          loading.innerHTML = '97% uploaded...';
          // because there's some lag between 100% and actually rendering
        } else {
          loading.innerHTML = currentStatus + '% uploaded...';
        }
      }
    };

    var widget = null;
    var insertPosition = cursorPosition || panel.getCursor();
    if (!jsbin.lameEditor) {
      var line = cursorPosition ? cursorPosition.line : panel.getCursor().line;
      widget = panel.addLineWidget(line, loading, {coverGutter: false, nohscroll: true});
    } else {
      insertTextArea(panel, 'Uploading ...', true);
    }

    var s3upload = new S3Upload({
      s3_sign_put_url: '/account/assets/sign',
      s3_object_name: file.name.replace(/\s+/g, '-'),
      files: [file],

      onProgress: function (percent, status) {
        if (!jsbin.lameEditor) {
          requestAnimationFrame(function () {
            progress(percent, status);
          });
        }
      },

      onError: function (reason, fromServer) {
        currentStatus = -1;
        console.error('Failed to upload: ' + fromServer);
        loading.innerHTML = fromServer || 'Failed to complete';
        loading.style.color = 'red';
        panel = null;
        cursorPosition = null;
        if (widget) {
          setTimeout(function () {
            widget.clear();
          }, 4000);
        }
      },

      onFinishS3Put: function (url) {
        if (!jsbin.lameEditor) {
          widget.clear();
          panel.replaceRange(getInsertText(file.type, panel, url), insertPosition);
        } else {
          insertTextArea(panel, getInsertText(file.type, panel, url));
          $(document).trigger('codeChange', { panelId: panel.id });
        }
        panel = null;
        cursorPosition = null;
      }
    });
  }
20.
VincentLoy/share-selected-text · shareSelectedText.js
Match rating: 37.53% · See similar code snippets
javascript logo
function (exports) {
    'use strict';

    var getPageUrl = function getPageUrl() {
        if (document.querySelector('meta[property="og:url"]') && document.querySelector('meta[property="og:url"]').getAttribute('content')) {
            return document.querySelector('meta[property="og:url"]').getAttribute('content');
        }

        return window.location.href;
    };

    // constants
    var TOOLTIP_HEIGHT = 50;
    var FACTOR = 1.33;
    var TWITTER_LIMIT_LENGTH = 140;
    var TWITTER_URL_LENGTH_COUNT = 24;
    var TWITTER_QUOTES = 2;
    var TWITTER_DOTS = 3;
    var TOOLTIP_TIMEOUT = 250;
    var FACEBOOK_DISPLAY_MODES = {
        popup: 'popup',
        page: 'page'
    };

    var REAL_TWITTER_LIMIT = TWITTER_LIMIT_LENGTH - TWITTER_URL_LENGTH_COUNT - TWITTER_QUOTES - TWITTER_DOTS;

    var SOCIAL = {
        twitter: 'twitter',
        buffer: 'buffer',
        digg: 'digg',
        linkedin: 'linkedin',
        stumbleupon: 'stumbleupon',
        reddit: 'reddit',
        tumblr: 'tumblr',
        facebook: 'facebook'
    };

    var NO_START_WITH = /[ .,!?/\\\+\-=*£$€:~§%^µ)(|@"{}&#><_]/g;
    var NO_ENDS_WITH = /[ ,/\\\+\-=*£$€:~§%^µ)(|@"{}&#><_]/g;
    var PAGE_URL = getPageUrl();

    // globals
    var tooltip = undefined;
    var parameters = undefined;
    var selected = {};

    var extend = function extend(out) {
        out = out || {};

        for (var i = 1; i < arguments.length; i += 1) {
            if (arguments[i]) {
                for (var key in arguments[i]) {
                    if (arguments[i].hasOwnProperty(key)) {
                        out[key] = arguments[i][key];
                    }
                }
            }
        }
        return out;
    };

    var hideTooltip = function hideTooltip() {
        tooltip.classList.remove('active');
    };

    var showTooltip = function showTooltip() {
        tooltip.classList.add('active');
    };

    var smartSanitize = function smartSanitize(text) {
        while (text.length && text[0].match(NO_START_WITH)) {
            text = text.substring(1, text.length);
        }

        while (text.length && text[text.length - 1].match(NO_ENDS_WITH)) {
            text = text.substring(0, text.length - 1);
        }

        return text;
    };

    var sanitizeText = function sanitizeText(text) {
        var sociaType = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];

        var author = '';
        var tweetLimit = REAL_TWITTER_LIMIT;

        if (!text) {
            return '';
        }

        if (parameters.twitterUsername && sociaType === SOCIAL.twitter) {
            author = ' via @' + parameters.twitterUsername;
            tweetLimit = REAL_TWITTER_LIMIT - author.length;
        }

        if (text.length > REAL_TWITTER_LIMIT) {
            text = text.substring(0, tweetLimit);
            text = text.substring(0, text.lastIndexOf(' ')) + '...';
        } else {
            text = text.substring(0, tweetLimit + TWITTER_DOTS);
        }

        return smartSanitize(text);
    };

    var generateSocialUrl = function generateSocialUrl(socialType, text) {
        if (parameters.sanitize) {
            text = sanitizeText(text, socialType);
        } else {
            text = smartSanitize(text);
        }

        var twitterUrl = 'https://twitter.com/intent/tweet?url=' + PAGE_URL + '&text="' + text + '"';

        if (parameters.twitterUsername && parameters.twitterUsername.length) {
            twitterUrl += '&via=' + parameters.twitterUsername;
        }

        var facebookUrl = 'https://facebook.com/dialog/share?display=' + parameters.facebookDisplayMode + '&href=' + PAGE_URL + '&quote=' + text;

        if (document.querySelector('meta[property="fb:app_id"]') && document.querySelector('meta[property="fb:app_id"]').getAttribute('content')) {
            var content = document.querySelector('meta[property="fb:app_id"]');
            facebookUrl += '&app_id=' + content;
        } else if (parameters.facebookAppID && parameters.facebookAppID.length) {
            facebookUrl += '&app_id=' + parameters.facebookAppID;
        } else {
            var idx = parameters.buttons.indexOf('facebook');
            if (idx > -1) {
                parameters.buttons.splice(idx, 1);
            }
        }

        var urls = {
            twitter: twitterUrl,
            buffer: 'https://buffer.com/add?text="' + text + '"&url=' + PAGE_URL,
            digg: 'http://digg.com/submit?url=' + PAGE_URL + '&title=' + text,
            linkedin: 'https://www.linkedin.com/shareArticle?url=' + PAGE_URL + '&title=' + text,
            stumbleupon: 'http://www.stumbleupon.com/submit?url=' + PAGE_URL + '&title=' + text,
            reddit: 'https://reddit.com/submit?url=' + PAGE_URL + '&title=' + text,
            tumblr: 'https://www.tumblr.com/widgets/share/tool?canonicalUrl=' + PAGE_URL + '&caption=' + text,
            facebook: facebookUrl
        };

        if (urls.hasOwnProperty(socialType)) {
            return urls[socialType];
        }

        return '';
    };

    var updateTooltip = function updateTooltip(rect) {
        var actualPosition = document.documentElement.scrollTop || document.body.scrollTop;
        var body = document.querySelector('body');

        tooltip.style.top = actualPosition + rect.top - TOOLTIP_HEIGHT * FACTOR + 'px';
        tooltip.style.left = rect.left + rect.width / 2 - body.getBoundingClientRect().width / 2 + 'px';

        Array.prototype.forEach.call(parameters.buttons, function (btn) {
            tooltip.querySelector('.share-selected-text-btn-' + btn).href = generateSocialUrl(btn, selected.text);
        });

        window.setTimeout(function () {
            showTooltip();
        }, parameters.tooltipTimeout);
    };

    var generateAnchorTag = function generateAnchorTag(anchorType) {
        var customIconClass = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];

        var anchorTag = document.createElement('A');
        var anchorIcon = document.createElement('i');

        if (parameters.anchorsClass) {
            ['share-selected-text-btn', 'share-selected-text-btn-' + anchorType, '' + parameters.anchorsClass].map(function (item) {
                return anchorTag.classList.add(item);
            });
        } else {
            ['share-selected-text-btn', 'share-selected-text-btn-' + anchorType].map(function (item) {
                return anchorTag.classList.add(item);
            });
        }

        if (customIconClass) {
            anchorIcon.classList.add('' + customIconClass);
        } else {
            ['icon-sst-' + anchorType, 'fa', 'fa-' + anchorType].map(function (item) {
                return anchorIcon.classList.add(item);
            });
        }

        anchorIcon.style.pointerEvents = 'none';
        anchorTag.addEventListener('click', function (e) {
            e.preventDefault();
            var windowFeatures = 'status=no,menubar=no,location=no,scrollbars=no,width=720,height=540';
            var url = e.target.href;
            window.open(url, 'Share this post', windowFeatures);
        });

        anchorTag.href = generateSocialUrl(anchorType, selected.text ? selected.text : '');
        anchorTag.appendChild(anchorIcon);
        return anchorTag;
    };

    var generateTooltip = function generateTooltip() {
        var body = document.querySelector('body');
        var mainDiv = document.createElement('DIV');
        var btnContainer = document.createElement('DIV');

        mainDiv.classList.add('share-selected-text-main-container');
        btnContainer.classList.add('share-selected-text-inner');

        if (parameters.tooltipClass) {
            btnContainer.classList.add(parameters.tooltipClass);
        }

        mainDiv.style.height = TOOLTIP_HEIGHT + 'px';
        mainDiv.style.top = 0;
        mainDiv.style.left = 0;

        Array.prototype.forEach.call(parameters.buttons, function (btn) {
            var aTag = generateAnchorTag(btn);
            btnContainer.appendChild(aTag);
        });

        mainDiv.appendChild(btnContainer);
        body.appendChild(mainDiv);

        return mainDiv;
    };

    var getSelectedText = function getSelectedText() {
        var text = '';
        var selection = undefined;

        if (window.getSelection) {
            selection = window.getSelection();
            text = selection.toString();
        } else if (document.selection && document.selection.type !== 'Control') {
            selection = document.selection.createRange();
            text = selection.text;
        }

        return {
            selection: selection,
            text: text
        };
    };

    var shareTooltip = function shareTooltip() {
        selected = getSelectedText();

        if (selected.text.length) {
            var oRange = selected.selection.getRangeAt(0);
            var oRect = oRange.getBoundingClientRect();
            updateTooltip(oRect);
        } else {
            hideTooltip();
        }
    };

    exports.shareSelectedText = function (element, args) {
        var elt = document.querySelectorAll(element);

        parameters = extend({
            tooltipClass: '',
            sanitize: true,
            buttons: [SOCIAL.twitter, SOCIAL.buffer],
            anchorsClass: '',
            twitterUsername: '',
            facebookAppID: '',
            facebookDisplayMode: FACEBOOK_DISPLAY_MODES.popup,
            tooltipTimeout: TOOLTIP_TIMEOUT
        }, args);

        tooltip = generateTooltip();

        Array.prototype.forEach.call(elt, function (el) {
            el.addEventListener('mouseup', function () {
                shareTooltip();
            });
        });
    };
}