text:
package uk.ac.gcu.bluedroid;

import uk.ac.gcu.bluedroid.game.GameState;
import uk.ac.gcu.bluedroid.game.Player;
import uk.ac.gcu.bluedroid.game.TurnInfo;
import uk.ac.gcu.bluedroid.resources.Camp;
import uk.ac.gcu.bluedroid.resources.Crop;
import uk.ac.gcu.bluedroid.resources.Mine;
import uk.ac.gcu.bluedroid.resources.Resource;
import uk.ac.gcu.bluedroid.units.Archer;
import uk.ac.gcu.bluedroid.units.Paladin;
import uk.ac.gcu.bluedroid.units.Soldier;
import uk.ac.gcu.bluedroid.units.Unit;
import uk.ac.gcu.bluedroid.util.CustomImageVIew;
import uk.ac.gcu.bluedroid.util.Util;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.GestureDetectorCompat;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is the main Activity that displays the current chat session.
 */
public class MainActivity extends Activity implements OnClickListener {
	// Debugging
	private static final String TAG = "MainActivity";
	private static final boolean D = true;

	// Message types sent from the BluetoothChatService Handler
	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_RECEIVED = 2;
	public static final int MESSAGE_SENT = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;

	// Key names received from the BluetoothChatService Handler
	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	// Intent request codes
	private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
	private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
	private static final int REQUEST_ENABLE_BT = 3;

	// Name of the connected device
	private String mConnectedDeviceName = null;
	// Array adapter for the conversation thread
	private ArrayAdapter<String> mConversationArrayAdapter;
	// String buffer for outgoing messages
	private StringBuffer mOutStringBuffer;
	// Local Bluetooth adapter
	private BluetoothAdapter mBluetoothAdapter = null;
	// Member object for the chat services
	private BluetoothChatService mChatService = null;

	// Game variables

	private static final String START_GAME = "start";
	private static final String END_GAME = "end";

	private Button startButton, connectionButton, mapButton1, mapButton2,
			mapButton3, exitButton; // buttons
	private final Context context = this;
	private boolean gameOn = false;
	private boolean server = false;
	private int player = 0;
	private boolean isMyTurn = false;

	private ScrollView scrollY;
	private HorizontalScrollView scrollX;
	private RelativeLayout mapContainer;

	private GameState state;
	private GestureDetectorCompat mDetector;

	// Selected unit and resource
	private Unit selectedUnit = null;
	private Resource selectedResource = null;

	// Constants
	private static final int ACTION_NONE = 0;
	private static final int ACTION_MOVE = 1;
	private static final int ACTION_ATTACK = 2;

	// Current action
	private int action = ACTION_NONE;

	private ProgressDialog progressDialog = null;

	private View viewMap = null;

	private TurnInfo myTurn = null, enemyTurn;

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

		if (D)
			Log.e(TAG, "+++ ON CREATE +++");

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// Set up the window layout
		setContentView(R.layout.main);

		startButton = (Button) findViewById(R.id.startButton);
		startButton.setOnClickListener(this);
		startButton.setVisibility(View.GONE);

		connectionButton = (Button) findViewById(R.id.connectionButton);
		connectionButton.setOnClickListener(this);

		mapButton1 = (Button) findViewById(R.id.mapButton1);
		mapButton1.setOnClickListener(this);

		mapButton2 = (Button) findViewById(R.id.mapButton2);
		mapButton2.setClickable(false);

