text:
import collections
from math import sqrt, ceil, floor
from functools import partial
import logging

import numpy as np
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from yass import geometry as geom

try:
    import matplotlib.pyplot as plt
    from matplotlib.ticker import FuncFormatter
    from matplotlib.patches import Circle
except ImportError:
    _matplotlib = False
    _matplotlib_message = ('Matplotlib is required to run this function, '
                           'install it and try again')
else:
    _matplotlib = True
    _matplotlib_message = None

from yass.util import ensure_iterator, sample, requires
from yass.batch import RecordingsReader
from yass.explore.table import Table

# TODO: use functions in util module
def _is_iter(obj):
    return isinstance(obj, collections.Iterable)

# TODO: use functions in util module
def _grid_size(group_ids, max_cols=None):
    total = len(group_ids)
    sq = sqrt(total)
    cols = int(floor(sq))
    rows = int(ceil(sq))
    rows = rows + 1 if rows * cols < len(group_ids) else rows

    if max_cols and cols > max_cols:
        rows = ceil(total/max_cols)
        cols = max_cols

    return rows, cols

# TODO: use functions in util module
def _make_grid_plot(fn, group_ids, ax, sharex, sharey, max_cols=None):
    rows, cols = _grid_size(group_ids, max_cols)

    f, axs = ax.subplots(rows, cols, sharex=sharex, sharey=sharey)

    axs = axs if _is_iter(axs) else [axs]

    if cols > 1:
        axs = [item for sublist in axs for item in sublist]

    for g, ax in zip(group_ids, axs):
        fn(group_id=g, ax=ax)

# TODO: refactor this, templates should be computed from raw data instead
# of being passed as parameter, or maybe allow both ways?
class SpikeTrainExplorer(object):
    """Explore spike trains and templates

    Parameters
    ----------
    spike_train: str or np.ndarray
        Path to npy spike train file or spike train np.ndarray. The first
        column of the file should be the spike index and the second the spike
        ID
    recording_explorer: RecordingExplorer
        Recording explorer instance
    templates: np.ndarray, optional
        Templates, if None, templates are computed using the recording explorer
    projection_matrix: np.ndarray, optional
        Projection Matrix, if None, methods that return scores will not work
    """

    def __init__(self, spike_train, recording_explorer,
                 templates=None, projection_matrix=None):

        self.logger = logging.getLogger(__name__)

        if isinstance(spike_train, str):
            name, extension = spike_train.split('.')

            if extension == 'csv':
                self.spike_train = np.loadtxt(spike_train,
                                              dtype='int32', delimiter=',')
            elif extension == 'npy':
                self.spike_train = np.load(spike_train)
            else:
                raise ValueError('Unsupported extension: {}'.format(extension))
        else:
            self.spike_train = spike_train

        self.all_ids = np.unique(self.spike_train[:, 1])
        self.recording_explorer = recording_explorer
        self.projection_matrix = projection_matrix

        if templates is not None:
            self.templates = templates
        else:
            self.templates, self.weights = self._compute_templates()

        self._spike_groups = {id_: self.spike_train[self.spike_train[:, 1] ==
                              id_, 0] for id_ in self.all_ids}

        if projection_matrix is not None:
            ft_space = self._reduce_dimension
            self.templates_feature_space = ft_space(self.templates)
        else:
            self.templates_feature_space = None

    def _reduce_dimension(self, data, flatten=False):
        """Reduce dimensionality
        """
        R, n_features = self.projection_matrix.shape
        nchannel, R, n_data = data.shape

        reduced = np.transpose(np.reshape(np.matmul(np.reshape(np.transpose(
            data, [0, 2, 1]), (-1, R)), [self.projection_matrix]),
            (nchannel, n_data, n_features)), (0, 2, 1))

        if flatten:
            reduced = np.reshape(reduced, [reduced.shape[0], -1])

        return reduced

    def _compute_templates(self):
        """Compute templates from spike train

        Returns
        -------
        numpy.ndarray
            [n_channels, n_features, n_templates] array with the templates
        numpy.ndarray
            1D array with the number of spikes used to form the ith template
        """
        # get waveforms
        waveforms = [self.waveforms_for_group(id_) for id_ in self.all_ids]

        self.logger.debug('Loaded {:,} waveforms'.format(len(waveforms)))

        # compute templates for every group
        templates = [np.mean(w, axis=0) for w in waveforms]

        # get weights (number of waveforms used to compute each template)
        weights = np.array([len(w) for w in waveforms])

        # stack
        templates = np.stack(templates, axis=2)

        self.logger.debug('Finished computing templates, shape is: {}'
                          .format(templates.shape))

        # return transposed templates (makes plotting easier) and weights
        return templates.transpose(1, 0, 2), weights

    @property
    def spike_groups(self):
        """Grouped spike times by ID

        Returns
        -------
        dictionary
            Dictionary where each key is the group ID and the value is a 1D
            numpy.ndarray with the spike times for that group
        """
        return self._spike_groups

    @ensure_iterator('group_ids')
    def scores_for_groups(self, group_ids, channels, flatten=True):
        """Get scores for one or more groups

        Parameters
        ----------
        group_id: int or list
            The id for one or more group
        channels: list
            Which channels to return
        flatten: bool, optional
            Flatten scores along channels, defaults to True
        """
        waveforms = [self.waveforms_for_group(g, channels) for g in group_ids]
        lengths = np.hstack([np.ones(w.shape[0])*g for g, w in zip(group_ids,
                                                                   waveforms)])

        return self._reduce_dimension(np.vstack(waveforms),
                                      flatten=flatten), lengths

    def times_for_group(self, group_id):
        """Get the spiking times for a group

        Parameters
        ----------
        group_id: int
            The id for the group
        """
        matches_group = self.spike_train[:, 1] == group_id
        return self.spike_train[matches_group][:, 0]

    def main_channel_for_group(self, group_id):
        """Get the main channel for a group

        Parameters
        ----------
        group_id: int
            The id for the group
        """
        template = self.templates[:, :, group_id]
        main = np.argmax(np.max(template, axis=1))
        return main

    def neighbor_channels_for_group(self, group_id):
        """Get the neighbor channels for a group

        Parameters
        ----------
        group_id: int
            The id for the group
        """
        main = self.main_channel_for_group(group_id)
        neigh_matrix = self.recording_explorer.neigh_matrix
        return np.where(neigh_matrix[main])[0]

    def template_for_group(self, group_id):
        """Get the template for a group

        Parameters
        ----------
        group_id: int
            The id for the group
        """
        return self.templates[:, :, group_id]

    def waveforms_for_group(self, group_id, channels='all'):
        """Get the waveforms for a group in selected channels

        Parameters
        ----------
        group_id: int
            The id for the group
        """

        if isinstance(channels, str) and channels == 'all':
            channels = range(self.recording_explorer.n_channels)

        # get all spike times that form this group
        times = self.times_for_group(group_id)

        # get waveforms in selected channels
        read_wf = self.recording_explorer.read_waveform
        return np.stack([read_wf(t, channels) for t in times])

    def close_templates(self, group_id, k):
        """return K similar templates
        """
        difference = np.sum(np.square(self.templates -
                                      self.templates[:, :, [group_id]]),
                            axis=(0, 1))
        close_to_far_idx = np.argsort(difference)
        return close_to_far_idx[:k+1]

    def _plot_template(self, group_id, ax=None):
        """Plot a single template
        """
        ax = ax if ax else plt.gca()
        template = self.template_for_group(group_id)
        ax.plot(template.T)
        ax.set_title('Template {}'.format(group_id))
        plt.tight_layout()

    @requires(_matplotlib, _matplotlib_message)
    def plot_templates(self, group_ids, ax=None, sharex=True, sharey=False):
        """Plot templates

        Parameters
        ----------
        group_ids: int or list or str
            Groups to plot, it can be either a single group, a list of groups
            or 'all'
        """
        ax = ax if ax else plt

        if isinstance(group_ids, str) and group_ids == 'all':
            group_ids = self.all_ids

        group_ids = group_ids if _is_iter(group_ids) else [group_ids]
        _make_grid_plot(self._plot_template, group_ids, ax, sharex, sharey)

    @requires(_matplotlib, _matplotlib_message)
    def plot_pca(self, group_ids, channels, sample=None, ax=None):
        """
        Reduce dimensionality using PCA and plot data
        """
        ax = ax if ax else plt

        scores, labels = self.scores_for_groups(group_ids, channels)

        pca = PCA(n_components=2)
        reduced = pca.fit_transform(scores)

        for color in np.unique(group_ids).astype('int'):
            x = reduced[labels == color, 0]
            y = reduced[labels == color, 1]

            if sample:
                x = np.random.choice(x, size=int(sample*len(x)), replace=False)
                y = np.random.choice(x, size=int(sample*len(y)), replace=False)

            plt.scatter(x, y, label='Group {}'.format(color, alpha=0.7))

        ax.legend()

    @requires(_matplotlib, _matplotlib_message)
    def plot_lda(self, group_ids, channels, sample=None, ax=None):
        """
        Reduce dimensionality using LDA and plot data
        """
        ax = plt if ax is None else ax

        scores, labels = self.scores_for_groups(group_ids, channels)

        lda = LDA(n_components=2)
        reduced = lda.fit_transform(scores, labels)

        for color in np.unique(group_ids).astype('int'):
            x = reduced[labels == color, 0]
            y = reduced[labels == color, 1]

            if sample:
                x = np.random.choice(x, size=int(sample*len(x)), replace=False)
                y = np.random.choice(x, size=int(sample*len(y)), replace=False)

            ax.scatter(x, y, label='Group {}'.format(color), alpha=0.7)

        ax.legend()

    @requires(_matplotlib, _matplotlib_message)
    def plot_closest_clusters_to(self, group_id, k, mode='LDA',
                                 sample=None, ax=None):
        """Visualize close clusters
        """
        ax = plt if ax is None else ax

        # get similar templates to template with id group_id
        groups = self.close_templates(group_id, k)

        # get the neighbors for the main channel in group_id
        main = self.main_channel_for_group(group_id)
        neighbors = self.recording_explorer.neighbors_for_channel(main)

        if mode == 'LDA':
            self.plot_lda(groups, neighbors, sample=sample, ax=ax)
        elif mode == 'PCA':
            self.plot_pca(groups, neighbors, sample=sample, ax=ax)
        else:
            raise ValueError('Only PCA and LDA modes are supported')

    @requires(_matplotlib, _matplotlib_message)
    def plot_closest_templates_to(self, group_id, k, ax=None,
                                  sharex=True, sharey=False):
        """Visualize close templates
        """
        ax = plt if ax is None else ax

        groups = self.close_templates(group_id, k)
        self.plot_templates(groups, ax=ax, sharex=sharex, sharey=sharey)

    @requires(_matplotlib, _matplotlib_message)
    def plot_all_clusters(self, k, mode='LDA', sample=None, ax=None,
                          sharex=True, sharey=False, max_cols=None):
        ax = plt if ax is None else ax

        fn = partial(self.plot_closest_clusters_to, k=k, mode=mode,
                     sample=sample)

        _make_grid_plot(fn, self.all_ids, ax, sharex, sharey, max_cols)

    @requires(_matplotlib, _matplotlib_message)
    def plot_waveforms_and_clusters(self, group_id, ax=None):
        """
        """
        ax = plt if ax is None else ax

        ax1 = plt.subplot2grid((6, 6), (0, 0), colspan=3, rowspan=3)
        ax2 = plt.subplot2grid((6, 6), (0, 3), colspan=3)
        ax3 = plt.subplot2grid((6, 6), (1, 3), colspan=3, sharey=ax2)
        ax4 = plt.subplot2grid((6, 6), (2, 3), colspan=3, sharey=ax3)

        self.plot_closest_clusters_to(group_id, k=2, ax=ax1)

        close = self.close_templates(group_id, k=2)

        for ax, template in zip([ax2, ax3, ax4], close):
            self._plot_template(template, ax=ax)

    def _stats_for_group(self, group_id):
        """Return some summary statistics for a single group

        Returns
        -------
        dict
            Dict with id, range, max, min and main channel for the selected
            group
        """
        template = self.template_for_group(group_id)
        max_ = np.max(template)
        min_ = np.min(template)
        range_ = max_ - min_
        main_channel = self.main_channel_for_group(group_id)

        return dict(id=group_id, range=range_, max=max_, min=min_,
                    main_channel=main_channel)

    @ensure_iterator('group_ids')
    def stats_for_groups(self, group_ids):
        """Return some summary statistics for certain groups
        """
        stats = [self._stats_for_group(g) for g in group_ids]
        content = [s.values() for s in stats]
        header = stats[0].keys()
        return Table(content=content, header=header)

    def stats_for_closest_groups_to(self, group_id, k):
        """Return some summary statistics a given group and its k neighbors
        """
        groups = self.close_templates(group_id, k)
        return self.stats_for_groups(groups)

