text:
package com.dd.mediaplayerexample;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.IBinder;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.IOException;
import java.util.ArrayList;

public class MediaService
	extends Service
{
	private static final String TAG = MediaService.class.getSimpleName();

	private static final int NOTIFICATION_ID = 1;

	private static final String ACTION_START = TAG + ".ACTION_START";
	private static final String ACTION_QUIT  = TAG + ".ACTION_QUIT";

	private static final String ACTION_PREV = TAG + ".ACTION_PREV";
	private static final String ACTION_PLAY = TAG + ".ACTION_PLAY";
	private static final String ACTION_NEXT = TAG + ".ACTION_NEXT";

	private static final String EXTRA_PLAYLIST = "extraPlaylist";

	private MediaPlayer mMediaPlayer;
	private boolean mIsBuffering = true;
	private boolean mIsReady     = false;

	private Notification           mNotification;
	private ArrayList<RemoteViews> mRemoteViews;

	private ArrayList<MediaItem> mPlaylist;
	private MediaItem            mCurrent;

	private String               mTrackImageUrl;
	private Bitmap               mTrackBitmap;

	public static Intent createSinglePlayIntent(Context context, MediaItem item)
	{
		ArrayList<MediaItem> playlist = new ArrayList<MediaItem>(1);
		playlist.add(item);
		return createPlaylistIntent(context, playlist);
	}

	public static Intent createPlaylistIntent(Context context, ArrayList<MediaItem> playlist)
	{
		return new Intent(context, MediaService.class).setAction(ACTION_START)
			.putParcelableArrayListExtra(EXTRA_PLAYLIST, playlist);
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	@Override
	public void onCreate()
	{
		super.onCreate();

		mMediaPlayer = new MediaPlayer();

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION_QUIT);
		intentFilter.addAction(ACTION_PREV);
		intentFilter.addAction(ACTION_PLAY);
		intentFilter.addAction(ACTION_NEXT);

		registerReceiver(mButtonReceiver, intentFilter);
	}

	private BroadcastReceiver mButtonReceiver = new BroadcastReceiver()
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			final String action = intent.getAction();

			Log.d(TAG, "onReceive: " + intent.getAction());

			if(ACTION_QUIT.equals(action)){
				onCommandQuit();
			}
			else if(ACTION_PREV.equals(action)){
				onCommandPrev();
			}
			else if(ACTION_PLAY.equals(action)){
				onCommandPlayPause();
			}
			else if(ACTION_NEXT.equals(action)){
				onCommandNext();
			}
		}
	};

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		unregisterReceiver(mButtonReceiver);
		mMediaPlayer.release();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		final String action = intent.getAction();

		Log.d(TAG, "onStartCommand: " + intent.getAction());

		if(ACTION_START.equals(action)){
			ArrayList<MediaItem> playlist = intent.getParcelableArrayListExtra(EXTRA_PLAYLIST);
			onCommandStart(playlist);
			return START_STICKY;
		}

		stopSelf();
		return 0;
	}

	private void onCommandStart(ArrayList<MediaItem> playlist)
	{
		RemoteViews collapsed = new RemoteViews(getPackageName(), R.layout.notification_collapsed);

		mPlaylist = playlist;
		mCurrent = null;

		mRemoteViews = new ArrayList<RemoteViews>(2);
		mRemoteViews.add(collapsed);

		mNotification = new NotificationCompat.Builder(this).setTicker("Media Service started...")
			.setSmallIcon(R.drawable.ic_launcher)
			.setContent(collapsed)
			.setAutoCancel(false)
			.setOngoing(true)
			.build();

		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
			mNotification.bigContentView = new RemoteViews(getPackageName(),
				R.layout.notification_expanded);
			mRemoteViews.add(mNotification.bigContentView);
		}

		updateRemoteViews();

		startForeground(NOTIFICATION_ID, mNotification);

		startPlaying(mPlaylist.get(0));
	}

	private PendingIntent getButtonPendingIntent(String action)
	{
		Intent intent = new Intent(action);
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	}

	private void updateRemoteViews()
	{
		for(RemoteViews remoteViews : mRemoteViews){
			remoteViews.setOnClickPendingIntent(R.id.media_quit,
				getButtonPendingIntent(ACTION_QUIT));
			remoteViews.setOnClickPendingIntent(R.id.track_prev,
				getButtonPendingIntent(ACTION_PREV));
			remoteViews.setOnClickPendingIntent(R.id.track_play,
				getButtonPendingIntent(ACTION_PLAY));
			remoteViews.setOnClickPendingIntent(R.id.track_next,
				getButtonPendingIntent(ACTION_NEXT));

			remoteViews.setTextViewText(R.id.track_title,
				(mCurrent != null ? mCurrent.getTitle() : getString(R.string.loading)));

			if(mCurrent != null){
				if(mTrackImageUrl == null || !mTrackImageUrl.equals(mCurrent.getImage())){
					mTrackImageUrl = mCurrent.getImage();
					Picasso picasso = Picasso.with(this);
					picasso.cancelRequest(mImageTarget);
					picasso.load(mTrackImageUrl)
						.placeholder(R.drawable.track_placeholder)
						.error(R.drawable.track_error)
						.into(mImageTarget);
				}
			}
			else{
				mTrackBitmap = null;
			}

			remoteViews.setImageViewBitmap(R.id.track_image, mTrackBitmap);

			remoteViews.setBoolean(R.id.track_prev, "setEnabled", canGoPrev());
			remoteViews.setBoolean(R.id.track_play, "setEnabled", mIsReady);
			remoteViews.setBoolean(R.id.track_next, "setEnabled", canGoNext());

			remoteViews.setViewVisibility(R.id.track_buffering,
				mIsBuffering ? View.VISIBLE : View.GONE);
			remoteViews.setViewVisibility(R.id.track_play,
				!mIsBuffering ? View.VISIBLE : View.GONE);

			if(mIsReady){
				try{
					if(mMediaPlayer.isPlaying()){
						remoteViews.setImageViewResource(R.id.track_play,
							R.drawable.ic_action_playback_pause);
					}
					else{
						remoteViews.setImageViewResource(R.id.track_play,
							R.drawable.ic_action_playback_play);
					}
				}
				catch(IllegalStateException e){
					//
				}
			}
		}

		NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
		managerCompat.notify(NOTIFICATION_ID, mNotification);
	}

	private Target mImageTarget = new Target()
	{
		@Override
		public void onPrepareLoad(Drawable placeHolderDrawable)
		{
			Log.d(TAG, "onPrepareLoad: " + placeHolderDrawable);
			updateTrackBitmapFromDrawable(placeHolderDrawable);
			updateRemoteViews();
		}

		@Override
		public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from)
		{
			Log.d(TAG, "onBitmapLoaded: " + bitmap);
			mTrackBitmap = bitmap;
			updateRemoteViews();
		}

		@Override
		public void onBitmapFailed(Drawable errorDrawable)
		{
			Log.d(TAG, "onBitmapFailed: " + errorDrawable);
			updateTrackBitmapFromDrawable(errorDrawable);
			updateRemoteViews();
		}

		private void updateTrackBitmapFromDrawable(Drawable drawable)
		{
			if(drawable instanceof BitmapDrawable){
				mTrackBitmap = ((BitmapDrawable) drawable).getBitmap();
			}
			else{
				mTrackBitmap = null;
			}

		}
	};

	private void onCommandQuit()
	{
		mIsReady = false;
		mMediaPlayer.reset();
		stopForeground(true);
		stopSelf();
	}

	private void onCommandPlayPause()
	{
		try{
			if(mMediaPlayer.isPlaying()){
				onCommandPause();
			}
			else{
				onCommandPlay();
			}
			updateRemoteViews();
		}
		catch(IllegalStateException e){
			Log.e(TAG, "onCommandPlayPause", e);
			onCommandQuit();
		}
	}

	private void onCommandPlay()
	{
		try{
			mMediaPlayer.start();
			updateRemoteViews();
		}
		catch(IllegalStateException e){
			Log.e(TAG, "onCommandPlay", e);
			onCommandQuit();
		}
	}

	private void onCommandPause()
	{
		try{
			mMediaPlayer.pause();
			updateRemoteViews();
		}
		catch(IllegalStateException e){
			Log.e(TAG, "onCommandPause", e);
			onCommandQuit();
		}
	}

	private boolean canGoPrev()
	{
		return (mPlaylist != null && mCurrent != null &&
			mPlaylist.indexOf(mCurrent) - 1 >= 0);
	}

	private boolean canGoNext()
	{
		return (mPlaylist != null && mCurrent != null &&
			mPlaylist.indexOf(mCurrent) + 1 < mPlaylist.size());
	}

	private void onCommandPrev()
	{
		int index = mPlaylist.indexOf(mCurrent) - 1;
		if(index >= 0){
			startPlaying(mPlaylist.get(index));
		}
	}

	private void onCommandNext()
	{
		int index = mPlaylist.indexOf(mCurrent) + 1;
		if(index < mPlaylist.size()){
			startPlaying(mPlaylist.get(index));
		}
	}

	private void startPlaying(MediaItem item)
	{
		mCurrent = item;
		try{
			mIsReady = false;
			mIsBuffering = true;
			mMediaPlayer.reset();
			mMediaPlayer.setOnPreparedListener(mMediaPrepared);
			mMediaPlayer.setOnCompletionListener(mMediaCompleted);
			mMediaPlayer.setOnInfoListener(mMediaInfo);
			mMediaPlayer.setOnErrorListener(mMediaError);
			mMediaPlayer.setDataSource(item.getUrl());
			mMediaPlayer.prepareAsync();

			updateRemoteViews();
		}
		catch(IOException e){
			Log.e(TAG, "startPlaying", e);
			onCommandQuit();
		}
	}

	private MediaPlayer.OnPreparedListener mMediaPrepared = new MediaPlayer.OnPreparedListener()
	{
		@Override
		public void onPrepared(MediaPlayer mp)
		{
			Log.d(TAG, "MediaPlayer.onPrepared");
			mIsReady = true;
			mIsBuffering = false;
			onCommandPlay();
		}
	};

	private MediaPlayer.OnCompletionListener mMediaCompleted = new MediaPlayer.OnCompletionListener()
	{
		@Override
		public void onCompletion(MediaPlayer mp)
		{
			Log.d(TAG, "MediaPlayer.onCompletion");
			onCommandQuit();
		}
	};

	private MediaPlayer.OnInfoListener mMediaInfo = new MediaPlayer.OnInfoListener()
	{
		@Override
		public boolean onInfo(MediaPlayer mp, int what, int extra)
		{
			Log.d(TAG, "MediaPlayer.onInfo: " + what + ", " + extra);
			switch(what){
				case MediaPlayer.MEDIA_INFO_BUFFERING_START:
					mIsBuffering = true;
					updateRemoteViews();
					break;

				case MediaPlayer.MEDIA_INFO_BUFFERING_END:
					mIsBuffering = false;
					updateRemoteViews();
					break;
			}

			return true;
		}
	};

	private MediaPlayer.OnErrorListener mMediaError = new MediaPlayer.OnErrorListener()
	{
		@Override
		public boolean onError(MediaPlayer mp, int what, int extra)
		{
			Log.e(TAG, "MediaPlayer.onError: " + what + ", " + extra);
			onCommandQuit();
			return true;
		}
	};

	public static class MediaItem
		implements Parcelable
	{
		private String mTitle;
		private String mUrl;
		private String mImage;

		public MediaItem(String title, String url, String image)
		{
			mTitle = title;
			mUrl = url;
			mImage = image;
		}

		public MediaItem(Parcel source)
		{
			mTitle = source.readString();
			mUrl = source.readString();
			mImage = source.readString();
		}

		@Override
		public void writeToParcel(Parcel dest, int flags)
		{
			dest.writeString(mTitle);
			dest.writeString(mUrl);
			dest.writeString(mImage);
		}

		public String getTitle()
		{
			return mTitle;
		}

		public String getUrl()
		{
			return mUrl;
		}

		public String getImage()
		{
			return mImage;
		}

		@Override
		public int describeContents()
		{
			return 0;
		}

		public static final Parcelable.Creator<MediaItem> CREATOR = new Parcelable.Creator<MediaItem>()
		{
			@Override
			public MediaItem createFromParcel(Parcel source)
			{
				return new MediaItem(source);
			}

			@Override
			public MediaItem[] newArray(int size)
			{
				return new MediaItem[size];
			}
		};
	}
}