		mapButton3 = (Button) findViewById(R.id.mapButton3);
		mapButton3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Util.simpleAlertDialog("Oops!",
						"I'm sorry.\nThis map is not available yet", context);
			}
		});

		exitButton = (Button) findViewById(R.id.exit);
		exitButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				View view = getLayoutInflater().inflate(
						R.layout.exit_confirmation, null);
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				builder.setView(view);
				final Dialog dialog = builder.show();

				view.findViewById(R.id.yes).setOnClickListener(
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								MainActivity.this.finish();

							}
						});

				view.findViewById(R.id.no).setOnClickListener(
						new OnClickListener() {

							@Override
							public void onClick(View v) {
								dialog.dismiss();

							}
						});

			}
		});

		mapButton1.setVisibility(View.GONE);
		mapButton2.setVisibility(View.GONE);
		mapButton3.setVisibility(View.GONE);

		// Get local Bluetooth adapter
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		// If the adapter is null, then Bluetooth is not supported
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "Bluetooth is not available",
					Toast.LENGTH_LONG).show();
			finish();
			return;
		}
	}

	@Override
	public void onClick(View v) {
		if (v == startButton) {
			mapButton1.setVisibility(View.VISIBLE);
			mapButton2.setVisibility(View.VISIBLE);
			mapButton3.setVisibility(View.VISIBLE);

			connectionButton.setVisibility(View.GONE);
			startButton.setVisibility(View.GONE);
		}

		if (v == connectionButton) {
			Log.d(TAG, "----Connections Button----");
			showCustomDialog();
		}

		if (v == mapButton1) {
			setupMap(1);
		}

		if (v == mapButton2) {
			setupMap(2);
		}

		if (v == mapButton3) {
			setupMap(3);
		}
	}

	/**
	 *
	 * @param mapId
	 */
	@SuppressLint("InflateParams")
	private void setupMap(int mapId) {

		Log.d(TAG, "----Start Button----");

		if (server)
			sendStart(mapId);

		gameOn = true;

		viewMap = getLayoutInflater().inflate(R.layout.map, null);

		setContentView(viewMap);

		state = new GameState(this);

		myTurn = new TurnInfo();
		enemyTurn = new TurnInfo();

		scrollY = (ScrollView) findViewById(R.id.scrollY);
		scrollX = (HorizontalScrollView) findViewById(R.id.scrollX);

		mapContainer = (RelativeLayout) findViewById(R.id.map);

		mDetector = new GestureDetectorCompat(this, new MyOnGestureListener());

		findViewById(R.id.endturn).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (isMyTurn) {
					endTurn();
				}
			}
		});

		if (!isMyTurn) {
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage("Waiting for other Player..");
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.show();
		}

		drawEverything();
	}

	private void showCustomDialog() {
		final Dialog dialog = new Dialog(this);

		// Gets the dialogs XML file.
		dialog.setContentView(R.layout.menu);
		dialog.setTitle("Connection Menu");
		dialog.setCancelable(true);

		// Intent serverIntent = null;

		Button dialogButton1 = (Button) dialog
				.findViewById(R.id.connectDialogButton);
		dialogButton1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent serverIntent = new Intent(context,
						DeviceListActivity.class);
				startActivityForResult(serverIntent,
						REQUEST_CONNECT_DEVICE_INSECURE);

				dialog.dismiss();
			}
		});

		Button dialogButton2 = (Button) dialog
				.findViewById(R.id.discoverableDialogButton);
		dialogButton2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				ensureDiscoverable();
				dialog.dismiss();
			}
		});
		dialog.show();
	}

	@Override
	public void onStart() {
		super.onStart();
		if (D)
			Log.e(TAG, "++ ON START ++");

		// If BT is not on, request that it be enabled.
		// setupChat() will then be called during onActivityResult
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
			// Otherwise, setup the chat session
		} else {
			if (mChatService == null)
				setupChat();
		}
	}

	@Override
	public synchronized void onResume() {
		super.onResume();
		if (D)
			Log.e(TAG, "+ ON RESUME +");

		// Performing this check in onResume() covers the case in which BT was
		// not enabled during onStart(), so we were paused to enable it...
		// onResume() will be called when ACTION_REQUEST_ENABLE activity
		// returns.
		if (mChatService != null) {
			// Only if the state is STATE_NONE, do we know that we haven't
			// started already
			if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
				// Start the Bluetooth chat services
				mChatService.start();
			}
		}
	}

	private void setupChat() {
		Log.d(TAG, "setupChat()");

		// Initialize the BluetoothChatService to perform bluetooth connections
		mChatService = new BluetoothChatService(this, mHandler);

		// Initialize the buffer for outgoing messages
		mOutStringBuffer = new StringBuffer("");
	}

	@Override
	public synchronized void onPause() {
		super.onPause();
		if (D)
			Log.e(TAG, "- ON PAUSE -");
	}

	@Override
	public void onStop() {
		super.onStop();
		if (D)
			Log.e(TAG, "-- ON STOP --");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// Stop the Bluetooth chat services
		if (mChatService != null)
			mChatService.stop();
		if (D)
			Log.e(TAG, "--- ON DESTROY ---");
	}

	/**
	 *
	 */
	private void ensureDiscoverable() {
		if (D)
			Log.d(TAG, "ensure discoverable");
		if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			startActivity(discoverableIntent);
		}
	}

	/**
	 *
	 * @return
	 */
	private boolean checkConnected() {
		if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
			Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT)
					.show();
			return false;
		} else
			return true;
	}

	/**
	 *
	 * @param mapId
	 */
	private void sendStart(int mapId) {
		if (checkConnected())
			mChatService.send("string", START_GAME + "," + mapId);
	}

	private void sendTurn() {
		if (checkConnected()) {
			mChatService.send("turn_info", myTurn);
			showProgressDialog();
		}
	}

	private void endTurn() {
		selectedUnit = null;
		action = ACTION_NONE;

		state.getMap().updateResources(state.getPlayers()[player - 1]);

		state.updateTurn();
		sendTurn();
	}

	/**
	 * The Handler that gets information back from the BluetoothChatService
	 */
	@SuppressLint("HandlerLeak")
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:
				if (D)
					Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
				switch (msg.arg1) {
				case BluetoothChatService.STATE_CONNECTED:
					if (server) {
						startButton.setVisibility(View.VISIBLE);
						player = 1;
						isMyTurn = true;
					} else {
						player = 2;
					}
					break;
				case BluetoothChatService.STATE_CONNECTING:
					break;
				case BluetoothChatService.STATE_LISTEN:
				case BluetoothChatService.STATE_NONE:
					break;
				}
				break;
			case MESSAGE_SENT:
				if (msg.obj instanceof String) {

				} else {
					isMyTurn = false;
				}
				break;
			case MESSAGE_RECEIVED:
				if (msg.obj instanceof String) {
					String message = (String) msg.obj;
					String[] pieces = message.split(",");
					if (pieces[0].equals(START_GAME)) {
						setupMap(Integer.valueOf(pieces[1]));
					}
				} else {
					enemyTurn = (TurnInfo) msg.obj;

					if (enemyTurn.getRecruitedUnit() != TurnInfo.HAS_NOT_RECRUITED) {
						if (enemyTurn.getHasMoved()
								&& state.getMap().getUnit(
										enemyTurn.getRecruitPos()) != null) {
							if(enemyTurn.getHasAttacked()) {
								attackAndMove(enemyTurn);
								enemyTurn.setHasAttacked(false);
							} else
								move(enemyTurn);

							enemyTurn.setHasMoved(false);
						}

						recruit(enemyTurn);
					}

					if (enemyTurn.getHasAttacked() && enemyTurn.getHasMoved())
						attackAndMove(enemyTurn);
					else if (enemyTurn.getHasMoved())
						move(enemyTurn);
					else if (enemyTurn.getHasAttacked())
						attack(enemyTurn);

					isMyTurn = true;
					myTurn = new TurnInfo();
					drawEverything();
					progressDialog.dismiss();
				}
				break;
			case MESSAGE_DEVICE_NAME:
				// save the connected device's name
				mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
				Toast.makeText(context, "Connected to " + mConnectedDeviceName,
						Toast.LENGTH_SHORT).show();
				break;
			case MESSAGE_TOAST:
				Toast.makeText(context, msg.getData().getString(TOAST),
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};

	private void recruit(TurnInfo enemyTurn) {
		int p = player == 1 ? 2 : 1;
		if (enemyTurn.getRecruitedUnit() == TurnInfo.ARCHER_RECRUITED)
			state.getMap().addUnit(new Archer(p, enemyTurn.getRecruitPos()));
		else if (enemyTurn.getRecruitedUnit() == TurnInfo.PALADIN_RECRUITED)
			state.getMap().addUnit(new Paladin(p, enemyTurn.getRecruitPos()));
		else if (enemyTurn.getRecruitedUnit() == TurnInfo.SOLDIER_RECRUITED)
			state.getMap().addUnit(new Soldier(p, enemyTurn.getRecruitPos()));

		((Camp) state.getMap().getResource(enemyTurn.getRecruitPos()))
				.setWorking(false);
	}

	private void attackAndMove(TurnInfo enemyTurn) {
		move(enemyTurn);

		state.getMap()
				.getUnit(enemyTurn.getUnitTargetPos())
				.takeDemage(
						state.getMap().getUnit(enemyTurn.getUnitEndPos())
								.getPower());
	}

	private void move(TurnInfo enemyTurn) {
		state.getMap().moveUnit(
				state.getMap().getUnit(enemyTurn.getUnitStartPos()),
				enemyTurn.getUnitEndPos());
	}

	private void attack(TurnInfo enemyTurn) {
		state.getMap()
				.getUnit(enemyTurn.getUnitTargetPos())
				.takeDemage(
						state.getMap().getUnit(enemyTurn.getUnitEndPos())
								.getPower());
	}

	/**
	 *
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (D)
			Log.d(TAG, "onActivityResult " + resultCode);
		switch (requestCode) {
		case REQUEST_CONNECT_DEVICE_INSECURE:
			// When DeviceListActivity returns with a device to connect
			if (resultCode == Activity.RESULT_OK) {
				connectDevice(data);
			}
			break;
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				setupChat();
			} else {
				// User did not enable Bluetooth or an error occurred
				Log.d(TAG, "BT not enabled");
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	/**
	 *
	 * @param data
	 */
	private void connectDevice(Intent data) {
		// Get the device MAC address
		String address = data.getExtras().getString(
				DeviceListActivity.EXTRA_DEVICE_ADDRESS);
		// Get the BluetoothDevice object
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		// Attempt to connect to the device
		mChatService.connect(device, false);

		server = true;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		super.dispatchTouchEvent(event);
		if (gameOn) {
			scrollX.dispatchTouchEvent(event);
			scrollY.onTouchEvent(event);
			mDetector.onTouchEvent(event);
		}
		return true;
	}

	/**
	 *
	 * @param context
	 * @param dp
	 * @return
	 */
	int DPtoPX(Context context, float dp) {
		Resources r = context.getResources();
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				r.getDisplayMetrics());
	}

	/**
	 *
	 * @param context
	 * @param px
	 * @return
	 */
	float PXtoDP(Context context, float px) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();
		return (px / (metrics.densityDpi / 158.4f));
	}

	/**
	 *
	 */
	void drawEverything() {
		// Remove views
		for (int i = mapContainer.getChildCount(); i > 0; i--) {
			View child = mapContainer.getChildAt(i - 1);
			if (child.getId() != R.id.mapimg)
				mapContainer.removeViewAt(i - 1);
		}

		// Add views
		addUnits();
		// Organize header
		refreshHeader(this.player);
	}

	/**
	 *
	 */
	private void addUnits() {
		for (int i = 0; i < state.getMap().getX(); i++) {
			for (int j = 0; j < state.getMap().getY(); j++) {
				Unit u = state.getMap().getUnit(i, j);
				if (u == null)
					continue;

				ImageView unit = new ImageView(this);
				unit.setImageResource(getResources().getIdentifier(
						(u.getPrefix() + u.getOwner()), "drawable",
						getPackageName()));

				ProgressBar lifeBar = new ProgressBar(this, null,
						android.R.attr.progressBarStyleHorizontal);

				if ((Math.round(100 * u.getLife() / (float) u.getMax_life())) < 50) {
					Drawable drawable = lifeBar.getProgressDrawable();
					drawable.setColorFilter(new LightingColorFilter(0x00000000,
							Color.RED));
				}

				lifeBar.setProgress(Math.round(100 * u.getLife()
						/ (float) u.getMax_life()));

				RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
						DPtoPX(this, 50), DPtoPX(this, 50));
				lp.addRule(RelativeLayout.ALIGN_PARENT_START);
				lp.leftMargin = DPtoPX(this, i * 50f);
				lp.topMargin = DPtoPX(this, j * 50f);

				RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
						DPtoPX(this, 50), DPtoPX(this, 50));
				lp2.addRule(RelativeLayout.BELOW, unit.getId());
				lp2.leftMargin = DPtoPX(this, i * 50f);
				lp2.topMargin = DPtoPX(this, (j * 50f) - 30f);

				mapContainer.addView(unit, lp);
				mapContainer.addView(lifeBar, lp2);
			}
		}
	}

	/**
	 * Refreshes header information of the game
	 *
	 * @param player
	 *            player who is on turn
	 */
	private void refreshHeader(final int player) {

		Button resources = (Button) viewMap.findViewById(R.id.resourcesButton);
		TextView food = (TextView) viewMap.findViewById(R.id.foodValue);
		TextView gold = (TextView) viewMap.findViewById(R.id.goldValue);
		TextView camps = (TextView) viewMap.findViewById(R.id.campValue);
		TextView player_text = (TextView) viewMap
				.findViewById(R.id.playerValue);

		player_text.setText(String.valueOf(this.player));
		food.setText(String.valueOf(state.getPlayers()[player - 1].getFood()));
		gold.setText(String.valueOf(state.getPlayers()[player - 1].getGold()));
		camps.setText(String.valueOf(state.getPlayers()[player - 1].getCamps()));

		resources.setOnClickListener(new OnClickListener() {

			@SuppressLint("InflateParams")
			@Override
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(context);
				View view = getLayoutInflater().inflate(R.layout.resources,
						null);
				builder.setView(view);
				final Dialog dialog = builder.show();

				TextView crops = (TextView) view.findViewById(R.id.cropsValue);
				TextView mines = (TextView) view.findViewById(R.id.minesValue);
				TextView camps = (TextView) view.findViewById(R.id.campsValue);
				Button ok = (Button) view.findViewById(R.id.ok);

				crops.setText(String.valueOf(state.getPlayers()[player - 1]
						.getCrops()));
				mines.setText(String.valueOf(state.getPlayers()[player - 1]
						.getMines()));
				camps.setText(String.valueOf(state.getPlayers()[player - 1]
						.getCamps()));

				ok.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});

			}
		});
	}

	private void showProgressDialog() {

		progressDialog = new ProgressDialog(context);
		progressDialog.setMessage("Waiting for Other Player..");
		progressDialog.show();
		progressDialog.setCanceledOnTouchOutside(false);
	}

	@SuppressLint("InflateParams")
	private void unitAction() {
		// Unit dialog creation
		View view = getLayoutInflater().inflate(R.layout.actions, null);
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setView(view);
		final Dialog dialog = builder.show();

		TextView name = (TextView) view.findViewById(R.id.name);
		TextView life = (TextView) view.findViewById(R.id.life);
		TextView id = (TextView) view.findViewById(R.id.id);
		TextView player_text = (TextView) view.findViewById(R.id.player);
		TextView power = (TextView) view.findViewById(R.id.power);
		TextView attack_range = (TextView) view.findViewById(R.id.attack_range);
		TextView move_range = (TextView) view.findViewById(R.id.move_range);

		ProgressBar lifebar = (ProgressBar) view.findViewById(R.id.lifebar);

		ImageView unit = (ImageView) view.findViewById(R.id.imageView1);

		unit.setImageResource(getResources().getIdentifier(
				(selectedUnit.getPrefix() + selectedUnit.getOwner()),
				"drawable", getPackageName()));

		if (selectedUnit.getPrefix().equals("a")) { // if it's an archer
			name.setText(R.string.archer);
		} else if (selectedUnit.getPrefix().equals("i")) { // if it's a soldier
			name.setText(R.string.soldier);
		} else if (selectedUnit.getPrefix().equals("c")) { // if it's a paladin
			name.setText(R.string.paladin);
		}
		name.setTypeface(null, Typeface.BOLD);

		player_text.setText(Html.fromHtml("<b>Player ID: </b>"
				+ selectedUnit.getOwner()));
		power.setText(Html.fromHtml("<b>Power: </b>" + selectedUnit.getPower()));
		life.setText(Html.fromHtml("<b>Life: </b>" + selectedUnit.getLife()
				+ "/" + selectedUnit.getMax_life()));
		lifebar.setProgress(Math.round(100 * selectedUnit.getLife()
				/ (float) selectedUnit.getMax_life()));
		Button cancel = (Button) view.findViewById(R.id.cancel);
		Button move = (Button) view.findViewById(R.id.move);
		Button attack = (Button) view.findViewById(R.id.attack);

		cancel.setOnClickListener(new OnClickListener() { // cancel button
															// action
			@Override
			public void onClick(View arg0) {
				dialog.dismiss();
			}
		});

		if (selectedUnit.getOwner() != player) { // if the unity it's an enemy
			id.setText("ENEMY");
			id.setTypeface(null, Typeface.BOLD);
			id.setTextColor(Color.RED);
			move.setVisibility(View.GONE);
			attack.setVisibility(View.GONE);
			move_range.setVisibility(View.GONE);
			attack_range.setVisibility(View.GONE);
		} else { // if it's a current player unit
			id.setText(Html.fromHtml("<b>Unit ID: </b>" + selectedUnit.getId()));
			attack_range.setText(Html.fromHtml("<b>Attack range: </b>"
					+ selectedUnit.getRange()));
			move_range.setText(Html.fromHtml("<b>Move range: </b>"
					+ selectedUnit.getMove()));

			if (myTurn.getHasMoved())
				move.setVisibility(View.GONE);
			else
				move.setOnClickListener(new OnClickListener() { // move action
					@Override
					public void onClick(View arg0) {
						action = ACTION_MOVE;
						dialog.dismiss();
					}
				});

			if (myTurn.getHasMoved()
					&& !selectedUnit.getPosition().equals(
							myTurn.getUnitEndPos()))
				attack.setVisibility(View.GONE);
			else
				attack.setOnClickListener(new OnClickListener() { // attack
																	// action
					@Override
					public void onClick(View arg0) {
						action = ACTION_ATTACK;
						dialog.dismiss();
					}
				});
		}
	}

	@SuppressLint("InflateParams")
	private void resourceAction() {
		// Resource dialog creation
		View view = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		if (selectedResource instanceof Mine
				|| selectedResource instanceof Crop) {
			view = getLayoutInflater().inflate(R.layout.resource, null);
			builder.setView(view);
			final Dialog dialog = builder.show();

			TextView type = (TextView) view.findViewById(R.id.type);
			TextView owner = (TextView) view.findViewById(R.id.owner);
			Button cancel = (Button) view.findViewById(R.id.cancel);

			owner.setText(Html.fromHtml("<b>Owner: </b>"
					+ (selectedResource.getOwner() == 0 ? "None" : "Player: "
							+ selectedResource.getOwner())));

			if (selectedResource instanceof Mine) {
				type.setText(Html.fromHtml("<b>Type: </b>Mine"));
			} else if (selectedResource instanceof Crop) {
				type.setText(Html.fromHtml("<b>Type: </b>Crop"));
			}

			cancel.setOnClickListener(new OnClickListener() { // cancel action
				@Override
				public void onClick(View arg0) {
					dialog.dismiss();
				}
			});

		} else if (selectedResource instanceof Camp) { // if it's a camp
			if (selectedResource.getOwner() == 0) { // if the camp has no owner
				// setup dialog
				view = getLayoutInflater().inflate(
						R.layout.camp_alert_no_owner, null);
				builder.setView(view);
				final Dialog dialog2 = builder.show();
				Button ok = (Button) view.findViewById(R.id.ok);
				ok.setOnClickListener(new OnClickListener() { // ok button
																// action
					@Override
					public void onClick(View arg0) {
						dialog2.dismiss();
					}
				});
			} else if (((Camp) selectedResource).isWorking() == false) { // if
																			// the
																			// camp
																			// has
																			// a
																			// owner
																			// but
																			// is
																			// not
																			// working
				// setup dialog
				view = getLayoutInflater().inflate(R.layout.camp_alert2, null);
				builder.setView(view);
				final Dialog dialog2 = builder.show();
				Button ok = (Button) view.findViewById(R.id.ok);
				ok.setOnClickListener(new OnClickListener() { // ok button
																// action
					@Override
					public void onClick(View arg0) {
						dialog2.dismiss();
					}
				});
			} else { // if has a owner, can recrute some unit
				view = getLayoutInflater().inflate(R.layout.camp, null);
				builder.setView(view);
				final Dialog dialog3 = builder.show();

				Button cancel = (Button) view.findViewById(R.id.cancel);
				Button paladin = (Button) view.findViewById(R.id.paladin);
				Button archer = (Button) view.findViewById(R.id.archer);
				Button soldier = (Button) view.findViewById(R.id.soldier);

				paladin.setOnClickListener(new OnClickListener() { // paladin
					// recruitment
					// action
					@Override
					public void onClick(View arg0) {
						if (((Camp) selectedResource).hasEnoughResources(
								Camp.PALADIN, state.getPlayers()[player - 1])) {
							state.getMap().addUnit(
									new Paladin(selectedResource.getOwner(),
											selectedResource.getPosition()));
							state.getPlayers()[player - 1].updateResource(
									Player.GOLD, -Camp.PALADIN_COST_GOLD);
							state.getPlayers()[player - 1].updateResource(
									Player.FOOD, -Camp.PALADIN_COST_FOOD);
							state.getPlayers()[player - 1].updateResource(
									Player.CAMPS, -1);
							drawEverything();
							((Camp) selectedResource).setWorking(false);

							myTurn.setRecruitPos(selectedResource.getPosition());
							myTurn.setRecruitedUnit(TurnInfo.PALADIN_RECRUITED);

						} else {
							Toast.makeText(context, R.string.enoughResources,
									Toast.LENGTH_SHORT).show();
						}
						dialog3.dismiss();
					}
				});
				archer.setOnClickListener(new OnClickListener() { // archer
					// recruitment
					// action
					@Override
					public void onClick(View arg0) {
						if (((Camp) selectedResource).hasEnoughResources(
								Camp.ARCHER, state.getPlayers()[player - 1])) {
							state.getMap().addUnit(
									new Archer(selectedResource.getOwner(),
											selectedResource.getPosition()));
							state.getPlayers()[player - 1].updateResource(
									Player.GOLD, -Camp.ARCHER_COST_GOLD);
							state.getPlayers()[player - 1].updateResource(
									Player.FOOD, -Camp.ARCHER_COST_FOOD);
							state.getPlayers()[player - 1].updateResource(
									Player.CAMPS, -1);
							drawEverything();
							((Camp) selectedResource).setWorking(false);

							myTurn.setRecruitPos(selectedResource.getPosition());
							myTurn.setRecruitedUnit(TurnInfo.ARCHER_RECRUITED);

						} else {
							Toast.makeText(context, R.string.enoughResources,
									Toast.LENGTH_SHORT).show();
						}
						dialog3.dismiss();
					}
				});
				soldier.setOnClickListener(new OnClickListener() {// soldier
					// recruitment
					// action
					@Override
					public void onClick(View arg0) {
						if (((Camp) selectedResource).hasEnoughResources(
								Camp.SOLDIER, state.getPlayers()[player - 1])) {
							state.getMap().addUnit(
									new Soldier(selectedResource.getOwner(),
											selectedResource.getPosition()));
							state.getPlayers()[player - 1].updateResource(
									Player.GOLD, -Camp.SOLDIER_COST_GOLD);
							state.getPlayers()[player - 1].updateResource(
									Player.FOOD, -Camp.SOLDIER_COST_FOOD);
							state.getPlayers()[player - 1].updateResource(
									Player.CAMPS, -1);
							drawEverything();
							((Camp) selectedResource).setWorking(false);

							myTurn.setRecruitPos(selectedResource.getPosition());
							myTurn.setRecruitedUnit(TurnInfo.SOLDIER_RECRUITED);

						} else {
							Toast.makeText(context, R.string.enoughResources,
									Toast.LENGTH_SHORT).show();
						}
						dialog3.dismiss();
					}
				});
				cancel.setOnClickListener(new OnClickListener() { // cancel
																	// action
					@Override
					public void onClick(View arg0) {
						dialog3.dismiss();
					}
				});
				refreshHeader(selectedResource.getOwner());
			}
		}
	}

	class MyOnGestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onSingleTapConfirmed(MotionEvent event) {
			Point size = new Point();
			Display display = getWindowManager().getDefaultDisplay();
			display.getSize(size);

			if (event.getY() < DPtoPX(context, 50)
					|| event.getY() > size.y - DPtoPX(context, 50))
				return true;

			int tmpX = ((int) event.getX() + scrollX.getScrollX());
			int tmpY = ((int) event.getY() + scrollY.getScrollY() - DPtoPX(
					context, 50));

			int x = (int) Math.floor((PXtoDP(context, tmpX) / 50));
			int y = (int) Math.floor((PXtoDP(context, tmpY) / 50));

			switch (action) {
			case ACTION_NONE:
				selectedUnit = state.getMap().getUnit(x, y);
				selectedResource = state.getMap().getResource(x, y);
				if (selectedUnit != null) {
					unitAction();
				} else if (selectedResource != null) {
					resourceAction();
				}
				break;
			case ACTION_MOVE:
				if (selectedUnit != null) {
					Log.e("pos", x + " " + y);
					if (state.getMap().walkable(x, y) == 0)
						Toast.makeText(context, R.string.cantMove,
								Toast.LENGTH_SHORT).show();
					else if (!state.getMap().canWalkTo(
							selectedUnit.getPosition().getX(),
							selectedUnit.getPosition().getY(), x, y,
							selectedUnit.getMove()))
						Toast.makeText(MainActivity.this, R.string.tooFar,
								Toast.LENGTH_SHORT).show();
					else { // can be a resource
						if (state.getMap().walkable(x, y) == Player.CAMPS) { // if
																				// it's
																				// a
																				// camp
							state.getPlayers()[player - 1].updateResource(
									Player.CAMPS, 1);
						} else if (state.getMap().walkable(x, y) == Player.MINES) { // if
																					// it's
																					// a
																					// mine
							state.getPlayers()[player - 1].updateResource(
									Player.MINES, 1);
						} else if (state.getMap().walkable(x, y) == Player.CROPS) { // if
																					// it's
																					// a
																					// crop
							state.getPlayers()[player - 1].updateResource(
									Player.CROPS, 1);
						}

						myTurn.setUnitStartPos(selectedUnit.getPosition());
						state.getMap().moveUnit(selectedUnit, x, y);
						myTurn.setUnitEndPos(selectedUnit.getPosition());
						myTurn.setHasMoved(true);

					}
					selectedUnit = null;
					action = ACTION_NONE;
				}
				break;
			case ACTION_ATTACK:
				if (selectedUnit != null) {
					Unit target = state.getMap().getUnit(x, y);
					if (target != null) {
						if (target.getOwner() == selectedUnit.getOwner()) {
							Toast.makeText(context, R.string.ownUnit,
									Toast.LENGTH_SHORT).show();
						} else if (Math.abs(selectedUnit.getPosition().getX()
								- target.getPosition().getX())
								+ Math.abs(selectedUnit.getPosition().getY()
										- target.getPosition().getY()) <= selectedUnit
									.getRange()) {
							myTurn.setUnitEndPos(selectedUnit.getPosition());
							myTurn.setHasAttacked(true);
							myTurn.setUnitTargetPos(target.getPosition());
							target.takeDemage(selectedUnit.getPower());
							Toast.makeText(
									context,
									"Unit " + target.getId() + " from Player "
											+ target.getOwner() + " took "
											+ selectedUnit.getPower()
											+ " points of damage from Unit "
											+ selectedUnit.getId()
											+ " (Player: "
											+ selectedUnit.getOwner() + ")",
									Toast.LENGTH_LONG).show();
							if (target.getLife() == 0) {
								state.getMap().removeUnit(target);
							}

							endTurn();
						} else
							Toast.makeText(context, R.string.tooFar,
									Toast.LENGTH_SHORT).show();
					} else
						Toast.makeText(context, R.string.noTarget,
								Toast.LENGTH_SHORT).show();

					selectedUnit = null;
					action = ACTION_NONE;
				}
				break;
			}

			drawEverything();
			return true;
		}
	}
}