# TODO: documentation, proper errors for optional parameters, check
# plotting functions (matplotlib gca and all that stuff)
class RecordingExplorer(object):
    """Explore neural recordings: observations, geometry and waveforms

    Parameters
    ----------
    path_to_recordings: str
        Path to binary recordings file
    spike_size: int
        Spike size, this is used to get waveforms around points in the
        recordings
    path_to_geom: str, optional
        Path to geometry file (npy or csv)
    neighbor_radius: float
        Maximum radius to consider two channels as neighbors
    dtype: str
        Recordings dtype
    n_channels: int
        Number of channels in the recordings
    data_order: str
        Recordings order, one of ('channels', 'samples'). In a dataset with k
        observations per channel and j channels: 'channels' means first k
        contiguous observations come from channel 0, then channel 1, and so
        on. 'sample' means first j contiguous data are the first observations
        from all channels, then the second observations from all channels and
        so on
    loader: str ('memmap', 'array' or 'python'), optional
        How to load the data. memmap loads the data using a wrapper around
        np.memmap (see :class:`~yass.batch.MemoryMap` for details), 'array'
        using numpy.fromfile and 'python' loads it using a wrapper
        around Python file API. Defaults to 'python'. Beware that the Python
        loader has limited indexing capabilities, see
        :class:`~yass.batch.BinaryReader` for details
    waveform_dtype: str, optional
        Waveform output type, defaults to 'default' which matches
        recordings dtype
    """

    def __init__(self, path_to_recordings, path_to_geom=None, spike_size=None,
                 neighbor_radius=None, dtype=None, n_channels=None,
                 data_order=None, loader='memmap', waveform_dtype='float32'):
        self.reader = RecordingsReader(path_to_recordings, dtype, n_channels,
                                       data_order, loader)

        if path_to_geom is not None:
            self.geom = geom.parse(path_to_geom, n_channels)
            self.neighbor_radius = neighbor_radius
            self.neigh_matrix = geom.find_channel_neighbors(self.geom,
                                                            neighbor_radius)
        self.n_channels = self.reader.channels
        self.spike_size = spike_size

        if waveform_dtype == 'default':
            waveform_dtype = dtype

        self.waveform_dtype = waveform_dtype

        self.logger = logging.getLogger(__name__)

    def neighbors_for_channel(self, channel):
        """Get the neighbors for the channel

        Returns
        -------
        numpy.array
            An array containing the neighbors of the given channel
        """
        return np.where(self.neigh_matrix[channel])[0]

    def read_waveform(self, time, channels='all'):
        """
        Read a single waveform of size 2*spike_size + 1 observations around
        the given time

        Parameters
        ----------
        time: int
            Waveform center

        Returns
        -------
        numpy.array
            A (2 * spike_size + 1, channels) 2D array with the waveform around
            the given time
        """
        start = time - self.spike_size
        end = time + self.spike_size + 1

        if isinstance(channels, str) and channels == 'all':
            wf = self.reader[start:end, :].astype(self.waveform_dtype)
        else:
            wf = self.reader[start:end, channels].astype(self.waveform_dtype)

        #if len(wf) != 2 * self.spike_size + 1:
        #    raise ValueError('Cannot read waveform at time {}, there is not '
        #                     'enough data to draw a complete waveform ({} '
        #                     'observations are needed to the left and to the '
        #                     'right)'.format(time, self.spike_size))

        return wf

    def read_waveforms(self, times, channels='all', flatten=False):
        """Read multiple waveforms around certain times

        Parameters
        ----------
        times: array-like
            1D array containing the times
        channels: array-like, optional
            Channels to be included in the waveforms, if 'all' it uses all
            channels
        flatten: bool, optional
            Whether to flat the first to dimensions, defaults to True

        Returns
        -------
        numpy.array
            A (times, 2 * spike_size + 1, channels) 3D array with the waveforms
            around the given times. If flatten is True, ir returns a
            (times * 2 * spike_size + 1, channels) 2D array
        """
        # TODO: may be faster by sending :?
        if isinstance(channels, str) and channels == 'all':
            channels = range(self.n_channels)

        total = len(times)
        #wfs = np.empty((total, self.spike_size * 2 + 1, len(channels)),
        #               dtype=self.waveform_dtype)
        wfs= []
        for i, t in enumerate(times):
            # Cat: TODO: implement this correctly;
            #       Checks if waeform too short
            temp = self.read_waveform(t, channels)
            if len(temp) != 2 * self.spike_size + 1:

                continue
            wfs.append(temp)

            #if i % 10000 == 0 and i > 0:
            #    self.logger.info('Loaded {:,}/{:,} waveforms...'
            #                     .format(i, total))

        #self.logger.info('Loaded all {:,} waveforms...'.format(total))

        wfs = np.array(wfs)

        if flatten:
            self.logger.debug('Flattening waveforms...')
            wfs = wfs.reshape(wfs.shape[0], -1)

        return wfs

    def read_waveform_around_channel(self, time, channel):
        """
        Read a single waveform around a given time and using the neighbors of
        the given channel

        Parameters
        ----------
        time: int
            Waveform center
        channel: int
            The waveform will only contain the channels that are neighbors
            of this channel

        Returns
        -------
        numpy.array
            A (2 * spike_size + 1, neighbors) 2D array with the waveform around
            the given time where neighbors is the number of neighbors of the
            given channel
        """
        return self.read_waveform(time,
                                  channels=self.neighbors_for_channel(channel))

    def read_waveform_around_main_channel(self, time):
        """
        Read a single waveform around a given time and using the neighbors of
        the channel with maximum amplitude

        Parameters
        ----------
        time: int
            Waveform center

        Returns
        -------
        numpy.array
            A (2 * spike_size + 1, neighbors) 2D array with the waveform around
            the given time where neighbors is the number of neighbors of the
            channel with maximum amplitude
        """

        # read waveform along every channel and find the one with max amplitude
        wf = self.read_waveform(time=time, channels='all')
        channel = np.argmax(np.max(wf, axis=0))

        # read waveform around the max amplitude channel
        return self.read_waveform(time,
                                  channels=self.neighbors_for_channel(channel))

    def main_channel_for_waveforms(self, waveforms):
        """Get the main channel (biggest amplitude) for the given waveforms

        Parameters
        ----------
        waveforms: numpy.ndarray
            An array of size (n_temporal_features, n_channels) if only one
            waveform or one of size (n_waveforms, n_temporal_features,
            n_channels) if more than one waveform

        Returns
        -------
        int/numpy.ndarray
            The main channel for every waveform, int if only one waveform or
            a 1D array if more than one
        """
        if waveforms.ndim == 2:
            return np.argmax(np.max(waveforms, axis=0), axis=0)
        elif waveforms.ndim == 3:
            return np.argmax(np.max(waveforms, axis=1), axis=1)
        else:
            raise ValueError('waveforms must be an 2D or 3D array')

    @requires(_matplotlib, _matplotlib_message)
    def plot_waveform(self, time, channels, ax=None, line_at_t=False,
                      overlay=False):
        """
        Plot a waveform around a window size in selected channels
        """
        ax = ax if ax else plt

        n_channels = len(channels)
        formatter = FuncFormatter(lambda x, pos: time - self.spike_size +
                                  int(x))

        if overlay:
            axs = [ax] * n_channels
        else:
            f, axs = ax.subplots(n_channels, 1)

        for ch, ax in zip(channels, axs):
            waveform = self.read_waveform(time, ch)
            ax.plot(waveform)
            ax.set_title('Channel {}'.format(ch), fontsize=12)
            ax.xaxis.set_major_formatter(formatter)
            ax.tick_params(axis='x', which='major', labelsize=10)

            if line_at_t:
                ax.axvline(x=time)

        plt.tight_layout()

    @requires(_matplotlib, _matplotlib_message)
    def plot_waveform_around_channel(self, time, channel, ax=None,
                                     line_at_t=False, overlay=False):
        return self.plot_waveform(time,
                                  channels=self.neighbors_for_channel(channel),
                                  ax=ax, line_at_t=line_at_t, overlay=overlay)

    @requires(_matplotlib, _matplotlib_message)
    def plot_waveform_around_main_channel(self, time, ax=None,
                                          line_at_t=False, overlay=False):
        # read waveform along every channel and find the one with max amplitude
        wf = self.read_waveform(time=time, channels='all')
        channel = np.argmax(np.max(wf, axis=0))

        return self.plot_waveform(time,
                                  channels=self.neighbors_for_channel(channel),
                                  ax=ax, line_at_t=line_at_t, overlay=overlay)

    @requires(_matplotlib, _matplotlib_message)
    def plot_geometry(self, channel_label=True, neighbor_radius=False,
                      ax=None):
        """Plot geometry file
        """
        ax = ax if ax else plt.gca()

        x, y = self.geom.T
        colors = range(len(x))

        plt.scatter(x, y, c=colors)

        if channel_label:
            for x, y, i in zip(x, y, range(self.n_channels)):
                ax.text(x, y, i, fontsize=15)

        if neighbor_radius:
            for x, y in zip(x, y):
                c = Circle((x, y), self.neighbor_radius, color='r',
                           fill=False)
                ax.add_artist(c)

    @requires(_matplotlib, _matplotlib_message)
    def plot_clusters(self, times, sample_percentage=None, ax=None):
        """
        """
        ax = ax if ax else plt.gca()

        if sample_percentage:
            times = sample(times, sample_percentage)

        wfs = self.read_waveforms(times, flatten=True)

        pca = PCA(n_components=2)
        reduced = pca.fit_transform(wfs)

        ax.scatter(reduced[:, 0], reduced[:, 1])

    @requires(_matplotlib, _matplotlib_message)
    def plot_series(self, from_time, to_time, channels='all', ax=None):
        """Plot observations in a selected number of channels
        """

        if channels == 'all':
            channels = range(self.n_channels)

        ax = ax if ax else plt

        f, axs = plt.subplots(len(channels), 1)

        formatter = FuncFormatter(lambda x, pos: from_time + int(x))

        for ax, ch in zip(axs, channels):
            ax.plot(self.reader[from_time:to_time, ch])
            ax.set_title('Channel {}'.format(ch), fontsize=25)
            ax.xaxis.set_major_formatter(formatter)
            ax.tick_params(axis='x', which='major', labelsize=25)

        plt.tight_layout()


