text:
package com.analysedesgeeks.android.os_service;

import java.io.IOException;
import java.lang.ref.WeakReference;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnInfoListener;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.RemoteException;
import android.util.Log;

import com.analysedesgeeks.android.MainActivity;
import com.analysedesgeeks.android.R;

public class PodcastPlaybackService extends Service {

	private boolean mIsSupposedToBePlaying = false;

	private int mServiceStartId = -1;

	public static final int PLAYBACKSERVICE_STATUS = 1;

	/**
	 * interval after which we stop the service when idle
	 */
	private static final int IDLE_DELAY = 60000;

	/**
	 * used to track what type of audio focus loss caused the playback to pause
	 */
	private boolean mPausedByTransientLossOfFocus = false;

	public static final String CMDTOGGLEPAUSE = "togglepause";
	public static final String CMDNAME = "command";
	public static final String CMDPAUSE = "pause";
	public static final String CMDSTOP = "stop";

	public static final String TOGGLEPAUSE_ACTION = "com.analysedesgeeks.android.os_service.musicservicecommand.togglepause";
	public static final String PAUSE_ACTION = "com.analysedesgeeks.android.os_service.musicservicecommand.pause";
	public static final String PLAYSTATE_CHANGED = "com.analysedesgeeks.android.os_service.playstatechanged";
	public static final String SERVICECMD = "com.analysedesgeeks.android.os_service.musicservicecommand";

	private MultiPlayer mPlayer;

	private final IBinder mBinder = new ServiceStub(this);

	private boolean mServiceInUse = false;