text:
package org.apache.flink.runtime.rest.messages;

import org.apache.flink.runtime.rest.handler.job.JobAccumulatorsHandler;
import org.apache.flink.runtime.rest.messages.json.SerializedValueDeserializer;
import org.apache.flink.runtime.rest.messages.json.SerializedValueSerializer;
import org.apache.flink.util.OptionalFailure;
import org.apache.flink.util.Preconditions;
import org.apache.flink.util.SerializedValue;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * Response type of the {@link JobAccumulatorsHandler}.
 */
public class JobAccumulatorsInfo implements ResponseBody {
	public static final String FIELD_NAME_JOB_ACCUMULATORS = "job-accumulators";
	public static final String FIELD_NAME_USER_TASK_ACCUMULATORS = "user-task-accumulators";
	public static final String FIELD_NAME_SERIALIZED_USER_TASK_ACCUMULATORS = "serialized-user-task-accumulators";

	@JsonProperty(FIELD_NAME_JOB_ACCUMULATORS)
	private List<JobAccumulator> jobAccumulators;

	@JsonProperty(FIELD_NAME_USER_TASK_ACCUMULATORS)
	private List<UserTaskAccumulator> userAccumulators;

	@JsonProperty(FIELD_NAME_SERIALIZED_USER_TASK_ACCUMULATORS)
	@JsonSerialize(contentUsing = SerializedValueSerializer.class)
	private Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators;