text: Angular2 Quickstart + Tutorial in TypeScript

redpajama_set_name: RedPajamaGithub


text:
require 'digest'

module TokenRespondable
  extend ActiveSupport::Concern

  def token_response
    hash = {
      issued_at: timestamp(Time.zone.now),
      methods: methods,
      audit_ids: [],
      expires_at: timestamp(credentials.expiration),
      user: user_hash
    }
    add_aditional_fields! hash

    { token: hash }
  end

  def add_aditional_fields!(hash)
    hash[:is_domain] = domain if respond_to? :domain
    hash[:roles] = roles if respond_to? :roles
    hash[:project] = project if respond_to? :project
    hash[:catalog] = catalog if respond_to? :catalog
  end

  def methods
    credentials.authentication[:method]
  end

  def user_hash
    {
      domain: {
        id: 'Federated',
        name: 'Federated'
      },
      id: Digest::SHA1.hexdigest(credentials.id),
      name: credentials.id,
      'OS-FEDERATION': federation_hash
    }
  end

  def federation_hash
    {
      identity_provider: {
        id: 'egi.eu'
      },
      protocol: {
        id: credentials.authentication[:method]
      },
      groups: credentials.groups.map { |group| { id: group[:id] } }
    }
  end

  def roles_array
    credentials.groups.detect { |group| group[:id] == project_id }[:roles].map { |role| role_hash role }
  end

  def role_hash(role)
    {
      domain_id: nil,
      name: role,
      id: Digest::SHA1.hexdigest(role)
    }
  end

  def project_hash
    {
      domain: {
        id: 'default',
        name: 'Default'
      },
      id: project_id,
      name: project_id
    }
  end

  private :token_response, :add_aditional_fields!, :methods, :user_hash, :federation_hash, :roles_array, :role_hash, :project_hash
end


text:
import sys
from subprocess import call

call(sys.argv[1:])


text:
from django.shortcuts import render, HttpResponseRedirect
from apps.calc.measurement import measurement_obj
from django.contrib.auth.decorators import login_required
import json
from .json import NumPyArangeEncoder
from apps.projects.models import Experiment, Datarow

# Create your views here.
@login_required
def from_dashboard(request, id):
    if not request.method == 'POST':
        return HttpResponseRedirect('/dashboard/')
    raise ValueError

    # Variablen aus dem Post-Request auslesen
    jsonHeader = request.POST.get("jsonHeader", "")
    jsonEinheiten = request.POST.get("jsonEinheiten", "")
    zeitreihenSpalte = request.POST.get("zeitreihenSpalte", "")
    jsonData = request.POST.get("jsonData", "")
    saveExperiment = request.POST.get("saveExperiment", "")
    datensatzName = request.POST.get("datensatzName", "")
    erfassungsDatum = request.POST.get("erfassungsDatum", "")

    # Das Experiment in das Objekt "measurement" einlesen
    measurement = measurement_obj.Measurement(jsonData,jsonHeader,jsonEinheiten,zeitreihenSpalte)

    #measurement in Session-Variable speichern
    request.session['measurementData'] = json.dumps(measurement.data, cls=NumPyArangeEncoder)
    request.session['measurementHeader'] = json.dumps(measurement.colNames, cls=NumPyArangeEncoder)
    request.session['measurementUnits'] = json.dumps(measurement.colUnits, cls=NumPyArangeEncoder)
    request.session['measurementTimeIndex'] = json.dumps(measurement.timeIndex, cls=NumPyArangeEncoder)

    # Daten zur Übergabe vorbereiten
    dataForRender = {
        'jsonHeader': jsonHeader,
        'jsonEinheiten': jsonEinheiten,
        'zeitreihenSpalte': zeitreihenSpalte,
        'jsonData': jsonData,
        'datensatzName': datensatzName,
        'erfassungsDatum': erfassungsDatum
        }

    newExperiment = Experiment(name=datensatzName, timerow=zeitreihenSpalte, project_id=id)
    newExperiment.save()

    #if saveExperiment == 1:

    saveExperiment(request, id, dataForRender)

    return render(request, "process/index.html", dataForRender)

def saveExperiment(request, id, dataForRender):
    jsonHeader = request.POST.get("jsonHeader", "")
    jsonEinheiten = request.POST.get("jsonEinheiten", "")
    zeitreihenSpalte = request.POST.get("zeitreihenSpalte", "")
    jsonData = request.POST.get("jsonData", "")
    saveExperiment = request.POST.get("saveExperiment", "")
    datensatzName = request.POST.get("datensatzName", "")
    erfassungsDatum = request.POST.get("erfassungsDatum", "")

    if saveExperiment == 1:
        newExperiment = Experiment(name=datensatzName, timerow=zeitreihenSpalte, project_id = id)
        newExperiment.save()

    dataForRender = dataForRender
    return render(request, "process/index.html", dataForRender)

@login_required
def analysis(request):

    if request.method != 'POST':
        return HttpResponseRedirect('/dashboard/')

    # measurement-Objekt aus den Session-Variablen auslesen und wieder erstellen
    measurement = measurement_obj.Measurement(request.session['measurementData'],request.session['measurementHeader'],
                                   request.session['measurementUnits'],request.session['measurementTimeIndex'])

    # Anz der Spalten
    anzSpalten = len(measurement.data[0])

    # Resampling?
    if request.POST.get('resampling','') == 'on':
        resamplingScale = request.POST.get('resamplingScale','')
        # Resampling aufrufen
        if resamplingScale == '':
            measurement.resample_data()
        else:
            measurement.resample_data(float(resamplingScale))

    # über alle Spalten iterieren (von 0 bis anzSpalten)
    for i in range(0, anzSpalten):
        if i != measurement.timeIndex:
            hochpassOrder = request.POST.get('hochpassOrder' + str(i),'')
            hochpassCofreq = request.POST.get('hochpassCofreq' + str(i),'')
            tiefpassOrder = request.POST.get('tiefpassOrder' + str(i),'')
            tiefpassCofreq = request.POST.get('tiefpassCofreq' + str(i),'')
            if request.POST.get('hochpass' + str(i),'') == 'on' and request.POST.get('tiefpass' + str(i),'') == 'on':
                if hochpassOrder != '':
                    if hochpassCofreq != '' and tiefpassCofreq != '':
                        measurement.butterworth_band_filter(data_index=i, lowcut=float(tiefpassCofreq),
                                                       highcut=float(hochpassCofreq), order=int(hochpassOrder))
                    elif hochpassCofreq != '':
                        measurement.butterworth_band_filter(data_index=i,
                                                       highcut=float(hochpassCofreq), order=int(hochpassOrder))
                    elif tiefpassCofreq != '':
                        measurement.butterworth_band_filter(data_index=i,
                                                       lowcut=float(tiefpassCofreq), order=int(hochpassOrder))
                    else:
                        measurement.butterworth_band_filter(data_index=i, order=int(hochpassOrder))
                elif hochpassCofreq != '':
                    if tiefpassCofreq != '':
                        measurement.butterworth_band_filter(data_index=i, lowcut=float(tiefpassCofreq),
                                                       highcut=float(hochpassCofreq))
                    else:
                        measurement.butterworth_band_filter(data_index=i, highcut=float(hochpassCofreq))
                elif tiefpassCofreq != '':
                    measurement.butterworth_band_filter(data_index=i, lowcut=float(tiefpassCofreq))
            else:
                if request.POST.get('hochpass' + str(i),'') == 'on':
                    if hochpassOrder != '' and hochpassCofreq != '':
                        measurement.butterworth_filter(data_index=i,cofreq=float(hochpassCofreq),
                                                       order= int(hochpassOrder),mode='high')
                    elif hochpassOrder != '':
                        measurement.butterworth_filter(data_index=i,
                                                       order= int(hochpassOrder),mode='high')
                    elif hochpassCofreq != '':
                        measurement.butterworth_filter(data_index=i,cofreq=float(hochpassCofreq),mode='high')
                    else:
                        measurement.butterworth_filter(data_index=i,mode='high')
                if request.POST.get('tiefpass' + str(i),'') == 'on':
                    if tiefpassOrder != '' and tiefpassCofreq != '':
                        measurement.butterworth_filter(data_index=i,cofreq=float(tiefpassCofreq),
                                                       order= int(tiefpassOrder),mode='low')
                    elif tiefpassOrder != '':
                        measurement.butterworth_filter(data_index=i,
                                                       order= int(tiefpassOrder),mode='low')
                    elif tiefpassCofreq != '':
                        measurement.butterworth_filter(data_index=i,cofreq=float(tiefpassCofreq),mode='low')
                    else:
                        measurement.butterworth_filter(data_index=i,mode='low')

            if request.POST.get('gauss' + str(i),'') == 'on':
                gaussStd = request.POST.get('gaussStd' + str(i),'')
                gaussM = request.POST.get('gaussM' + str(i),'')
                if gaussStd != '' and gaussM != '':
                    measurement.gaussian_filter(index=i,gauss_M=gaussM,gauss_std=gaussStd)
                elif gaussStd != '':
                    measurement.gaussian_filter(index=i,gauss_std=gaussStd)
                elif gaussM != '':
                    measurement.gaussian_filter(index=i,gauss_M=gaussM)
                else:
                    measurement.gaussian_filter(index=i)

    # Daten zum Rendern vorbereiten
    dataForRender = {
        'jsonData': json.dumps(measurement.data, cls=NumPyArangeEncoder),
        'jsonHeader': json.dumps(measurement.colNames, cls=NumPyArangeEncoder),
        'jsonEinheiten': json.dumps(measurement.colUnits, cls=NumPyArangeEncoder),
        'zeitreihenSpalte': json.dumps(measurement.timeIndex, cls=NumPyArangeEncoder)
    }

    return render(request, "process/analysis.html", dataForRender)


text:
function restoreSaveWebStorage(storage){
    var i;
    var value;
    for(i=0; i<savableData.length; i++){
        value=localStorage.getItem(storage+" "+savableData[i].name);
        restoreValue(savableData[i], value);
    }
    addToDisplay("done");
    updateAll();
    //restoreOtherValues(storage);
}

function storeSaveWebStorage(storage){
    addToDisplay("starting");
    var i;
    var value;
    for(i=0; i<savableData.length; i++){
        value=getValue(savableData[i].name);
        localStorage.setItem(storage+" "+savableData[i].name, value);
    }
    localStorage.setItem(storage+" exists", "true");
    addToDisplay("done");
}

function saveWebStorage(storage){
    var keys=getListOfVariables();
}

function restoreValue(key,value){
    var realValue;
    if(/list/.test(key.type)){
        realValue=convertToListValue(key.type.replace(" list",""), value);
    }
    else{
        realValue=convertToValue(key.type, value);
    }
    findObject(key.name).value=realValue;
}

function convertToValue(type, value){
    if(type == "boolean"){
        return value == "true";
    }
    else if(type == "number")
        return parseInt(value);
    else
        return value;
}