	private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(final Context context, final Intent intent) {
			final String action = intent.getAction();
			final String cmd = intent.getStringExtra("command");

			if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
				if (isPlaying()) {
					pause();
					mPausedByTransientLossOfFocus = false;
				} else {
					play();
				}
			} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
				pause();
				mPausedByTransientLossOfFocus = false;
			} else if (CMDSTOP.equals(cmd)) {
				pause();
				mPausedByTransientLossOfFocus = false;
				seek(0);
			}
		}
	};

	private final Handler mDelayedStopHandler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			// Check again to make sure nothing is playing right now
			if (isPlaying() || mPausedByTransientLossOfFocus || mServiceInUse || mMediaplayerHandler.hasMessages(TRACK_ENDED)) {
				return;
			}
			stopSelf(mServiceStartId);
		}
	};

	private final Handler mMediaplayerHandler = new Handler() {

		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case RELEASE_WAKELOCK:
				mWakeLock.release();
				break;
			default:
				break;
			}
		}
	};

	private WakeLock mWakeLock;

	private static final int TRACK_ENDED = 1;

	private static final int RELEASE_WAKELOCK = 2;

	private static final int SERVER_DIED = 3;

	private AudioManager mAudioManager;

	private String mFileToPlay;

	private String description = "";

	private boolean hasPlayed;

	public String description() {
		return description;
	}

	/**
	 * Returns the duration of the file in milliseconds.
	 * Currently this method returns -1 for the duration of MIDI files.
	 */
	public long duration() {
		if (mPlayer != null && mPlayer.isInitialized()) {
			return mPlayer.duration();
		}
		return -1;
	}

	/**
	 * Returns the path of the currently playing file, or null if
	 * no file is currently playing.
	 */
	public String getPath() {
		return mFileToPlay;
	}

	public boolean hasPlayed() {
		return hasPlayed;
	}

	/**
	 * Returns whether something is currently playing
	 *
	 * @return true if something is playing (or will be playing shortly, in case
	 *         we're currently transitioning between tracks), false if not.
	 */
	public boolean isPlaying() {
		return mIsSupposedToBePlaying;
	}

	@Override
	public IBinder onBind(final Intent intent) {
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		mServiceInUse = true;
		return mBinder;
	}

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

		mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		mAudioManager.registerMediaButtonEventReceiver(new ComponentName(getPackageName(), MediaButtonIntentReceiver.class.getName()));

		// Needs to be done in this thread, since otherwise ApplicationContext.getPowerManager() crashes.
		mPlayer = new MultiPlayer();
		mPlayer.setHandler(mMediaplayerHandler);

		final IntentFilter commandFilter = new IntentFilter();
		commandFilter.addAction(SERVICECMD);
		commandFilter.addAction(TOGGLEPAUSE_ACTION);
		commandFilter.addAction(PAUSE_ACTION);

		registerReceiver(mIntentReceiver, commandFilter);

		final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this.getClass().getName());
		mWakeLock.setReferenceCounted(false);

		// If the service was idle, but got killed before it stopped itself, the
		// system will relaunch it. Make sure it gets stopped again in that case.
		final Message msg = mDelayedStopHandler.obtainMessage();
		mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
	}

	@Override
	public void onDestroy() {

		mPlayer.release();
		mPlayer = null;

		// make sure there aren't any other messages coming
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		mMediaplayerHandler.removeCallbacksAndMessages(null);

		unregisterReceiver(mIntentReceiver);

		mWakeLock.release();
		super.onDestroy();
	}

	@Override
	public void onRebind(final Intent intent) {
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		mServiceInUse = true;
	}

	@Override
	public int onStartCommand(final Intent intent, final int flags, final int startId) {
		mServiceStartId = startId;
		mDelayedStopHandler.removeCallbacksAndMessages(null);

		if (intent != null) {
			final String action = intent.getAction();
			final String cmd = intent.getStringExtra("command");

			if (CMDTOGGLEPAUSE.equals(cmd) || TOGGLEPAUSE_ACTION.equals(action)) {
				if (isPlaying()) {
					pause();
					mPausedByTransientLossOfFocus = false;
				} else {
					play();
				}
			} else if (CMDPAUSE.equals(cmd) || PAUSE_ACTION.equals(action)) {
				pause();
				mPausedByTransientLossOfFocus = false;
			} else if (CMDSTOP.equals(cmd)) {
				pause();
				mPausedByTransientLossOfFocus = false;
				seek(0);
			}
		}

		// make sure the service will shut down on its own if it was
		// just started but not bound to and nothing is playing
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		final Message msg = mDelayedStopHandler.obtainMessage();
		mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
		return START_STICKY;
	}

	@Override
	public boolean onUnbind(final Intent intent) {
		mServiceInUse = false;

		if (isPlaying() || mPausedByTransientLossOfFocus) {
			// something is currently playing, or will be playing once
			// an in-progress action requesting audio focus ends, so don't stop the service now.
			return true;
		}

		// No active playlist, OK to stop the service right now
		stopSelf(mServiceStartId);
		return true;
	}

	/**
	 * Opens the specified file and readies it for playback.
	 *
	 * @param path
	 *            The full path of the file to be opened.
	 */
	public void open(final String path) {
		synchronized (this) {
			if (path == null) {
				return;
			}

			mFileToPlay = path;

			mPlayer.setDataSource(mFileToPlay);
			if (!mPlayer.isInitialized()) {
				stop(true);
			}
		}
	}

	/**
	 * Pauses playback (call play() to resume)
	 */
	public void pause() {
		synchronized (this) {
			if (isPlaying()) {
				mPlayer.pause();
				gotoIdleState();
				mIsSupposedToBePlaying = false;
			}
		}
	}

	/**
	 * Starts playback of a previously opened file.
	 */
	public void play() {
		mAudioManager.registerMediaButtonEventReceiver(new ComponentName(this.getPackageName(), MediaButtonIntentReceiver.class.getName()));

		if (mPlayer.isInitialized()) {
			mPlayer.start();

			final int icon = R.drawable.ic_notification;
			final CharSequence tickerText = description;
			final String title = getString(R.string.analyseDesGeeks);
			final long when = System.currentTimeMillis();

			final Notification notification = new Notification(icon, tickerText, when);
			notification.flags |= Notification.FLAG_ONGOING_EVENT;

			final Intent contentIntent = new Intent(this, MainActivity.class);
			final PendingIntent appIntent = PendingIntent.getActivity(this, 0, contentIntent, 0);
			notification.setLatestEventInfo(this, title, description, appIntent);

			startForeground(PLAYBACKSERVICE_STATUS, notification);
			if (!mIsSupposedToBePlaying) {
				mIsSupposedToBePlaying = true;
				hasPlayed = true;
			}

		}
	}

	/**
	 * Returns the current playback position in milliseconds
	 */
	public long position() {
		if (mPlayer.isInitialized()) {
			return mPlayer.position();
		}
		return -1;
	}

	/**
	 * Seeks to the position specified.
	 *
	 * @param pos
	 *            The position to seek to, in milliseconds
	 */
	public long seek(long pos) {
		if (mPlayer.isInitialized()) {
			if (pos < 0) {
				pos = 0;
			}
			if (pos > mPlayer.duration()) {
				pos = mPlayer.duration();
			}
			return mPlayer.seek(pos);
		}
		return -1;
	}

	public void setDescription(final String description) {
		this.description = description;
	}

	/**
	 * Stops playback.
	 */
	public void stop() {
		stop(true);
		hasPlayed = false;
	}

	private void gotoIdleState() {
		mDelayedStopHandler.removeCallbacksAndMessages(null);
		final Message msg = mDelayedStopHandler.obtainMessage();
		mDelayedStopHandler.sendMessageDelayed(msg, IDLE_DELAY);
		stopForeground(true);
	}

	private void stop(final boolean remove_status_icon) {
		if (mPlayer.isInitialized()) {
			mPlayer.stop();
		}
		mFileToPlay = null;

		if (remove_status_icon) {
			gotoIdleState();
		} else {
			stopForeground(false);
		}
		if (remove_status_icon) {
			mIsSupposedToBePlaying = false;
		}
	}

	/*
	 * By making this a static class with a WeakReference to the Service, we
	 * ensure that the Service can be GCd even when the system process still
	 * has a remote reference to the stub.
	 */
	static class ServiceStub extends IMediaPlaybackService.Stub {
		WeakReference<PodcastPlaybackService> mService;

		ServiceStub(final PodcastPlaybackService service) {
			mService = new WeakReference<PodcastPlaybackService>(service);
		}

		@Override
		public long duration() {
			return mService.get().duration();
		}

		@Override
		public String getDescription() {
			return mService.get().description();
		}

		@Override
		public String getPath() throws RemoteException {
			return mService.get().getPath();
		}

		@Override
		public boolean hasPlayed() throws RemoteException {
			return mService.get().hasPlayed();
		}

		@Override
		public boolean isPlaying() {
			return mService.get().isPlaying();
		}

		@Override
		public void openFile(final String path) {
			mService.get().open(path);
		}

		@Override
		public void pause() {
			mService.get().pause();
		}

		@Override
		public void play() {
			mService.get().play();
		}

		@Override
		public long position() throws RemoteException {
			return mService.get().position();
		}

		@Override
		public long seek(final long pos) throws RemoteException {
			return mService.get().seek(pos);
		}

		@Override
		public void setDescription(final String description) {
			mService.get().setDescription(description);
		}

		@Override
		public void stop() {
			mService.get().stop();
		}

	}

	/**
	 * Provides a unified interface for dealing with midi files and
	 * other media files.
	 */
	private class MultiPlayer {
		private MediaPlayer mMediaPlayer = new MediaPlayer();
		private Handler mHandler;
		private boolean mIsInitialized = false;

		MediaPlayer.OnCompletionListener listener = new MediaPlayer.OnCompletionListener() {
			@Override
			public void onCompletion(final MediaPlayer mp) {
				// Acquire a temporary wakelock, since when we return from
				// this callback the MediaPlayer will release its wakelock
				// and allow the device to go to sleep.
				// This temporary wakelock is released when the RELEASE_WAKELOCK
				// message is processed, but just in case, put a timeout on it.
				mWakeLock.acquire(30000);
				mHandler.sendEmptyMessage(TRACK_ENDED);
				mHandler.sendEmptyMessage(RELEASE_WAKELOCK);
			}
		};

		MediaPlayer.OnErrorListener errorListener = new MediaPlayer.OnErrorListener() {
			@Override
			public boolean onError(final MediaPlayer mp, final int what, final int extra) {
				switch (what) {
				case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
					mIsInitialized = false;
					mMediaPlayer.release();
					// Creating a new MediaPlayer and settings its wakemode does not
					// require the media service, so it's OK to do this now, while the
					// service is still being restarted
					mMediaPlayer = new MediaPlayer();
					mMediaPlayer.setWakeMode(PodcastPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);
					mHandler.sendMessageDelayed(mHandler.obtainMessage(SERVER_DIED), 2000);
					return true;
				default:
					Log.d("MultiPlayer", "Error: " + what + "," + extra);
					break;
				}
				return false;
			}
		};

		public MultiPlayer() {
			mMediaPlayer.setWakeMode(PodcastPlaybackService.this, PowerManager.PARTIAL_WAKE_LOCK);

			mMediaPlayer.setOnInfoListener(new OnInfoListener() {

				@Override
				public boolean onInfo(final MediaPlayer mp, final int what, final int extra) {
					// TODO Auto-generated method stub
					return false;
				}

			});
		}

		public long duration() {
			return mMediaPlayer.getDuration();
		}

		public boolean isInitialized() {
			return mIsInitialized;
		}

		public void pause() {
			mMediaPlayer.pause();
		}

		public long position() {
			return mMediaPlayer.getCurrentPosition();
		}

		/**
		 * You CANNOT use this player anymore after calling release()
		 */
		public void release() {
			stop();
			mMediaPlayer.release();
		}

		public long seek(final long whereto) {
			mMediaPlayer.seekTo((int) whereto);
			return whereto;
		}

		public void setDataSource(final String path) {
			try {
				mMediaPlayer.reset();
				mMediaPlayer.setOnPreparedListener(null);
				mMediaPlayer.setDataSource(PodcastPlaybackService.this, Uri.parse(path));
				mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mMediaPlayer.prepare();
			} catch (final IOException ex) {
				// TODO: notify the user why the file couldn't be opened
				mIsInitialized = false;
				return;
			} catch (final IllegalArgumentException ex) {
				// TODO: notify the user why the file couldn't be opened
				mIsInitialized = false;
				return;
			}
			mMediaPlayer.setOnCompletionListener(listener);
			mMediaPlayer.setOnErrorListener(errorListener);
			mIsInitialized = true;
		}

		public void setHandler(final Handler handler) {
			mHandler = handler;
		}

		public void start() {
			mMediaPlayer.start();
		}

		public void stop() {
			mMediaPlayer.reset();
			mIsInitialized = false;
		}
	}
}