text:
import urllib.request, urllib.error, urllib.parse
try:
    import json
except ImportError:
    import simplejson as json

import hashlib
from .proxies import TrackProxy
from . import util
import time

# Seconds to wait for asynchronous track/upload or track/analyze jobs to complete.
DEFAULT_ASYNC_TIMEOUT = 60

class Track(TrackProxy):
    """
    Represents an audio file and its analysis from The Echo Nest.
    All public methods in this module return Track objects.

    Depending on the information available, a Track may have some or all of the
    following attributes:

        acousticness            float: confidence the track is "acoustic" (0.0 to 1.0)
        analysis_url            URL to retrieve the complete audio analysis (time expiring)
        analyzer_version        str: e.g. '3.01a'
        artist                  str or None: artist name
        artist_id               Echo Nest ID of artist, if known
        danceability            float: relative danceability (0.0 to 1.0)
        duration                float: length of track in seconds
        energy                  float: relative energy (0.0 to 1.0)
        id                      str: Echo Nest Track ID, e.g. 'TRTOBXJ1296BCDA33B'
        key                     int: between 0 (key of C) and 11 (key of B flat) inclusive
        liveness                float: confidence the track is "live" (0.0 to 1.0)
        loudness                float: overall loudness in decibels (dB)
        md5                     str: 32-character checksum of the original audio file, if available
        mode                    int: 0 (major) or 1 (minor)
        song_id                 The Echo Nest song ID for the track, if known
        speechiness             float: likelihood the track contains speech (0.0 to 1.0)
        status                  str: analysis status, e.g. 'complete'
        tempo                   float: overall BPM (beats per minute)
        time_signature          beats per measure (e.g. 3, 4, 5, 7)
        title                   str or None: song title
        valence                 float: a range from negative to positive emotional content (0.0 to 1.0)

    The following attributes are available only after calling Track.get_analysis():

        analysis_channels       int: the number of audio channels used during analysis
        analysis_sample_rate    int: the sample rate used during analysis
        bars                    list of dicts: timing of each measure
        beats                   list of dicts: timing of each beat
        codestring              ENMFP code string
        code_version            version of ENMFP code generator
        decoder                 audio decoder used by the analysis (e.g. ffmpeg)
        echoprintstring         fingerprint string using Echoprint (http://echoprint.me)
        echoprint_version       version of Echoprint code generator
        end_of_fade_in          float: time in seconds track where fade-in ends
        key_confidence          float: confidence that key detection was accurate
        meta                    dict: other track metainfo (bitrate, album, genre, etc.)
        mode_confidence         float: confidence that mode detection was accurate
        num_samples             int: total samples in the decoded track
        offset_seconds          unused, always 0
        sample_md5              str: 32-character checksum of the decoded audio file
        samplerate              the audio sample rate detected in the file
        sections                list of dicts: larger sections of song (chorus, bridge, solo, etc.)
        segments                list of dicts: timing, pitch, loudness and timbre for each segment
        start_of_fade_out       float: time in seconds where fade out begins
        synchstring             string providing synchronization points throughout the track
        synch_version           version of the synch string algorithm
        tatums                  list of dicts: the smallest metrical unit (subdivision of a beat)
        tempo_confidence        float: confidence that tempo detection was accurate
        time_signature_confidence float: confidence that time_signature detection was accurate

    Each bar, beat, section, segment and tatum has a start time, a duration, and a confidence,
    in addition to whatever other data is given.

    Examples:

    >>> t = track.track_from_id('TRJSEBQ1390EC0B548')
    >>> t
    <track - Dark Therapy>

    >>> t = track.track_from_md5('96fa0180d225f14e9f8cbfffbf5eb81d')
    >>> t
    <track - Spoonful - Live At Winterland>
    >>>

    >>> t = track.track_from_filename('Piano Man.mp3')
    >>> t.meta
    AttributeError: 'Track' object has no attribute 'meta'
    >>> t.get_analysis()
    >>> t.meta
    {u'album': u'Piano Man',
     u'analysis_time': 8.9029500000000006,
     u'analyzer_version': u'3.1.3',
     u'artist': u'Billy Joel',
     u'bitrate': 160,
     u'detailed_status': u'OK',
     u'filename': u'/tmp/tmphrBQL9/fd2b524958548e7ecbaf758fb675fab1.mp3',
     u'genre': u'Soft Rock',
     u'sample_rate': 44100,
     u'seconds': 339,
     u'status_code': 0,
     u'timestamp': 1369400122,
     u'title': u'Piano Man'}
    >>>
    """
    def __repr__(self):
        try:
            return "<%s - %s>" % (self._object_type.encode('utf-8'), self.title.encode('utf-8'))
        except AttributeError:
            # the title is None
            return "< Track >"

    def __str__(self):
        return self.title.encode('utf-8')

    def get_analysis(self):
        """ Retrieve the detailed analysis for the track, if available.
            Raises Exception if unable to create the detailed analysis. """
        if self.analysis_url:
            try:
                # Try the existing analysis_url first. This expires shortly
                # after creation.
                try:
                    json_string = urllib.request.urlopen(self.analysis_url).read()
                except urllib.error.HTTPError:
                    # Probably the analysis_url link has expired. Refresh it.
                    param_dict = dict(id = self.id)
                    new_track = _profile(param_dict, DEFAULT_ASYNC_TIMEOUT)
                    if new_track and new_track.analysis_url:
                        self.analysis_url = new_track.analysis_url
                        json_string = urllib.request.urlopen(self.analysis_url).read()
                    else:
                        raise Exception("Failed to create track analysis.")

                analysis = json.loads(json_string.decode('utf-8'))
                analysis_track = analysis.pop('track', {})
                self.__dict__.update(analysis)
                self.__dict__.update(analysis_track)
            except Exception: #pylint: disable=W0702
                # No detailed analysis found.
                raise Exception("Failed to create track analysis.")
        else:
            raise Exception("Failed to create track analysis.")

def _wait_for_pending_track(trid, timeout):
    status = 'pending'
    param_dict = {'id': trid}
    param_dict['format'] = 'json'
    param_dict['bucket'] = 'audio_summary'
    start_time = time.time()
    end_time = start_time + timeout
    # counter for seconds to wait before checking track profile again.
    timeout_counter = 3
    while status == 'pending' and time.time() < end_time:
        time.sleep(timeout_counter)
        result = util.callm('track/profile', param_dict)
        status = result['response']['track']['status'].lower()
        # Slowly increment to wait longer each time.
        timeout_counter += timeout_counter / 2
    return result

def _track_from_response(result, timeout):
    """
    This is the function that actually creates the track object
    """
    response = result['response']
    status = response['track']['status'].lower()

    if status == 'pending':
        # Need to wait for async upload or analyze call to finish.
        result = _wait_for_pending_track(response['track']['id'], timeout)
        response = result['response']
        status = response['track']['status'].lower()

    if not status == 'complete':
        track_id = response['track']['id']
        if status == 'pending':
            raise Exception('%s: the operation didn\'t complete before the timeout (%d secs)' %
                            (track_id, timeout))
        else:
            raise Exception('%s: there was an error analyzing the track, status: %s' % (track_id, status))
    else:
        # track_properties starts as the response dictionary.
        track_properties = response['track']
        # 'id' and 'md5' are separated to construct the Track object.
        identifier = track_properties.pop('id')
        md5        = track_properties.pop('md5', None) # tracks from song api calls will not have an md5
        # Pop off the audio_summary dict and make those keys attributes
        # of the Track. This includes things like tempo, energy, and loudness.
        track_properties.update(track_properties.pop('audio_summary'))
        return Track(identifier, md5, track_properties)

def _upload(param_dict, timeout, data):
    """
    Calls upload either with a local audio file,
    or a url. Returns a track object.
    """
    param_dict['format'] = 'json'
    param_dict['wait'] = 'true'
    param_dict['bucket'] = 'audio_summary'
    result = util.callm('track/upload', param_dict, POST = True, socket_timeout = 300,  data = data)
    return _track_from_response(result, timeout)

def _profile(param_dict, timeout):
    param_dict['format'] = 'json'
    param_dict['bucket'] = 'audio_summary'
    result = util.callm('track/profile', param_dict)
    return _track_from_response(result, timeout)

""" Below are convenience functions for creating Track objects, you should use them """