function convertToListValue(type, input){
    var newList=[];
    var value;
    input=input.split(",");
    for(var key in input){
        value=convertToValue(type, input[key]);
        newList.push(value);
    }
    return newList;
}
var compiled="compiled";


text:
package com.piasy.client;

import android.os.Bundle;
public interface CallbackBundle
{
	abstract void callback(Bundle bundle);
}


text:
InventoryEngine::Engine.routes.draw do
end


text:
package org.apache.isis.core.commons.xml;

import java.io.IOException;
import java.io.Writer;

public interface ContentWriter {

    void write(Writer writer) throws IOException;

}


text:
const assert = require('assert');

module.exports = {
	description: 'exports from an internal module',
	exports(exports) {
		assert.equal(exports.foo, 42);
	}
};


text:
<!DOCTYPE html>
<script src='../../../resources/js-test.js'></script>
<script>
description('Test that Custom Element should be defined while navigating between frames.');

var customBody;
var jsTestIsAsync = true;

function linkInserter(doc) {
    return function() {
        customBody = doc.getElementById('thebody');
        shouldBeDefined('customBody');
        shouldBeEqualToString('customBody.toLocaleString()', '[object HTMLBodyElement]');
        finishJSTest();
    }
}

function navigateIFrameThenInsertLink() {
    var iframe = document.getElementById('iframe');
    iframe.onload = linkInserter(iframe.contentDocument);
    iframe.contentWindow.location = 'resources/empty-custom-body.html';
}
</script>
<iframe id='iframe' onload='navigateIFrameThenInsertLink()' src='resources/empty-custom-body.html'>
</iframe>


text:
//
//  DetailDiscoverController.m
//  ApeTribe_6.22
//
//  Created by ibokan on 16/6/29.
//  Copyright © 2016年 One. All rights reserved.
//

#import "DetailDiscoverController.h"
#import "AFHTTPRequestOperationManager+Util.h"
#import "Ono.h"
#import "URL.h"
#import "LoadModel.h"
#import "SVProgressHUD.h"
#import "DetailScrollFootView.h"
#import "DetailSecondController.h"
#import "MenuTool.h"
#import "SoftWareCommintViewController.h"
#import "SoftWareXMLModel.h"
#import "ExpressionView.h"
//友盟
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaSSOHandler.h"
#define SCREEN_SIZE [UIScreen mainScreen].bounds.size
@interface DetailDiscoverController ()<UIWebViewDelegate,UIScrollViewDelegate,MenuToolDelegate,UITextFieldDelegate,UMSocialUIDelegate>
/**uiview*/
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)MenuTool *menuTool;
/**尾部视图*/
@property(nonatomic,strong)DetailScrollFootView*footView;
@property(nonatomic,strong)UITextField *textField;
/**uiview*/
@property(nonatomic,strong)UIView*buttomV;
/**计算个数*/
@property(nonatomic,strong)NSMutableArray*countMArr;
@property(nonatomic,assign)BOOL isFavorite;//是否收藏
@property(nonatomic,strong)ExpressionView*expressV;
@property(nonatomic,assign)BOOL isFace;
@end

@implementation DetailDiscoverController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"软件详情";
    self.view.backgroundColor = [UIColor whiteColor];
    //创建webview
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_SIZE.width, SCREEN_SIZE.height-44)];
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.delegate = self;
    self.webView.scrollView.delegate = self;
    NSString *str;
    if (self.url)
    {
       str =[self.url substringFromIndex:25];

    }else
    {
        str =[self.softXMLModel.url substringFromIndex:25];
    }

    NSDictionary *dic = @{@"ident":str};
    [self loadMyDataDict:dic];
    [self.view addSubview:self.webView];

    [self registerForKeyboardNotifications];
    //初始化
    self.isFavorite = YES;

    [self creatQQkeyBoard];

}
//下载评论的个数
-(void)loadCount:(NSDictionary *)param
{
    NSString *strUrl = [NSString stringWithFormat:@"%@%@?",URL_HTTP_PREFIX,URL_SOFTWARE_TWEET_LIST];
    [LoadModel postRequestWithUrl:strUrl andParams:param andSucBlock:^(id responseObject) {

        ONOXMLDocument *obj = responseObject;
        ONOXMLElement *result = obj.rootElement;
        ONOXMLElement *softObj = [result firstChildWithTag:@"tweets"];
        NSArray *arr = [softObj childrenWithTag:@"tweet"];

        self.countMArr = [NSMutableArray new];
        for (ONOXMLElement * object in arr)
        {
            SoftWareXMLModel * swXMLModel = [[SoftWareXMLModel alloc]initWithXML:object];
            [self.countMArr addObject:swXMLModel];
        }
        if (self.countMArr.count ==0)
        {
            self.menuTool.commentCount.hidden =YES;
        }else
        {
            self.menuTool.commentCount.hidden =NO;
            self.menuTool.commentCount.text =[NSString stringWithFormat:@"%ld",self.countMArr.count];

        }
        [self.view addSubview:self.menuTool];
        //创建视图===========
        [self setButtom];

    } andFailBlock:^(NSError *error) {

    }];

}
-(void)setButtom
{
    UIView *buttomV = [[UIView alloc]initWithFrame:CGRectMake(0, SCREEN_SIZE.height-45, SCREEN_SIZE.width, 45)];
    self.buttomV = buttomV;
    buttomV.backgroundColor = [UIColor colorWithRed:0.922 green:0.922 blue:0.945 alpha:1.000];
    //=================================btn==============
    UIButton * btnleft = [UIButton buttonWithType:UIButtonTypeCustom];
    btnleft.frame = CGRectMake(5, 7, 25,25);
    btnleft.tag = 0;
    [btnleft setBackgroundImage:[UIImage imageNamed:@"toolbar-text@2x"] forState:UIControlStateNormal];
    [btnleft addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttomV addSubview:btnleft];
    //========================textfield============================
    UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(35, 5 , SCREEN_SIZE.width-70, 30)];
    textField.backgroundColor = [UIColor whiteColor];
    UIView *vv = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    UIButton * btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn1.frame = CGRectMake(5, 5, 20,20);
    [btn1 setBackgroundImage:[UIImage imageNamed:@"toolbar-emoji2.png"] forState:UIControlStateNormal];
    btn1.tag = 1;
    [btn1 addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [vv addSubview:btn1];
    textField.rightView = vv;
    textField.rightViewMode = UITextFieldViewModeAlways;
    self.textField = textField;
    textField.placeholder = @"说点什么吧...";
    textField.delegate = self;
    [buttomV addSubview:textField];
    //==========================btn2====================
    UIButton * btnright = [UIButton buttonWithType:UIButtonTypeCustom];
    btnright.frame = CGRectMake(SCREEN_SIZE.width-30, 7, 25,25);
    btnright.tag = 2;
    [btnright setBackgroundImage:[UIImage imageNamed:@"send.jpg"] forState:UIControlStateNormal];
    [btnright addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
    [buttomV addSubview:btnright];
    buttomV.hidden = YES;
    [self.view addSubview:buttomV];

}

-(void)creatQQkeyBoard
{
    self.expressV = (ExpressionView *)[[NSBundle mainBundle]loadNibNamed:@"ExpressionView" owner:nil options:nil][0];
    self.expressV.frame = CGRectMake(0, 0, SCREEN_SIZE.width, 120);
    __weak typeof(self) weakSelf = self;
    self.expressV.textCallBlock = ^(NSString *text)
    {

        weakSelf.textField.text = [NSString stringWithFormat:@"%@%@",weakSelf.textField.text,text];
        //        weakSelf.btnSend.userInteractionEnabled = YES;
        //        [weakSelf.btnSend setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //        [weakSelf text00];

    };
    //删除按钮
    [self.expressV.btnDelete addTarget:self action:@selector(btnseleteAction:) forControlEvents:UIControlEventTouchUpInside];

    UILongPressGestureRecognizer *longPG = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(Action:)];
    [self.expressV.btnDelete addGestureRecognizer:longPG];

}
-(void)Action:(UILongPressGestureRecognizer *)longPG
{

    self.textField.text =nil;

}

-(void)btnseleteAction:(UIButton *)sender
{

    if (self.textField.text.length>0)
    {
        self.textField.text = [self.textField.text substringToIndex:self.textField.text.length-1];
        //        self.tipLabel.text = [NSString stringWithFormat:@"%ld/%ld字",self.textView.text.length+1, (long)MAXVALUE];

    }else{

        if (self.textField.text.length==0) {

           }

    }

}

-(void)btnAction:(UIButton *)sender
{
    switch (sender.tag) {
        case 0:
        {
            self.buttomV.hidden = YES;
            [self.textField resignFirstResponder];

        }
            break;
        case 1:
        {
           //自定义表情

            //改变键盘状态
               [self.textField becomeFirstResponder];
                self.isFace = !self.isFace;
                if (self.isFace) {

                    self.textField.inputView = self.expressV;

                }else
                {
                    self.textField.inputView = nil;
                }

                [self.textField reloadInputViews];

        }
            break;
        case 2:
        {
            if (self.textField.text.length == 0)
            {
                [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                [SVProgressHUD showInfoWithStatus:@"内容不能为空"];
            }else
            {
                //发送评论
                NSDictionary * dic = @{@"uid":@(USER_MODEL.userId),@"msg":self.textField.text,@"project":@(self.detailXMLModel.strID)};
                [self UpMyCommitData:dic andType:Comment];
            }
        }
            break;
        default:
            break;
    }

}

//上传评论
-(void)UpMyCommitData:(NSDictionary *)param andType:(typeStyle)typeStyle
{
    //上传数据,判断是否登录
    if (![[Tool readLoginState:LOGIN_STATE] isEqualToString:@"1"])
    {
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        [self.navigationController presentViewController:[Tool getNavigationController:loginVC andtransitioningDelegate:nil andNavigationViewControllerType:NavigationControllerMineType] animated:YES completion:nil];

    }else
    {

    NSString *strUrl;
    if (typeStyle == Favortie)
    {
        //判断添加还是删除
        if (self.isFavorite)
        {
            strUrl = [NSString stringWithFormat:@"%@%@?",URL_HTTP_PREFIX,URL_FAVORITE_ADD];
        }else
        {
            strUrl = [NSString stringWithFormat:@"%@%@?",URL_HTTP_PREFIX,URL_FAVORITE_DELETE];
        }

    }else
    {
        strUrl = [NSString stringWithFormat:@"%@%@?",URL_HTTP_PREFIX,URL_SOFTWARE_TWEET_PUB];

    }

    [LoadModel postRequestWithUrl:strUrl andParams:param andSucBlock:^(id responseObject) {
//        NSLog(@"========%@",responseObject);
        //类型转换
        ONOXMLDocument *obj = responseObject;
        ONOXMLElement *result = obj.rootElement;//根元素
        ONOXMLElement *softwares = [result firstChildWithTag:@"result"];
        int errorCode = [[[softwares firstChildWithTag:@"errorCode"] numberValue] intValue];
        NSString *errorMessage = [[result firstChildWithTag:@"errorMessage"] stringValue];
        if (errorCode == -1) {
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            [SVProgressHUD setMinimumDismissTimeInterval:1];
            [SVProgressHUD showInfoWithStatus:errorMessage];
        } else {
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
            [SVProgressHUD setMinimumDismissTimeInterval:1];

            if (typeStyle == Favortie)
            {

                if (self.isFavorite) {
                    [SVProgressHUD showInfoWithStatus:@"收藏添加成功"];
                    //设置收藏图片
                    [self.menuTool.btnFavorite setBackgroundImage:[UIImage imageNamed:@"toolbar-starred@2x"] forState:UIControlStateNormal];
                }else
                {
                    [SVProgressHUD showInfoWithStatus:@"收藏删除成功"];
                    //设置收藏图片
                    [self.menuTool.btnFavorite setBackgroundImage:[UIImage imageNamed:@"toolbar-star@2x"] forState:UIControlStateNormal];
                }
                self.isFavorite  =!self.isFavorite;

            }else
            {
                [SVProgressHUD showInfoWithStatus:@"恭喜您评论发送成功"];
            }

        }

    } andFailBlock:^(NSError *error) {

    }];

    }
}

//输入框代理方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textField resignFirstResponder];
    return YES;
}

- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification object:nil];

}
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    self.buttomV.hidden = NO;
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;

    self.buttomV.frame = CGRectMake(0, SCREEN_SIZE.height-45-kbSize.height, SCREEN_SIZE.width, 45);

}
- (void)keyboardWillHide:(NSNotification *)notification {

    self.buttomV.frame = CGRectMake(0, SCREEN_SIZE.height-45, SCREEN_SIZE.width, 45);

}

//菜单代理方法
-(void)doSomethingWithTag:(NSInteger)tag
{
    switch (tag) {
        case 0:
        {
            self.buttomV.hidden =NO;

        }
            break;
        case 1:
        {
            //软件动弹列表
            SoftWareCommintViewController *softVC = [[SoftWareCommintViewController alloc]init];
            softVC.softId = self.detailXMLModel.strID;
            [self.navigationController pushViewController:softVC animated:YES];

        }
            break;
        case 2:
        {
            //弹出键盘
            [self.textField becomeFirstResponder];

        }
            break;
        case 3:
        {
            //收藏
            NSDictionary * dic = @{@"uid":@(USER_MODEL.userId),@"objid":@(self.detailXMLModel.strID),@"type":@(1)};
            [self UpMyCommitData:dic andType:Favortie];

        }
            break;
        case 4:
        {
            [UMSocialWechatHandler setWXAppId:@"wx6f2c2f302768cf07" appSecret:@"309d97f1e1da94fdb3427fad32fc2b5d" url:self.detailXMLModel.url];
            //微信、微信朋友圈
            [UMSocialData defaultData].extConfig.wechatTimelineData.title = self.detailXMLModel.title;
            [UMSocialData defaultData].extConfig.wechatSessionData.url = self.detailXMLModel.url;
            //QQ、QQ空间
            [UMSocialData defaultData].extConfig.qqData.url = self.detailXMLModel.url;
            [UMSocialData defaultData].extConfig.qzoneData.url = self.detailXMLModel.url;

            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"5774e4aee0f55a0ae6001483"
                                              shareText:self.detailXMLModel.url
                                             shareImage:[UIImage imageNamed:@"10"]
                                        shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToSina,UMShareToQQ,UMShareToQzone,UMShareToTencent,UMShareToRenren,UMShareToDouban,UMShareToEmail,UMShareToSms]
                                               delegate:self];

        }
            break;

        default:
            break;
    }

}
//设置头部视图
-(void)setheadView
{
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(110 , 0, 196, 0);
    self.webView.scrollView.backgroundColor = [UIColor whiteColor];
    UILabel *lblTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, -55, SCREEN_SIZE.width, 80)];
    lblTitle.font = [UIFont systemFontOfSize:20 weight:0.5];
    lblTitle.numberOfLines = 0;
    //创建文本附件包含图片
    NSTextAttachment *attachMent = [[NSTextAttachment alloc]init];
    //设置大小
    CGFloat height = lblTitle.font.lineHeight;
    //设置图片
    attachMent.image = [UIImage imageNamed:@"recommend_tag"];
    attachMent.bounds = CGRectMake(0, -7, height, height);
    //使用附件创建属性字符串
    NSAttributedString *attrString = [NSAttributedString attributedStringWithAttachment:attachMent];
    //拼接文字
    NSString * str = [self.detailXMLModel.extensionTitle stringByAppendingString:self.detailXMLModel.title];
    //创建可变字符 拼接字符串
    NSMutableAttributedString *strM = [[NSMutableAttributedString alloc]initWithString:str];
    if (self.detailXMLModel.recommended == 4)
    {
        [strM appendAttributedString:attrString];
    }
    //获取logo
    UIImage *img = [self getImageFromURL:self.detailXMLModel.logo];
    NSTextAttachment *attachMentLogo = [[NSTextAttachment alloc]init];
    attachMentLogo.image = img;
    attachMentLogo.bounds = CGRectMake(0, -7, height, height);
    //使用附件创建属性字符串
    NSAttributedString *attrStringLogo = [NSAttributedString attributedStringWithAttachment:attachMentLogo];
    NSMutableAttributedString *strMLogo = [[NSMutableAttributedString alloc]initWithAttributedString:attrStringLogo];
    [strMLogo appendAttributedString:strM];
    //设置lable内容
    lblTitle.attributedText = strMLogo;
    [self.webView.scrollView addSubview:lblTitle];

}
//logo图片
-(UIImage*)getImageFromURL:(NSString*)fileURL
{
    NSURL *url = [NSURL URLWithString:fileURL];

    NSData * data = [NSData dataWithContentsOfURL:url];
    UIImage *result = [UIImage imageWithData:data];
    return result;
}
//尾部视图
-(void)setfootView
{
    //加载xib
    DetailScrollFootView *footView = [[NSBundle mainBundle]loadNibNamed:@"DetailScrollFootView" owner:nil options:nil][0];
    self.footView = footView;
    footView.frame = CGRectMake(0, 700, SCREEN_SIZE.width, 194);
    [self.webView.scrollView addSubview:self.footView];
    footView.hidden = YES;
    footView.author.text = self.detailXMLModel.authorid;
    footView.deal.text = self.detailXMLModel.license;
    footView.language.text = self.detailXMLModel.language;
    footView.system.text = self.detailXMLModel.os;
    footView.time.text =self.detailXMLModel.recordtime;
    footView.footBlock = ^(NSInteger tagV)
    {
        switch (tagV) {
            case 1:
            {

                DetailSecondController *detailVC = [[DetailSecondController alloc]init];
                detailVC.detailTitlt = self.detailXMLModel.title;
                detailVC.url =self.detailXMLModel.homepage;
                [self.navigationController pushViewController:detailVC animated:YES];

            }
                break;
            case 2:
            {

                DetailSecondController *detailVC = [[DetailSecondController alloc]init];
                detailVC.detailTitlt = self.detailXMLModel.title;
                detailVC.url =self.detailXMLModel.document;
                [self.navigationController pushViewController:detailVC animated:YES];

            }
                break;
            case 3:
            {
                DetailSecondController *detailVC = [[DetailSecondController alloc]init];
                detailVC.detailTitlt = self.detailXMLModel.title;
                detailVC.url =self.detailXMLModel.download;
                [self.navigationController pushViewController:detailVC animated:YES];

            }
                break;

            default:
                break;
        }

    };

}

-(void)loadMyDataDict:(NSDictionary *)param
{
    NSString *strUrl = [NSString stringWithFormat:@"%@%@?",URL_HTTP_PREFIX,URL_SOFTWARE_DETAIL];

    [LoadModel postRequestWithUrl:strUrl andParams:param andSucBlock:^(id responseObject) {

        //类型转换
        ONOXMLDocument *obj = responseObject;
        ONOXMLElement *result = obj.rootElement;//根元素
        ONOXMLElement *softwares = [result firstChildWithTag:@"software"];
        //转模型
        self.detailXMLModel = [[DetailXMLModel alloc]initWithXML:softwares];
        [self setUp];
        if (self.detailXMLModel.body == nil) return ;
        //下载评论个数
        NSDictionary *dic2 = @{@"project":@(self.detailXMLModel.strID),@"pageIndex":@(0),@"pageSize":@(20)};

        [self loadCount:dic2];
        //设置头部视图
        [self setheadView];
        //设置尾部视图
        [self setfootView];

    } andFailBlock:^(NSError *error) {
        NSLog(@"err:%@",error);
    }];

}
-(void)setUp
{
    [SVProgressHUD setMinimumDismissTimeInterval:1];
    if (self.detailXMLModel.body == nil)
    {
        [SVProgressHUD showErrorWithStatus:@"没有相关的详情"];
        return;
    }
    NSString *str1 = [NSString stringWithFormat:@"<head><style>img{width:%fpx !important;}</style></head>",(SCREEN_SIZE.width*0.95)];
    [self.webView loadHTMLString:[str1 stringByAppendingString:self.detailXMLModel.body]  baseURL:nil];

}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.footView.frame = CGRectMake(0, self.webView.scrollView.contentSize.height, SCREEN_SIZE.width, 194);

    self.footView.hidden = NO;
}
-(MenuTool*)menuTool
{
    if (_menuTool == nil)
    {
        _menuTool = [[NSBundle mainBundle] loadNibNamed:@"MenuTool" owner:nil options:nil][1];
        _menuTool.frame = CGRectMake(0, SCREEN_SIZE.height-45, SCREEN_SIZE.width, 45);
        _menuTool.gDelegate = self;

    }
    return  _menuTool;
}

@end


text:
{% case site.tag_archive.type %}
  {% when "liquid" %}
    {% assign path_type = "#" %}
  {% when "jekyll-archives" %}
    {% assign path_type = nil %}
{% endcase %}

{{ site.data.ui-text[site.locale].tags_label | default: "Tags:" }}

  {% capture page_tags %}{% for tag in post.tags %}{{ tag | downcase }}#{{ tag }}{% unless forloop.last %},{% endunless %}{% endfor %}{% endcapture %}
  {% assign tag_hashes = (page_tags | split: ',' | sort:0) %}

    {% for hash in tag_hashes %}
      {% assign keyValue = hash | split: '#' %}
      {% capture tag_word %}{{ keyValue[1] | strip_newlines }}{% endcapture %}
      {{ tag_word }}{% unless forloop.last %}, {% endunless %}
    {% endfor %}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search -->
    <item
        android:id="@+id/action_search"
	android:icon="@drawable/ic_action_search"
	android:title="@string/action_search"
	android:showAsAction="ifRoom" />
    <!-- Settings -->
    <item
        android:id="@+id/action_settings"
	android:title="@string/action_settings"
	android:showAsAction="never" />
</menu>


text:
#ifndef __RENDERPROGS_H__
#define __RENDERPROGS_H__

static const int PC_ATTRIB_INDEX_VERTEX		= 0;
static const int PC_ATTRIB_INDEX_NORMAL		= 2;
static const int PC_ATTRIB_INDEX_COLOR		= 3;
static const int PC_ATTRIB_INDEX_COLOR2		= 4;
static const int PC_ATTRIB_INDEX_ST			= 8;
static const int PC_ATTRIB_INDEX_TANGENT	= 9;