text:
'use strict';
const deepEqual = require('deep-equal');

module.exports = (obj, search) => {
	if (typeof obj !== 'object') {
		return;
	}

	return Object.keys(obj).reduce((all, key) => {
		if (deepEqual(obj[key], search)) {
			all[key] = obj[key];
		}

		return all;
	}, {});
};

redpajama_set_name: RedPajamaGithub


text:
layout: experiment
name:  "secular-measure-of-work-ethic-survey"
maintainer: "@juhng62"
github: "https://github.com/expfactory-experiments/secular-measure-of-work-ethic-survey"
preview: "https://expfactory-experiments.github.io/secular-measure-of-work-ethic-survey"
tags:
- personality
- survey
---

A short form designed for researchers wanting to assess social desirability when time is limited. From [John, O. P., Donahue, E. M., & Kentle, R. L. (1991)](https://doi.org/10.1037/t07550-000)


text:
import com.prancingdonkey.domain.Order;
import org.junit.Test;
import org.mule.api.context.notification.ComponentMessageNotificationListener;
import org.mule.api.context.notification.ServerNotification;
import org.mule.tck.junit4.FunctionalTestCase;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import static org.junit.Assert.assertTrue;

public class RouteHighPriorityOrdersWithPropertiesFunctionalTestCase  extends FunctionalTestCase {

    CountDownLatch latch;

    @Override
    protected String getConfigResources() {
        return "src/main/app/routeHighPriorityOrdersOfTheCorrectType.xml";
    }

    @Override
    protected void doSetUp() throws Exception {
        latch = new CountDownLatch(2);

        muleContext.registerListener(new ComponentMessageNotificationListener() {
            public void onNotification(final ServerNotification notification) {
                latch.countDown();
            }
        });
    }

    @Test
    public void testCanRouteOrders() throws Exception {
        Order order = new Order();
        order.setPriority("HIGH");
        muleContext.getClient().dispatch("jms://topic:orders", order, null);

        assertTrue(latch.await(15, TimeUnit.SECONDS));
    }
}


text:
package org.dmfs.httpclientinterfaces.exceptions;

/**
 * An {@link Exception} that's thrown when an unrecoverable protocol error at application level occurred while handling a response.
 * <p>
 * An example of a {@link ProtocolException} is if the XML in the response of an XML-based protocol is not well-formed or the server returned a status code
 * that's not allowed for this kind of request.
 * </p>
 * This is different from an {@link ProtocolError} which is thrown if the server returned an error that's valid with respect to the application protocol.
 *
 * @author Marten Gajda <marten@dmfs.org>
 *
 * @see ProtocolError
 */
public class ProtocolException extends Exception
{
	/**
	 * Serial UID.
	 */
	private static final long serialVersionUID = 0;

	/**
	 * Create a new {@link ProtocolException} with a message.
	 *
	 * @param message
	 *            An error message.
	 */
	public ProtocolException(String message)
	{
		super(message);
	}

	/**
	 * Create a new {@link ProtocolException} with a message and a cause.
	 *
	 * @param message
	 *            An error message.
	 * @param cause
	 *            The reason for this error.
	 */
	public ProtocolException(String message, Throwable cause)
	{
		super(message, cause);
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta name="generator" content="JsDoc Toolkit" />

		<title>JsDoc Reference - CAAT.B2DBodyActor</title>

Class Index
| File Index

Classes

_global_

CAAT

CAAT.Actor

CAAT.ActorContainer

CAAT.AudioManager

CAAT.B2DBodyActor

CAAT.B2DCircularBody

CAAT.B2DPolygonBody

CAAT.Bezier

CAAT.Button

CAAT.CatmullRom

CAAT.Color

CAAT.Color.RGB

CAAT.CompoundImage

CAAT.Curve

CAAT.CurvePath

CAAT.Director

CAAT.IMActor

CAAT.ImageActor

CAAT.ImagePreloader

CAAT.ImageProcessor

CAAT.IMBump

CAAT.IMPlasma

CAAT.IMRotoZoom

CAAT.Interpolator

CAAT.InterpolatorActor

CAAT.LinearPath

CAAT.Matrix3

CAAT.MatrixStack

CAAT.modules

CAAT.modules.CircleManager

CAAT.modules.CircleManager.PackedCircle

CAAT.modules.CircleManager.PackedCircleManager

CAAT.modules.LocalStorage

CAAT.MouseEvent

CAAT.Path

CAAT.PathActor

CAAT.PathSegment

CAAT.Point

CAAT.Rectangle

CAAT.Scene

CAAT.ShapeActor

CAAT.SpriteActor

CAAT.SpriteImage

CAAT.StarActor

CAAT.TextActor

CAAT.TimerTask

Function

				Class CAAT.B2DBodyActor

Defined in:  box2Dactor.js.

Class Summary

						Constructor Attributes
						Constructor Name and Description

								CAAT.B2DBodyActor()

Define a binding beween a box2D Body instance and a CAAT.Actor.

Field Summary

							Field Attributes
							Field Name and Description

								bodyData

BodyData object linked to the box2D body.

								bodyType

Dynamic bodies by default

								density

Body dentisy

								friction

Body friction.

								restitution

Body restitution.

								worldBody

Box2D body

								worldBodyFixture

Box2d fixture

Method Summary

							Method Attributes
							Method Name and Description

check(obj, prop, def)

Helper method to check whether this js object contains a given property and if it doesn't exist
create and set it to def value.

createBody(world, bodyData)

Create an actor as a box2D body binding, create it on the given world and with
the initialization data set in bodyData object.

destroy()

getCenter()

Get this body's center on screen regardless of its shape.

getDistanceJointLocalAnchor()

Get a distance joint's position on pixels.

setAwake(bool)

setBodyType(bodyType)

Set this body's type:

setDensity(d)

Set this body's
density.

setFriction(f)

Set this body's friction.

setLocation(x, y)

setRecycle()

set this actor to recycle its body, that is, do not destroy it.

setRestitution(r)

Set this body's restitution coeficient.

setSleepingAllowed(bool)

					Class Detail

						CAAT.B2DBodyActor()

					Define a binding beween a box2D Body instance and a CAAT.Actor.
This function object should not be directly instantiated.
By now, one Box2D body can contain one single fixture and shape.

					Field Detail

					bodyData

						BodyData object linked to the box2D body.

					bodyType

						Dynamic bodies by default

					density

						Body dentisy

					friction

						Body friction.

					restitution

						Body restitution.

					worldBody

						Box2D body

					worldBodyFixture

						Box2d fixture

					Method Detail

					check(obj, prop, def)

						Helper method to check whether this js object contains a given property and if it doesn't exist
create and set it to def value.

Parameters:

									obj

{object}

									prop

{string}

									def

{object}

					createBody(world, bodyData)

						Create an actor as a box2D body binding, create it on the given world and with
the initialization data set in bodyData object.

Parameters:

									world

{Box2D.Dynamics.b2World} a Box2D world instance

									bodyData

{object} An object with body info.

					destroy()

					getCenter()

						Get this body's center on screen regardless of its shape.
This method will return box2d body's centroid.

					getDistanceJointLocalAnchor()

						Get a distance joint's position on pixels.

					setAwake(bool)

Parameters:

									bool

					setBodyType(bodyType)

						Set this body's type:

Parameters:

									bodyType

{Box2D.Dynamics.b2Body.b2_*}

					setDensity(d)

						Set this body's
density.

Parameters:

									d

{number}

					setFriction(f)

						Set this body's friction.

Parameters:

									f

{number}

					setLocation(x, y)

Parameters:

									x

									y

					setRecycle()

						set this actor to recycle its body, that is, do not destroy it.

					setRestitution(r)

						Set this body's restitution coeficient.

Parameters:

									r

{number}

					setSleepingAllowed(bool)

Parameters:

									bool

			Documentation generated by JsDoc Toolkit 2.4.0 on Thu Oct 27 2011 00:48:03 GMT+0200 (CEST)


text:
package com.sadofftext.jobapplication;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.stream.IntStream;

import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;

/**
* The class Date stores a date.
* While the class might seem trivial,
* it is simpler to have a class for dates
* than to have many constructors for Applicant.
*
* @since 1.0.0
* @author Eli Sadoff
*/
public class Date implements Comparable<Date> {
  /* Stores the day */
  private int day;
  /* Stores the month */
  private int month;
  /* Stores the year */
  private int year;

  /**
  * This is the constructor for the
  * Date class.
  * @param day the day to set
  * @param month the month to set
  * @param year the year to set
  */
  public Date(int day, int month, int year) {
    this.day = day;
    this.month = month;
    this.year = year;
  }

  /**
  * This gets the day.
  * @return the day
  */
  public int getDay() {
    return day;
  }

  /**
  * This sets the day.
  * @param day the day to set
  */
  public void setDay(int day) {
    this.day = day;
  }

  /**
  * This gets the month.
  * @return the month
  */
  public int getMonth() {
    return month;
  }

  /**
  * This sets the month.
  * @param month the month to set
  */
  public void setMonth(int month) {
    this.month = month;
  }

  /**
  * This gets the year.
  * @return the year
  */
  public int getYear() {
    return year;
  }

  /**
  * This sets the year.
  * @param year the year to set
  */
  public void setYear(int year) {
    this.year = year;
  }

  /**
  * This override's Object's
  * toString method.
  * @return string representation of a
  * date in the format MONTH DAY, YEAR.
  */
  @Override
  public String toString() {
    String day = Integer.toString(getDay());
    String month;
    switch (getMonth()) {
      case 1:
        month = "January";
        break;
      case 2:
        month = "February";
        break;
      case 3:
        month = "March";
        break;
      case 4:
        month = "April";
        break;
      case 5:
        month = "May";
        break;
      case 6:
        month = "June";
        break;
      case 7:
        month = "July";
        break;
      case 8:
        month = "August";
        break;
      case 9:
        month = "September";
        break;
      case 10:
        month = "October";
        break;
      case 11:
        month = "November";
        break;
      case 12:
        month = "December";
        break;
      default:
        month = "";
    }
    String year = Integer.toString(getYear());
    return month + " " + day + ", " + year;
  }

  @Override
  public boolean equals(Object o){
    if(o instanceof Date){
      Date d = (Date) o;
      boolean day = (getDay() == d.getDay());
      boolean month = (getMonth() == d.getMonth());
      boolean year = (getYear() == d.getYear());
      return day && month && year;
    }
    return false;
  }

  @Override
  public int compareTo(Date d){
    if(getYear() > d.getYear()){
      return 1;
    } else if(getYear() < d.getYear()){
      return -1;
    } else if(getMonth() > d.getMonth()){
      return 1;
    } else if(getMonth() < d.getMonth()){
      return -1;
    } else if(getDay() > d.getDay()){
      return 1;
    } else if(getDay() < d.getDay()){
      return -1;
    } else{
      return 0;
    }
  }
}


text:
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->backButton, SIGNAL(clicked(bool)), ui->webView, SLOT(back()));
    connect(ui->forwardButton, SIGNAL(clicked(bool)), ui->webView, SLOT(forward()));
    connect(ui->webView, SIGNAL(loadProgress(int)), ui->progressOfLoading, SLOT(setValue(int)));
    connect(ui->webView, SIGNAL(linkClicked(QUrl)), this, SLOT(loadPage(QUrl)));
    connect(ui->refreshButton, SIGNAL(clicked(bool)), this, SLOT(on_refreshButton_clicked()));
    connect(ui->urlEdit, SIGNAL(returnPressed()), SLOT(enterPressed()));
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    QString url = "http://www.google.com";
    ui->webView->load(url);
}

void MainWindow::loadPage(QUrl url)
{
    ui->webView->load(url);
    ui->urlEdit->setText(url.toString());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::textToUrl()
{
    printf("fds");
    if (ui->urlEdit->text().endsWith(".com") || ui->urlEdit->text().endsWith(".ru")
            || ui->urlEdit->text().endsWith(".net"))
    {
        if (ui->urlEdit->text().startsWith("http://www."))
        {
            ui->webView->load(ui->urlEdit->text());
        }
        else
        {
            if (ui->urlEdit->text().startsWith("www."))
            {
                ui->webView->load("http://" + ui->urlEdit->text());
            }
            else
            {
                ui->webView->load("http://www." + ui->urlEdit->text());
            }
        }
    }
    else
    {
        ui->webView->load("http://www.google.ru/#newwindow=1&q=" + ui->urlEdit->text());
    }
}

void MainWindow::on_goButton_clicked()
{
    textToUrl();
}
void MainWindow::enterPressed()
{
    textToUrl();
}

void MainWindow::on_refreshButton_clicked()
{
    ui->webView->load(ui->webView->url());
    ui->urlEdit->setText(ui->webView->url().toString());
}


text:
title: "RabbitMQ Connector"
nav-title: RabbitMQ
nav-parent_id: connectors
nav-pos: 6
---

## License of the RabbitMQ Connector

Flink's RabbitMQ connector defines a Maven dependency on the
"RabbitMQ AMQP Java Client", is triple-licensed under the Mozilla Public License 1.1 ("MPL"), the GNU General Public License version 2 ("GPL") and the Apache License version 2 ("ASL").

Flink itself neither reuses source code from the "RabbitMQ AMQP Java Client"
nor packages binaries from the "RabbitMQ AMQP Java Client".

Users that create and publish derivative work based on Flink's
RabbitMQ connector (thereby re-distributing the "RabbitMQ AMQP Java Client")
must be aware that this may be subject to conditions declared in the Mozilla Public License 1.1 ("MPL"), the GNU General Public License version 2 ("GPL") and the Apache License version 2 ("ASL").

## RabbitMQ Connector

This connector provides access to data streams from [RabbitMQ](http://www.rabbitmq.com/). To use this connector, add the following dependency to your project:

{% highlight xml %}
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-connector-rabbitmq{{ site.scala_version_suffix }}</artifactId>
  <version>{{site.version }}</version>
</dependency>
{% endhighlight %}

Note that the streaming connectors are currently not part of the binary distribution. See linking with them for cluster execution [here]({{site.baseurl}}/dev/project-configuration.html).

### Installing RabbitMQ
Follow the instructions from the [RabbitMQ download page](http://www.rabbitmq.com/download.html). After the installation the server automatically starts, and the application connecting to RabbitMQ can be launched.

### RabbitMQ Source

This connector provides a `RMQSource` class to consume messages from a RabbitMQ
queue. This source provides three different levels of guarantees, depending
on how it is configured with Flink:

1. **Exactly-once**: In order to achieve exactly-once guarantees with the
RabbitMQ source, the following is required -
 - *Enable checkpointing*: With checkpointing enabled, messages are only
 acknowledged (hence, removed from the RabbitMQ queue) when checkpoints
 are completed.
 - *Use correlation ids*: Correlation ids are a RabbitMQ application feature.
 You have to set it in the message properties when injecting messages into RabbitMQ.
 The correlation id is used by the source to deduplicate any messages that
 have been reprocessed when restoring from a checkpoint.
 - *Non-parallel source*: The source must be non-parallel (parallelism set
 to 1) in order to achieve exactly-once. This limitation is mainly due to
 RabbitMQ's approach to dispatching messages from a single queue to multiple
 consumers.

2. **At-least-once**: When checkpointing is enabled, but correlation ids
are not used or the source is parallel, the source only provides at-least-once
guarantees.

3. **No guarantee**: If checkpointing isn't enabled, the source does not
have any strong delivery guarantees. Under this setting, instead of
collaborating with Flink's checkpointing, messages will be automatically
acknowledged once the source receives and processes them.

Below is a code example for setting up an exactly-once RabbitMQ source.
Inline comments explain which parts of the configuration can be ignored
for more relaxed guarantees.

{% highlight java %}
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// checkpointing is required for exactly-once or at-least-once guarantees
env.enableCheckpointing(...);

final RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder()
    .setHost("localhost")
    .setPort(5000)
    ...
    .build();

final DataStream<String> stream = env
    .addSource(new RMQSource<String>(
        connectionConfig,            // config for the RabbitMQ connection
        "queueName",                 // name of the RabbitMQ queue to consume
        true,                        // use correlation ids; can be false if only at-least-once is required
        new SimpleStringSchema()))   // deserialization schema to turn messages into Java objects
    .setParallelism(1);              // non-parallel source is only required for exactly-once
{% endhighlight %}

{% highlight scala %}
val env = StreamExecutionEnvironment.getExecutionEnvironment
// checkpointing is required for exactly-once or at-least-once guarantees
env.enableCheckpointing(...)

val connectionConfig = new RMQConnectionConfig.Builder()
    .setHost("localhost")
    .setPort(5000)
    ...
    .build

val stream = env
    .addSource(new RMQSource[String](
        connectionConfig,            // config for the RabbitMQ connection
        "queueName",                 // name of the RabbitMQ queue to consume
        true,                        // use correlation ids; can be false if only at-least-once is required
        new SimpleStringSchema))     // deserialization schema to turn messages into Java objects
    .setParallelism(1)               // non-parallel source is only required for exactly-once
{% endhighlight %}

#### Quality of Service (QoS) / Consumer Prefetch

The RabbitMQ Source provides a simple way to set the `basicQos` on the source's channel through the `RMQConnectionConfig`.
Since there is one connection/ channel per-parallel source, this prefetch count will effectively be multiplied by the
source's parallelism for how many total unacknowledged messages can be sent to the job at one time.
If more complex configuration is required, `RMQSource#setupChannel(Connection)` can be overridden and manually configured.

{% highlight java %}
final RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder()
    .setPrefetchCount(30_000)
    ...
    .build();

{% endhighlight %}

{% highlight scala %}
val connectionConfig = new RMQConnectionConfig.Builder()
    .setPrefetchCount(30000)
    ...
    .build
{% endhighlight %}

The prefetch count is unset by default, meaning the RabbitMQ server will send unlimited messages. In production, it
is best to set this value. For high volume queues and checkpointing enabled, some tuning may be required to reduce
wasted cycles, as messages are only acknowledged on checkpoints if enabled.

More about QoS and prefetch can be found [here](https://www.rabbitmq.com/confirms.html#channel-qos-prefetch)
and more about the options available in AMQP 0-9-1 [here](https://www.rabbitmq.com/consumer-prefetch.html).

### RabbitMQ Sink
This connector provides a `RMQSink` class for sending messages to a RabbitMQ
queue. Below is a code example for setting up a RabbitMQ sink.

{% highlight java %}
final DataStream<String> stream = ...

final RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder()
    .setHost("localhost")
    .setPort(5000)
    ...
    .build();

stream.addSink(new RMQSink<String>(
    connectionConfig,            // config for the RabbitMQ connection
    "queueName",                 // name of the RabbitMQ queue to send messages to
    new SimpleStringSchema()));  // serialization schema to turn Java objects to messages
{% endhighlight %}

{% highlight scala %}
val stream: DataStream[String] = ...

val connectionConfig = new RMQConnectionConfig.Builder()
    .setHost("localhost")
    .setPort(5000)
    ...
    .build

stream.addSink(new RMQSink[String](
    connectionConfig,         // config for the RabbitMQ connection
    "queueName",              // name of the RabbitMQ queue to send messages to
    new SimpleStringSchema))  // serialization schema to turn Java objects to messages
{% endhighlight %}

More about RabbitMQ can be found [here](http://www.rabbitmq.com/).

{% top %}