def _track_from_data(audio_data, filetype, timeout):
    param_dict = {}
    param_dict['filetype'] = filetype
    return _upload(param_dict, timeout, audio_data)

def track_from_file(file_object, filetype, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
    """
    Create a track object from a file-like object.

    NOTE: Does not create the detailed analysis for the Track. Call
    Track.get_analysis() for that.

    Args:
        file_object: a file-like Python object
        filetype: the file type. Supported types include mp3, ogg, wav, m4a, mp4, au
        force_upload: skip the MD5 shortcut path, force an upload+analysis
    Example:
        >>> f = open("Miaow-01-Tempered-song.mp3")
        >>> t = track.track_from_file(f, 'mp3')
        >>> t
        < Track >
        >>>
    """
    if not force_upload:
        try:
            # Check if this file has already been uploaded.
            # This is much faster than uploading.
            md5 = hashlib.md5(file_object.read()).hexdigest()
            return track_from_md5(md5)
        except util.EchoNestAPIError:
            # Fall through to do a fresh upload.
            pass

    file_object.seek(0)
    return _track_from_data(file_object.read(), filetype, timeout)

def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
    """
    Create a track object from a filename.

    NOTE: Does not create the detailed analysis for the Track. Call
    Track.get_analysis() for that.

    Args:
        filename: A string containing the path to the input file.
        filetype: A string indicating the filetype; Defaults to None (type determined by file extension).
        force_upload: skip the MD5 shortcut path, force an upload+analysis

    Example:
        >>> t = track.track_from_filename("Miaow-01-Tempered-song.mp3")
        >>> t
        < Track >
        >>>
    """
    filetype = filetype or filename.split('.')[-1]
    file_object = open(filename, 'rb')
    result = track_from_file(file_object, filetype, timeout, force_upload)
    file_object.close()
    return result

def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT):
    """
    Create a track object from a public http URL.

    NOTE: Does not create the detailed analysis for the Track. Call
    Track.get_analysis() for that.

    Args:
        url: A string giving the URL to read from. This must be on a public machine accessible by HTTP.

    Example:
        >>> t = track.track_from_url("http://www.miaowmusic.com/mp3/Miaow-01-Tempered-song.mp3")
        >>> t
        < Track >
        >>>

    """
    param_dict = dict(url = url)
    return _upload(param_dict, timeout, data=None)

def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT):
    """
    Create a track object from an Echo Nest track ID.

    NOTE: Does not create the detailed analysis for the Track. Call
    Track.get_analysis() for that.

    Args:
        identifier: A string containing the ID of a previously analyzed track.

    Example:
        >>> t = track.track_from_id("TRWFIDS128F92CC4CA")
        >>> t
        <track - Let The Spirit>
        >>>
    """
    param_dict = dict(id = identifier)
    return _profile(param_dict, timeout)

def track_from_md5(md5, timeout=DEFAULT_ASYNC_TIMEOUT):
    """
    Create a track object from an md5 hash.

    NOTE: Does not create the detailed analysis for the Track. Call
    Track.get_analysis() for that.

    Args:
        md5: A string 32 characters long giving the md5 checksum of a track already analyzed.

    Example:
        >>> t = track.track_from_md5('b8abf85746ab3416adabca63141d8c2d')
        >>> t
        <track - Neverwas Restored (from Neverwas Soundtrack)>
        >>>
    """
    param_dict = dict(md5 = md5)
    return _profile(param_dict, timeout)

redpajama_set_name: RedPajamaGithub


text:
Goroutine based asynchronous event logger for Fluentd

## Project status