// This enum list corresponds to the global constant register indecies as defined in global.inc for all
// shaders.  We used a shared pool to keeps things simple.  If something changes here then it also
// needs to change in global.inc and vice versa
enum renderParm_t {
	// For backwards compatibility, do not change the order of the first 17 items
	RENDERPARM_SCREENCORRECTIONFACTOR = 0,
	RENDERPARM_WINDOWCOORD,
	RENDERPARM_DIFFUSEMODIFIER,
	RENDERPARM_SPECULARMODIFIER,

	RENDERPARM_LOCALLIGHTORIGIN,
	RENDERPARM_LOCALVIEWORIGIN,

	RENDERPARM_LIGHTPROJECTION_S,
	RENDERPARM_LIGHTPROJECTION_T,
	RENDERPARM_LIGHTPROJECTION_Q,
	RENDERPARM_LIGHTFALLOFF_S,

	RENDERPARM_BUMPMATRIX_S,
	RENDERPARM_BUMPMATRIX_T,

	RENDERPARM_DIFFUSEMATRIX_S,
	RENDERPARM_DIFFUSEMATRIX_T,

	RENDERPARM_SPECULARMATRIX_S,
	RENDERPARM_SPECULARMATRIX_T,

	RENDERPARM_VERTEXCOLOR_MODULATE,
	RENDERPARM_VERTEXCOLOR_ADD,

	// The following are new and can be in any order

	RENDERPARM_COLOR,
	RENDERPARM_VIEWORIGIN,
	RENDERPARM_GLOBALEYEPOS,

	RENDERPARM_MVPMATRIX_X,
	RENDERPARM_MVPMATRIX_Y,
	RENDERPARM_MVPMATRIX_Z,
	RENDERPARM_MVPMATRIX_W,

	RENDERPARM_MODELMATRIX_X,
	RENDERPARM_MODELMATRIX_Y,
	RENDERPARM_MODELMATRIX_Z,
	RENDERPARM_MODELMATRIX_W,

	RENDERPARM_PROJMATRIX_X,
	RENDERPARM_PROJMATRIX_Y,
	RENDERPARM_PROJMATRIX_Z,
	RENDERPARM_PROJMATRIX_W,

	RENDERPARM_MODELVIEWMATRIX_X,
	RENDERPARM_MODELVIEWMATRIX_Y,
	RENDERPARM_MODELVIEWMATRIX_Z,
	RENDERPARM_MODELVIEWMATRIX_W,

	RENDERPARM_TEXTUREMATRIX_S,
	RENDERPARM_TEXTUREMATRIX_T,

	RENDERPARM_TEXGEN_0_S,
	RENDERPARM_TEXGEN_0_T,
	RENDERPARM_TEXGEN_0_Q,
	RENDERPARM_TEXGEN_0_ENABLED,

	RENDERPARM_TEXGEN_1_S,
	RENDERPARM_TEXGEN_1_T,
	RENDERPARM_TEXGEN_1_Q,
	RENDERPARM_TEXGEN_1_ENABLED,

	RENDERPARM_WOBBLESKY_X,
	RENDERPARM_WOBBLESKY_Y,
	RENDERPARM_WOBBLESKY_Z,

	RENDERPARM_OVERBRIGHT,
	RENDERPARM_ENABLE_SKINNING,
	RENDERPARM_ALPHA_TEST,

	RENDERPARM_TOTAL,
	RENDERPARM_USER = 128,
};

struct glslUniformLocation_t {
	int		parmIndex;
	GLint	uniformIndex;
};

/*
================================================================================================
idRenderProgManager
================================================================================================
*/
class idRenderProgManager {
public:
	idRenderProgManager();
	virtual ~idRenderProgManager();

	void	Init();
	void	Shutdown();

	void	SetRenderParm( renderParm_t rp, const float * value );
	void	SetRenderParms( renderParm_t rp, const float * values, int numValues );

	int		FindVertexShader( const char * name );
	int		FindFragmentShader( const char * name );

	void	BindShader( int vIndex, int fIndex );

	void	BindShader_GUI( ) { BindShader_Builtin( BUILTIN_GUI ); }
	void	BindShader_Color( ) { BindShader_Builtin( BUILTIN_COLOR ); }
	void	BindShader_Texture( ) { BindShader_Builtin( BUILTIN_TEXTURED ); }
	void	BindShader_TextureVertexColor() { BindShader_Builtin( BUILTIN_TEXTURE_VERTEXCOLOR ); };
	void	BindShader_TextureVertexColorSkinned() { BindShader_Builtin( BUILTIN_TEXTURE_VERTEXCOLOR_SKINNED ); };
	void	BindShader_TextureTexGenVertexColor() { BindShader_Builtin( BUILTIN_TEXTURE_TEXGEN_VERTEXCOLOR ); };
	void	BindShader_Interaction()  { BindShader_Builtin( BUILTIN_INTERACTION ); }
	void	BindShader_InteractionSkinned()  { BindShader_Builtin( BUILTIN_INTERACTION_SKINNED ); }
	void	BindShader_InteractionAmbient()  { BindShader_Builtin( BUILTIN_INTERACTION_AMBIENT ); }
	void	BindShader_InteractionAmbientSkinned()  { BindShader_Builtin( BUILTIN_INTERACTION_AMBIENT_SKINNED ); }
	void	BindShader_SimpleShade() { BindShader_Builtin( BUILTIN_SIMPLESHADE ); }
	void	BindShader_Environment() { BindShader_Builtin( BUILTIN_ENVIRONMENT ); }
	void	BindShader_EnvironmentSkinned() { BindShader_Builtin( BUILTIN_ENVIRONMENT_SKINNED ); }
	void	BindShader_BumpyEnvironment() { BindShader_Builtin( BUILTIN_BUMPY_ENVIRONMENT ); }
	void	BindShader_BumpyEnvironmentSkinned() { BindShader_Builtin( BUILTIN_BUMPY_ENVIRONMENT_SKINNED ); }

	void	BindShader_Depth() { BindShader_Builtin( BUILTIN_DEPTH ); }
	void	BindShader_DepthSkinned() { BindShader_Builtin( BUILTIN_DEPTH_SKINNED ); }
	void	BindShader_Shadow() { BindShader( builtinShaders[BUILTIN_SHADOW], -1 ); }
	void	BindShader_ShadowSkinned() { BindShader( builtinShaders[BUILTIN_SHADOW_SKINNED], -1 ); }
	void	BindShader_ShadowDebug() { BindShader_Builtin( BUILTIN_SHADOW_DEBUG ); }
	void	BindShader_ShadowDebugSkinned() { BindShader_Builtin( BUILTIN_SHADOW_DEBUG_SKINNED ); }

	void	BindShader_BlendLight() { BindShader_Builtin( BUILTIN_BLENDLIGHT ); }
	void	BindShader_Fog() { BindShader_Builtin( BUILTIN_FOG ); }
	void	BindShader_FogSkinned() { BindShader_Builtin( BUILTIN_FOG_SKINNED ); }
	void	BindShader_SkyBox() { BindShader_Builtin( BUILTIN_SKYBOX ); }
	void	BindShader_WobbleSky() { BindShader_Builtin( BUILTIN_WOBBLESKY ); }
	void	BindShader_StereoDeGhost() { BindShader_Builtin( BUILTIN_STEREO_DEGHOST ); }
	void	BindShader_StereoWarp() { BindShader_Builtin( BUILTIN_STEREO_WARP ); }
	void	BindShader_StereoInterlace() { BindShader_Builtin( BUILTIN_STEREO_INTERLACE ); }
	void	BindShader_PostProcess() { BindShader_Builtin( BUILTIN_POSTPROCESS ); }
	void	BindShader_ZCullReconstruct() { BindShader_Builtin( BUILTIN_ZCULL_RECONSTRUCT ); }
	void	BindShader_Bink() { BindShader_Builtin( BUILTIN_BINK ); }
	void	BindShader_BinkGUI() { BindShader_Builtin( BUILTIN_BINK_GUI ); }
	void	BindShader_MotionBlur() { BindShader_Builtin( BUILTIN_MOTION_BLUR); }

	// the joints buffer should only be bound for vertex programs that use joints
	bool	ShaderUsesJoints() const { return vertexShaders[currentVertexShader].usesJoints; }
	// the rpEnableSkinning render parm should only be set for vertex programs that use it
	bool	ShaderHasOptionalSkinning() const { return vertexShaders[currentVertexShader].optionalSkinning; }

	// unbind the currently bound render program
	void	Unbind();

	// this should only be called via the reload shader console command
	void	LoadAllShaders();
	void	KillAllShaders();

	static const int	MAX_GLSL_USER_PARMS = 8;
	const char*	GetGLSLParmName( int rp ) const;
	int			GetGLSLCurrentProgram() const { return currentRenderProgram; }
	void		SetUniformValue( const renderParm_t rp, const float * value );
	void		CommitUniforms();
	int			FindGLSLProgram( const char* name, int vIndex, int fIndex );
	void		ZeroUniforms();

protected:
	void	LoadVertexShader( int index );
	void	LoadFragmentShader( int index );

	enum {
		BUILTIN_GUI,
		BUILTIN_COLOR,
		BUILTIN_SIMPLESHADE,
		BUILTIN_TEXTURED,
		BUILTIN_TEXTURE_VERTEXCOLOR,
		BUILTIN_TEXTURE_VERTEXCOLOR_SKINNED,
		BUILTIN_TEXTURE_TEXGEN_VERTEXCOLOR,
		BUILTIN_INTERACTION,
		BUILTIN_INTERACTION_SKINNED,
		BUILTIN_INTERACTION_AMBIENT,
		BUILTIN_INTERACTION_AMBIENT_SKINNED,
		BUILTIN_ENVIRONMENT,
		BUILTIN_ENVIRONMENT_SKINNED,
		BUILTIN_BUMPY_ENVIRONMENT,
		BUILTIN_BUMPY_ENVIRONMENT_SKINNED,

		BUILTIN_DEPTH,
		BUILTIN_DEPTH_SKINNED,
		BUILTIN_SHADOW,
		BUILTIN_SHADOW_SKINNED,
		BUILTIN_SHADOW_DEBUG,
		BUILTIN_SHADOW_DEBUG_SKINNED,

		BUILTIN_BLENDLIGHT,
		BUILTIN_FOG,
		BUILTIN_FOG_SKINNED,
		BUILTIN_SKYBOX,
		BUILTIN_WOBBLESKY,
		BUILTIN_POSTPROCESS,
		BUILTIN_STEREO_DEGHOST,
		BUILTIN_STEREO_WARP,
		BUILTIN_ZCULL_RECONSTRUCT,
		BUILTIN_BINK,
		BUILTIN_BINK_GUI,
		BUILTIN_STEREO_INTERLACE,
		BUILTIN_MOTION_BLUR,

		MAX_BUILTINS
	};
	int builtinShaders[MAX_BUILTINS];
	void BindShader_Builtin( int i ) { BindShader( builtinShaders[i], builtinShaders[i] ); }

	GLuint	LoadShader( GLenum target, const char * name, const char * startToken );
	bool	CompileGLSL( GLenum target, const char * name );
	GLuint	LoadGLSLShader( GLenum target, const char * name, idList<int> & uniforms );
	void	LoadGLSLProgram( const int programIndex, const int vertexShaderIndex, const int fragmentShaderIndex );

	static const GLuint INVALID_PROGID = 0xFFFFFFFF;