	@JsonCreator
	public JobAccumulatorsInfo(
			@JsonProperty(FIELD_NAME_JOB_ACCUMULATORS) List<JobAccumulator> jobAccumulators,
			@JsonProperty(FIELD_NAME_USER_TASK_ACCUMULATORS) List<UserTaskAccumulator> userAccumulators,
			@JsonDeserialize(contentUsing = SerializedValueDeserializer.class) @JsonProperty(FIELD_NAME_SERIALIZED_USER_TASK_ACCUMULATORS) Map<String, SerializedValue<OptionalFailure<Object>>> serializedUserAccumulators) {
		this.jobAccumulators = Preconditions.checkNotNull(jobAccumulators);
		this.userAccumulators = Preconditions.checkNotNull(userAccumulators);
		this.serializedUserAccumulators = Preconditions.checkNotNull(serializedUserAccumulators);
	}

	@JsonIgnore
	public List<JobAccumulator> getJobAccumulators() {
		return jobAccumulators;
	}

	@JsonIgnore
	public List<UserTaskAccumulator> getUserAccumulators() {
		return userAccumulators;
	}

	@JsonIgnore
	public Map<String, SerializedValue<OptionalFailure<Object>>> getSerializedUserAccumulators() {
		return serializedUserAccumulators;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		JobAccumulatorsInfo that = (JobAccumulatorsInfo) o;
		return Objects.equals(userAccumulators, that.userAccumulators);
	}

	@Override
	public int hashCode() {
		return Objects.hash(userAccumulators);
	}

	//---------------------------------------------------------------------------------
	// Static helper classes
	//---------------------------------------------------------------------------------

	/**
	 * Json serializer for the {@link JobAccumulatorsInfo}.
	 */
	public static final class JobAccumulator {
		// empty for now
	}

	/**
	 * Json serializer for the {@link JobAccumulatorsInfo}.
	 */
	public static final class UserTaskAccumulator {

		public static final String FIELD_NAME_ACC_NAME = "name";
		public static final String FIELD_NAME_ACC_TYPE = "type";
		public static final String FIELD_NAME_ACC_VALUE = "value";

		@JsonProperty(FIELD_NAME_ACC_NAME)
		private String name;

		@JsonProperty(FIELD_NAME_ACC_TYPE)
		private String type;

		@JsonProperty(FIELD_NAME_ACC_VALUE)
		private String value;

		@JsonCreator
		public UserTaskAccumulator(
			@JsonProperty(FIELD_NAME_ACC_NAME) String name,
			@JsonProperty(FIELD_NAME_ACC_TYPE) String type,
			@JsonProperty(FIELD_NAME_ACC_VALUE) String value) {
			this.name = Preconditions.checkNotNull(name);
			this.type = Preconditions.checkNotNull(type);
			this.value = Preconditions.checkNotNull(value);
		}

		@JsonIgnore
		public String getName() {
			return name;
		}

		@JsonIgnore
		public String getType() {
			return type;
		}

		@JsonIgnore
		public String getValue() {
			return value;
		}

		@Override
		public boolean equals(Object o) {
			if (this == o) {
				return true;
			}
			if (o == null || getClass() != o.getClass()) {
				return false;
			}
			UserTaskAccumulator that = (UserTaskAccumulator) o;
			return Objects.equals(name, that.name) &&
				Objects.equals(type, that.type) &&
				Objects.equals(value, that.value);
		}