Not maintained. Please use [fluent/fluent-logger-golang](https://github.com/fluent/fluent-logger-golang) instead.

## Features

* Channel based non-blocking logging interface
* Queued events are periodically sent to fluentd altogether

## Installation

```
$ go get github.com/k0kubun/fluent-logger-go
```

## Usage

```go
package main

import "github.com/gin-gonic/gin"
import "github.com/k0kubun/fluent-logger-go"

var logger *fluent.Logger

func logId(c *gin.Context) {
	id := c.Params.ByName("id")
	logger.Post("idlog", map[string]string{"id": id})
	c.String(200, "Logged id")
}

func main() {
	logger = fluent.NewLogger(fluent.Config{})
	r := gin.Default()
	r.GET("/:id", logId)
	r.Run(":3000")
}
```

### Documentation

API documentation can be found here: https://godoc.org/github.com/k0kubun/fluent-logger-go

## Related projects

You would like to use another one for some use case.

* [t-k/fluent-logger-golang](https://github.com/t-k/fluent-logger-golang)


text:
describe('Take the Black', function() {
    integration(function() {
        beforeEach(function() {
            const deck = this.buildDeck('thenightswatch', [
                'Trading with the Pentoshi',
                'Take the Black', 'Dothraki Outriders', 'Maester Aemon (Core)', 'Wildling Horde'
            ]);
            this.player1.selectDeck(deck);
            this.player2.selectDeck(deck);
            this.startGame();
            this.keepStartingHands();

            this.player1.togglePromptedActionWindow('dominance', true);

            this.tooExpensive = this.player2.findCardByName('Dothraki Outriders', 'hand');
            this.unique = this.player2.findCardByName('Maester Aemon', 'hand');
            this.eligible = this.player2.findCardByName('Wildling Horde', 'hand');

            this.player2.clickCard(this.tooExpensive);
            this.completeSetup();
            this.player1.selectPlot('Trading with the Pentoshi');
            this.player2.selectPlot('Trading with the Pentoshi');
            this.selectFirstPlayer(this.player1);
            this.selectPlotOrder(this.player1);

            this.player1.clickPrompt('Done');
            this.player2.clickCard(this.unique);
            this.player2.clickCard(this.eligible);
            this.player2.clickPrompt('Done');

            this.completeChallengesPhase();

            this.player1.clickCard('Take the Black', 'hand');
        });

        it('should allow take control of non-unique, 6-gold-or-less characters', function() {
            this.player1.clickCard(this.eligible);

            expect(this.eligible.controller.name).toBe(this.player1Object.name);
        });

        it('should not allow take control of unique characters', function() {
            this.player1.clickCard(this.unique);

            expect(this.unique.controller).not.toBe(this.player1Object);
        });

        it('should not allow take control of more expensive than 6 gold characters', function() {
            this.player1.clickCard(this.tooExpensive);

            expect(this.tooExpensive.controller).not.toBe(this.player1Object);
        });
    });
});


text:
@class FBSDKProfilePictureView;

// the child view controller displaying the active user.
@interface SUActiveViewController : UIViewController

@property (strong, nonatomic) IBOutlet FBSDKProfilePictureView *profilePictureView;
@property (strong, nonatomic) IBOutlet UILabel *titleLabel;
@property (strong, nonatomic) IBOutlet UILabel *subtitleLabel;

@end


text:
from setuptools import setup

# Taken from scikit-learn setup.py
DISTNAME = 'scikit-commpy'
DESCRIPTION = 'Digital Communication Algorithms with Python'
LONG_DESCRIPTION = open('README.md', encoding="utf8").read()
MAINTAINER = 'Veeresh Taranalli & Bastien Trotobas'
MAINTAINER_EMAIL = 'bastien.trotobas@gmail.com'
URL = 'http://veeresht.github.com/CommPy'
LICENSE = 'BSD 3-Clause'
VERSION = '0.8.0'

#This is a list of files to install, and where
#(relative to the 'root' dir, where setup.py is)
#You could be more specific.
files = ["channelcoding/*", "channelcoding/tests/*", "tests/*", "channelcoding/designs/ldpc/gallager/*", "channelcoding/designs/ldpc/wimax/*"]

setup(
    name=DISTNAME,
    maintainer=MAINTAINER,
    maintainer_email=MAINTAINER_EMAIL,
    description=DESCRIPTION,
    license=LICENSE,
    url=URL,
    version=VERSION,
    #Name the folder where your packages live:
    #(If you have other packages (dirs) or modules (py files) then
    #put them into the package directory - they will be found
    #recursively.)
    packages=['commpy', 'commpy.channelcoding', 'commpy.channelcoding.tests', 'commpy.tests'],
    install_requires=[
          'numpy',
          'scipy',
          'matplotlib',
          'sympy'
    ],
    #'package' package must contain files (see list above)
    #This dict maps the package name =to=> directories
    #It says, package *needs* these files.
    package_data={'commpy': files},
    #'runner' is in the root.
    scripts=["runner"],
    test_suite='nose.collector',
    tests_require=['nose'],

    long_description=LONG_DESCRIPTION,
    long_description_content_type="text/markdown",
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Science/Research',
        'Intended Audience :: Telecommunications Industry',
        'Operating System :: Unix',
        'Operating System :: Microsoft :: Windows',
        'Programming Language :: Python',
        'Topic :: Scientific/Engineering',
        'Topic :: Software Development',
    ],
    python_requires='>=3.2',
)


text:
Gem that wraps a subset of the [Braincert Virtual Classroom API](https://www.braincert.com/developer/virtualclassroom-api)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'braincert', :git => 'git://github.com/armandofox/braincert.git'
```

And then execute:

    $ bundle

## Usage

BrainCert calls a live meeting a "class" or "live class", and a
recurring series of classes a "course".

This gem maps their notion of a "class" (including possible repetition)
to a Ruby object called `Braincert::LiveClass`.

## Get info about classes

```
Braincert.api_key = 'xxx'
# Get list of all classes we own.  Each includes an id attribute.
classes = Braincert::LiveClass.all
# Or get details about a particular course by id:
one_class = Braincert::LiveClass.find(classes.first.id)
# Returns nil and populates one_class.errors (ActiveModel errors object) if fail
```

Because the API doesn't support updating a class in place (you have to
delete it and create a new class), `Braincert::LiveClass` objects are
frozen.

## Get "launch URL" for a class

The launch URL is the one that opens a browser window allowing people to
attend the class.

## Create (schedule) a new class

Just as with ActiveModel, you create a new object, set its attributes,
and then save it.  The attributes can be set individually or passed as a
hash to the constructor.  Required attributes are shown here, see docs
for optional attributes.

```
new_class = Braincert::LiveClass.new
new_class.title = 'New Test Class'

new_class.start_time_with_zone = Time.zone.parse("Aug 05, 5:00pm")
# must be ActiveSupport::TimeWithZone instance (ie, responds to :time_zone)

new_class.duration = 3600        # in seconds
new_class.seat_attendees = 25    # max attendees including teacher

# optional for recurring classes:
new_class.repeat = Braincert::REPEAT_WEEKLY  # see doc for other values
new_class.end_classes_count = 3  # 3rd meeting is the final one

# nonrecurring classes (default)
new_class.repeat = nil

new_class.valid?        # runs validations as usual
new_class.save          # if result is nil, check new_class.errors
new_class.save!         # like save but raise Braincert::LiveClass::SaveError if fail
new_class.id            # => after save, will be non-nil (numeric)
new_class.persisted?    # => true after successful save
new_class.duration = 7200  # => raises exception, since object is now frozen
```

## Contributing

1. Fork it ( https://github.com/[my-github-username]/braincert/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
export default (superClass) => {

  return class extends superClass {

    _getDirectView() {
      let child, children = [];

      for (let i in this.children) {
        child = this.children[i];
        if (child.tagName && child.tagName !== 'LAZY-BOARD-VIEW') {
          children.push(child);
        }
      }

      return children;
    }

    _getDirectLazyBoardView() {
      let child, children = [];

      for (let i in this.children) {
        child = this.children[i];
        if (child.tagName === 'LAZY-BOARD-VIEW') {
          children.push(child);
        }
      }

      return children;
    }
  }
}


text:
package org.optaplanner.examples.curriculumcourse.solver.move;

import org.optaplanner.core.api.score.director.ScoreDirector;
import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionFilter;
import org.optaplanner.core.impl.heuristic.selector.move.generic.SwapMove;
import org.optaplanner.examples.curriculumcourse.domain.CourseSchedule;
import org.optaplanner.examples.curriculumcourse.domain.Lecture;

public class DifferentCourseSwapMoveFilter implements SelectionFilter<CourseSchedule, SwapMove> {

    @Override
    public boolean accept(ScoreDirector<CourseSchedule> scoreDirector, SwapMove move) {
        Lecture leftLecture = (Lecture) move.getLeftEntity();
        Lecture rightLecture = (Lecture) move.getRightEntity();
        return !leftLecture.getCourse().equals(rightLecture.getCourse());
    }

}


text:
<resources>
    <string name="app_name">ContentSharing</string>
</resources>


text:
/*
 * L.PatternCircle is the implementation of PatternShape for adding Circles
 */

L.PatternCircle = L.PatternShape.extend({
	options: {
        x: 0,
        y: 0,
        radius: 0
	},

	_initDom: function () {
		this._initDomElement('circle');
	},

	_updateShape: function () {
        if (!this._dom) { return; }
		this._dom.setAttribute('cx', this.options.x);
		this._dom.setAttribute('cy', this.options.y);
		this._dom.setAttribute('r', this.options.radius);
	}
});


text:
package org.apache.harmony.tests.java.lang.reflect;

import java.io.ByteArrayOutputStream;
import java.io.CharArrayWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class InvocationTargetExceptionTest extends junit.framework.TestCase {

    static class TestMethod {
        public TestMethod() {
        }

        public void voidMethod() throws IllegalArgumentException {
        }

        public void parmTest(int x, short y, String s, boolean bool, Object o,
                long l, byte b, char c, double d, float f) {
        }

        public int intMethod() {
            return 1;
        }

        public static final void printTest(int x, short y, String s,
                boolean bool, Object o, long l, byte b, char c, double d,
                float f) {
        }

        public double doubleMethod() {
            return 1.0;
        }

        public short shortMethod() {
            return (short) 1;
        }

        public byte byteMethod() {
            return (byte) 1;
        }

        public float floatMethod() {
            return 1.0f;
        }

        public long longMethod() {
            return 1l;
        }

        public char charMethod() {
            return 'T';
        }

        public Object objectMethod() {
            return new Object();
        }

        private static void prstatic() {
        }

        public static void pustatic() {
        }

        public static synchronized void pustatsynch() {
        }

        public static int invokeStaticTest() {
            return 1;
        }

        public int invokeInstanceTest() {
            return 1;
        }

        private int privateInvokeTest() {
            return 1;
        }

        public int invokeExceptionTest() throws NullPointerException {
            throw new NullPointerException();
        }

        public static synchronized native void pustatsynchnat();

    }

    abstract class AbstractTestMethod {
        public abstract void puabs();
    }

    class SubInvocationTargetException extends InvocationTargetException {}

    /**
     * java.lang.reflect.InvocationTargetException#InvocationTargetException()
     */
    public void test_Constructor() throws Exception {
        Constructor<InvocationTargetException> ctor = InvocationTargetException.class
                .getDeclaredConstructor();
        assertNotNull("Parameterless constructor does not exist.", ctor);
        assertTrue("Constructor is not protected", Modifier.isProtected(ctor
                .getModifiers()));
        //create an instance of a subtype using this constructor
        SubInvocationTargetException subException = new SubInvocationTargetException();
    }

    /**
     * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable)
     */
    public void test_ConstructorLjava_lang_Throwable() {
        // Test for method
        // java.lang.reflect.InvocationTargetException(java.lang.Throwable)
        try {
            Method mth = TestMethod.class.getDeclaredMethod(
                    "invokeExceptionTest", new Class[0]);
            Object[] args = { Object.class };
            Object ret = mth.invoke(new TestMethod(), new Object[0]);
        } catch (InvocationTargetException e) {
            // Correct behaviour
            return;
        } catch (NoSuchMethodException e) {
        } catch (IllegalAccessException e) {
        }
        fail("Failed to throw exception");
    }

    /**
     * java.lang.reflect.InvocationTargetException#InvocationTargetException(java.lang.Throwable,
     *        java.lang.String)
     */
    public void test_ConstructorLjava_lang_ThrowableLjava_lang_String() {
        // Test for method
        // java.lang.reflect.InvocationTargetException(java.lang.Throwable,
        // java.lang.String)
        try {
            Method mth = TestMethod.class.getDeclaredMethod(
                    "invokeExceptionTest", new Class[0]);
            Object[] args = { Object.class };
            Object ret = mth.invoke(new TestMethod(), new Object[0]);
        } catch (InvocationTargetException e) {
            // Correct behaviour
            return;
        } catch (NoSuchMethodException e) {
            ;
        } catch (IllegalAccessException e) {
        }
        fail("Failed to throw exception");
    }

    /**
     * java.lang.reflect.InvocationTargetException#getTargetException()
     */
    public void test_getTargetException() {
        // Test for method java.lang.Throwable
        // java.lang.reflect.InvocationTargetException.getTargetException()
        try {
            Method mth = TestMethod.class.getDeclaredMethod(
                    "invokeExceptionTest", new Class[0]);
            Object[] args = { Object.class };
            Object ret = mth.invoke(new TestMethod(), new Object[0]);
        } catch (InvocationTargetException e) {
            // Correct behaviour
            assertTrue("Returned incorrect target exception", e
                    .getTargetException() instanceof NullPointerException);
            return;
        } catch (Exception e) {
            fail("Exception during constructor test : " + e.getMessage());
        }
        fail("Failed to throw exception");
    }

    /**
     * java.lang.reflect.InvocationTargetException#getCause()
     */
    public void test_getCause() {
        // java.lang.reflect.InvocationTargetException.getCause()
        try {
            Method mth = TestMethod.class.getDeclaredMethod(
                    "invokeExceptionTest", new Class[0]);
            Object[] args = {Object.class};
            Object ret = mth.invoke(new TestMethod(), new Object[0]);
        } catch (InvocationTargetException e) {
            // Correct behaviour
            assertTrue("Returned incorrect cause",
                    e.getCause() instanceof NullPointerException);
            return;
        } catch (Exception e) {
            fail("Exception during InvocationTargetException test : "
                    + e.getMessage());
        }
        fail("Failed to throw exception");
    }

    /**
     * java.lang.reflect.InvocationTargetException#printStackTrace()
     */
    public void test_printStackTrace() {
        // Test for method void
        // java.lang.reflect.InvocationTargetException.printStackTrace()
        try {
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            PrintStream ps = new PrintStream(bao);
            PrintStream oldErr = System.err;
            System.setErr(ps);
            InvocationTargetException ite = new InvocationTargetException(null);
            ite.printStackTrace();
            System.setErr(oldErr);

            String s = new String(bao.toByteArray());

            assertTrue("Incorrect Stack trace: " + s, s != null
                    && s.length() > 300);
        } catch (Exception e) {
            fail("printStackTrace() caused exception : " + e.getMessage());
        }
    }

    /**
     * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintStream)
     */
    public void test_printStackTraceLjava_io_PrintStream() {
        // Test for method void
        // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintStream)
        assertTrue("Tested via test_printStackTrace().", true);
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bao);
        InvocationTargetException ite = new InvocationTargetException(
                new InvocationTargetException(null));
        ite.printStackTrace(ps);
        String s = bao.toString();
        assertTrue("printStackTrace failed." + s.length(), s != null
                && s.length() > 400);
    }

    /**
     * java.lang.reflect.InvocationTargetException#printStackTrace(java.io.PrintWriter)
     */
    public void test_printStackTraceLjava_io_PrintWriter() {
        // Test for method void
        // java.lang.reflect.InvocationTargetException.printStackTrace(java.io.PrintWriter)
        try {
            PrintWriter pw;
            InvocationTargetException ite;
            String s;
            CharArrayWriter caw = new CharArrayWriter();
            pw = new PrintWriter(caw);
            ite = new InvocationTargetException(new InvocationTargetException(
                    null));
            ite.printStackTrace(pw);

            s = caw.toString();
            assertTrue("printStackTrace failed." + s.length(), s != null
                    && s.length() > 400);
            pw.close();

            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            pw = new PrintWriter(bao);
            ite = new InvocationTargetException(new InvocationTargetException(
                    null));
            ite.printStackTrace(pw);

            pw.flush(); // Test will fail if this line removed.
            s = bao.toString();
            assertTrue("printStackTrace failed." + s.length(), s != null
                    && s.length() > 400);

        } catch (Exception e) {
            fail("Exception during test : " + e.getMessage());
        }
    }

    /**
     * Sets up the fixture, for example, open a network connection. This method
     * is called before a test is executed.
     */
    protected void setUp() {
    }

    /**
     * Tears down the fixture, for example, close a network connection. This
     * method is called after a test is executed.
     */
    protected void tearDown() {
    }
}


text:
<?php

/**
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
 *
 */
class AddDatasourceResponse {

  static $swaggerTypes = array(
      'result' => 'AddDatasourceResult',
      'status' => 'string',
      'error_message' => 'string',
      'composedOn' => 'string'

    );

  public $result; // AddDatasourceResult
  public $status; // string
  public $error_message; // string
  public $composedOn; // string
  }


text:
import os
import re
import json
import pyastyle
from pygments import highlight
from pygments.lexers import JavaLexer
from pygments.formatters import HtmlFormatter

p = re.compile('import (.*);')

class ResultsReader:

	def read_file(self, query_file, results_file):
		# Read data
		with open(results_file) as infile:
			finalresult = json.load(infile)
		with open(query_file) as infile:
			queryresults = {}
			for page in json.load(infile):
				queryresults[page["url"]] = {}
				for segment in page["segments"]:
					queryresults[page["url"]][segment["in_page_order"]] = segment

		for fcluster in finalresult["clusters"]:
			fcluster["Score"] = []
			fcluster["imports"] = {}
			top_apis = fcluster["top_apis_by_cluster"]
			new_top_apis = []
			for fsnippet in fcluster["cluster_snippets"]:
				# Get stats and method invocations
				snip = queryresults[fsnippet["Url"]][fsnippet["In_Page_Order"]]
				fsnippet["API_Ratio"] = snip["API_Ratio"]
				fsnippet["readability"] = snip["readability"] if snip["readability"] == True else False
				MethodInvocationsFull = fsnippet["MethodInvocations"]
				MethodInvocations = []
				for mi in MethodInvocationsFull:
					if mi.endswith('__init__'):
						MethodInvocations.append(mi.split('.')[0])
					else:
						if len(mi.split('.')) > 1:
							MethodInvocations.append(mi.split('.')[1])
				fsnippet["MethodInvocationsFull"] = MethodInvocationsFull
				fsnippet["MethodInvocations"] = MethodInvocations

				# Compute snippet API score
				for mi in MethodInvocationsFull:
					fsnippet["API_Score"] = snip["APIsProjects"][mi] / 1000 if mi in snip["APIsProjects"] else 0

				# Find API qualified names
				for api in top_apis:
					for m in MethodInvocationsFull:
						if api == m.lower() and m not in new_top_apis:
							new_top_apis.append(m)

				# Format code
				code = fsnippet["Code"]
				fsnippet["Code"] = ';\n'.join(code.split(';')) if '\n' not in code else code
				fsnippet["formatted_code"] = pyastyle.format(fsnippet["Code"], "--style=java --delete-empty-lines")
				fsnippet["full_code"] = highlight(fsnippet["formatted_code"], JavaLexer(), HtmlFormatter())

				# Find imports
				fsnippet["imports"] = p.findall(fsnippet["formatted_code"])
				fsnippet["imports"] += ['.'.join(snip["APIsQualifiedNames"][m].split('.')[:-1]) for m in MethodInvocationsFull if m in snip["APIsQualifiedNames"]]
				for im in fsnippet["imports"]:
					if len(im) <= 100:# and not im.endswith("Exception"):
						fcluster["imports"][im] = 1 if im not in fcluster["imports"] else fcluster["imports"][im] + 1

				# Highlight api calls
				lines = fsnippet["full_code"].split('\n')
				hapicalls = 0
				for mi in MethodInvocations:
					for l, line in enumerate(lines):
						if 'import' not in line:
							while '' + mi + '' in line:
								line = line.replace('' + mi + '', '' + mi + '')
								hapicalls += 1
						while '' + mi + '' in line:
							line = line.replace('' + mi + '', '' + mi + '')
						lines[l] = line
				fsnippet["Num_Highlighted_API_Calls"] = hapicalls
				fsnippet["full_code"] = '\n'.join(lines)
				fcluster["Score"].append(fsnippet["Score"])

				# Get important lines
				first = fsnippet["full_code"][0:28]
				lines = fsnippet["full_code"][28:-14].split('\n')
				last = fsnippet["full_code"][-13:]
				newlineids = []
				for l, line in enumerate(lines):
					if any('' + mi + '' in line for mi in MethodInvocations):
						newlineids.append(l)
					if any('' + mi + '' in line for mi in MethodInvocations):
						newlineids.append(l)
				newlines = []
				used_ids = set()
				for newlineid in newlineids:
					for k in [-1, 0, 1]:
						if newlineid + k >= 0 and newlineid + k < len(lines) and newlineid + k not in used_ids:
							newlines.append(lines[newlineid + k])
							used_ids.add(newlineid + k)
				fsnippet["invocations_code"] = first + '\n'.join(newlines) + last
				fsnippet["LOC"] = len([line for line in lines if line.strip()])
			# Create score
			scores = fcluster["Score"]
			fcluster["Score"] = sum(scores[:min(10, len(scores))]) / len(scores[:min(10, len(scores))])

			if len(fcluster["imports"]) < 5:
				for j, _ in enumerate(fcluster["cluster_snippets"]):
					if "API_Qualified_Names" in fsnippet:
						fsnippet["API_Qualified_Names"] = [im.split('.')[-1] for im in fsnippet["API_Qualified_Names"]]
						for im in fsnippet["API_Qualified_Names"]:
							if im not in fcluster["imports"]:
								if len(im) <= 100:
									fcluster["imports"][im] = 1

			fcluster["top_apis_by_cluster"] = new_top_apis

			fcluster["API_Score"] = sum([fsnippet["API_Score"] for fsnippet in fcluster["cluster_snippets"]]) / len(fcluster["cluster_snippets"])
			fcluster["cluster_snippets"].sort(reverse = True, key = lambda x: (x["API_Score"], x["Score"]))
		finalresult["clusters"].sort(reverse = True, key = lambda x: x["API_Score"])
		return finalresult


text:
package org.b3log.latke.http.handler;

import org.b3log.latke.http.Request;
import org.b3log.latke.http.RequestContext;
import org.b3log.latke.http.renderer.StaticFileRenderer;

/**
 * Static resource handler.
 *
 * @author Liang Ding
 * @version 3.0.0.0, Nov 3, 2019
 */
public class StaticResourceHandler implements Handler {

    @Override
    public void handle(final RequestContext context) {
        final Request request = context.getRequest();
        if (request.isStaticResource()) {
            context.setRenderer(new StaticFileRenderer());
            context.abort();

            return;
        }

        context.handle();
    }
}


text:
/*
 * Date built-in description
 */
#ifndef OBJECT_VALUE
# define OBJECT_VALUE(name, obj_builtin_id, prop_attributes)
#endif /* !OBJECT_VALUE */

#ifndef NUMBER_VALUE
# define NUMBER_VALUE(name, number_value, prop_attributes)
#endif /* !NUMBER_VALUE */

#ifndef ROUTINE
# define ROUTINE(name, c_function_name, args_number, length_prop_value)
#endif /* !ROUTINE */

/* ECMA-262 v5, 15.9.4.1 */
OBJECT_VALUE (LIT_MAGIC_STRING_PROTOTYPE,
              ECMA_BUILTIN_ID_DATE_PROTOTYPE,
              ECMA_PROPERTY_FIXED)

NUMBER_VALUE (LIT_MAGIC_STRING_LENGTH,
              7,
              ECMA_PROPERTY_FIXED)

ROUTINE (LIT_MAGIC_STRING_PARSE, ecma_builtin_date_parse, 1, 1)
ROUTINE (LIT_MAGIC_STRING_UTC_U, ecma_builtin_date_utc, NON_FIXED, 7)
ROUTINE (LIT_MAGIC_STRING_NOW, ecma_builtin_date_now, 0, 0)

#undef SIMPLE_VALUE
#undef NUMBER_VALUE
#undef STRING_VALUE
#undef OBJECT_VALUE
#undef ROUTINE
#undef ACCESSOR_READ_WRITE
#undef ACCESSOR_READ_ONLY


text:
/*
 * metismenu - v2.7.0
 * A jQuery menu plugin
 * https://github.com/onokumus/metismenu#readme
 *
 * Made by Osman Nuri Okumus <onokumus@gmail.com> (https://github.com/onokumus)
 * Under MIT License
 */

(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports !== "undefined") {
    factory(require('jquery'));
  } else {
    var mod = {
      exports: {}
    };
    factory(global.jquery);
    global.metisMenu = mod.exports;
  }
})(this, function (_jquery) {
  'use strict';

  var _jquery2 = _interopRequireDefault(_jquery);

  function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
      default: obj
    };
  }

  var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  };

  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }

  var Util = function ($) {
    var transition = false;

    var TransitionEndEvent = {
      WebkitTransition: 'webkitTransitionEnd',
      MozTransition: 'transitionend',
      OTransition: 'oTransitionEnd otransitionend',
      transition: 'transitionend'
    };

    function getSpecialTransitionEndEvent() {
      return {
        bindType: transition.end,
        delegateType: transition.end,
        handle: function handle(event) {
          if ($(event.target).is(this)) {
            return event.handleObj.handler.apply(this, arguments);
          }
          return undefined;
        }
      };
    }

    function transitionEndTest() {
      if (window.QUnit) {
        return false;
      }

      var el = document.createElement('mm');

      for (var name in TransitionEndEvent) {
        if (el.style[name] !== undefined) {
          return {
            end: TransitionEndEvent[name]
          };
        }
      }

      return false;
    }

    function transitionEndEmulator(duration) {
      var _this2 = this;

      var called = false;

      $(this).one(Util.TRANSITION_END, function () {
        called = true;
      });

      setTimeout(function () {
        if (!called) {
          Util.triggerTransitionEnd(_this2);
        }
      }, duration);

      return this;
    }

    function setTransitionEndSupport() {
      transition = transitionEndTest();
      $.fn.emulateTransitionEnd = transitionEndEmulator;

      if (Util.supportsTransitionEnd()) {
        $.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent();
      }
    }

    var Util = {
      TRANSITION_END: 'mmTransitionEnd',

      triggerTransitionEnd: function triggerTransitionEnd(element) {
        $(element).trigger(transition.end);
      },
      supportsTransitionEnd: function supportsTransitionEnd() {
        return Boolean(transition);
      }
    };

    setTransitionEndSupport();

    return Util;
  }(jQuery);

  var MetisMenu = function ($) {

    var NAME = 'metisMenu';
    var DATA_KEY = 'metisMenu';
    var EVENT_KEY = '.' + DATA_KEY;
    var DATA_API_KEY = '.data-api';
    var JQUERY_NO_CONFLICT = $.fn[NAME];
    var TRANSITION_DURATION = 350;

    var Default = {
      toggle: true,
      preventDefault: true,
      activeClass: 'active',
      collapseClass: 'collapse',
      collapseInClass: 'in',
      collapsingClass: 'collapsing',
      triggerElement: 'a',
      parentTrigger: 'li',
      subMenu: 'ul'
    };

    var Event = {
      SHOW: 'show' + EVENT_KEY,
      SHOWN: 'shown' + EVENT_KEY,
      HIDE: 'hide' + EVENT_KEY,
      HIDDEN: 'hidden' + EVENT_KEY,
      CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
    };

    var MetisMenu = function () {
      function MetisMenu(element, config) {
        _classCallCheck(this, MetisMenu);

        this._element = element;
        this._config = this._getConfig(config);
        this._transitioning = null;

        this.init();
      }

      MetisMenu.prototype.init = function init() {
        var self = this;
        $(this._element).find(this._config.parentTrigger + '.' + this._config.activeClass).has(this._config.subMenu).children(this._config.subMenu).attr('aria-expanded', true).addClass(this._config.collapseClass + ' ' + this._config.collapseInClass);

        $(this._element).find(this._config.parentTrigger).not('.' + this._config.activeClass).has(this._config.subMenu).children(this._config.subMenu).attr('aria-expanded', false).addClass(this._config.collapseClass);

        $(this._element).find(this._config.parentTrigger).has(this._config.subMenu).children(this._config.triggerElement).on(Event.CLICK_DATA_API, function (e) {
          var _this = $(this);
          var _parent = _this.parent(self._config.parentTrigger);
          var _siblings = _parent.siblings(self._config.parentTrigger).children(self._config.triggerElement);
          var _list = _parent.children(self._config.subMenu);
          if (self._config.preventDefault) {
            e.preventDefault();
          }
          if (_this.attr('aria-disabled') === 'true') {
            return;
          }
          if (_parent.hasClass(self._config.activeClass)) {
            _this.attr('aria-expanded', false);
            self._hide(_list);
          } else {
            self._show(_list);
            _this.attr('aria-expanded', true);
            if (self._config.toggle) {
              _siblings.attr('aria-expanded', false);
            }
          }

          if (self._config.onTransitionStart) {
            self._config.onTransitionStart(e);
          }
        });
      };

      MetisMenu.prototype._show = function _show(element) {
        if (this._transitioning || $(element).hasClass(this._config.collapsingClass)) {
          return;
        }
        var _this = this;
        var _el = $(element);

        var startEvent = $.Event(Event.SHOW);
        _el.trigger(startEvent);

        if (startEvent.isDefaultPrevented()) {
          return;
        }

        _el.parent(this._config.parentTrigger).addClass(this._config.activeClass);

        if (this._config.toggle) {
          this._hide(_el.parent(this._config.parentTrigger).siblings().children(this._config.subMenu + '.' + this._config.collapseInClass).attr('aria-expanded', false));
        }

        _el.removeClass(this._config.collapseClass).addClass(this._config.collapsingClass).height(0);

        this.setTransitioning(true);

        var complete = function complete() {

          _el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass + ' ' + _this._config.collapseInClass).height('').attr('aria-expanded', true);

          _this.setTransitioning(false);

          _el.trigger(Event.SHOWN);
        };

        if (!Util.supportsTransitionEnd()) {
          complete();
          return;
        }

        _el.height(_el[0].scrollHeight).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
      };

      MetisMenu.prototype._hide = function _hide(element) {

        if (this._transitioning || !$(element).hasClass(this._config.collapseInClass)) {
          return;
        }
        var _this = this;
        var _el = $(element);

        var startEvent = $.Event(Event.HIDE);
        _el.trigger(startEvent);

        if (startEvent.isDefaultPrevented()) {
          return;
        }

        _el.parent(this._config.parentTrigger).removeClass(this._config.activeClass);
        _el.height(_el.height())[0].offsetHeight;

        _el.addClass(this._config.collapsingClass).removeClass(this._config.collapseClass).removeClass(this._config.collapseInClass);

        this.setTransitioning(true);

        var complete = function complete() {
          if (_this._transitioning && _this._config.onTransitionEnd) {
            _this._config.onTransitionEnd();
          }

          _this.setTransitioning(false);
          _el.trigger(Event.HIDDEN);

          _el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass).attr('aria-expanded', false);
        };

        if (!Util.supportsTransitionEnd()) {
          complete();
          return;
        }

        _el.height() == 0 || _el.css('display') == 'none' ? complete() : _el.height(0).one(Util.TRANSITION_END, complete).emulateTransitionEnd(TRANSITION_DURATION);
      };

      MetisMenu.prototype.setTransitioning = function setTransitioning(isTransitioning) {
        this._transitioning = isTransitioning;
      };

      MetisMenu.prototype.dispose = function dispose() {
        $.removeData(this._element, DATA_KEY);

        $(this._element).find(this._config.parentTrigger).has(this._config.subMenu).children(this._config.triggerElement).off('click');

        this._transitioning = null;
        this._config = null;
        this._element = null;
      };

      MetisMenu.prototype._getConfig = function _getConfig(config) {
        config = $.extend({}, Default, config);
        return config;
      };

      MetisMenu._jQueryInterface = function _jQueryInterface(config) {
        return this.each(function () {
          var $this = $(this);
          var data = $this.data(DATA_KEY);
          var _config = $.extend({}, Default, $this.data(), (typeof config === 'undefined' ? 'undefined' : _typeof(config)) === 'object' && config);

          if (!data && /dispose/.test(config)) {
            this.dispose();
          }

          if (!data) {
            data = new MetisMenu(this, _config);
            $this.data(DATA_KEY, data);
          }

          if (typeof config === 'string') {
            if (data[config] === undefined) {
              throw new Error('No method named "' + config + '"');
            }
            data[config]();
          }
        });
      };

      return MetisMenu;
    }();

    /**
     * ------------------------------------------------------------------------
     * jQuery
     * ------------------------------------------------------------------------
     */

    $.fn[NAME] = MetisMenu._jQueryInterface;
    $.fn[NAME].Constructor = MetisMenu;
    $.fn[NAME].noConflict = function () {
      $.fn[NAME] = JQUERY_NO_CONFLICT;
      return MetisMenu._jQueryInterface;
    };
    return MetisMenu;
  }(jQuery);
});

/**
 * onoffcanvas - A jQuery offcanvas plugin
 * @version v1.1.2
 * @link https://github.com/onokumus/onoffcanvas#readme
 * @license MIT
 */
(function (global, factory) {
  if (typeof define === "function" && define.amd) {
    define(['jquery'], factory);
  } else if (typeof exports !== "undefined") {
    factory(require('jquery'));
  } else {
    var mod = {
      exports: {}
    };
    factory(global.jquery);
    global.onoffcanvas = mod.exports;
  }
})(this, function (_jquery) {
  'use strict';

  var _jquery2 = _interopRequireDefault(_jquery);

  function _interopRequireDefault(obj) {
    return obj && obj.__esModule ? obj : {
      default: obj
    };
  }

  var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj;
  } : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  };

  (function ($) {
    var OnoffCanvas = function OnoffCanvas(element, options) {
      this.$element = $(element);
      this.options = $.extend({}, OnoffCanvas.DEFAULTS, options);
      this.$trigger = $('[data-toggle="onoffcanvas"][href="#' + element.id + '"],[data-toggle="onoffcanvas"][data-target="#' + element.id + '"]');

      this.addAriaCollapsedClass(this.$element, this.$trigger);
    };

    OnoffCanvas.DEFAULTS = {
      toggle: true
    };

    OnoffCanvas.prototype.show = function () {
      var openClass = 'is-open';

      if (this.$element.hasClass(openClass)) {
        return;
      }

      this.$element.addClass(openClass).attr('aria-expanded', true);

      this.$trigger.attr('aria-expanded', true);
    };

    OnoffCanvas.prototype.hide = function () {
      var openClass = 'is-open';

      if (!this.$element.hasClass(openClass)) {
        return;
      }

      this.$element.removeClass(openClass).attr('aria-expanded', false);

      this.$trigger.attr('aria-expanded', false);
    };

    OnoffCanvas.prototype.toggle = function () {
      var openClass = 'is-open';
      this[this.$element.hasClass(openClass) ? 'hide' : 'show']();
    };

    function getTargetFromTrigger($trigger) {
      var href = void 0;
      var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '');

      return $(target);
    }

    OnoffCanvas.prototype.getParent = function () {
      return $(this.options.parent).find('[data-toggle="onoffcanvas"][data-parent="' + this.options.parent + '"]').each($.proxy(function (i, element) {
        var $element = $(element);
        this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element);
      }, this)).end();
    };

    OnoffCanvas.prototype.addAriaCollapsedClass = function ($element, $trigger) {
      var openClass = 'is-open';
      var isOpen = $element.hasClass(openClass);

      $trigger.attr('aria-expanded', !isOpen);
      $element.toggleClass(openClass, !isOpen).attr('aria-expanded', !isOpen);
    };

    function Plugin(option) {
      return this.each(function () {
        var $this = $(this);
        var data = $this.data('onoffcanvas');
        var options = $.extend({}, OnoffCanvas.DEFAULTS, $this.data(), (typeof option === 'undefined' ? 'undefined' : _typeof(option)) === 'object' && option);

        if (!data && options.toggle && /show|hide/.test(option)) {
          options.toggle = false;
        }
        if (!data) {
          $this.data('onoffcanvas', data = new OnoffCanvas(this, options));
        }
        if (typeof option === 'string') {
          data[option]();
        }
      });
    }

    var old = $.fn.onoffcanvas;

    $.fn.onoffcanvas = Plugin;
    $.fn.onoffcanvas.Constructor = OnoffCanvas;

    // CANVAS NO CONFLICT
    // ====================

    $.fn.onoffcanvas.noConflict = function () {
      $.fn.onoffcanvas = old;
      return this;
    };

    $(document).on('click.onoffcanvas.data-api', '[data-toggle="onoffcanvas"]', function (e) {
      var $this = $(this);

      if (!$this.attr('data-target')) {
        e.preventDefault();
      }

      var $target = getTargetFromTrigger($this);
      var data = $target.data('onoffcanvas');
      var option = data ? 'toggle' : $this.data();

      Plugin.call($target, option);
    });
  })(jQuery);
});
/*!
* screenfull
* v3.2.0 - 2017-04-16
* (c) Sindre Sorhus; MIT License
*/
(function () {
	'use strict';

	var document = typeof window === 'undefined' ? {} : window.document;
	var isCommonjs = typeof module !== 'undefined' && module.exports;
	var keyboardAllowed = typeof Element !== 'undefined' && 'ALLOW_KEYBOARD_INPUT' in Element;

	var fn = (function () {
		var val;

		var fnMap = [
			[
				'requestFullscreen',
				'exitFullscreen',
				'fullscreenElement',
				'fullscreenEnabled',
				'fullscreenchange',
				'fullscreenerror'
			],
			// New WebKit
			[
				'webkitRequestFullscreen',
				'webkitExitFullscreen',
				'webkitFullscreenElement',
				'webkitFullscreenEnabled',
				'webkitfullscreenchange',
				'webkitfullscreenerror'

			],
			// Old WebKit (Safari 5.1)
			[
				'webkitRequestFullScreen',
				'webkitCancelFullScreen',
				'webkitCurrentFullScreenElement',
				'webkitCancelFullScreen',
				'webkitfullscreenchange',
				'webkitfullscreenerror'

			],
			[
				'mozRequestFullScreen',
				'mozCancelFullScreen',
				'mozFullScreenElement',
				'mozFullScreenEnabled',
				'mozfullscreenchange',
				'mozfullscreenerror'
			],
			[
				'msRequestFullscreen',
				'msExitFullscreen',
				'msFullscreenElement',
				'msFullscreenEnabled',
				'MSFullscreenChange',
				'MSFullscreenError'
			]
		];

		var i = 0;
		var l = fnMap.length;
		var ret = {};

		for (; i < l; i++) {
			val = fnMap[i];
			if (val && val[1] in document) {
				for (i = 0; i < val.length; i++) {
					ret[fnMap[0][i]] = val[i];
				}
				return ret;
			}
		}

		return false;
	})();

	var screenfull = {
		request: function (elem) {
			var request = fn.requestFullscreen;

			elem = elem || document.documentElement;

			// Work around Safari 5.1 bug: reports support for
			// keyboard in fullscreen even though it doesn't.
			// Browser sniffing, since the alternative with
			// setTimeout is even worse.
			if (/5\.1[.\d]* Safari/.test(navigator.userAgent)) {
				elem[request]();
			} else {
				elem[request](keyboardAllowed && Element.ALLOW_KEYBOARD_INPUT);
			}
		},
		exit: function () {
			document[fn.exitFullscreen]();
		},
		toggle: function (elem) {
			if (this.isFullscreen) {
				this.exit();
			} else {
				this.request(elem);
			}
		},
		onchange: function (callback) {
			document.addEventListener(fn.fullscreenchange, callback, false);
		},
		onerror: function (callback) {
			document.addEventListener(fn.fullscreenerror, callback, false);
		},
		raw: fn
	};

	if (!fn) {
		if (isCommonjs) {
			module.exports = false;
		} else {
			window.screenfull = false;
		}

		return;
	}

	Object.defineProperties(screenfull, {
		isFullscreen: {
			get: function () {
				return Boolean(document[fn.fullscreenElement]);
			}
		},
		element: {
			enumerable: true,
			get: function () {
				return document[fn.fullscreenElement];
			}
		},
		enabled: {
			enumerable: true,
			get: function () {
				// Coerce to boolean in case of old WebKit
				return Boolean(document[fn.fullscreenEnabled]);
			}
		}
	});

	if (isCommonjs) {
		module.exports = screenfull;
	} else {
		window.screenfull = screenfull;
	}
})();

/**
 * bootstrap-admin-template - Free Admin Template Based On Twitter Bootstrap 3.x
 * @version 2.4.2
 * @license MIT
 * @link https://github.com/puikinsh/Bootstrap-Admin-Template
 */
'use strict';

;(function (window) {
    var
    // Are we expecting a touch or a click?
    buttonPressedEvent = 'touchstart click',
        Metis = function Metis() {
        this.init();
    };

    // Initialization method
    Metis.prototype.init = function () {
        this.buttonPressedEvent = buttonPressedEvent;
    };

    Metis.prototype.getViewportHeight = function () {

        var docElement = document.documentElement,
            client = docElement.clientHeight,
            inner = window.innerHeight;

        if (client < inner) return inner;else return client;
    };

    Metis.prototype.getViewportWidth = function () {

        var docElement = document.documentElement,
            client = docElement.clientWidth,
            inner = window.innerWidth;

        if (client < inner) return inner;else return client;
    };

    // Creates a Metis object.
    window.Metis = new Metis();
})(window);
'use strict';

;(function ($) {
    "use strict";

    var $navBar = $('nav.navbar'),
        $body = $('body'),
        $menu = $('#menu'),
        $left = $('#left');

    function addPaddingTop(el, val) {
        el.css('padding-top', val);
    }
    function removePaddingTop(el) {
        el.css('padding-top', 'inherit');
    }
    function getHeight(el) {
        return el.outerHeight();
    }

    function init() {
        var isFixedNav = $navBar.hasClass('navbar-fixed-top');
        var bodyPadTop = isFixedNav ? $navBar.outerHeight(true) : 0;

        $body.css('padding-top', bodyPadTop);

        if ($body.hasClass('menu-affix')) {
            $left.css({
                top: bodyPadTop
            });
            console.log($navBar.outerHeight(true));
        }
    }

    Metis.navBar = function () {
        var resizeTimer;
        init();
        $(window).resize(function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(init(), 250);
        });
    };
    return Metis;
})(jQuery);
'use strict';

;(function ($, Metis) {
  "use strict";
  // Define toggleFullScreen

  Metis.toggleFullScreen = function () {
    if (window.screenfull !== undefined && screenfull.enabled) {
      $('#toggleFullScreen').on(Metis.buttonPressedEvent, function (e) {
        screenfull.toggle(window.document[0]);
        $('body').toggleClass('fullScreen');
        e.preventDefault();
      });
    } else {
      $('#toggleFullScreen').addClass('hidden');
    }
  };
  // Define boxFullScreen
  Metis.boxFullScreen = function () {
    if (window.screenfull !== undefined && screenfull.enabled) {
      $('.full-box').on(Metis.buttonPressedEvent, function (e) {
        var $toggledPanel = $(this).parents('.box')[0];
        screenfull.toggle($toggledPanel);
        $(this).parents('.box').toggleClass('full-screen-box');
        $(this).parents('.box').children('.body').toggleClass('full-screen-box');
        $(this).children('i').toggleClass('fa-compress');
        e.preventDefault();
      });
    } else {
      $('.full-box').addClass('hidden');
    }
  };
  Metis.panelBodyCollapse = function () {
    var $collapseButton = $('.collapse-box'),
        $collapsedPanelBody = $collapseButton.closest('.box').children('.body');

    $collapsedPanelBody.collapse('show');

    $collapseButton.on(Metis.buttonPressedEvent, function (e) {
      var $collapsePanelBody = $(this).closest('.box').children('.body'),
          $toggleButtonImage = $(this).children('i');
      $collapsePanelBody.on('show.bs.collapse', function () {
        $toggleButtonImage.removeClass('fa-minus fa-plus').addClass('fa-spinner fa-spin');
      });
      $collapsePanelBody.on('shown.bs.collapse', function () {
        $toggleButtonImage.removeClass('fa-spinner fa-spin').addClass('fa-minus');
      });

      $collapsePanelBody.on('hide.bs.collapse', function () {
        $toggleButtonImage.removeClass('fa-minus fa-plus').addClass('fa-spinner fa-spin');
      });

      $collapsePanelBody.on('hidden.bs.collapse', function () {
        $toggleButtonImage.removeClass('fa-spinner fa-spin').addClass('fa-plus');
      });

      $collapsePanelBody.collapse('toggle');

      e.preventDefault();
    });
  };
  Metis.boxHiding = function () {
    $('.close-box').on(Metis.buttonPressedEvent, function () {
      $(this).closest('.box').hide('slow');
    });
  };
  return Metis;
})(jQuery, Metis || {});
'use strict';

;(function ($, Metis) {
    var $body = $('body'),
        $leftToggle = $('.toggle-left'),
        $count = 0;

    Metis.metisAnimatePanel = function () {

        if ($('#left').length) {
            $leftToggle.on(Metis.buttonPressedEvent, function (e) {

                if ($(window).width() < 768) {
                    $body.toggleClass('sidebar-left-opened');
                } else {
                    switch (true) {

                        case $body.hasClass("sidebar-left-mini"):
                            $body.removeClass("sidebar-left-mini");
                            break;
                        default:
                            $body.addClass("sidebar-left-mini");
                    }

                    e.preventDefault();
                }
            });
        } else {
            $leftToggle.addClass('hidden');
        }
    };
    return Metis;
})(jQuery, Metis || {});
'use strict';

;(function ($) {
   $(document).ready(function () {

      $('[data-toggle="tooltip"]').tooltip();

      $('#menu').metisMenu();
      Metis.navBar();
      Metis.metisAnimatePanel();
      Metis.toggleFullScreen();
      Metis.boxFullScreen();
      Metis.panelBodyCollapse();
      Metis.boxHiding();
   });
})(jQuery);


text:
/**
 * Created by d.tokarev on 02/12/15.
 */

package com.moneytapp.restapi.infrastructure.spark;

public class ConfigurationFactoryException extends Exception {

    private Environments environment;

    public ConfigurationFactoryException(String message, Environments environment) {
        super(message);
        setEnvironment(environment);
    }

    public Environments getEnvironment() {
        return environment;
    }

    public void setEnvironment(Environments environment) {
        this.environment = environment;
    }

    @Override
    public String getMessage() {
        return String.format(super.getMessage(), getEnvironment().name());
    }
}


text:
package com.microsoft.azure.management.sql;

import com.microsoft.azure.management.apigeneration.Fluent;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasId;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasName;
import com.microsoft.azure.management.resources.fluentcore.arm.models.HasResourceGroup;
import com.microsoft.azure.management.resources.fluentcore.model.Refreshable;
import com.microsoft.azure.management.resources.fluentcore.model.Wrapper;
import com.microsoft.azure.management.sql.implementation.ServiceObjectiveInner;

/**
 * An immutable client-side representation of an Azure SQL Service Objective.
 */
@Fluent
public interface ServiceObjective extends
        Wrapper<ServiceObjectiveInner>,
        Refreshable<ServiceObjective>,
        HasResourceGroup,
        HasName,
        HasId {
    /**
     * @return name of the SQL Server to which this replication belongs
     */
    String sqlServerName();

    /**
     * @return the name for the service objective.
     */
    String serviceObjectiveName();

    /**
     * @return whether the service level objective is the default service
     * objective.
     */
    boolean isDefault();

    /**
     * @return whether the service level objective is a system service objective.
     */
    boolean isSystem();

    /**
     * @return the description for the service level objective.
     */
    String description();

    /**
     * @return whether the service level objective is enabled.
     */
    boolean enabled();
}


text:
"use strict";

// import * as Debug from "debug";
import * as util from "util";
import {Component, ViewChild, ElementRef, AfterViewInit} from "angular2/core";
import {Tabs} from "../tabs/tabs";
import {Tab} from "../../model/tab";
import {TopNav} from "../top-nav/top-nav";
import {ConnectionModal} from "../modal/connection-modal/connection-modal";
import {ServerConnection} from "../server-connection/server-connection";
import {SessionState} from "../../model/session-state";
import {SessionService} from "../../service/session-service";

// const debug = Debug("mf:component/app/App");

@Component({
    directives: [Tabs, TopNav, ConnectionModal, ServerConnection],
    // encapsulation: ViewEncapsulation.Native,
    // moduleId: module.id,
    providers: [SessionService],
    selector: "app",
    styleUrls: ["component/app/app.css"],
    templateUrl: "component/app/app.html",
})

export class App implements AfterViewInit {
    @ViewChild("topBar") public topBar: ElementRef;
    @ViewChild("tabs") public tabs: Tabs;
    public topBarHeight = "9em";
    public currentSession: SessionState;
    public get hello() {
        return !this.currentSession;
    }

    constructor(private sessionService: SessionService) { }

    public resize() {
        if (!this.topBar || !this.topBar.nativeElement) {
            // throw new Error("Nothig found for topBar: " + util.inspect(this.topBar));
            console.error("Nothig found for topBar: " + util.inspect(this.topBar));
            return;
        }
        let newHeight = this.topBar.nativeElement.clientHeight + "px";
        // debug("app.resize newHeight: %s, topBarHeight: %s",
        //     newHeight, this.topBarHeight);
        if (this.topBarHeight !== newHeight) {
            // setImmediate prevents mutate after check exception
            setImmediate(() => this.topBarHeight = newHeight);
        }
    }

    public ngAfterViewInit() {
        this.resize();
    }

    public connectToServer(uri: string, showOptions: boolean) {
        let tab = new Tab(uri);
        this.tabs.addTab(tab);
        this.tabs.selectTab(tab);
        this.currentSession = this.sessionService.getSession(tab.id);
        this.currentSession.uri = uri;
        if (showOptions) {
            this.currentSession.modal = "connection";
        } else {
            this.currentSession.connect();
        }
        setImmediate(() => this.resize());
    }

    public tabSelected(tab: Tab) {
        this.currentSession = this.sessionService.getSession(tab.id);
    }
}


text:
package example;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Optional;
import java.util.stream.Stream;
import javax.swing.*;

public final class MainPanel extends JPanel {
  private MainPanel() {
    super(new BorderLayout());
    // UIManager.put("FileChooser.readOnly", Boolean.TRUE);
    JTextArea log = new JTextArea();

    JFileChooser fileChooser0 = new JFileChooser();
    JButton button0 = new JButton("default");
    button0.addActionListener(e -> {
      setViewTypeDetails(fileChooser0);
      descendants(fileChooser0)
          .filter(JTable.class::isInstance).map(JTable.class::cast)
          .findFirst()
          .ifPresent(table -> append(log, "isEditing: " + table.isEditing()));
      int retValue = fileChooser0.showOpenDialog(getRootPane());
      if (retValue == JFileChooser.APPROVE_OPTION) {
        append(log, fileChooser0.getSelectedFile().getAbsolutePath());
      }
    });

    JFileChooser fileChooser1 = new JFileChooser();
    JButton button1 = new JButton("removeEditor");
    button1.addActionListener(e -> {
      setViewTypeDetails(fileChooser1);
      descendants(fileChooser1)
        .filter(JTable.class::isInstance).map(JTable.class::cast)
        // debugging: .peek(table -> append(log, "isEditing: " + table.isEditing()))
        .findFirst()
        .filter(JTable::isEditing).ifPresent(JTable::removeEditor);
      int retValue = fileChooser1.showOpenDialog(getRootPane());
      if (retValue == JFileChooser.APPROVE_OPTION) {
        append(log, fileChooser1.getSelectedFile().getAbsolutePath());
      }
    });

    JPanel p = new JPanel();
    p.setBorder(BorderFactory.createTitledBorder("JFileChooser(viewTypeDetails)"));
    p.add(button0);
    p.add(button1);
    add(p, BorderLayout.NORTH);
    add(new JScrollPane(log));
    setPreferredSize(new Dimension(320, 240));
  }

  private static void setViewTypeDetails(JFileChooser fc) {
    String cmd = "viewTypeDetails";
    Optional.ofNullable(fc.getActionMap().get(cmd))
        .ifPresent(a -> a.actionPerformed(new ActionEvent(fc, ActionEvent.ACTION_PERFORMED, cmd)));
  }

  private static void append(JTextArea log, String str) {
    log.append(str + "\n");
    log.setCaretPosition(log.getDocument().getLength());
  }

  public static Stream<Component> descendants(Container parent) {
    return Stream.of(parent.getComponents())
        .filter(Container.class::isInstance).map(Container.class::cast)
        .flatMap(c -> Stream.concat(Stream.of(c), descendants(c)));
  }

  public static void main(String[] args) {
    EventQueue.invokeLater(MainPanel::createAndShowGui);
  }

  private static void createAndShowGui() {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
      ex.printStackTrace();
      Toolkit.getDefaultToolkit().beep();
    }
    JFrame frame = new JFrame("@title@");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(new MainPanel());
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>IndexRule (Apache UIMA Java SDK 2.8.1 User-Level API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.uima.search

Interface IndexRule

All Superinterfaces:

Serializable, XMLizable

public interface IndexRule
extends XMLizable, Serializable

A rule that specifies indexing behavior. An indexing rule is attached to an
 IndexBuildItem in order to assign indexing behavior to an annotation type. An Index Rule
 consists of zero or more Styles.

 This object implements the XMLizable interface and can be parsed from an XML
 representation.

Method Summary

Methods

Modifier and Type
Method and Description

Style[]
getStyles()

Gets the styles that comprise this index rule.

void
setStyles(Style[] aStyles)

Sets the styles that comprise this index rule.

Methods inherited from interface org.apache.uima.util.XMLizable

buildFromXMLElement, buildFromXMLElement, toXML, toXML, toXML, toXML

Method Detail

getStyles

Style[] getStyles()

Gets the styles that comprise this index rule.

Returns:

the CAS type name for this build item

setStyles

void setStyles(Style[] aStyles)

Sets the styles that comprise this index rule.

Parameters:

aStyles - the CAS type name for this build item

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2006–2015 The Apache Software Foundation. All rights reserved.


text:
var LanceTrack;
(function (LanceTrack) {
    var Statistics;
    (function (Statistics) {
        function statisticsServiceFactory($q, $http, dates) {
            return new StatisticsService($q, $http, dates);
        }
        Statistics.statisticsServiceFactory = statisticsServiceFactory;
        var StatisticsService = (function () {
            function StatisticsService($q, $http, dates) {
                this.$q = $q;
                this.$http = $http;
                this.dates = dates;
            }
            StatisticsService.prototype.statistic = function () {
                var deferred = this.$q.defer();
                this.$http.get(urls.data.statistics).success(function (result) { return deferred.resolve(result); }).error(function (err) { return deferred.reject(err); });
                return deferred.promise;
            };
            return StatisticsService;
        })();
        Statistics.StatisticsService = StatisticsService;
    })(Statistics = LanceTrack.Statistics || (LanceTrack.Statistics = {}));
})(LanceTrack || (LanceTrack = {}));
LanceTrack.Statistics.statisticsServiceFactory.$inject = ["$q", "$http", "dates"];
//# sourceMappingURL=statisticsService.js.map


text:
package cmd

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/golang/glog"
	multierror "github.com/hashicorp/go-multierror"
	"github.com/spf13/cobra"
	"k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"

	proxyconfig "istio.io/api/proxy/v1/config"
	"istio.io/pilot/model"
	"istio.io/pilot/proxy"
)

const (
	// ConfigMapKey is the key for mesh configuration data in the config map
	ConfigMapKey = "mesh"

	// DefaultConfigMapName is the default config map name that holds the mesh configuration.
	DefaultConfigMapName = "istio"
)

// GetMeshConfig fetches configuration from a config map
func GetMeshConfig(kube kubernetes.Interface, namespace, name string) (*proxyconfig.ProxyMeshConfig, error) {
	config, err := kube.CoreV1().ConfigMaps(namespace).Get(name, v1.GetOptions{})
	if err != nil {
		return nil, err
	}

	// values in the data are strings, while proto might use a different data type.
	// therefore, we have to get a value by a key
	yaml, exists := config.Data[ConfigMapKey]
	if !exists {
		return nil, fmt.Errorf("missing configuration map key %q", ConfigMapKey)
	}

	mesh := proxy.DefaultMeshConfig()
	if err = model.ApplyYAML(yaml, &mesh); err != nil {
		return nil, multierror.Prefix(err, "failed to convert to proto.")
	}

	if err = model.ValidateProxyMeshConfig(&mesh); err != nil {
		return nil, err
	}

	return &mesh, nil
}

// AddFlags carries over glog flags with new defaults
func AddFlags(rootCmd *cobra.Command) {
	flag.CommandLine.VisitAll(func(gf *flag.Flag) {
		switch gf.Name {
		case "logtostderr":
			if err := gf.Value.Set("true"); err != nil {
				fmt.Printf("missing logtostderr flag: %v", err)
			}
		case "alsologtostderr", "log_dir", "stderrthreshold":
			// always use stderr for logging
		default:
			rootCmd.PersistentFlags().AddGoFlag(gf)
		}
	})
}

// WaitSignal awaits for SIGINT or SIGTERM and closes the channel
func WaitSignal(stop chan struct{}) {
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	<-sigs
	close(stop)
	glog.Flush()
}