	struct vertexShader_t {
					vertexShader_t() : progId( INVALID_PROGID ), usesJoints( false ), optionalSkinning( false ) {}
		idStr		name;
		GLuint		progId;
		bool		usesJoints;
		bool		optionalSkinning;
		idList<int>	uniforms;
	};
	struct fragmentShader_t {
					fragmentShader_t() : progId( INVALID_PROGID ) {}
		idStr		name;
		GLuint		progId;
		idList<int>	uniforms;
	};

	struct glslProgram_t {
		glslProgram_t() :	progId( INVALID_PROGID ),
							vertexShaderIndex( -1 ),
							fragmentShaderIndex( -1 ),
							vertexUniformArray( -1 ),
							fragmentUniformArray( -1 ) {}
		idStr		name;
		GLuint		progId;
		int			vertexShaderIndex;
		int			fragmentShaderIndex;
		GLint		vertexUniformArray;
		GLint		fragmentUniformArray;
		idList<glslUniformLocation_t> uniformLocations;
	};
	int	currentRenderProgram;
	idList<glslProgram_t, TAG_RENDER> glslPrograms;
	idStaticList<idVec4, RENDERPARM_USER + MAX_GLSL_USER_PARMS> glslUniforms;

	int				currentVertexShader;
	int				currentFragmentShader;
	idList<vertexShader_t, TAG_RENDER> vertexShaders;
	idList<fragmentShader_t, TAG_RENDER> fragmentShaders;
};

extern idRenderProgManager renderProgManager;

#endif


text:
package org.apache.yoko.rmi.impl;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.logging.Logger;

import org.omg.CORBA.MARSHAL;

public final class CopyState {

    static Logger logger = Logger.getLogger(CopyState.class.getName());

    private IdentityHashMap copied;

    private IdentityHashMap recursionResolverMap;

    private TypeRepository rep;

    private static Object recursionCheck = new Object();

    public CopyState(TypeRepository rep) {
        this.rep = rep;
        this.copied = new IdentityHashMap();
        this.recursionResolverMap = new IdentityHashMap();
    }

    public void registerRecursion(CopyRecursionResolver resolver) {
        Object key = resolver.orig;
        CopyRecursionResolver orig = (CopyRecursionResolver) recursionResolverMap
                .get(key);
        resolver.next = orig;
        recursionResolverMap.put(key, resolver);

        logger.fine("registering recursion resolver " + resolver + " for "
                + key.getClass() + "@" + System.identityHashCode(key));

    }

    public void put(Object orig, Object copy) {
        Object old = copied.put(orig, copy);
        if (old == recursionCheck) {
            for (CopyRecursionResolver resolver = (CopyRecursionResolver) recursionResolverMap
                    .get(orig); resolver != null; resolver = resolver.next) {

                logger
                        .fine("invoking " + resolver + " for "
                                + orig.getClass() + "@"
                                + System.identityHashCode(orig) + " ===> "
                                + copy.getClass() + "@"
                                + System.identityHashCode(copy));

                resolver.resolve(copy);
            }
        }
    }

    private String spaces(int c) {
        StringBuffer sb = new StringBuffer();
        while (c-- != 0) {
            sb.append(' ');
        }
        return sb.toString();
    }

    private int idx;

    public Object copy(Object orig) throws CopyRecursionException {
        if (orig == null)
            return orig;

        Object copy = copied.get(orig);
        if (copy != null) {
            if (copy == recursionCheck) {
                logger.fine("throwign CopyRecursion for " + orig.getClass()
                        + "@" + System.identityHashCode(orig));

                throw new CopyRecursionException(this, orig);
            }
            return copy;
        }

        Class origClass = orig.getClass();

        logger.fine("[" + hashCode() + "]" + spaces(idx++)
                + "copying instance of " + origClass);

        TypeDescriptor desc = rep.getDescriptor(origClass);

        copied.put(orig, recursionCheck);
        copy = desc.copyObject(orig, this);
        copied.put(orig, copy);

        logger.fine(spaces(--idx) + "=> " + copy);

        return copy;
    }

    public ObjectWriter createObjectWriter(final java.io.Serializable obj) {
        try {
            return (ObjectWriter) java.security.AccessController
                    .doPrivileged(new java.security.PrivilegedExceptionAction() {
                        public Object run() throws IOException {
                            return new Writer(obj);
                        }
                    });

        } catch (java.security.PrivilegedActionException e) {
            throw (InternalError)new InternalError(e.getMessage()).initCause(e);
        }
    }

    class Writer extends ObjectWriter {
        List contents = new ArrayList();

        private void enqueue(Object o) {
            contents.add(o);
        }

        Writer(java.io.Serializable obj) throws java.io.IOException {
            super(obj);
        }

        public ObjectReader getObjectReader(Object val) {
            try {
                // register mapping from old value to new
                put(object, val);
                return new Reader((Serializable) val, contents);
            } catch (IOException ex) {
                throw (MARSHAL)new MARSHAL(ex.getMessage()).initCause(ex);
            }

        }

        public void write(int val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Byte((byte) val));
        }

        public void write(byte[] val) throws java.io.IOException {
            write(val, 0, val.length);
        }

        public void write(byte[] arr, int off, int len)
                throws java.io.IOException {
            if (arr == null || arr.length == 0) {
                beforeWriteData();
                enqueue(null);
            } else if (off == 0 && len == arr.length) {
                beforeWriteData();
                enqueue(arr);
            } else {
                byte[] data = new byte[len];
                System.arraycopy(arr, off, data, 0, len);
                beforeWriteData();
                enqueue(data);
            }
        }