		@Override
		public int hashCode() {
			return Objects.hash(name, type, value);
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
. /rd-util.sh

if ! find "$HOME/rundeck/packaging/rpmdist/RPMS/noarch/" -name '*.rpm' ; then
	echo "rpm not found at $HOME/rundeck/packaging/rpmdist/RPMS/noarch/rundeck*.rpm"
	exit 2
fi

rpm -ivh "$HOME"/rundeck/packaging/rpmdist/RPMS/noarch/rundeck*.rpm

entry_start "$*"


text:
This is going to be the most basic example of linear regression.

I have generated 1000 samples of amount of meal and tip. This is going to be perfect data which you probable won't find that in the real world.

Based on this 1000 samples, how much a customer would leave the tip if the meal is $70

# What you need
1. Python notebook
2. numpy
3. scipy
4. pandas
5. Scikitlearn

After you install all of the dependencies you can run the notebook by.

```
ipython notebook
```


text:
@echo off
echo Starting UltraType++... (Press enter to terminate)
start /B UltraTypePP.exe
pause >nul


text:
❌Больше не поддерживается.

Скрипт изменения обложки в ВК генерирует обложку, помещая на нее пользователя, вступившего в сообщество и пользователя, поставившего наибольшее количество лайков за определенный промежуток времени.

Посмотреть [Демо](https://vk.com/vkgroupcover) :eyes:.

По всем вопросам можно писать [в личку](https://vk.com/im?sel=92682082) в ВК или на <savelev.aleksandr.96@yandex.ru>.

### Функционал
- Отправка сообщений пользователям от имени группы
- Помещение на обложку группы аватара, имени и фамилии вступившего в группу пользователя
- Помещение на обложку группы аватара, имени и фамилии пользователя, поставившего наибольшее количество лайков за определенный промежуток времени
- Получение информации о пользователе
- Получение пользователя, поставившего наибольшее количество лайков за определенный промежуток времени
- Получение постов группы или пользователя
- Получение лайков у постов, фотографий, видео, комментариев и т.д.
- Изменение обложки группы

### Возможности настройки
- Расположить аватар, имя и фамилию по заданным координатам
- Менять размер и форму аватара: квадратную или круглую
- Менять шрифт, размер, цвет, выравнивание, угол наклона текста
- Менять промежуток времени по которому выбирается пользователь поставивший наибольшее количество лайков

## Настройка
1. Скрипт необходимо загрузить на Ваш сервер.
2. В настройках группы, в разделе Работа с API получить ключ доступа с правами доступа к фотографиям (можно выбрать все права).
3. Вставить ключ доступа в файл config.php в поле `access_token`.
4. На той же странице настроек группы перейти на вкладку Callback API и ввести URL до скрипта на Вашем сервере (пример: https://savelev.xyz/vk_cover/index.php).
5. С этой же страницы настроек скопировать ID группы и строку (которую должен вернуть скрипт), и вставить в файл config.php в поля `group_id` и `confirmation_token` соответственно, и нажать кнопку Подтвердить на странице настроек.
6. На вкладке Типы событий выбрать Вступление в сообщество.
7. Создать [приложение](https://vk.com/apps?act=manage) и скопировать Сервисный ключ доступа в файл config.php в поле `service_token`.


text:
import FontIcon from 'material-ui/FontIcon'
import React, { PureComponent, PropTypes } from 'react'
import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation'
import { withRouter } from 'react-router'

const infoIcon = <FontIcon className='material-icons'>info_outline</FontIcon>
const filesIcon = <FontIcon className='material-icons'>storage</FontIcon>
const logsIcon = <FontIcon className='material-icons'>subject</FontIcon>
const rawIcon = <FontIcon className='material-icons'>code</FontIcon>

class _AllocationTopbar extends PureComponent {

  handleActive (tab) {
    const path = ['nomad', this.props.router.params.region, 'allocations', this.props.allocation.ID, tab]
    this.props.router.push(path.map(encodeURIComponent).join('/'))
  }

  getActiveTab () {
    const location = this.props.location
    const end = location.pathname.split('/').pop()

    if (end.startsWith('info')) {
      return 0
    }

    if (location.query.path && location.query.path.indexOf('alloc/logs') !== -1) {
      return 2
    }

    if (end.startsWith('files')) {
      return 1
    }

    if (end.startsWith('raw')) {
      return 3
    }

    return 0
  }

  getStyle () {
    return {
      borderBottom: '1px solid #e0e0e0',
      marginBottom: 10
    }
  }

  render () {
    return (
      <BottomNavigation selectedIndex={ this.getActiveTab() } style={ this.getStyle() }>
        <BottomNavigationItem label='Info' icon={ infoIcon } onTouchTap={ () => this.handleActive('info') } />
        <BottomNavigationItem label='Files' icon={ filesIcon } onTouchTap={ () => this.handleActive('files') } />
        <BottomNavigationItem label='Logs' icon={ logsIcon } onTouchTap={ () => this.handleActive('logs') } />
        <BottomNavigationItem label='Raw' icon={ rawIcon } onTouchTap={ () => this.handleActive('raw') } />
      </BottomNavigation>
    )
  }
}

_AllocationTopbar.propTypes = {
  router: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired,
  allocation: PropTypes.object.isRequired
}

const AllocationTopbar = withRouter(_AllocationTopbar)

export default AllocationTopbar


text:
/**
 * Analytics class
 */

// set up analytics
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
	(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

// create tracker
ga('create', 'UA-44581945-5', 'auto');

// override function that checks for valid protocol - https://code.google.com/p/analytics-issues/issues/detail?id=312
ga('set', 'checkProtocolTask', function(){});

// send pageview
//ga('send', 'pageview');

(function(i) {

	i.common.Analytics = {

		/**
		 * Checks that analytics is enabled by the 'statistics' setting
		 * If enabled, the callback function is called which will contain the tracking code
		 *
		 * @param {Function} callback
		 */
		checkEnabled: function(callback) {

			if (i.common.Util.isDevMode()) {

				console.warn('Analytics disabled in dev mode');

			}
			else {

				i.common.Settings.getSync('statistics', function(enabled) {

					if (!enabled) {
						console.warn('statistics disabled');
					}
					else {
						callback();
					}

				});

			}

		},

		/**
		 * Tracks a pageview
		 *
		 * @param {String} page
		 */
		pageview: function(page, title) {

			console.log('Analytics.pageview: ', arguments);

			// if analytics is enabled track the pageview
			this.checkEnabled(function() {

				var opts = {
					'page': page,
					'title': title
				};

				ga('send', 'pageview', opts);

				console.log('Analytics.pageview sent: ', opts);

			});

		},

		/**
		 * Tracks an event
		 *
		 * @param {String} category
		 * @param {String} action
		 * @param {String} label
		 * @param {Number} value
		 */
		event: function(category, action, label, value) {

			console.log('Analytics.event: ', arguments);

			// if analytics is enabled track the event
			this.checkEnabled(function() {

				var opts = {
					'hitType': 'event',
					'eventCategory': category,
					'eventAction': action
				};

				// optional args
				if (!!label) {
					opts.eventLabel = label;
					if (!!value) {
						opts.eventValue = value;
					}
				}

				ga('send', opts);

				console.log('Analytics event sent: ', opts);

			});

		}

	};

})(Invigilator);


text:
package com.ikouz.algorithm.leetcode;

import com.ikouz.algorithm.leetcode.domain.ListNode;

/**
 * Created by liujiaming on 2016/08/19 10:53.
 */
public class List_328_OddEvenLinkedList {

    /**
     * Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
     *

     * You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
     *

     * Example:
     * Given 1->2->3->4->5->NULL,
     * return 1->3->5->2->4->NULL.
     *

     * Note:
     * The relative order inside both the even and odd groups should remain as it was in the input.
     * The first node is considered odd, the second node even and so on ...
     */
    public static ListNode oddEvenList(ListNode head) {
        // TODO
        return null;
    }
}


text:
import unittest

from lxml import etree
from models import NCAAGame

class ScrapersTestCase(unittest.TestCase):
    def clean_get(self, input):
        if input == u"\xa0":
            return "0"
        return input

    def testLoadingGameFromXML(self):
        ncaa_game = NCAAGame("fixtures/akron_vs_gardner-webb.xml")

        self.assertEqual("10046", ncaa_game.attendance)
        self.assertEqual(10046, int(ncaa_game.attendance))

        self.assertEqual("3:15", ncaa_game.duration)

        duration_hours, duration_minutes = ncaa_game.duration.split(":")
        self.assertEqual("3", duration_hours)
        self.assertEqual("15", duration_minutes)

        self.assertEquals(3, int(duration_hours))
        self.assertEquals(15, int(duration_minutes))

        self.assertEqual(6, len(ncaa_game.visitor_stats.quarters))

        self.assertEqual(6, len(ncaa_game.home_stats.quarters))

        home_top = ncaa_game.home_stats.time_of_possession.split(":") or None
        visitor_top = ncaa_game.visitor_stats.time_of_possession.split(":") or None

        self.assertEqual(2, len(home_top))
        self.assertEqual("29", home_top[0])
        self.assertEqual(29, int(home_top[0]))
        self.assertEqual("34", home_top[1])
        self.assertEqual(34, int(home_top[1]))

        self.assertEqual(2, len(visitor_top))
        self.assertEqual("30", visitor_top[0])
        self.assertEqual(30, int(visitor_top[0]))
        self.assertEqual("26", visitor_top[1])
        self.assertEqual(26, int(visitor_top[1]))

        self.assertEqual(12, ncaa_game.home_stats.third_down_attempts)
        self.assertEqual(6, ncaa_game.home_stats.third_down_conversions)

        self.assertEqual(1, ncaa_game.home_stats.fourth_down_attempts)
        self.assertEqual(1, ncaa_game.home_stats.fourth_down_conversions)

        self.assertEqual(13, ncaa_game.home_stats.first_downs_rushing)
        self.assertEqual(8, ncaa_game.home_stats.first_downs_passing)
        self.assertEqual(1, ncaa_game.home_stats.first_downs_penalty)
        self.assertEqual(22, ncaa_game.home_stats.first_downs_total)

        self.assertEqual(5, ncaa_game.home_stats.penalties)
        self.assertEqual(50, ncaa_game.home_stats.penalty_yards)

        self.assertEqual(3, ncaa_game.home_stats.fumbles)
        self.assertEqual(1, ncaa_game.home_stats.fumbles_lost)

        self.assertEqual(44, ncaa_game.home_stats.rushes)
        self.assertEqual(235, ncaa_game.home_stats.rush_gain)
        self.assertEqual(11, ncaa_game.home_stats.rush_loss)
        self.assertEqual(224, ncaa_game.home_stats.rush_net)
        self.assertEqual(4, ncaa_game.home_stats.rush_touchdowns)
        self.assertEqual(65, ncaa_game.home_stats.total_plays)
        self.assertEqual(389, ncaa_game.home_stats.total_yards)

        self.assertEqual(21, ncaa_game.home_stats.pass_attempts)
        self.assertEqual(14, ncaa_game.home_stats.pass_completions)
        self.assertEqual(1, ncaa_game.home_stats.pass_interceptions)
        self.assertEqual(165, ncaa_game.home_stats.pass_yards)
        self.assertEqual(1, ncaa_game.home_stats.pass_touchdowns)

        self.assertEqual(14, ncaa_game.home_stats.receptions)
        self.assertEqual(165, ncaa_game.home_stats.receiving_yards)
        self.assertEqual(1, ncaa_game.home_stats.receiving_touchdowns)

        self.assertEqual(3, ncaa_game.home_stats.punts)
        self.assertEqual(103, ncaa_game.home_stats.punt_yards)

        self.assertEqual(5, ncaa_game.home_stats.punt_returns)
        self.assertEqual(120, ncaa_game.home_stats.punt_return_yards)
        self.assertEqual(0, ncaa_game.home_stats.punt_return_touchdowns)
        self.assertEqual(2, ncaa_game.home_stats.kickoff_returns)
        self.assertEqual(15, ncaa_game.home_stats.kickoff_return_yards)
        self.assertEqual(0, ncaa_game.home_stats.kickoff_return_touchdowns)

        self.assertEqual(5, ncaa_game.home_stats.touchdowns)
        self.assertEqual(5, ncaa_game.home_stats.pat_attempts)
        self.assertEqual(4, ncaa_game.home_stats.pat_made)
        self.assertEqual(0, ncaa_game.home_stats.two_point_conversion_attempts)
        self.assertEqual(0, ncaa_game.home_stats.two_point_conversions)
        self.assertEqual(2, ncaa_game.home_stats.field_goal_attempts)
        self.assertEqual(1, ncaa_game.home_stats.field_goals_made)
        self.assertEqual(37, ncaa_game.home_stats.points)
        self.assertEqual(0, ncaa_game.home_stats.safeties)

        self.assertEqual(42, ncaa_game.home_stats.unassisted_tackles)
        self.assertEqual(33, ncaa_game.home_stats.assisted_tackles)

        self.assertEqual(4, ncaa_game.home_stats.unassisted_tackles_for_loss)
        self.assertEqual(4, ncaa_game.home_stats.assisted_tackles_for_loss)
        self.assertEqual(19, ncaa_game.home_stats.tackles_for_loss_yards)
        self.assertEqual(0, ncaa_game.home_stats.unassisted_sacks)
        self.assertEqual(0, ncaa_game.home_stats.assisted_sacks)
        self.assertEqual(15, ncaa_game.home_stats.sack_yards)

        self.assertEqual(1, ncaa_game.home_stats.defensive_interceptions)
        self.assertEqual(12, ncaa_game.home_stats.defensive_interception_yards)
        self.assertEqual(0, ncaa_game.home_stats.defensive_interception_touchdowns)
        self.assertEqual(3, ncaa_game.home_stats.pass_breakups)

        self.assertEqual(1, ncaa_game.home_stats.fumbles_forced)
        self.assertEqual(0, ncaa_game.home_stats.fumbles_number)
        self.assertEqual(0, ncaa_game.home_stats.fumbles_yards)
        self.assertEqual(0, ncaa_game.home_stats.fumbles_touchdowns)

        # Visitor Stats
        self.assertEqual(20, ncaa_game.visitor_stats.third_down_attempts)
        self.assertEqual(11, ncaa_game.visitor_stats.third_down_conversions)

        self.assertEqual(1, ncaa_game.visitor_stats.fourth_down_attempts)
        self.assertEqual(1, ncaa_game.visitor_stats.fourth_down_conversions)

        self.assertEqual(8, ncaa_game.visitor_stats.first_downs_rushing)
        self.assertEqual(14, ncaa_game.visitor_stats.first_downs_passing)
        self.assertEqual(2, ncaa_game.visitor_stats.first_downs_penalty)
        self.assertEqual(24, ncaa_game.visitor_stats.first_downs_total)

        self.assertEqual(2, ncaa_game.visitor_stats.penalties)
        self.assertEqual(30, ncaa_game.visitor_stats.penalty_yards)

        self.assertEqual(1, ncaa_game.visitor_stats.fumbles)
        self.assertEqual(0, ncaa_game.visitor_stats.fumbles_lost)

        self.assertEqual(37, ncaa_game.visitor_stats.rushes)
        self.assertEqual(122, ncaa_game.visitor_stats.rush_gain)
        self.assertEqual(21, ncaa_game.visitor_stats.rush_loss)
        self.assertEqual(101, ncaa_game.visitor_stats.rush_net)
        self.assertEqual(2, ncaa_game.visitor_stats.rush_touchdowns)
        self.assertEqual(80, ncaa_game.visitor_stats.total_plays)
        self.assertEqual(391, ncaa_game.visitor_stats.total_yards)

        self.assertEqual(43, ncaa_game.visitor_stats.pass_attempts)
        self.assertEqual(25, ncaa_game.visitor_stats.pass_completions)
        self.assertEqual(1, ncaa_game.visitor_stats.pass_interceptions)
        self.assertEqual(290, ncaa_game.visitor_stats.pass_yards)
        self.assertEqual(3, ncaa_game.visitor_stats.pass_touchdowns)

        self.assertEqual(25, ncaa_game.visitor_stats.receptions)
        self.assertEqual(290, ncaa_game.visitor_stats.receiving_yards)
        self.assertEqual(3, ncaa_game.visitor_stats.receiving_touchdowns)

        self.assertEqual(6, ncaa_game.visitor_stats.punts)
        self.assertEqual(223, ncaa_game.visitor_stats.punt_yards)

        self.assertEqual(4, ncaa_game.visitor_stats.punt_returns)
        self.assertEqual(74, ncaa_game.visitor_stats.punt_return_yards)
        self.assertEqual(0, ncaa_game.visitor_stats.punt_return_touchdowns)
        self.assertEqual(0, ncaa_game.visitor_stats.kickoff_returns)
        self.assertEqual(0, ncaa_game.visitor_stats.kickoff_return_yards)
        self.assertEqual(0, ncaa_game.visitor_stats.kickoff_return_touchdowns)

        self.assertEqual(5, ncaa_game.visitor_stats.touchdowns)
        self.assertEqual(5, ncaa_game.visitor_stats.pat_attempts)
        self.assertEqual(5, ncaa_game.visitor_stats.pat_made)
        self.assertEqual(0, ncaa_game.visitor_stats.two_point_conversion_attempts)
        self.assertEqual(0, ncaa_game.visitor_stats.two_point_conversions)
        self.assertEqual(1, ncaa_game.visitor_stats.field_goal_attempts)
        self.assertEqual(1, ncaa_game.visitor_stats.field_goals_made)
        self.assertEqual(38, ncaa_game.visitor_stats.points)
        self.assertEqual(0, ncaa_game.visitor_stats.safeties)

        self.assertEqual(46, ncaa_game.visitor_stats.unassisted_tackles)
        self.assertEqual(22, ncaa_game.visitor_stats.assisted_tackles)

        self.assertEqual(5, ncaa_game.visitor_stats.unassisted_tackles_for_loss)
        self.assertEqual(2, ncaa_game.visitor_stats.assisted_tackles_for_loss)
        self.assertEqual(10, ncaa_game.visitor_stats.tackles_for_loss_yards)
        self.assertEqual(0, ncaa_game.visitor_stats.unassisted_sacks)
        self.assertEqual(0, ncaa_game.visitor_stats.assisted_sacks)
        self.assertEqual(6, ncaa_game.visitor_stats.sack_yards)

        self.assertEqual(1, ncaa_game.visitor_stats.defensive_interceptions)
        self.assertEqual(17, ncaa_game.visitor_stats.defensive_interception_yards)
        self.assertEqual(0, ncaa_game.visitor_stats.defensive_interception_touchdowns)
        self.assertEqual(1, ncaa_game.visitor_stats.pass_breakups)

        self.assertEqual(2, ncaa_game.visitor_stats.fumbles_forced)
        self.assertEqual(0, ncaa_game.visitor_stats.fumbles_number)
        self.assertEqual(0, ncaa_game.visitor_stats.fumbles_yards)
        self.assertEqual(0, ncaa_game.visitor_stats.fumbles_touchdowns)


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v11/resources/customer_conversion_goal.proto

package com.google.ads.googleads.v11.resources;

public interface CustomerConversionGoalOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v11.resources.CustomerConversionGoal)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Immutable. The resource name of the customer conversion goal.
   * Customer conversion goal resource names have the form:
   * `customers/{customer_id}/customerConversionGoals/{category}~{origin}`
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The resourceName.
   */
  java.lang.String getResourceName();
  /**
   *

   * Immutable. The resource name of the customer conversion goal.
   * Customer conversion goal resource names have the form:
   * `customers/{customer_id}/customerConversionGoals/{category}~{origin}`
   *

   *
   * string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }
   * @return The bytes for resourceName.
   */
  com.google.protobuf.ByteString
      getResourceNameBytes();

  /**
   *

   * The conversion category of this customer conversion goal. Only
   * conversion actions that have this category will be included in this goal.
   *

   *
   * .google.ads.googleads.v11.enums.ConversionActionCategoryEnum.ConversionActionCategory category = 2;
   * @return The enum numeric value on the wire for category.
   */
  int getCategoryValue();
  /**
   *

   * The conversion category of this customer conversion goal. Only
   * conversion actions that have this category will be included in this goal.
   *

   *
   * .google.ads.googleads.v11.enums.ConversionActionCategoryEnum.ConversionActionCategory category = 2;
   * @return The category.
   */
  com.google.ads.googleads.v11.enums.ConversionActionCategoryEnum.ConversionActionCategory getCategory();

  /**
   *

   * The conversion origin of this customer conversion goal. Only
   * conversion actions that have this conversion origin will be included in
   * this goal.
   *

   *
   * .google.ads.googleads.v11.enums.ConversionOriginEnum.ConversionOrigin origin = 3;
   * @return The enum numeric value on the wire for origin.
   */
  int getOriginValue();
  /**
   *

   * The conversion origin of this customer conversion goal. Only
   * conversion actions that have this conversion origin will be included in
   * this goal.
   *

   *
   * .google.ads.googleads.v11.enums.ConversionOriginEnum.ConversionOrigin origin = 3;
   * @return The origin.
   */
  com.google.ads.googleads.v11.enums.ConversionOriginEnum.ConversionOrigin getOrigin();

  /**
   *

   * The biddability of the customer conversion goal.
   *

   *
   * bool biddable = 4;
   * @return The biddable.
   */
  boolean getBiddable();
}


text:
export enum TutorialStep {
  NotApplicable = 'NotApplicable',
  PickEditor = 'PickEditor',
  CreateBranch = 'CreateBranch',
  EditFile = 'EditFile',
  MakeCommit = 'MakeCommit',
  PushBranch = 'PushBranch',
  OpenPullRequest = 'OpenPullRequest',
  AllDone = 'AllDone',
  Paused = 'Paused',
}

export type ValidTutorialStep =
  | TutorialStep.PickEditor
  | TutorialStep.CreateBranch
  | TutorialStep.EditFile
  | TutorialStep.MakeCommit
  | TutorialStep.PushBranch
  | TutorialStep.OpenPullRequest
  | TutorialStep.AllDone

export function isValidTutorialStep(
  step: TutorialStep
): step is ValidTutorialStep {
  return step !== TutorialStep.NotApplicable && step !== TutorialStep.Paused
}

export const orderedTutorialSteps: ReadonlyArray<ValidTutorialStep> = [
  TutorialStep.PickEditor,
  TutorialStep.CreateBranch,
  TutorialStep.EditFile,
  TutorialStep.MakeCommit,
  TutorialStep.PushBranch,
  TutorialStep.OpenPullRequest,
  TutorialStep.AllDone,
]


text:
package org.mapfish.print.processor.http;

import org.mapfish.print.config.Configuration;
import org.mapfish.print.http.MfClientHttpRequestFactory;
import org.mapfish.print.output.Values;
import org.mapfish.print.processor.AbstractProcessor;
import org.mapfish.print.processor.ProcessorUtils;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Nullable;

/**
 *
A processor that wraps several {@link AbstractClientHttpRequestFactoryProcessor}s.

 *

 * This makes it more convenient to configure multiple processors that modify {@link
 * org.mapfish.print.http.MfClientHttpRequestFactory} objects.
 *

 *

 * Consider the case where you need to:
 *

 *

 *
Restrict allowed URIS using the !restrictUris processor

 *
Forward all headers from print request to all requests using !forwardHeaders

 *
Change the url using the !mapUri processor

 *

 *

 * In this case the !mapUri processor must execute before the !restrictUris processor but it is difficult to
 * enforce this, the inputMapping and outputMapping must be carefully designed in order to do it.  The
 * following should work but compare it with the example below:
 *

 *

 * - !mapUri
 *   mapping:
 *     (http)://localhost(.*): "$1://127.0.0.1$2"
 *   outputMapper: {clientHttpRequestFactoryProvider: clientHttpRequestFactoryMapped}
 * - !forwardHeaders
 *   all: true
 *   inputMapper: {clientHttpRequestFactoryMapped :clientHttpRequestFactoryProvider}
 *   outputMapper: {clientHttpRequestFactoryProvider: clientHttpRequestFactoryWithHeaders}
 * - !restrictUris
 *   matchers: [!localMatch {}]
 *   inputMapper: {clientHttpRequestFactoryWithHeaders:clientHttpRequestFactoryProvider}
 *

 *
 *

 * The recommended way to write the above configuration is as follows:
 *

 *

 * - !configureHttpRequests
 *   httpProcessors:
 *     - !mapUri
 *       mapping:
 *         (http)://localhost(.*): "$1://127.0.0.1$2"
 *     - !forwardHeaders
 *       all: true
 *     - !restrictUris
 *       matchers: [!localMatch {}]
 *

 * [[examples=http_processors]]
 */
public final class CompositeClientHttpRequestFactoryProcessor
        extends AbstractProcessor<CompositeClientHttpRequestFactoryProcessor.Input, Void>
        implements HttpProcessor<CompositeClientHttpRequestFactoryProcessor.Input> {
    private List<HttpProcessor> httpProcessors = new ArrayList<>();

    /**
     * Constructor.
     */
    protected CompositeClientHttpRequestFactoryProcessor() {
        super(Void.class);
    }

    /**
     * Sets all the http processors that will executed by this processor.
     *
     * @param httpProcessors the sub processors
     */
    public void setHttpProcessors(final List<HttpProcessor> httpProcessors) {
        this.httpProcessors = httpProcessors;
    }

    @SuppressWarnings("unchecked")
    @Override
    public MfClientHttpRequestFactory createFactoryWrapper(
            final Input input,
            final MfClientHttpRequestFactory requestFactory) {
        MfClientHttpRequestFactory finalRequestFactory = requestFactory;
        // apply the parts in reverse so that the last part is the inner most wrapper (will be last to be
        // called)
        for (int i = this.httpProcessors.size() - 1; i > -1; i--) {
            final HttpProcessor processor = this.httpProcessors.get(i);
            Object populatedInput = ProcessorUtils.populateInputParameter(processor, input.values);
            finalRequestFactory = processor.createFactoryWrapper(populatedInput, finalRequestFactory);
        }
        return finalRequestFactory;
    }

    @Override
    protected void extraValidation(
            final List<Throwable> validationErrors,
            final Configuration configuration) {
        if (this.httpProcessors.isEmpty()) {
            validationErrors.add(new IllegalStateException("There are no composite elements for this " +
                                                                   "processor"));
        } else {
            for (Object part: this.httpProcessors) {
                if (!(part instanceof HttpProcessor)) {
                    validationErrors.add(new IllegalStateException("One of the parts of " + getClass()
                            .getSimpleName() + " is not a " + HttpProcessor.class.getSimpleName()));
                }
            }
        }
    }

    @Nullable
    @Override
    public Input createInputParameter() {
        return new Input();
    }

    @Nullable
    @Override
    public Void execute(
            final Input values,
            final ExecutionContext context) {
        values.clientHttpRequestFactoryProvider.set(createFactoryWrapper(
                values, values.clientHttpRequestFactoryProvider.get()));
        return null;
    }

    @Override
    public void toString(final StringBuilder builder, final int indent, final String parent) {
        super.toString(builder, indent, parent);
        for (HttpProcessor sub: this.httpProcessors) {
            sub.toString(builder, indent + 1, this.toString());
        }
    }

    /**
     * The input.
     */
    public static class Input extends ClientHttpFactoryProcessorParam {
        /**
         * The values.
         */
        public Values values;
    }
}


text:
import logging
import os
import tempfile
from subprocess import check_output

import nltk

from typecraft_python.core.models import Word, Morpheme, Phrase
from typecraft_python.core.interfaces import TypecraftTagger

# Try to load OBT by the use of the OBT_PATH
# environment variable. Also verify that the
# file tag-bm.sh file exists.
FNULL = open(os.devnull, 'w')
obt_available = False
obt_path = os.environ.get('OBT_PATH')
if obt_path is None:
    logging.error("Error loading OBT, environment variable `OBT_PATH` not set.")
else:
    tag_bm_path = os.path.join(obt_path, 'tag-bm.sh')
    if not os.path.exists(tag_bm_path):
        logging.error("Error loading OBT, the script %s does not exist" % (tag_bm_path,))
    else:
        obt_available = True

class ObtTagger(TypecraftTagger):
    def __init__(self):
        pass

    @staticmethod
    def _store_string_temporarily(raw_string):
        fd, path = tempfile.mkstemp()

        with os.fdopen(fd, "wb") as _file:
            _file.write(raw_string.encode("utf-8").strip())

        return path

    @staticmethod
    def _call_obt(tempfile):
        return check_output([os.path.join(obt_path, 'tag-bm.sh'), tempfile], stderr=FNULL).decode("utf-8")

    @staticmethod
    def _word_is_sentence_breaker(tags):
        return '<<<' in tags

    @staticmethod
    def _parse_output_to_phrases(output, original_input, language):
        """
        Parses the output of the OBT to a number of phrases.
        Su

        :param output:
        :return:
        """
        # Import here the avoid circular dependency
        from typecraft_python.util import batch
        phrases = []
        output_lines = output.split("\n")
        batched = batch(output_lines, 3)
        current_phrase = Phrase()
        batched = filter(lambda x: len(x) == 3, batched)

        for original, _, tags in batched:
            # The original is wrapped in <word></word> tags
            original = original[6:-7]
            split_tags = tags.split()
            # The lemma is wrapped in double quotes
            lemma = split_tags[0][1:-1]
            # Punctuations have weird lemmas
            lemma = lemma if not lemma.startswith("$") else original
            pos = split_tags[1]
            word = Word(word=original, pos=pos)
            morpheme = Morpheme(morpheme=original, baseform=lemma)
            word.add_morpheme(morpheme)
            current_phrase.add_word(word)

            if ObtTagger._word_is_sentence_breaker(tags):
                phrases.append(current_phrase)
                current_phrase = Phrase()
                current_phrase.phrase = current_phrase.detokenize()

        # At this stage we have the words contents, but the phrases are not given
        # detokenized versions. We first try to match sentence tokenized phrase from
        # nltk with the phrases. If the amount is uneven we use the `detokenize` method.
        sent_tokenized = nltk.sent_tokenize(original_input)
        if len(sent_tokenized) == len(phrases):
            for i, phrase in enumerate(sent_tokenized):
                phrases[i].phrase = phrase
        else:
            logging.error("Output from OBT does not have as many sentences the tokenized sentences from nltk."
                          "\nFalling back to using `detokenize`."
                          "\n\tOBT:%d"
                          "\n\tNltk:%d" % (len(sent_tokenized), len(phrases)))
            for phrase in phrases:
                phrase.phrase = phrase.detokenize()

        return phrases

    @staticmethod
    def _parse_output_to_phrase(output):
        pass

    def is_parser(self):
        return True

    def has_automatic_sentence_tokenization_support(self, language='en'):
        return True

    def has_automatic_word_tokenization_support(self, language='en'):
        return True

    def tag_raw(self, raw_text, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to the Oslo-Bergen tagger.")
        temp_file_path = ObtTagger._store_string_temporarily(raw_text)
        output = self._call_obt(temp_file_path)
        return self._parse_output_to_phrases(output, raw_text, language)

    def tag_raw_phrases(self, phrases, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to ")
        pass

    def tag_raw_words(self, word_list, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to ")
        pass

    def tag_text(self, text, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to ")
        pass

    def tag_phrases(self, phrases, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to ")
        pass

    def tag_phrase(self, phrase, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to ")
        pass

    def tag_words(self, words, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to ")
        pass

    def tag_word(self, word, language='nob'):
        if not obt_available:
            raise EnvironmentError("Attempted to parse using OBT when OBT is not available.")
        if not language.startswith('no'):
            logging.error("A non-norwegian language supplied to ")
        pass


text:
'use strict';

import React from 'react';
import classnames from 'classnames';
import Helpers from './mixins/helpers';

export var PrevArrow = React.createClass({

  clickHandler: function (options, e) {
    if (e) { e.preventDefault(); }
    this.props.clickHandler(options, e);
  },
  render: function () {
    var prevClasses = {'slick-arrow': true, 'slick-prev': true};
    var prevHandler = this.clickHandler.bind(this, {message: 'previous'});

    if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) {
      prevClasses['slick-disabled'] = true;
      prevHandler = null;
    }

    var prevArrowProps = {
      key: '0',
      'data-role': 'none',
      className: classnames(prevClasses),
      style: {display: 'block'},
      onClick: prevHandler
    };
    var customProps = {
      currentSlide: this.props.currentSlide,
      slideCount: this.props.slideCount
    };
    var prevArrow;

    if (this.props.prevArrow) {
      prevArrow = React.cloneElement(this.props.prevArrow, { ...prevArrowProps, ...customProps });
    } else {
      prevArrow = <button key='0' type='button' {...prevArrowProps}> Previous</button>;
    }

    return prevArrow;
  }
});

export var NextArrow = React.createClass({
  clickHandler: function (options, e) {
    if (e) { e.preventDefault(); }
    this.props.clickHandler(options, e);
  },
  render: function () {
    var nextClasses = {'slick-arrow': true, 'slick-next': true};
    var nextHandler = this.clickHandler.bind(this, {message: 'next'});

    if (!Helpers.canGoNext(this.props)) {
      nextClasses['slick-disabled'] = true;
      nextHandler = null;
    }

    var nextArrowProps = {
      key: '1',
      'data-role': 'none',
      className: classnames(nextClasses),
      style: {display: 'block'},
      onClick: nextHandler
    };
    var customProps = {
      currentSlide: this.props.currentSlide,
      slideCount: this.props.slideCount
    };
    var nextArrow;

    if (this.props.nextArrow) {
      nextArrow = React.cloneElement(this.props.nextArrow, { ...nextArrowProps, ...customProps });
    } else {
      nextArrow = <button key='1' type='button' {...nextArrowProps}> Next</button>;
    }

    return nextArrow;
  }
});


text:
The AAA (Arrange, Act, Assert) pattern is a common way of writing unit tests for a method under test.

* The **Arrange** section of a unit test method initializes objects and sets the value of the data that is passed to the method under test.
* The **Act** section invokes the method under test with the arranged parameters.
* The **Assert** section verifies that the action of the method under test behaves as expected.

Taken from https://docs.microsoft.com/en-us/visualstudio/test/unit-test-basics?view=vs-2019

If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.

Taken from https://stackoverflow.com/questions/9122708/unit-testing-private-methods-in-c-sharp


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions];
    [[ECViewManager sharedInstance] setupNavigationBar2White];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginChanged:)
                                                 name:LOGIN_CHANGE_NOTIFICATION
                                               object:nil];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = WINDOW_BACKCOLOR;
    if ([[EaseMob sharedInstance].chatManager isAutoLoginEnabled]) {
        [self showMainView];
    }else {
        [self showLoginView];
    }

    [self setupParse];
    // for test
    [ECDBManager openEasemobDatabaseWithAccount:@"6001"];

    NSMutableArray *members = [[NSMutableArray alloc] init];
    for (int i = 0; i < 100; i ++) {
        ECContactModel *contactModel = [[ECContactModel alloc] init];
        contactModel = [[ECContactModel alloc] init];
        contactModel.eid = [NSString stringWithFormat:@"test%d",i];
        contactModel.nickname = [NSString stringWithFormat:@"用户%d",i];
        [members addObject:contactModel.eid];
        [[ECDBManager sharedInstance] insertContact:contactModel loginAccount:@"6001"];
    }

    ECDepartmentModel *model = [[ECDepartmentModel alloc] init];
    model.departmentId = @"001";
    model.departmentName = @"环信";
    model.departmentLevel = 0;
    model.deparementMembers = [[NSMutableArray alloc] initWithArray:members];
    model.departmentSubIds = [[NSMutableArray alloc] initWithArray:@[@"002"]];
    model.departmentSupId = @"000";
    model.departmentImagePath = @"www.baidu.com";
    [[ECDBManager sharedInstance] insertDepartment:model loginAccount:@"6001"];

    ECDepartmentModel *model1 = [[ECDepartmentModel alloc] init];
    model1.departmentId = @"002";
    model1.departmentName = @"销售部";
    model1.departmentLevel = 1;
    model1.deparementMembers = [[NSMutableArray alloc] initWithArray:@[@"test4",@"tes5",@"test6"]];
    model1.departmentSubIds = [[NSMutableArray alloc] initWithArray:@[@"003",@"004"]];
    model1.departmentSupId = @"001";
    model1.departmentImagePath = @"www.baidu.com";
    [[ECDBManager sharedInstance] insertDepartment:model1 loginAccount:@"6001"];

    ECDepartmentModel *model2 = [[ECDepartmentModel alloc] init];
    model2.departmentId = @"003";
    model2.departmentName = @"电话销售部";
    model2.departmentLevel = 3;
    model2.deparementMembers = [[NSMutableArray alloc] initWithArray:@[@"test7",@"test8",@"test9"]];
    model2.departmentSubIds = [[NSMutableArray alloc] initWithArray:@[@"004"]];
    model2.departmentSupId = @"002";
    model2.departmentImagePath = @"www.baidu.com";
    [[ECDBManager sharedInstance] insertDepartment:model2 loginAccount:@"6001"];

    ECDepartmentModel *model3 = [[ECDepartmentModel alloc] init];
    model3.departmentId = @"004";
    model3.departmentName = @"客服系统电话销售部";
    model3.departmentLevel = 4;
    model3.deparementMembers = [[NSMutableArray alloc] initWithArray:@[@"test7",@"test8",@"test9"]];
    model3.departmentSubIds = [[NSMutableArray alloc] initWithArray:@[@"005",@"006"]];
    model3.departmentSupId = @"003";
    model3.departmentImagePath = @"www.baidu.com";
    [[ECDBManager sharedInstance] insertDepartment:model3 loginAccount:@"6001"];

    [self.window makeKeyAndVisible];
    return YES;
}

- (void)showMainView{
    self.window.rootViewController = [[ECMainViewController alloc] init];
}

- (void)showLoginView{
    self.window.rootViewController = [ECLoginViewController showLoginViewController];
}

- (void)loginChanged:(NSNotification *)noti{
    if ([noti.object boolValue]) {
        [self showMainView];
    }else {
        [self showLoginView];
    }
}

@end


text:
require 'naught'

NullObject = Naught.build

include NullObject::Conversions


text:
<?php

namespace App\Exception;

class Exception_404 extends Exception {

	private $message = '404 not found';

	public function __construct($message) {
		$this->message = $message;
		$this->display();
	}

	public function display() {
		echo "Whhops! Something wrong. " . $this->message;
	}

}


text:
project_path: /web/_project.yaml
book_path: /web/updates/_book.yaml

{# wf_published_on: 2018-11-12 #}
{# wf_updated_on: 2019-03-07 #}
{# wf_featured_image: /web/updates/images/generic/file.png #}
{# wf_tags: writable-files,capabilities,file,filesystem #}
{# wf_featured_snippet: The writable files API is being designed to increase interoperability of web applications with native applications, making it possible for users to choose files or directories that a web app can interact with on the native file system. #}
{# wf_blink_components: Blink>Storage>FileSystem #}

{# When updating this post, don't forget to update /updates/capabilities.md #}

# The Writable Files API: Simplifying local file access {: .page-title }

{% include "web/_shared/contributors/petelepage.html" %}

{% include "web/updates/_shared/capabilities.html" %}

## What is the Writable Files API {: #explainer }

Today, if a user wants to edit a local file in a web app, the web app needs
to ask the user to open the file. Then, after editing the file, the only way
to save changes is by downloading the file to the Downloads folder, or having
to replace the original file by navigating the directory structure to find the
original folder and file. This user experience leaves a lot to be desired, and
makes it hard to build web apps that access user files.

The writable files API is designed to increase interoperability of web
applications with native applications, making it possible for users to choose
files or directories that a web app can interact with on the native file
system, and without having to use a native wrapper like Electron to ship your
web app.

With the Writable Files API, you could create a simple, single file editor
that opens a file, allows the user to edit it, and save the changes back to
the same file. Or a multi-file editor like an IDE or CAD style application
where the user opens a project containing multiple files, usually together in
the same directory. And there are plenty more.

Note: Want to see how this might be implemented? Check the explainer for
some [sample code](https://github.com/WICG/writable-files/blob/master/EXPLAINER.md#example-code).

[Read explainer][explainer]{: .button .button-primary }

## Security considerations

The primary entry point for this API is a
file picker, which ensures that the user is always in full control over
what files and directories a website has access to. Every access to a
user selected file (either reading or writing) is done through an
asynchronous API, allowing the browser to potentially include additional
prompting and/or permission checks.

The Writable Files API provides web developers with significant access
to user data and has potential to be abused. There are both privacy
risks, for example websites getting access to private data they weren't
supposed to have access to, as well as security risks, for example
websites able to modify executables, encrypt user data, and so forth.
The Writable Files API must be designed in such a way as to limit how
much damage a website can do, and make sure that the user understands
what they're giving the site access to.

  We need your help - we're at the design phase for the Writable Files
  API. We are investigating how the permission model should work, and
  what restrictions should be placed on the API. Check out the

  proposed security model, then let us know about
  your use cases. We will use your input to make sure what is spec'ed and
  built, meets your needs.

## Current status {: #status }

| Step                                       | Status                       |
| ------------------------------------------ | ---------------------------- |
| 1. Create explainer                        | [Complete][explainer]        |
| 2. Create initial draft of specification   | [In progress][spec]          |
| **3. Gather feedback & iterate on design** | [**In progress**](#feedback) |
| 4. Origin trial                            | Not started                  |
| 5. Launch                                  | Not started                  |

## Feedback {: #feedback }

We need your help to design the Writable Files API in a way that will be
useful in a way that is both secure and protects user privacy.

* Have an idea for a use case or an idea where you'd use it?
* Are there types of files or directories you don't expect to have access to?
* Do you plan to use this?
* Like it, and want to show your support?

Share your thoughts on the [Writable Files WICG Discourse][wicg-discourse]
discussion.

{% include "web/_shared/helpful.html" %}

## Helpful Links

* [Public explainer][explainer]
* [Tracking bug][cr-bug]
* [ChromeStatus.com entry][cr-status]
* Blink Component: `Blink>Storage>FileSystem`

{% include "web/_shared/rss-widget-updates.html" %}

[spec]: https://wicg.github.io/writable-files/
[cr-bug]: https://bugs.chromium.org/p/chromium/issues/detail?id=853326
[cr-status]: https://www.chromestatus.com/features/6284708426022912
[explainer]: https://github.com/WICG/writable-files/blob/master/EXPLAINER.md
[wicg-discourse]: https://discourse.wicg.io/t/writable-file-api/1433


text:
package com.ledi.dry.utils;

import com.ledi.util.DateInterval;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Created by berny on 12/1/15.
 */
public class WeekUtils {

    private static final Logger log = LoggerFactory.getLogger(WeekUtils.class);

    private static final int _DEFAULTS = -1;

    /**
     * Retorna el numero de semana al que pertenece una fecha.
     * <p>
     * Se emplea la configuración por defecto de la maquina virtual.
     * </p>
     *
     * @param date Fecha, se ignora la zona horaria.
     * @return El número de la semana que contiene la fecha pasada como parámetro.
     */
    public static int getWeekNumber(Date date) {
        return getWeekNumber(date, _DEFAULTS);
    }

    /**
     * Retorna el número de semana en el año al que pertenece una fecha dada considerando
     * el inicio del día indicado.
     *
     * @param date        Fecha de la que se desea obtener la semana.
     * @param startOfWeek Número del día en el que comienza la semana.
     * @return El número de la semana en el año.
     */
    public static int getWeekNumber(Date date, int startOfWeek) {
        Calendar cal = Calendar.getInstance();
        if (startOfWeek != _DEFAULTS) {
            cal.setFirstDayOfWeek(startOfWeek);
        }
        cal.setTime(date);

        return cal.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * Retorna la semana a la que pertenece la fecha UTC dada.
     *
     * @param utc Fecha en UTC.
     * @param tz  Zona horaria en la que se desea obtener la semana.
     * @return El número de la semana a la que pertenece a la fecha.
     */
    public static int getWeekNumber(Date utc, TimeZone tz) {
        return getWeekNumber(utc, tz, _DEFAULTS);
    }

    public static int getWeekNumber(Date utc, TimeZone tz, int firstDay) {
        Calendar aux = Calendar.getInstance();
        if (firstDay != _DEFAULTS) {
            aux.setFirstDayOfWeek(firstDay);
            aux.setMinimalDaysInFirstWeek(4);
        }

        aux.setTime(TzDateUtils.toTimeZone(utc, tz));
        return aux.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     *
     * @param date
     * @param tz
     * @return
     */
    public static DateInterval getUTCWeek(Date date, TimeZone tz) {
        return getUTCWeek(date, tz, Calendar.MONDAY);
    }

    public static DateInterval getUTCWeek(Date utc, TimeZone tz, int firstDay) {
        Calendar aux = Calendar.getInstance();
            aux.setFirstDayOfWeek(firstDay);

        Date local = TzDateUtils.toTimeZone(utc, tz);
        aux.setTime(local);
        aux.set(Calendar.DAY_OF_WEEK, firstDay);

        DateInterval res = new DateInterval();
        Date utcStart = TzDateUtils.getUTC(DateUtils.truncate(aux.getTime(), Calendar.DATE), tz);
        res.setStart(utcStart);

        Date auxEnd = DateUtils.addDays(aux.getTime(), 7);
        res.setEnd(TzDateUtils.getUTC(DateUtils.truncate(auxEnd, Calendar.DATE), tz));
        return res;
    }

    public static String toString(Date date) {
        return DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(date);
    }
}


text:
import angular from 'angular';
import DialogService from './dialog.service';

export default angular
  .module('app.common.services.dialog', [])
  .service('dialog', DialogService)
  .name;


text:
module ClientSideValidations
  module ActiveModel
    module Acceptance
      private

      def message_type
        :accepted
      end
    end
  end
end


text:
layout: post
title: Heuristic for selecting a Trainer
date: 2014-04-14
categories:
- Education
tags: []
status: publish
type: post
published: true
meta:
  _wpcom_is_markdown: '1'
  _publicize_pending: '1'
author:
---
When looking at a potential coach or teacher, I find myself often using the following criteria to help me make a selection.

*   **Openness**: Do they expose their ideas and opinions in public forums? Do they allow discourse and feedback on their material, or is it a one-way channel?
*   **Prior Art**: Research material authored by the coach: articles, blog posts, videos, code, tweets, publications. Are ideas clearly expressed and compatible to your mode of learning?
*   **Bias**: Do they present multiple facets to ideas? Is there personal incentive for endorsing one idea over another?
*   **Interpersonal**: The "Play nice with others" factor. How to they behave in a group? Do they foster relationships and enable growth? Do they advocate for peers in their profession?
*   **Referral**: Use your network of both people you know or online personas you respect and see if any of them approve or refer to the trainer or their material.
*   **Experience**: Review the individual's listed skills, credentials, and experience. Can you trust them to bring authentic information that you believe applies to your needs?

This is not a comprehensive lists (all models are flawed). What questions do you ask yourself when evaluating potential mentors, coaches, trainers, or teachers?


text:
package github

import (
	"context"
	"fmt"
)

// ListEvents drinks from the firehose of all public events across GitHub.
//
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events
func (s *ActivityService) ListEvents(ctx context.Context, opts *ListOptions) ([]*Event, *Response, error) {
	u, err := addOptions("events", opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*Event
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}

// ListRepositoryEvents lists events for a repository.
//
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-repository-events
func (s *ActivityService) ListRepositoryEvents(ctx context.Context, owner, repo string, opts *ListOptions) ([]*Event, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/events", owner, repo)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*Event
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}

// ListIssueEventsForRepository lists issue events for a repository.
//
// GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository
func (s *ActivityService) ListIssueEventsForRepository(ctx context.Context, owner, repo string, opts *ListOptions) ([]*IssueEvent, *Response, error) {
	u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*IssueEvent
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}

// ListEventsForRepoNetwork lists public events for a network of repositories.
//
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories
func (s *ActivityService) ListEventsForRepoNetwork(ctx context.Context, owner, repo string, opts *ListOptions) ([]*Event, *Response, error) {
	u := fmt.Sprintf("networks/%v/%v/events", owner, repo)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*Event
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}

// ListEventsForOrganization lists public events for an organization.
//
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-organization-events
func (s *ActivityService) ListEventsForOrganization(ctx context.Context, org string, opts *ListOptions) ([]*Event, *Response, error) {
	u := fmt.Sprintf("orgs/%v/events", org)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*Event
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}

// ListEventsPerformedByUser lists the events performed by a user. If publicOnly is
// true, only public events will be returned.
//
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-for-the-authenticated-user
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-a-user
func (s *ActivityService) ListEventsPerformedByUser(ctx context.Context, user string, publicOnly bool, opts *ListOptions) ([]*Event, *Response, error) {
	var u string
	if publicOnly {
		u = fmt.Sprintf("users/%v/events/public", user)
	} else {
		u = fmt.Sprintf("users/%v/events", user)
	}
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*Event
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}

// ListEventsReceivedByUser lists the events received by a user. If publicOnly is
// true, only public events will be returned.
//
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-received-by-the-authenticated-user
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-received-by-a-user
func (s *ActivityService) ListEventsReceivedByUser(ctx context.Context, user string, publicOnly bool, opts *ListOptions) ([]*Event, *Response, error) {
	var u string
	if publicOnly {
		u = fmt.Sprintf("users/%v/received_events/public", user)
	} else {
		u = fmt.Sprintf("users/%v/received_events", user)
	}
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*Event
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}

// ListUserEventsForOrganization provides the user's organization dashboard. You
// must be authenticated as the user to view this.
//
// GitHub API docs: https://developer.github.com/v3/activity/events/#list-organization-events-for-the-authenticated-user
func (s *ActivityService) ListUserEventsForOrganization(ctx context.Context, org, user string, opts *ListOptions) ([]*Event, *Response, error) {
	u := fmt.Sprintf("users/%v/events/orgs/%v", user, org)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	var events []*Event
	resp, err := s.client.Do(ctx, req, &events)
	if err != nil {
		return nil, resp, err
	}

	return events, resp, nil
}


text:
import React, { Component } from 'react'
import axios from 'axios'
import { browserHistory} from 'react-router'

//music for the lounge
const loungeMusic = new Audio('../../assets/audio/yanSimBed.mp3');

//children
import Star from './children/Star'

class Lounges extends Component{

	constructor(props) {
	    super(props);

	   	this.startPlayingMusic = this.startPlayingMusic.bind(this);

		this.stopPlayingMusic = this.stopPlayingMusic.bind(this);

	    this.state = {

	      user:'',

	      music:loungeMusic,

	      lounges:[],

	      playingMusic:false ,

		  loggingOut:function(){
	      	localStorage.removeItem('hsjwt');
	      	//rediredct to the login page
			browserHistory.push('/');
			}

	    }

  }

  	startPlayingMusic(){
  		this.state.music.play();
  		this.state.playingMusic = true;
	}

	stopPlayingMusic(){
		this.state.music.pause();
		this.state.playingMusic = false;
	}

	loopMusic(){
		this.state.music.loop = true;
	}

	joinLounge(){
		browserHistory.push('/chat=test');
	}

	componentWillMount(){

		const headers = {
			'Authorization': 'Bearer '+ localStorage.getItem('hsjwt')
		}
		axios.get('/api/lounges' , {headers:headers})
				.then(res=>{
					const lounges = res.data;
					this.setState({lounges});
					return axios.get('/api/account/info', {headers:headers});
				}).then(res=>{
					let username = res.data.userName
					this.setState({user:username})
				})

				.catch(err=>{
					console.error(err)
					browserHistory.push('/');
				});
	}

	componentDidMount(){
		this.loopMusic();

	}

	componentWillUnmount(){
		this.stopPlayingMusic();
	}

	render(){
		return(

					<Star />

 Lounges

						  <button className="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
						    Logged in as {this.state.user}

						  </button>

										Log out

Manage Account

						<button className="btn btn-controls" onClick ={this.stopPlayingMusic}>

							 stop playing
						</button>
						<button className="btn btn-controls" onClick = {this.startPlayingMusic}>

								start playing
						</button>

Welcome to Hangout Simulator Alpha! As of now , the only lounge available is test. Thank you.

							{this.state.lounges.map(lounge=>{
								return (

{lounge.name }

								)
							})}

		)
	}
}

export default Lounges