        public void writeBoolean(boolean val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Boolean(val));
        }

        public void writeByte(int val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Byte((byte) val));
        }

        public void writeShort(int val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Short((short) val));
        }

        public void writeChar(int val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Character((char) val));
        }

        public void writeInt(int val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Integer(val));
        }

        public void writeLong(long val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Long(val));
        }

        public void writeFloat(float val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Float(val));
        }

        public void writeDouble(double val) throws java.io.IOException {
            beforeWriteData();
            enqueue(new Double(val));
        }

        public void writeBytes(java.lang.String val) throws java.io.IOException {
            beforeWriteData();
            byte[] data = val.getBytes();
            enqueue(data);
        }

        public void writeChars(java.lang.String val) throws java.io.IOException {
            beforeWriteData();
            char[] data = val.toCharArray();
            enqueue(data);
        }

        public void writeUTF(java.lang.String val) throws java.io.IOException {
            beforeWriteData();
            enqueue(val);
        }

        public void writeObjectOverride(final Object obj) {
            Object copy;

            try {
                copy = copy(obj);
            } catch (CopyRecursionException rec) {
                copy = recursionCheck;

                // save position of newly added element
                final int idx = contents.size();

                registerRecursion(new CopyRecursionResolver(obj) {
                    public void resolve(Object newValue) {
                        contents.set(idx, newValue);
                    }
                });
            }

            enqueue(copy);
        }

        public void writeValueObject(Object obj) {
            writeObjectOverride(obj);
        }

        public void writeCorbaObject(Object obj) {
            writeObjectOverride(obj);
        }

        public void writeRemoteObject(Object obj) {
            writeObjectOverride(obj);
        }

        public void writeAny(Object obj) {
            writeObjectOverride(obj);
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.yoko.rmi.impl.ObjectWriter#_startValue(java.lang.String)
         */
        protected void _startValue(String rep_id) throws IOException {
        }

        /*
         * (non-Javadoc)
         *
         * @see org.apache.yoko.rmi.impl.ObjectWriter#_endValue()
         */
        protected void _endValue() throws IOException {
        }

        protected void _nullValue() throws IOException {
        }

    }

    public class Reader extends ObjectReaderBase {

        int cpos;

        List contents;

        private Object dequeue() {
            Object result = contents.get(cpos++);

            if (result == recursionCheck) {
                throw new IllegalStateException("recursion was not resolved?");
            } else {
                return result;
            }
        }

        private void undequeue(Object o) {
            contents.set(--cpos, o);
        }

        Reader(java.io.Serializable obj, List data) throws IOException {
            super(obj);
            contents = data;
            cpos = 0;
        }

        public Object readAbstractObject() {
            return dequeue();
        }

        public Object readAny() {
            return dequeue();
        }

        public Object readValueObject() {
            return dequeue();
        }

        public Object readValueObject(Class<?> clz) {
            return dequeue();
        }

        public org.omg.CORBA.Object readCorbaObject(Class<?> type) {
            return (org.omg.CORBA.Object) dequeue();
        }

        public java.rmi.Remote readRemoteObject(Class<?> type) {
            return (java.rmi.Remote) dequeue();
        }

        public void readFully(byte[] arr, int off, int val)
                throws java.io.IOException {
            while (val > 0) {
                int bytes = read(arr, off, val);
                off += bytes;
                val -= bytes;
            }
        }

        public int read(byte[] arr, int off, int len)
                throws java.io.IOException {
            Object obj = dequeue();

            if (obj instanceof byte[]) {
                byte[] data = (byte[]) obj;
                if (data.length <= len) {
                    System.arraycopy(data, 0, arr, off, data.length);
                    return data.length;
                } else {
                    // copy only portion of the data
                    System.arraycopy(data, 0, arr, off, len);
                    byte[] newdata = new byte[data.length - len];
                    System.arraycopy(data, len, newdata, 0, data.length - len);
                    undequeue(newdata);
                    return len;
                }
            } else if (obj instanceof Byte) {
                Byte b = (Byte) obj;
                arr[off] = b.byteValue();
                return 1;
            } else {
                throw new IOException("stream contents is not byte[], it is: "
                        + obj.getClass().getName());
            }
        }

        public int skipBytes(int len) throws java.io.IOException {
            byte[] data = new byte[len];
            readFully(data);
            return len;
        }

        public boolean readBoolean() throws java.io.IOException {
            try {
                return ((Boolean) dequeue()).booleanValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        public byte readByte() throws java.io.IOException {
            try {
                return ((Byte) dequeue()).byteValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        public short readShort() throws java.io.IOException {
            try {
                return ((Short) dequeue()).shortValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        public char readChar() throws java.io.IOException {
            try {
                return ((Character) dequeue()).charValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        public int readInt() throws java.io.IOException {
            try {
                return ((Integer) dequeue()).intValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        public long readLong() throws java.io.IOException {
            try {
                return ((Long) dequeue()).longValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        public float readFloat() throws java.io.IOException {
            try {
                return ((Float) dequeue()).floatValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        public double readDouble() throws java.io.IOException {
            try {
                return ((Double) dequeue()).doubleValue();
            } catch (ClassCastException ex) {
                IOException iox = new IOException(ex.getMessage());
                iox.initCause(ex);
                throw iox;
            }
        }

        /** @deprecated */
        public java.lang.String readLine() throws java.io.IOException {
            throw new InternalError("cannot use readline");
        }

        public java.lang.String readUTF() throws java.io.IOException {
            return (String) dequeue();
        }

        @Override
        protected void _startValue() {
        }

        @Override
        protected void _endValue() {
        }

    }

}


text:
<?php session_start(); include('../../../../dbaccess/index.php');  include('../../../../dbaccess/modules.php');

	$username = $_SESSION['username'];

	unset($_SESSION['postEdit']);

	if(isset($_SESSION["username"]) == false)
	{
		header("Location: ../");
	}
	$galleryName = $_GET['galleryName'];

	$statement = $conn->prepare("SELECT image.location FROM image LEFT JOIN gallery ON gallery.ID = image.galleryId WHERE gallery.galleryName = :galleryName");
    $statement->bindParam(":galleryName", $galleryName);
    $statement->execute();
    $results = $statement->fetchAll();
    echo stripcslashes(json_encode($results));
?>


text:
package com.azure.resourcemanager.devcenter.implementation;

import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.devcenter.fluent.DevBoxDefinitionsClient;
import com.azure.resourcemanager.devcenter.fluent.models.DevBoxDefinitionInner;
import com.azure.resourcemanager.devcenter.models.DevBoxDefinition;
import com.azure.resourcemanager.devcenter.models.DevBoxDefinitions;

public final class DevBoxDefinitionsImpl implements DevBoxDefinitions {
    private static final ClientLogger LOGGER = new ClientLogger(DevBoxDefinitionsImpl.class);

    private final DevBoxDefinitionsClient innerClient;

    private final com.azure.resourcemanager.devcenter.DevCenterManager serviceManager;

    public DevBoxDefinitionsImpl(
        DevBoxDefinitionsClient innerClient, com.azure.resourcemanager.devcenter.DevCenterManager serviceManager) {
        this.innerClient = innerClient;
        this.serviceManager = serviceManager;
    }

    public PagedIterable<DevBoxDefinition> listByDevCenter(String resourceGroupName, String devCenterName) {
        PagedIterable<DevBoxDefinitionInner> inner =
            this.serviceClient().listByDevCenter(resourceGroupName, devCenterName);
        return Utils.mapPage(inner, inner1 -> new DevBoxDefinitionImpl(inner1, this.manager()));
    }

    public PagedIterable<DevBoxDefinition> listByDevCenter(
        String resourceGroupName, String devCenterName, Integer top, Context context) {
        PagedIterable<DevBoxDefinitionInner> inner =
            this.serviceClient().listByDevCenter(resourceGroupName, devCenterName, top, context);
        return Utils.mapPage(inner, inner1 -> new DevBoxDefinitionImpl(inner1, this.manager()));
    }

    public Response<DevBoxDefinition> getWithResponse(
        String resourceGroupName, String devCenterName, String devBoxDefinitionName, Context context) {
        Response<DevBoxDefinitionInner> inner =
            this.serviceClient().getWithResponse(resourceGroupName, devCenterName, devBoxDefinitionName, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                new DevBoxDefinitionImpl(inner.getValue(), this.manager()));
        } else {
            return null;
        }
    }

    public DevBoxDefinition get(String resourceGroupName, String devCenterName, String devBoxDefinitionName) {
        DevBoxDefinitionInner inner = this.serviceClient().get(resourceGroupName, devCenterName, devBoxDefinitionName);
        if (inner != null) {
            return new DevBoxDefinitionImpl(inner, this.manager());
        } else {
            return null;
        }
    }

    public void delete(String resourceGroupName, String devCenterName, String devBoxDefinitionName) {
        this.serviceClient().delete(resourceGroupName, devCenterName, devBoxDefinitionName);
    }

    public void delete(String resourceGroupName, String devCenterName, String devBoxDefinitionName, Context context) {
        this.serviceClient().delete(resourceGroupName, devCenterName, devBoxDefinitionName, context);
    }

    public PagedIterable<DevBoxDefinition> listByProject(String resourceGroupName, String projectName) {
        PagedIterable<DevBoxDefinitionInner> inner = this.serviceClient().listByProject(resourceGroupName, projectName);
        return Utils.mapPage(inner, inner1 -> new DevBoxDefinitionImpl(inner1, this.manager()));
    }

    public PagedIterable<DevBoxDefinition> listByProject(
        String resourceGroupName, String projectName, Integer top, Context context) {
        PagedIterable<DevBoxDefinitionInner> inner =
            this.serviceClient().listByProject(resourceGroupName, projectName, top, context);
        return Utils.mapPage(inner, inner1 -> new DevBoxDefinitionImpl(inner1, this.manager()));
    }

    public Response<DevBoxDefinition> getByProjectWithResponse(
        String resourceGroupName, String projectName, String devBoxDefinitionName, Context context) {
        Response<DevBoxDefinitionInner> inner =
            this
                .serviceClient()
                .getByProjectWithResponse(resourceGroupName, projectName, devBoxDefinitionName, context);
        if (inner != null) {
            return new SimpleResponse<>(
                inner.getRequest(),
                inner.getStatusCode(),
                inner.getHeaders(),
                new DevBoxDefinitionImpl(inner.getValue(), this.manager()));
        } else {
            return null;
        }
    }

    public DevBoxDefinition getByProject(String resourceGroupName, String projectName, String devBoxDefinitionName) {
        DevBoxDefinitionInner inner =
            this.serviceClient().getByProject(resourceGroupName, projectName, devBoxDefinitionName);
        if (inner != null) {
            return new DevBoxDefinitionImpl(inner, this.manager());
        } else {
            return null;
        }
    }

    public DevBoxDefinition getById(String id) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String devCenterName = Utils.getValueFromIdByName(id, "devcenters");
        if (devCenterName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'devcenters'.", id)));
        }
        String devBoxDefinitionName = Utils.getValueFromIdByName(id, "devboxdefinitions");
        if (devBoxDefinitionName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format(
                                "The resource ID '%s' is not valid. Missing path segment 'devboxdefinitions'.", id)));
        }
        return this.getWithResponse(resourceGroupName, devCenterName, devBoxDefinitionName, Context.NONE).getValue();
    }

    public Response<DevBoxDefinition> getByIdWithResponse(String id, Context context) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String devCenterName = Utils.getValueFromIdByName(id, "devcenters");
        if (devCenterName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'devcenters'.", id)));
        }
        String devBoxDefinitionName = Utils.getValueFromIdByName(id, "devboxdefinitions");
        if (devBoxDefinitionName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format(
                                "The resource ID '%s' is not valid. Missing path segment 'devboxdefinitions'.", id)));
        }
        return this.getWithResponse(resourceGroupName, devCenterName, devBoxDefinitionName, context);
    }

    public void deleteById(String id) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String devCenterName = Utils.getValueFromIdByName(id, "devcenters");
        if (devCenterName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'devcenters'.", id)));
        }
        String devBoxDefinitionName = Utils.getValueFromIdByName(id, "devboxdefinitions");
        if (devBoxDefinitionName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format(
                                "The resource ID '%s' is not valid. Missing path segment 'devboxdefinitions'.", id)));
        }
        this.delete(resourceGroupName, devCenterName, devBoxDefinitionName, Context.NONE);
    }

    public void deleteByIdWithResponse(String id, Context context) {
        String resourceGroupName = Utils.getValueFromIdByName(id, "resourceGroups");
        if (resourceGroupName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format("The resource ID '%s' is not valid. Missing path segment 'resourceGroups'.", id)));
        }
        String devCenterName = Utils.getValueFromIdByName(id, "devcenters");
        if (devCenterName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String.format("The resource ID '%s' is not valid. Missing path segment 'devcenters'.", id)));
        }
        String devBoxDefinitionName = Utils.getValueFromIdByName(id, "devboxdefinitions");
        if (devBoxDefinitionName == null) {
            throw LOGGER
                .logExceptionAsError(
                    new IllegalArgumentException(
                        String
                            .format(
                                "The resource ID '%s' is not valid. Missing path segment 'devboxdefinitions'.", id)));
        }
        this.delete(resourceGroupName, devCenterName, devBoxDefinitionName, context);
    }

    private DevBoxDefinitionsClient serviceClient() {
        return this.innerClient;
    }

    private com.azure.resourcemanager.devcenter.DevCenterManager manager() {
        return this.serviceManager;
    }

    public DevBoxDefinitionImpl define(String name) {
        return new DevBoxDefinitionImpl(name, this.manager());
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

          <title>ParallelCorrelationClustering documentation</title>
          <meta name="description" content="ParallelCorrelationClustering documentation" />
          <meta name="keywords" content="ParallelCorrelationClustering documentation" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../lib/ref-index.css" media="screen" type="text/css" rel="stylesheet" />

nSuccessor

SparseGraph

numArcs

SparseGraph

numNodes

SparseGraph


text:
//  Binh2.java
//
//  Author:
//       Antonio J. Nebro <antonio@lcc.uma.es>
//
//  Copyright (c) 2012 Antonio J. Nebro
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU Lesser General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

package org.uma.jmetal.problem.multiobjective;

import org.uma.jmetal.problem.ConstrainedProblem;
import org.uma.jmetal.problem.impl.AbstractDoubleProblem;
import org.uma.jmetal.solution.DoubleSolution;
import org.uma.jmetal.util.solutionattribute.impl.NumberOfViolatedConstraints;
import org.uma.jmetal.util.solutionattribute.impl.OverallConstraintViolation;

import java.util.Arrays;
import java.util.List;

/** Class representing problem Binh2 */
@SuppressWarnings("serial")
public class Binh2 extends AbstractDoubleProblem implements ConstrainedProblem<DoubleSolution> {

  public OverallConstraintViolation<DoubleSolution> overallConstraintViolationDegree ;
  public NumberOfViolatedConstraints<DoubleSolution> numberOfViolatedConstraints ;
  /**
   * Constructor
   * Creates a default instance of the Binh2 problem
   */
  public Binh2() {
    setNumberOfVariables(2);
    setNumberOfObjectives(2);
    setNumberOfConstraints(2);
    setName("Binh2");

    List<Double> lowerLimit = Arrays.asList(0.0, 0.0) ;
    List<Double> upperLimit = Arrays.asList(5.0, 3.0) ;

    setLowerLimit(lowerLimit);
    setUpperLimit(upperLimit);

    overallConstraintViolationDegree = new OverallConstraintViolation<DoubleSolution>() ;
    numberOfViolatedConstraints = new NumberOfViolatedConstraints<DoubleSolution>() ;
  }

  /** Evaluate() method */
  @Override
  public void evaluate(DoubleSolution solution) {
    double[] fx = new double[getNumberOfObjectives()];
    double[] x = new double[getNumberOfVariables()];
    for (int i = 0; i < getNumberOfVariables(); i++) {
      x[i] = solution.getVariableValue(i) ;
    }

    fx[0] = 4.0 * x[0] * x[0] + 4 * x[1] * x[1];
    fx[1] = (x[0] - 5.0) * (x[0] - 5.0) + (x[1] - 5.0) * (x[1] - 5.0);

    solution.setObjective(0, fx[0]);
    solution.setObjective(1, fx[1]);
  }

  /** EvaluateConstraints() method */
  @Override
  public void evaluateConstraints(DoubleSolution solution)  {
    double[] constraint = new double[this.getNumberOfConstraints()];

    double x0 = solution.getVariableValue(0) ;
    double x1 = solution.getVariableValue(1) ;

    constraint[0] = -1.0 * (x0 - 5) * (x0 - 5) - x1 * x1 + 25.0;
    constraint[1] = (x0 - 8) * (x0 - 8) + (x1 + 3) * (x1 + 3) - 7.7;

    double overallConstraintViolation = 0.0;
    int violatedConstraints = 0;
    for (int i = 0; i < this.getNumberOfConstraints(); i++) {
      if (constraint[i] < 0.0) {
        overallConstraintViolation += constraint[i];
        violatedConstraints++;
      }
    }

    overallConstraintViolationDegree.setAttribute(solution, overallConstraintViolation);
    numberOfViolatedConstraints.setAttribute(solution, violatedConstraints);
  }
}