text:
class Iterator;
typedef int Object;
class Interator;

class Aggregate
{
public:
	virtual ~Aggregate();
	virtual Iterator* CreateIterator() = 0;
	virtual Object GetItem(int idx) = 0;
	virtual int GetSize() = 0;
protected:
	Aggregate();
private:
};
class ConcreteAggregate:public Aggregate
{
public:
	enum { SIZE = 3 };
	ConcreteAggregate();
	~ConcreteAggregate();
	Iterator* CreateIterator();
	Object GetItem(int idx);
	int GetSize();
protected:
private:
	Object _objs[SIZE];
};
#endif


text:
/*Maphancement - Google Maps (progressive enhanced) - At first load only the static image of the map is loaded, once the user interacts with the map the iframe with the dynamic map is loaded Author: Michael Scharnagl, @justmarkup, 2014 | License: MIT */

/*global document*/
(function (doc) {

	// Enable strict mode
	"use strict";

	// Loop the pictures
	var map,
		maps = doc.getElementsByTagName("img");

	for( var i = 0, il = maps.length; i < il; i++ ){
		if( maps[i].getAttribute( "data-map" ) !== null ){
			map = maps[i];
		}
	}

	// Replace img with dynamic map in iframe
	var maphancement = function() {
		var mapIframe = doc.createElement("iframe"),
			mapSource = map.src.replace("http://maps.googleapis.com/maps/api/staticmap", "http://maps.google.de/maps").replace("?center", "?q");

		mapIframe.height = map.height;
		mapIframe.width = map.width;
		mapIframe.src = mapSource + "&output=embed";
		map.parentNode.appendChild(mapIframe);
		map.parentNode.removeChild(map);
	};

	if (map) {
		// Run on click and dragstart
		if (map.addEventListener) {
			map.addEventListener("dragstart", maphancement, false);
			map.addEventListener("click", maphancement, false);
		} else if (map.attachEvent) {
			map.attachEvent ("ondragstart", maphancement);
			map.attachEvent ("onclick", maphancement);
		}
	}

}( document ));

redpajama_set_name: RedPajamaGithub


text:
class ConfigureModule():

	def init(self):

		''' Inits SmartBody'''

		#Add asset paths
		print "Adding assets paths"
		scene.addAssetPath('mesh', 'mesh')
		scene.addAssetPath('motion', 'ChrBrad')
		scene.addAssetPath('motion', 'ChrRachel')
		scene.addAssetPath("script", "behaviorsets")
		scene.addAssetPath('script', 'scripts')
		scene.loadAssets()

		#Set scene scale
		print "Setting scene scale"
		scene.setScale(1.0)

		# Set joint map for agents
		print 'Setting up joint map for agents'
		scene.run('zebra2-map.py')
		zebra2Map = scene.getJointMapManager().getJointMap('zebra2')
		bradSkeleton = scene.getSkeleton('ChrBrad.sk')
		zebra2Map.applySkeleton(bradSkeleton)
		zebra2Map.applyMotionRecurse('ChrBrad')
		rachelSkeleton = scene.getSkeleton('ChrRachel.sk')
		zebra2Map.applySkeleton(rachelSkeleton)
		zebra2Map.applyMotionRecurse('ChrRachel')

		#Creates scene
		print "Creating scene"
		getViewer().show()

	def initGlobalVariables(self, amountAgents):
		for i in range (amountAgents):
			inside.append(True)
			firstStep.append(True)

	def camera(self, cameraEye, cameraCenter, cameraPosition):

		''' Configures camera'''

		#Gets camera
		getCamera().reset()
		scene.createPawn('camera')
		camera = getCamera()

		#Sets camera with provided values
		camera.setEye(cameraEye[0], cameraEye[1], cameraEye[2])
		camera.setCenter(cameraCenter[0], cameraCenter[1], cameraCenter[2])
		scene.getPawn('camera').setPosition(SrVec(cameraPosition[0], cameraPosition[1], cameraPosition[2]))

	def autoSetCamera(self, amountAgents):

		xCamera = 0
		yCamera = 0

		for i in range (amountAgents):

			character = scene.getCharacter(scene.getCharacterNames()[i])

			xCamera = xCamera + character.getPosition().getData(0)
			yCamera = yCamera + character.getPosition().getData(2)

		xCamera = xCamera/amountAgents
		yCamera = yCamera/amountAgents

		centerCamera = [xCamera, 0, yCamera]
		return centerCamera

	def setLimits(self, xLimitScene, yLimitScene):

		'''Sets limits of scene grid'''

		steerManager = scene.getSteerManager()

		steerManager.setDoubleAttribute('gridDatabaseOptions.gridSizeX', xLimitScene)
		steerManager.setDoubleAttribute('gridDatabaseOptions.gridSizeZ', yLimitScene)

	def autoSetLimits(self, ubikSimServer):
		vectorLimits = ConnectionsModule().getMaxScenario(ubikSimServer)

		vectorLimits = [vectorLimits[0] + 100, vectorLimits[1] + 100]

		return vectorLimits


text:
require File.dirname(__FILE__) + '/spec_helper.rb'

include RR

describe DatabaseProxy do
  before(:each) do
    Initializer.configuration = standard_config
  end

  it "initialize should create an empty session regiser" do
    proxy =  DatabaseProxy.new
    expect(proxy.session_register).to eq({})
  end

  def create_proxy_and_session
    proxy = DatabaseProxy.new
    session = proxy.create_session Initializer.configuration.left
    return proxy, session
  end

  it "create_session should register the created session" do
    proxy, session = create_proxy_and_session

    expect(session).to be_an_instance_of(ProxyConnection)
    expect(proxy.session_register.include?(session)).to eq(true)
  end

  it "destroy_session should destroy and unregister the session" do
    proxy, session = create_proxy_and_session
    expect(session).to receive(:destroy)

    proxy.destroy_session session

    expect(proxy.session_register.include?(session)).to eq(false)
  end

  it "ping should respond with 'pong'" do
    proxy = DatabaseProxy.new
    expect(proxy.ping).to eq('pong')
  end

  it "terminate should exit the proxy" do
    proxy = DatabaseProxy.new
    expect(Thread.main).to receive(:raise).with(SystemExit)

    proxy.terminate!
  end
end


text:
package legends.model.events;

import legends.xml.annotation.XmlComponent;
import legends.xml.annotation.XmlSubtype;

@XmlSubtype("masterpiece engraving")
public class MasterpieceEngravingEvent extends MasterpieceEvent {
	@XmlComponent
	private Art art = new Art();

	@Override
	public String getCreation() {
		return "a masterful engraving \"" + art.getLink() + "\"";
	}

}


text:
using System;

namespace Newtonsoft.Json.Utilities
{
  /// <summary>
  /// Builds a string. Unlike StringBuilder this class lets you reuse it's internal buffer.
  /// </summary>
  internal class StringBuffer
  {
    private char[] _buffer;
    private int _position;

    private static readonly char[] _emptyBuffer = new char[0];

    public int Position
    {
      get { return _position; }
      set { _position = value; }
    }

    public StringBuffer()
    {
      _buffer = _emptyBuffer;
    }

    public StringBuffer(int initalSize)
    {
      _buffer = new char[initalSize];
    }

    public void Append(char value)
    {
      // test if the buffer array is large enough to take the value
      if (_position == _buffer.Length)
      {
        EnsureSize(1);
      }

      // set value and increment poisition
      _buffer[_position++] = value;
    }

    public void Clear()
    {
      _buffer = _emptyBuffer;
      _position = 0;
    }

    private void EnsureSize(int appendLength)
    {
      char[] newBuffer = new char[(_position + appendLength) * 2];

      Array.Copy(_buffer, newBuffer, _position);

      _buffer = newBuffer;
    }

    public override string ToString()
    {
      return ToString(0, _position);
    }

    public string ToString(int start, int length)
    {
      // TODO: validation
      return new string(_buffer, start, length);
    }

    public char[] GetInternalBuffer()
    {
      return _buffer;
    }
  }
}


text:
% Copyright (c) 2003-2008, Arnold Neumaier
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of the University of Vienna nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY ARNOLD NEUMAIER ''AS IS'' AND ANY
% EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL  ARNOLD NEUMAIER BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% snobnewb.m %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% function [xl,xu,vol,u,v] = snobnewb(xnew,xl,xu,small,u,v,u1,v1)
% if xnew contains points outside the box [u,v], the box is made larger
% such that it just contains all new points; moreover, if necessary,
% [u,v] is made larger to contain [u1,v1]
% the box bounds xl and xu of the boxes on the boundary and the volume
% measures small of these boxes are updated if necessary
%
% Input:
% xnew	the rows of xnew contain the new points
% xl	xl(j,:) is the lower bound of box j
% xu	xu(j,:) is the upper bound of box j
% small	small(j) is the volume measure of box j
% u,v	old box bounds
% u1,v1 box in which the points are to be generated
%
% Output:
% xl	updated version of xl
% xu 	updated version of xu
% small	updated version of small
% u,v	updated box bounds (the old box is contained in the new one)
%
function [xl,xu,small,u,v] = snobnewb(xnew,xl,xu,small,u,v,u1,v1)
nx = size(xl,1);
n = size(xl,2);
uold = u;
vold = v;
u = min([xnew;u],[],1);
v = max([xnew;v],[],1);
u = min(u,u1);
v = max(v,v1);
i1 = find(u<uold);
i2 = find(v>vold);
ind = [];
for j=1:length(i1)
  j1 = find(xl(:,i1(j))==uold(i1(j)));
  ind = [ind; j1];
  xl(j1,i1(j)) = u(i1(j));
end
for j=1:length(i2)
  j2 = find(xu(:,i2(j))==vold(i2(j)));
  ind = [ind; j2];
  xu(j2,i2(j)) = v(i2(j));
end
if length(i1)+length(i2)  % at least one of the bounds was changed
  small = -sum(round(log2((xu-xl)./(ones(nx,1)*(v-u)))),2);
end


text:
//
// Dixie
// Copyright 2015 Skyscanner Limited
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.

@import Foundation;
#import <objc/runtime.h>

#import "DixieCallEnvironment.h"
#import "DixieChaosContext.h"
#import "DixieMethodInfo.h"

#define DixieMethodPrefix @"dixie_"

#define isType(typeEncoding, type2) (strcmp(typeEncoding, @encode(type2)) == 0)

/**
 *  Block type to describe a method's concrete implementation
 *
 *  @param victim      The receiver of the ObjC message
 *  @param environment The environment of the call
 */
typedef void(^DixieImplementationBlock)(id victim, DixieCallEnvironment* environment);

/**
 *  Helper to generate behaviour implementation, transparently call implementations and provide Runtime informations
 */
@interface DixieRunTimeHelper : NSObject

/**
 *  Generates an implementation pointer that confirms to the chaosContext and block
 *
 *  @param chaosContext The context of the implementation
 *  @param block        Block for the body of the implementation pointer
 *
 *  @return the implementation pointer
 */
+(IMP) implementationWithChaosContext:(DixieChaosContext*)chaosContext environment:(DixieImplementationBlock)block;

/**
 *  Calls the implementation pointer
 *
 *  @param implementation The IMP pointer to call
 *  @param puppet         The receiver of the ObjC message
 *  @param chaosContext   The context of the behaviour
 *  @param environment    The environment of the method's implementation call
 */
+(void) callImplementation:(IMP)implementation on:(id)puppet chaosContext:(DixieChaosContext*)chaosContext environment:(DixieCallEnvironment*)environment;

/**
 *  Collects the runtime public methodnames for a given class
 *
 *  @param targetClass The class
 *
 *  @return Array of public selector strings
 */
+(NSArray*) selectorsForClass:(Class)targetClass;

/**
 *  Returns the Method pointer for a given MethodInfo object
 *
 *  @param methodInfo Describes the target class and it's method
 *
 *  @return The Method pointer
 */
+(Method) methodForMethodInfo:(DixieMethodInfo*)methodInfo;

/**
 *  Returns the string representation of the method encoding describes by the MethodInfo object
 *
 *  @param methodInfo Describes the target class and it's method
 *
 *  @return the string representation of the method encoding
 */
+(const char*) methodTypeEncodingForMethodInfo:(DixieMethodInfo*)methodInfo;

/**
 *  Returns the class for the method described in the MethodInfo.
 *
 *  @param methodInfo Describes the target class and it's method
 *
 *  @return A Class object for instance methods and meta class object for class methods
 */
+(Class) classForMethodInfo:(DixieMethodInfo*)methodInfo;

@end


text:
#ifndef APPS_H
#define APPS_H

#include <ff.h>
#include <stm324xg_eval_sdio_sd.h>

#define NO_SDCARD 0
#define OPEN_FILE 1

extern char current_directory_path[20];
extern char visited_directories[50][13];
extern char target_file[13];
extern uint16_t cursors[50];
extern uint8_t depth;

extern const uint16_t arrow_up_image[];
extern const uint16_t arrow_down_image[];
extern const uint16_t folder_up_image[];
extern const uint16_t arrow_up_pressed_image[];
extern const uint16_t arrow_down_pressed_image[];
extern const uint16_t folder_up_pressed_image[];

/*
 * Struct that serves to display and identify the files presented in file
 * manager's menu that lists the file in a directory.
 */
struct Menu_object {
	BYTE	fattrib;
	TCHAR	fname[13];
	uint8_t exists;
};

/*
 * Struct for menu area, a special type of object on touch screen that is
 * composed of several elements that have the same dimensions and that form
 * one rectangular area on the screen. It's much more efficient to use it
 * instead of composing the menu with button-like objects and try to identify
 * an object by checking all the objects one by one.
 */
struct Menu_area {
	uint16_t x_start;
	uint16_t y_start;
	uint16_t x_end;
	uint16_t y_end;
	uint8_t step;
};

void system_message(uint8_t number);
uint8_t txt_viewer();
uint8_t file_manager();

#endif /* APPS_H */


text:
package com.example.cmput401.classdiscuss;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.PushService;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;
import java.util.List;

/**
 * Created by Valerie on 2015-03-25.
 */
public class CustomReceiver extends BroadcastReceiver {
    private static final String TAG = "MyCustomReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        //String name = intent.getAction();
        String name = "";
        String message = "";
       // Log.d(TAG, "got action name" + name );
        Notice notice = Notice.getInstance();
        try {
            JSONObject json = new JSONObject(intent.getExtras().getString("com.parse.Data"));
            //String name = json.getString("alert").toString();
            name = json.getString("username");
            message = json.getString("message");
            Log.d(TAG, "json: " + message );
        }
        catch (JSONException e){
                Log.d(TAG, "JSONException: " + e.getMessage());
            }
        //Notice notice = new Notice();
        notice.iconAppear();
        notice.setUsername(name);
        if (!notice.getLive()) {
            Intent cIntent = new Intent(context, MainActivity.class);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, cIntent, 0);

            NotificationManager mNotifM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            Toast.makeText(context, message, Toast.LENGTH_LONG).show();
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_nimicon)
                    .setContentTitle(name)
                    .setContentText(message)
                    .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                    .setAutoCancel(true);

            mBuilder.setContentIntent(contentIntent);
            mNotifM.notify(5, mBuilder.build());
        }
    }
}


text:
class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.text :email
      t.text :username
      t.text :password_hash
      t.boolean :faculty

      t.timestamps
    end
  end
end


text:
layout: default
title: Jekyll Themes
---

	{% for post in site.posts %}

{{ post.title }}

	{% endfor %}


text:
package com.eaw1805.map;

import com.eaw1805.data.constants.NationConstants;
import com.eaw1805.data.constants.ProductionSiteConstants;
import com.eaw1805.data.constants.TerrainConstants;
import com.eaw1805.data.dto.common.CoordinateDTO;
import com.eaw1805.data.dto.common.SectorDTO;
import com.eaw1805.data.dto.converters.SectorConverter;
import com.eaw1805.data.model.Game;
import com.eaw1805.data.model.Nation;
import com.eaw1805.data.model.map.Sector;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.awt.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Loads the tiles of a map.
 */
public class TilesLoader
        implements TerrainConstants {

    /**
     * a log4j logger to print messages.
     */
    private static final Logger LOGGER = LogManager.getLogger(TilesLoader.class);

    /**
     * The maximum X coordinate.
     */
    private final transient int maxX;

    /**
     * The maximum Y coordinate.
     */
    private final transient int maxY;

    /**
     * The minimumx X coordinate.
     */
    private final transient int minX;

    /**
     * The minimum Y coordinate.
     */
    private final transient int minY;

    /**
     * The color of each x,y coordinate. Selection is based on color of sector's owner.
     */
    private final transient Color[][] mapNation;

    /**
     * The base image assigned to each coordinate.
     */
    private final transient String[][] sectorTiles;

    /**
     * The list of additional tiles that are required as image overlays.
     */
    private final transient List<CoordinateDTO> sectorOverlayTiles;

    /**
     * Indicates if that fog-of-war will be used.
     */
    private final transient boolean showFOWBorders;

    /**
     * Indicates if that fog-of-war will be used.
     */
    private final transient boolean deactivateFOW;

    /**
     * Default constructor.
     *
     * @param game          the game (for calculating winter).
     * @param sectorList    list of sectors to draw.
     * @param viewer        the nation viewing the map.
     * @param useFOWborders display alternative national borders for foreign nations on the map.
     * @param disableFOW    de-activate FOW rules.
     */
    public TilesLoader(final Game game,
                       final List<Sector> sectorList,
                       final Nation viewer,
                       final boolean useFOWborders,
                       final boolean disableFOW) {
        showFOWBorders = useFOWborders;
        deactivateFOW = disableFOW;
        final List<SectorDTO> sectors = new ArrayList<SectorDTO>();
        final Set<SectorDTO> sectorsVisible = new HashSet<SectorDTO>();
        int tempXmax = 0;
        int tempYmax = 0;
        int tempXmin = Integer.MAX_VALUE;
        int tempYmin = Integer.MAX_VALUE;

        final String viewerToken;
        if (viewer.getId() == NationConstants.NATION_NEUTRAL) {
            viewerToken = "*";
        } else {
            viewerToken = "*" + viewer.getId() + "*";
        }

        for (final Sector value : sectorList) {
            final SectorDTO convSector = SectorConverter.convert(value);
            sectors.add(convSector);
            tempXmax = Math.max(tempXmax, value.getPosition().getX());
            tempYmax = Math.max(tempYmax, value.getPosition().getY());
            tempXmin = Math.min(tempXmin, value.getPosition().getX());
            tempYmin = Math.min(tempYmin, value.getPosition().getY());

            if (value.getTerrain().getId() == TERRAIN_O
                    || value.getNation().getId() == viewer.getId()
                    || (value.getFow() != null && value.getFow().contains(viewerToken))
                    || deactivateFOW) {
                convSector.setVisible(true);
                sectorsVisible.add(convSector);
            }
        }

        LOGGER.debug("Loaded " + sectors.size() + " sectors.");
        LOGGER.debug("Map size is " + (tempXmin + 1) + "/" + (tempYmin + 1) + "..." + (tempXmax + 1) + "/" + (tempYmax + 1));

        maxX = tempXmax;
        maxY = tempYmax;
        minX = tempXmin;
        minY = tempYmin;

        final SectorDTO[][] mapSector = new SectorDTO[maxX + 1][maxY + 1];
        mapNation = new Color[maxX + 1][maxY + 1];
        sectorTiles = new String[maxX + 1][maxY + 1];
        final CoordinateDTO[][][] sectorOverlays = new CoordinateDTO[maxX + 1][maxY + 1][TilesSelector.LAYER_BORDERS];

        // Iterate through all sectors
        for (SectorDTO sector : sectors) {
            final int coordX = sector.getX();
            final int coordY = sector.getY();
            mapSector[coordX][coordY] = sector;
            if (sector.getNationId() > 0) {
                mapNation[coordX][coordY] = Color.decode("#" + sector.getNationDTO().getColor().toUpperCase());

            } else {
                mapNation[coordX][coordY] = null;
            }
        }

        // Setup tiles selector
        final TilesSelector tilesSelector = new TilesSelector(mapSector, game, maxX, maxY, minX, minY);

        // Identify base image
        for (int coordX = minX; coordX <= maxX; coordX++) {
            for (int coordY = minY; coordY <= maxY; coordY++) {
                final SectorDTO thisSector = mapSector[coordX][coordY];
                sectorOverlays[coordX][coordY][0] = new CoordinateDTO();

                if (thisSector.getTerrainId() == TERRAIN_O) {
                    sectorTiles[coordX][coordY] = tilesSelector.getOceanCoastTile(coordX, coordY);

                    // Check for off-map trade cities
                    if (thisSector.getTradeCity()) {
                        tilesSelector.addTCityTile(coordX, coordY);
                    }
                } else {
                    sectorTiles[coordX][coordY] = tilesSelector.getBaseTile(coordX, coordY);
                }

                if (deactivateFOW || sectorsVisible.contains(thisSector)) {
                    if ((thisSector.getProductionSiteId() > 0) || (thisSector.getPopulation() > 6)) {
                        if (thisSector.getTradeCity()) {
                            tilesSelector.addTCityTile(coordX, coordY);

                        } else {
                            tilesSelector.addPSiteTile(coordX, coordY);
                        }

                        // Add fortifications
                        if (thisSector.getProductionSiteId() > ProductionSiteConstants.PS_BARRACKS) {
                            tilesSelector.addFortTile(coordX, coordY);
                        }
                    }
                }

                if (thisSector.getNatResId() > 0) {
                    tilesSelector.addNatResTile(coordX, coordY, thisSector.getNatResId());
                }

                if (thisSector.getEpidemic()) {
                    tilesSelector.addEpidemicTile(coordX, coordY);
                }

                if (thisSector.getRebelled()) {
                    tilesSelector.addRebellionTile(coordX, coordY);
                }

                if (thisSector.getConquered()) {
                    tilesSelector.addConquerTile(coordX, coordY);
                }

                if (thisSector.getNationId() != NationConstants.NATION_NEUTRAL) {
                    tilesSelector.addBorderName(deactivateFOW || (showFOWBorders && sectorsVisible.contains(thisSector)), coordX, coordY);
                }
            }
        }

        // Get result of tile selection process
        sectorOverlayTiles = tilesSelector.getSectorTiles();
    }

    /**
     * Get the maximum X coordinate of the map.
     *
     * @return the maximum X coordinate of the map.
     */
    public int getMaxX() {
        return maxX;
    }

    /**
     * Get the maximum Y coordinate of the map.
     *
     * @return the maximum Y coordinate of the map.
     */
    public int getMaxY() {
        return maxY;
    }

    /**
     * Get the minimum X coordinate of the map.
     *
     * @return the minimum X coordinate of the map.
     */
    public int getMinX() {
        return minX;
    }

    /**
     * Get the minimum Y coordinate of the map.
     *
     * @return the minimum Y coordinate of the map.
     */
    public int getMinY() {
        return minY;
    }

    /**
     * Get the tile tint color.
     *
     * @param coordX the X coordinate.
     * @param coordY the Y coordinate.
     * @return the RGB color for tinting the coordinate.
     */
    public Color getTintColor(final int coordX, final int coordY) {
        return mapNation[coordX][coordY];
    }

    /**
     * Get the base tiles.
     *
     * @param coordX the X coordinate.
     * @param coordY the Y coordinate.
     * @return the filename of the base tile.
     */
    public String getSectorTile(final int coordX, final int coordY) {
        return sectorTiles[coordX][coordY];
    }

    /**
     * Get overlay tiles.
     *
     * @return list of Coordinates with overlay tiles.
     */
    public List<CoordinateDTO> getSectorOverlayTiles() {
        return sectorOverlayTiles;
    }

}


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title><?php echo $title; ?></title>
        <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
        <link href="http://<?php echo base_url(); ?>/assets/css/bootstrap.css" rel="stylesheet" type="text/css" />
        <link href="http://<?php echo base_url(); ?>/assets/css/font-awesome.css" rel="stylesheet" type="text/css" />
        <link href="http://<?php echo base_url(); ?>/assets/css/ionicons.css" rel="stylesheet" type="text/css" />
        <link href="http://<?php echo base_url(); ?>/assets/css/AdminLTE.css" rel="stylesheet" type="text/css" />

        <link href="http://<?php echo base_url(); ?>/assets/css/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
        <link href="http://<?php echo base_url(); ?>/assets/css/smoothness/jquery-ui-1.9.0.custom.css" rel="stylesheet" type="text/css" />

            <a href="#" class="logo"  title="<?php echo $title; ?>">

                    Toggle navigation

			                    Makan Yuk !?

			                        <img src="http://<?php echo base_url(); ?>/assets/img/avatar.png" class="img-circle" alt="User Image" />

			                            Makan Yuk !?
			                            Direktur

			                            Password

			                            Logout

			                <img src="http://<?php echo base_url(); ?>/assets/img/avatar.png" class="img-circle" alt="User Image" />

Hi, Makan Yuk !?

			                 Online

			                <a href="http://<?php echo base_url(); ?>index.php/" title="Home">
			                	<img src="http://<?php echo base_url(); ?>/assets/img/home.png" />
			                    Home

			                <a href="http://<?php echo base_url(); ?>index.php/todo" title="To Do List">
			                	<img src="http://<?php echo base_url(); ?>/assets/img/daftar.png" />
			                    To Do List

			                <a href="http://<?php echo base_url(); ?>index.php/json" title="JSON To Do List">
			                	<img src="http://<?php echo base_url(); ?>/assets/img/ouput.png" />
			                    JSON To Do List

			                <a href="http://<?php echo base_url(); ?>index.php/about" title="About Us">
			                	<img src="http://<?php echo base_url(); ?>/assets/img/about.png" />
			                    About Us

	                <?php echo $title;?>

 Home

<?php echo $title;?>


text:
__author__ = 'SL_RU'

### Логика музыкального плеера

import os
import aplayer
import random
import json
import aplayer
import musicplaylist
import audiobook
import time

def log(s):
    print("BOOKS_PLAYER:" + s)

class BooksPlayer(object):
    aplayer = None
    books = list()
    cur_book = None
    path = ""
    cur_audio = ""

    def __init__(self, audioPlayer, path):
        self.set_aplayer(audioPlayer)
        self.path = path
        #self.create_playlist()
        self.turn_on()

    def refresh_path(self):
        """Find and enumerate books in the path"""
        self.books = list()
        wa = list(os.walk(self.path))[0]
        for i in wa[1]:
            self.books.append(i)

    def play_audio_by_name(self, name, offset=0):
        if(self.aplayer is not None) and os.path.isfile(self.path + name):
            b = self.aplayer.play_file(self.path + name)
            time.sleep(0.1)
            self.aplayer.set_pos(offset)
            self.cur_audio = name
            log("playing " + name)
            return b
        else:
            return False

    def set_aplayer(self, apl):
        if(self.aplayer is not None):
            self.aplayer.turn_off()
        self.update_book_state()
        self.aplayer = apl

    def get_aplayer(self):
        return aplayer

    def play_book(self, name):
        """Starting or continueing playing book. If other book playing in this time, it will be saved and stopped"""
        self.update_book_state()
        if(self.cur_book is not None):
            self.cur_book.save()
        self.cur_book = audiobook.Audiobook(self, name)
        log("Cur book is " + name)

    def play(self):
        if(self.aplayer is not None):
            self.aplayer.play()

    def pause(self):
        self.update_book_state()
        if(self.aplayer is not None):
            self.aplayer.pause()

    def play_forw(self):
        self.update_book_state()
        a = self.cur_book.get_cur_file_and_time()
        log(a)
        self.play_audio_by_name(a)

    def play_back(self):
        self.update_book_state()

    def load(self):
        if(os.path.isfile(self.path + "booksplayer.json")):
            with open(self.path + "booksplayer.json", "r") as fl:
                dt = json.load(fl)
                fl.close()

    def save(self):
        dt = {
            }
        if(self.cur_book is not None):
            self.cur_book.save()
        self.update_book_state()
        with open(self.path + "booksplayer.json", "w") as fl:
            json.dump(dt, fl)
            fl.close()

    def update_book_state(self):
        try:
            if(self.cur_book is not None):
                time.sleep(0.05)
                self.cur_book.set_cur_state(audio=self.cur_book.player_to_local_path(self.cur_audio), time=self.aplayer.get_pos())
        except:
            pass

    def turn_on(self):
        self.refresh_path()
        self.aplayer.add_endevent(self.on_audio_end)

    def turn_off(self):
        if(self.aplayer is not None):
            self.aplayer.turn_off()
        self.save()

    def get_type(self):
        return "book_player"

    def on_audio_end(self):
        self.play_forw()

    def play_pos(self, p):
        b = self.cur_book.get_audio_and_time_by_pos(p)
        self.play_audio_by_name(b[0], offset=b[1])


text:
module SphereBVEModule

use NumberKindsModule
use OutputWriterModule
use LoggerModule
use ParticlesModule
use EdgesModule
use FacesModule
use PolyMesh2dModule
use FieldModule
use MPISetupModule
use SphereGeomModule

implicit none

include 'mpif.h'

private
!
!----------------
! Module types and public declarations
!----------------
!
public BVEMesh, New, Delete, Copy
public AddTracers
public LogStats
public OutputToVTK
public SetInitialVorticityOnMesh, SetVelocityOnMesh, SetStreamFunctionsOnMesh
public TotalKE, TotalEnstrophy
public MaxCirculationMagnitudePerFace

type BVEMesh
	type(PolyMesh2d) :: mesh
	type(Field) :: absVort
	type(Field) :: relVort
	type(Field) :: relStream
	type(Field) :: absStream
	type(Field) :: velocity
	type(Field), dimension(:), pointer :: tracers => null()
	real(kreal) :: radius = 1.0_kreal
	real(kreal) :: rotationRate = 0.0_kreal
	type(MPISetup) :: mpiParticles

	contains
		final :: deletePrivate
end type

!
!----------------
! Module interfaces
!----------------
!
!interface
!	real(8) function scalarFnOf3DSpace( x, y, z)
!		real(8), intent(in) :: x, y, z
!	end function
!end interface
!
!interface
!	function vectorFnOf3DSpace( x, y, z)
!		real(8), dimension(3) :: vectorFnOf3DSpace
!		real(8), intent(in) :: x, y, z
!	end function
!end interface

interface New
	module procedure newPrivate
end interface

interface Delete
	module procedure deletePrivate
end interface

interface Copy
	module procedure copyPrivate
end interface

interface LogStats
	module procedure logStatsPrivate
end interface

interface SetVelocityOnMesh
	module procedure setVelocityFromFunction
	module procedure setVelocityFromVorticity
end interface

!
!----------------
! Logging
!----------------
!
logical(klog), save :: logInit = .FALSE.
type(Logger) :: log
character(len=28), save :: logKey = 'BVE'
integer(kint), parameter :: logLevel = DEBUG_LOGGING_LEVEL

contains
!
!----------------
! public methods
!----------------
!
subroutine newPrivate( self, meshSeed, initNest, maxNest, amrLimit, sphereRadius, rotationRate )
	type(BVEMesh), intent(out) :: self
	integer(kint), intent(in) :: meshSeed
	integer(kint), intent(in) :: initNest
	integer(kint), intent(in) :: maxNest
	integer(kint), intent(in) :: amrLimit
	real(kreal), intent(in) :: sphereRadius
	real(kreal), intent(in) :: rotationRate

	if ( .NOT. logInit) call InitLogger(log, procRank)

	if ( meshSeed /= ICOS_TRI_SPHERE_SEED .AND. meshSeed /= CUBED_SPHERE_SEED ) then
		call LogMessage(log, ERROR_LOGGING_LEVEL, trim(logKey), "new BVEMesh ERROR : invalid meshSeed.")
		return
	endif

	call New(self%mesh, meshSeed, initNest, maxNest, amrLimit, sphereRadius)

	call New(self%absVort, 1, self%mesh%particles%N_Max, "absVort", "1/s")
	call New(self%relVort, 1, self%mesh%particles%N_Max, "relVort", "1/s")
	call New(self%absStream, 1, self%mesh%particles%N_Max, "absStreamFn", "m^2/s")
	call New(self%relStream, 1, self%mesh%particles%N_Max, "relStreamFn", "m^2/s")
	call New(self%velocity, 3, self%mesh%particles%N_Max, "velocity", "m/s")
	call New(self%mpiParticles, self%mesh%particles%N_Max, numProcs)

	self%radius = sphereRadius
	self%rotationRate = rotationRate
end subroutine

subroutine deletePrivate( self )
	type(BVEMesh), intent(inout) :: self
	integer(kint) :: i

	call Delete(self%mpiParticles)
	call Delete(self%velocity)
	call Delete(self%relStream)
	call Delete(self%absStream)
	call Delete(self%absVort)
	call Delete(self%relVort)
	call Delete(self%mesh)
	if ( associated(self%tracers) ) then
		do i = 1, size(self%tracers)
			call Delete(self%tracers(i))
		enddo
		deallocate(self%tracers)
	endif
end subroutine

subroutine copyPrivate(self, other)
	type(BVEMesh), intent(inout) :: self
	type(BVEMesh), intent(in) :: other
	integer(kint) :: i

	call Copy(self%mesh, other%mesh)
	call Copy(self%relVort, other%relVort)
	call Copy(self%absVort, other%absVort)
	call Copy(self%velocity, other%velocity)
	call Copy(self%absStream, other%absStream)
	call Copy(self%relStream, other%relStream)
	call Copy(self%mpiParticles, other%mpiParticles)
	self%rotationRate = other%rotationRate
	self%radius = other%radius

	if ( associated(other%tracers)) then
		if ( associated(self%tracers)) then
			if ( size(self%tracers) /= size(other%tracers) ) then
				call LogMessage(log, ERROR_LOGGING_LEVEL, logkey, " copy BVEMesh ERROR : tracers not allocated properly.")
			else
				do i = 1, size(other%tracers)
					call Copy(self%tracers(i), other%tracers(i))
				enddo
			endif
		else
			call LogMessage(log, WARNING_LOGGING_LEVEL, logKey, " copy BVEMesh ERROR : tracers not copied.")
		endif
	endif
end subroutine

subroutine AddTracers(self, nTracers, tracerDims)
	type(BVEMesh), intent(inout) :: self
	integer(kint), intent(in) :: nTracers
	integer(kint), dimension(:), intent(in) :: tracerDims
	integer(kint) :: i

	if ( size(tracerDims) /= nTracers ) then
		call LogMessage(log, ERROR_LOGGING_LEVEL, trim(logkey)//" AddTracers ERROR : ", &
			" must specify dimension of each tracer field.")
		return
	endif

	allocate(self%tracers(nTracers))
	do i = 1, nTracers
		call New(self%tracers(i), tracerDims(i), self%mesh%particles%N_Max)
	enddo
end subroutine

subroutine logStatsPrivate( self, aLog)
	type(BVEMEsh), intent(in) :: self
	type(Logger), intent(inout) :: aLog
	call LogMessage(aLog, TRACE_LOGGING_LEVEL, "BVEMesh ", "stats : ")
	call LogStats(self%mesh, aLog)
	call LogStats(self%velocity, aLog)
	call LogStats(self%relVort, aLog)
	call LogStats(self%absVort, aLog)
	call LogStats(self%relStream, aLog)
	call LogStats(self%absStream, aLog)
end subroutine

subroutine OutputToVTK(self, filename)
	type(BVEMesh), intent(in) :: self
	character(len=*), intent(in) :: filename
	integer(kint) :: i, writeStat

	open(unit=WRITE_UNIT_1, file=filename, status='REPLACE', action='WRITE', iostat=writeStat)
		if ( writeStat /= 0 ) then
			call LogMessage(log, ERROR_LOGGING_LEVEL, trim(logkey)//" OutputToVTK ERROR writing to file = ", trim(filename))
			return
		endif
		!
		!	write points and topology
		!
		call WriteVTKPoints(self%mesh%particles, WRITE_UNIT_1)
		call WriteFacesToVTKPolygons(self%mesh%faces, WRITE_UNIT_1)
		!
		!	write vtk point data
		!
		call WriteVTKPointDataSectionHeader(WRITE_UNIT_1, self%mesh%particles%N)
		call WriteVTKLagCoords( self%mesh%particles, WRITE_UNIT_1)
		call WriteFieldToVTKPointData( self%relVort, WRITE_UNIT_1)
		call WriteFieldToVTKPointData( self%absVort, WRITE_UNIT_1)
		call WriteFieldToVTKPointData( self%velocity, WRITE_UNIT_1)
		call WriteFieldToVTKPointData( self%relStream, WRITE_UNIT_1)
		call WriteFieldToVTKPointData( self%absStream, WRITE_UNIT_1)
		if ( associated( self%tracers ) ) then
			do i = 1, size(self%tracers)
				call WriteFieldToVTKPointData( self%tracers(i), WRITE_UNIT_1)
			enddo
		endif
		!
		!	write vtk cell data
		!
		call WriteFaceAreaToVTKCellData( self%mesh%faces, self%mesh%particles, WRITE_UNIT_1)
	close(WRITE_UNIT_1)
end subroutine

subroutine SetInitialVorticityOnMesh(self, relVortFn )
	type(BVEMesh), intent(inout) :: self
	procedure(scalarFnOf3DSpace) :: relVortFn
	integer(kint) :: i
	real(kreal) :: zeta

	self%relVort%N = self%mesh%particles%N
	self%absVort%N = self%mesh%particles%N
	do i = 1, self%mesh%particles%N
		zeta = relVortFn( self%mesh%particles%x0(i), self%mesh%particles%y0(i), self%mesh%particles%z0(i) )
		!call InsertScalarToField(self%relVort, zeta )
		!call InsertScalarToField(self%absVort, zeta + 2.0_kreal*self%rotationRate*self%mesh%particles%z0(i) / self%radius)
		self%relVort%scalar(i) = zeta
		self%absVort%scalar(i) = zeta + 2.0_kreal * self%rotationRate * self%mesh%particles%z0(i) / self%radius
	enddo
end subroutine

subroutine setVelocityFromFunction(self, velFn )
	type(BVEMesh), intent(inout) :: self
	procedure(vectorFnOf3DSpace) :: velFn
	integer(kint) :: i

	do i = 1, self%mesh%particles%N
		call InsertVectorToField(self%velocity, &
			velFn( self%mesh%particles%x0(i), self%mesh%particles%y0(i), self%mesh%particles%z0(i)) )
	enddo
end subroutine

subroutine SetScalarTracerOnMesh(self, tracerId, tracerFn )
	type(BVEMesh), intent(inout) :: self
	integer(kint), intent(in) :: tracerId
	procedure(scalarFnOf3DSpace) :: tracerFn
	integer(kint) :: i

	call SetFieldToZero(self%tracers(tracerID))
	self%tracers(tracerId)%N = self%mesh%particles%N
	do i = 1, self%mesh%particles%N
		self%tracers(tracerID)%scalar(i) = tracerFn( self%mesh%particles%x0(i), self%mesh%particles%y0(i), &
												     self%mesh%particles%z0(i) )
	enddo
end subroutine

subroutine SetVectorTracerOnMesh( self, tracerID, tracerFn )
	type(BVEMesh), intent(inout) :: self
	integer(kint), intent(in) :: tracerId
	procedure(vectorFnOf3DSpace) :: tracerFn
	integer(kint) :: i
	real(kreal), dimension(3) :: vec

	call SetFieldToZero(self%tracers(tracerID))
	self%tracers(tracerID)%N = self%mesh%particles%N
	do i = 1, self%mesh%particles%N
		vec = tracerFn(self%mesh%particles%x0(i), self%mesh%particles%y0(i), self%mesh%particles%z0(i))
		self%tracers(tracerID)%xComp(i) = vec(1)
		self%tracers(tracerID)%yComp(i) = vec(2)
		self%tracers(tracerID)%zComp(i) = vec(3)
	enddo
end subroutine

function TotalKE( self )
	real(kreal) :: TotaLKE
	type(BVEMesh), intent(in) :: self
	integer(kint) :: i
	real(kreal) :: magSq

	TotalKE = 0.0_kreal
	do i = 1, self%mesh%particles%N
		if ( self%mesh%particles%isActive(i) ) then
			magSq = self%velocity%xComp(i)**2 + self%velocity%yComp(i)**2 + self%velocity%zComp(i)**2
			TotalKE = TotalKE + magSq * self%mesh%particles%area(i)
		endif
	enddo
	TotalKE = 0.5_kreal * TotalKE
end function

function TotalEnstrophy( self )
	real(kreal) :: TotalEnstrophy
	type(BVEMesh), intent(in) :: self
	integer(kint) :: i

	TotalEnstrophy = 0.0_kreal
	do i = 1, self%mesh%particles%N
		if ( self%mesh%particles%isActive(i) ) then
			TotalEnstrophy = TotalEnstrophy + self%relVort%scalar(i)**2 * self%mesh%particles%area(i)
		endif
	enddo
	TotalEnstrophy = 0.5_kreal * TotalEnstrophy
end function

subroutine SetStreamFunctionsOnMesh( self )
	type(BVEMesh), intent(inout) :: self
	integer(kint) :: i, j, mpiErrCode
	real(kreal) :: greensKernel
	real(kreal), dimension(3) :: xi, xj

	self%relStream%n = self%mesh%particles%n
	self%absStream%n = self%mesh%particles%n
	do i = self%mpiParticles%indexStart(procRank), self%mpiParticles%indexEnd(procRank)
		self%relStream%scalar(i) = 0.0_kreal
		self%absStream%scalar(i) = 0.0_kreal
		xi = PhysCoord(self%mesh%particles, i)
		do j = 1, i - 1
			if ( self%mesh%particles%isActive(j) ) then
				xj = PhysCoord(self%mesh%particles, j)
				greensKernel = - dlog( self%radius * self%radius - sum(xi * xj)) / (4.0_kreal * PI * self%radius)
				self%relStream%scalar(i) = self%relStream%scalar(i) + greensKernel * &
					self%relVort%scalar(j) * self%mesh%particles%area(j)
				self%absStream%scalar(i) = self%absStream%scalar(i) + greensKernel * &
					self%absVort%scalar(j) * self%mesh%particles%area(j)
			endif
		enddo
		do j = i + 1, self%mesh%particles%N
			if ( self%mesh%particles%isActive(j) ) then
				xj = PhysCoord(self%mesh%particles, j)
				greensKernel = - dlog( self%radius * self%radius - sum(xi * xj)) / (4.0_kreal * PI * self%radius)
				self%relStream%scalar(i) = self%relStream%scalar(i) + greensKernel * &
					self%relVort%scalar(j) * self%mesh%particles%area(j)
				self%absStream%scalar(i) = self%absStream%scalar(i) + greensKernel * &
					self%absVort%scalar(j) * self%mesh%particles%area(j)
			endif
		enddo
	enddo

	do i = 0, numProcs - 1
		call MPI_BCAST(self%relStream%scalar(self%mpiParticles%indexStart(i):self%mpiParticles%indexEnd(i)), &
			self%mpiParticles%messageLength(i), MPI_DOUBLE_PRECISION, i, MPI_COMM_WORLD, mpiErrCode)
		call MPI_BCAST(self%absStream%scalar(self%mpiParticles%indexStart(i):self%mpiParticles%indexEnd(i)), &
			self%mpiParticles%messageLength(i), MPI_DOUBLE_PRECISION, i, MPI_COMM_WORLD, mpiErrCode)
	enddo
end subroutine

subroutine setVelocityFromVorticity( self )
	type(BVEMesh), intent(inout) :: self
	integer(kint) :: i, j, mpiErrCode
	real(kreal) :: strength
	real(kreal), dimension(3) :: xi, xj

	self%velocity%n = self%mesh%particles%N
	do i = self%mpiParticles%indexStart(procRank), self%mpiParticles%indexEnd(procRank)
		self%velocity%xComp(i) = 0.0_kreal
		self%velocity%yComp(i) = 0.0_kreal
		self%velocity%zComp(i) = 0.0_kreal
		xi = PhysCoord(self%mesh%particles, i)
		do j = 1, i - 1
			if ( self%mesh%particles%isActive(j) ) then
				xj = PhysCoord(self%mesh%particles, j)
				strength = -self%relVort%scalar(j)*self%mesh%particles%area(j) / &
					(4.0_kreal * PI * self%radius * (self%radius * self%radius - sum( xi * xj )))
				self%velocity%xComp(i) = self%velocity%xComp(i) + (xi(2)*xj(3) - xi(3)*xj(2)) * strength
				self%velocity%yComp(i) = self%velocity%yComp(i) + (xi(3)*xj(1) - xi(1)*xj(3)) * strength
				self%velocity%zComp(i) = self%velocity%zComp(i) + (xi(1)*xj(2) - xi(2)*xj(1)) * strength
			endif
		enddo
		do j = i + 1, self%mesh%particles%N
			if ( self%mesh%particles%isActive(j) ) then
				xj = PhysCoord(self%mesh%particles, j)
				strength = -self%relVort%scalar(j)*self%mesh%particles%area(j) / &
					(4.0_kreal * PI * self%radius * (self%radius * self%radius - sum( xi * xj )))
				self%velocity%xComp(i) = self%velocity%xComp(i) + (xi(2)*xj(3) - xi(3)*xj(2)) * strength
				self%velocity%yComp(i) = self%velocity%yComp(i) + (xi(3)*xj(1) - xi(1)*xj(3)) * strength
				self%velocity%zComp(i) = self%velocity%zComp(i) + (xi(1)*xj(2) - xi(2)*xj(1)) * strength
			endif
		enddo
	enddo

	do i = 0, numProcs - 1
		call MPI_BCAST(self%velocity%xComp(self%mpiParticles%indexStart(i):self%mpiParticles%indexEnd(i)), &
					   self%mpiParticles%messageLength(i), MPI_DOUBLE_PRECISION, i, MPI_COMM_WORLD, mpiErrCode)
		call MPI_BCAST(self%velocity%yComp(self%mpiParticles%indexStart(i):self%mpiParticles%indexEnd(i)), &
					   self%mpiParticles%messageLength(i), MPI_DOUBLE_PRECISION, i, MPI_COMM_WORLD, mpiErrCode)
		call MPI_BCAST(self%velocity%zComp(self%mpiParticles%indexStart(i):self%mpiParticles%indexEnd(i)), &
					   self%mpiParticles%messageLength(i), MPI_DOUBLE_PRECISION, i, MPI_COMM_WORLD, mpiErrCode)
	enddo
end subroutine

function MaxCirculationMagnitudePerFace( self )
	real(kreal) :: MaxCirculationMagnitudePerFace
	type(BVEMesh), intent(in) :: self
	!
	integer(kint) :: i
	real(kreal) :: testCirc
	integer(kint) :: particleIndex

	MaxCirculationMagnitudePerFace = 0.0_kreal
	do i = 1, self%mesh%faces%N
		if ( .NOT. self%mesh%faces%hasChildren(i) ) then
			particleIndex = self%mesh%faces%centerParticle(i)
			testCirc = abs( self%relVort%scalar(particleIndex) ) * self%mesh%particles%area(particleIndex)
			if ( testCirc > MaxCirculationMagnitudePerFace ) MaxCirculationMagnitudePerFace = testCirc
		endif
	enddo
end function

!
!----------------
! private methods
!----------------
!
subroutine InitLogger(aLog,rank)
	type(Logger), intent(out) :: aLog
	integer(kint), intent(in) :: rank
	write(logKey,'(A,A,I0.2,A)') trim(logKey),'_',rank,' : '
	if ( rank == 0 ) then
		call New(aLog,logLevel)
	else
		call New(aLog,ERROR_LOGGING_LEVEL)
	endif
	logInit = .TRUE.
end subroutine

end module


text:
interface Date {
    getUTCTime(): number
    getTimeAge(d?: Date, i?: string, o?: any): number
    getYearAge(d?: Date): number
    getMonthAge(d?: Date): number
    add(i: string, n: number): void
    addMonth(n: number): void
    addYear(n: number): void
    addDate(n: number): void
    isPast(d?: Date): boolean
    isFuture(d?: Date): boolean
    isToday(): boolean
    getAge(d?: Date): any
    isNow(): boolean
    isSameDate(d?: Date): boolean
}

/**
 * get UTC Time
 * @return a utc time of the current date
 */
Date.prototype.getUTCTime = function(): number
{
    var now = new Date(0)
    now.setUTCFullYear(this.getUTCFullYear())
    now.setUTCMonth(this.getUTCMonth())
    now.setUTCDate(this.getUTCDate())

    now.setUTCHours(this.getUTCHours())
    now.setUTCMinutes(this.getUTCMinutes())
    now.setUTCSeconds(this.getUTCSeconds())
    now.setUTCMilliseconds(this.getUTCMilliseconds())

    return now.getTime()
}

Date.prototype.getTimeAge = function(d?: Date, i: string = 't', o?: any): number
{
	d = d || new Date();
	i = i || 't';
	o = o || { abs: false } ;
	var diff: number = d.getTime() - this.getTime();
	if(o.abs) { diff = Math.abs(diff); }
	switch(i)
	{
		case 'd':	return diff / 1000 / 3600 / 24;
		case 'h':	return diff / 1000 / 3600;
		case 'n':	return diff / 1000 / 60;
		case 's':   return diff / 1000;
		case 't':
		default:	return diff;
	}
}

Date.prototype.getYearAge = function(d?: Date): number
{
	var dDiff_: Date = new Date(this.getTimeAge(d));
	return dDiff_.getFullYear() - 1970;
}

Date.prototype.getMonthAge = function(d?: Date): number
{
	var dDiff_: Date = new Date(this.getTimeAge(d));
	return (dDiff_.getFullYear() - 1970) * 12 + (dDiff_.getMonth() + 1);
}

Date.prototype.add = function(i: string, n: number): void
{
	switch(i)
	{
		case 'y':	this.addYear(n); break;
		case 'm':	this.addMonth(n); break;
		case 'd':	this.addDate(n); break;
		case 'h':	this.setHours(this.getHours() + n); break;
		case 'n':	this.setMinutes(this.getMinutes() + n);	break;
		case 's':   this.setSeconds(this.getSeconds() + n); break;
		case 't':
		default:	this.setTime(this.getTime() + n);
	}
}

Date.prototype.addDate = function(n: number): void
{
    this.setDate(this.getDate() + n);
}

Date.prototype.addMonth = function(n: number): void
{
	this.setMonth(this.getMonth() + n);
}

Date.prototype.addYear = function(n: number): void
{
	this.setFullYear(this.getFullYear() + n);
}

Date.prototype.isPast = function(d?: Date): boolean
{
	d = d || new Date();
	return this.getTime() < d.getTime();
}

Date.prototype.isFuture = function(d?: Date): boolean
{
	d = d || new Date();
	return this.getTime() > d.getTime();
}

Date.prototype.isToday = function(): boolean
{
	return this.isSameDate();
}

Date.prototype.isSameDate = function(d?: Date): boolean {
	var dNow_: Date  	= d || new Date();
	return this.getFullYear() == dNow_.getFullYear() && this.getMonth() == dNow_.getMonth() && this.getDate() == dNow_.getDate();
}

Date.prototype.getAge = function(d?: Date): any
{
	var dDiff_: Date = new Date(this.getTimeAge(d));
	return {
		Date	:	dDiff_,
		Year	:	dDiff_.getFullYear() - 1970,
		Month	:	dDiff_.getMonth() + 1,
		Day		:	dDiff_.getDate(),
		Hours	:	dDiff_.getHours(),
		Minutes	:	dDiff_.getMinutes(),
		Seconds	:	dDiff_.getSeconds(),
		Time	:	dDiff_.getTime()
	};
}

Date.prototype.isNow = function(): boolean
{
	var dNow_: Date  	= new Date();
	return this.isToday() && this.getHours() == dNow_.getHours() && this.getMinutes() == dNow_.getMinutes();
}


text:
namespace Fort.Info.SkinnerBox
{
    public abstract class PurchableSkinnerBoxInfo : SkinnerBoxInfo
    {

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <committees>
      <billCommittees>
        <item>
          <type>Standing</type>
          <subcommittees />
          <systemCode>hsha00</systemCode>
          <activities>
            <item>
              <date>2017-06-14T14:00:09Z</date>
              <name>Referred to</name>
            </item>
          </activities>
          <chamber>House</chamber>
          <name>House Administration Committee</name>
        </item>
      </billCommittees>
    </committees>
    <originChamber>House</originChamber>
    <cosponsors>
      <item>
        <middleName>G.</middleName>
        <lastName>Reichert</lastName>
        <firstName>David</firstName>
        <bioguideId>R000578</bioguideId>
        <party>R</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <fullName>Rep. Reichert, David G. [R-WA-8]</fullName>
        <identifiers>
          <lisID>1810</lisID>
          <gpoId>8212</gpoId>
          <bioguideId>R000578</bioguideId>
        </identifiers>
        <district>8</district>
        <state>WA</state>
        <sponsorshipDate>2017-06-14</sponsorshipDate>
      </item>
      <item>
        <middleName />
        <lastName>Carson</lastName>
        <firstName>Andre</firstName>
        <bioguideId>C001072</bioguideId>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <fullName>Rep. Carson, Andre [D-IN-7]</fullName>
        <identifiers>
          <bioguideId>C001072</bioguideId>
          <gpoId>7946</gpoId>
          <lisID>1889</lisID>
        </identifiers>
        <district>7</district>
        <state>IN</state>
        <sponsorshipDate>2017-06-14</sponsorshipDate>
      </item>
      <item>
        <middleName>J.</middleName>
        <lastName>PASCRELL</lastName>
        <firstName>WILLIAM</firstName>
        <bioguideId>P000096</bioguideId>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>True</isOriginalCosponsor>
        <fullName>Rep. Pascrell, Bill, Jr. [D-NJ-9]</fullName>
        <identifiers>
          <lisID>1510</lisID>
          <gpoId>8050</gpoId>
          <bioguideId>P000096</bioguideId>
        </identifiers>
        <district>9</district>
        <state>NJ</state>
        <sponsorshipDate>2017-06-14</sponsorshipDate>
      </item>
      <item>
        <middleName>HOLMES</middleName>
        <lastName>NORTON</lastName>
        <firstName>ELEANOR</firstName>
        <bioguideId>N000147</bioguideId>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <fullName>Rep. Norton, Eleanor Holmes [D-DC-At Large]</fullName>
        <identifiers>
          <bioguideId>N000147</bioguideId>
          <lisID>868</lisID>
          <gpoId>7871</gpoId>
        </identifiers>
        <district>0</district>
        <state>DC</state>
        <sponsorshipDate>2017-06-26</sponsorshipDate>
      </item>
      <item>
        <middleName>M.</middleName>
        <lastName>VELAZQUEZ</lastName>
        <firstName>NYDIA</firstName>
        <bioguideId>V000081</bioguideId>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <fullName>Rep. Velazquez, Nydia M. [D-NY-7]</fullName>
        <identifiers>
          <gpoId>8073</gpoId>
          <lisID>1184</lisID>
          <bioguideId>V000081</bioguideId>
        </identifiers>
        <district>7</district>
        <state>NY</state>
        <sponsorshipDate>2017-06-26</sponsorshipDate>
      </item>
      <item>
        <middleName />
        <lastName>Loebsack</lastName>
        <firstName>David</firstName>
        <bioguideId>L000565</bioguideId>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <fullName>Rep. Loebsack, David [D-IA-2]</fullName>
        <identifiers>
          <bioguideId>L000565</bioguideId>
          <gpoId>7915</gpoId>
          <lisID>1846</lisID>
        </identifiers>
        <district>2</district>
        <state>IA</state>
        <sponsorshipDate>2017-06-26</sponsorshipDate>
      </item>
      <item>
        <middleName />
        <lastName>Comstock</lastName>
        <firstName>Barbara</firstName>
        <bioguideId>C001105</bioguideId>
        <party>R</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <fullName>Rep. Comstock, Barbara [R-VA-10]</fullName>
        <identifiers>
          <lisID>2273</lisID>
          <gpoId />
          <bioguideId>C001105</bioguideId>
        </identifiers>
        <district>10</district>
        <state>VA</state>
        <sponsorshipDate>2017-06-26</sponsorshipDate>
      </item>
      <item>
        <middleName>L.</middleName>
        <lastName>Kelly</lastName>
        <firstName>Robin</firstName>
        <bioguideId>K000385</bioguideId>
        <party>D</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <fullName>Rep. Kelly, Robin L. [D-IL-2]</fullName>
        <identifiers>
          <lisID>2190</lisID>
          <bioguideId>K000385</bioguideId>
          <gpoId />
        </identifiers>
        <district>2</district>
        <state>IL</state>
        <sponsorshipDate>2017-06-26</sponsorshipDate>
      </item>
      <item>
        <middleName>M.</middleName>
        <lastName>Donovan</lastName>
        <firstName>Daniel</firstName>
        <bioguideId>D000625</bioguideId>
        <party>R</party>
        <sponsorshipWithdrawnDate />
        <isOriginalCosponsor>False</isOriginalCosponsor>
        <fullName>Rep. Donovan, Daniel M., Jr. [R-NY-11]</fullName>
        <identifiers>
          <bioguideId>D000625</bioguideId>
          <gpoId />
          <lisID>2293</lisID>
        </identifiers>
        <district>11</district>
        <state>NY</state>
        <sponsorshipDate>2017-06-26</sponsorshipDate>
      </item>
    </cosponsors>
    <notes />
    <introducedDate>2017-06-14</introducedDate>
    <committeeReports />
    <createDate>2017-06-15T03:11:34Z</createDate>
    <actions>
      <item>
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <committee>
          <name>House Administration Committee</name>
          <systemCode>hsha00</systemCode>
        </committee>
        <actionDate>2017-06-14</actionDate>
        <actionCode>H11100</actionCode>
        <links />
        <type>IntroReferral</type>
        <text>Referred to the House Committee on House Administration.</text>
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <committee />
        <actionDate>2017-06-14</actionDate>
        <actionCode>Intro-H</actionCode>
        <links />
        <type>IntroReferral</type>
        <text>Introduced in House</text>
      </item>
      <item>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <committee />
        <actionDate>2017-06-14</actionDate>
        <actionCode>1000</actionCode>
        <links />
        <type>IntroReferral</type>
        <text>Introduced in House</text>
      </item>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
      <actionTypeCounts>
        <introducedInHouse>1</introducedInHouse>
        <introducedInTheHouse>1</introducedInTheHouse>
        <billReferrals>1</billReferrals>
      </actionTypeCounts>
    </actions>
    <updateDate>2017-08-10T12:27:05Z</updateDate>
    <billType>HCONRES</billType>
    <constitutionalAuthorityStatementText />
    <policyArea>
      <name>Congress</name>
    </policyArea>
    <congress>115</congress>
    <sponsors>
      <item>
        <fullName>Rep. Johnson, Eddie Bernice [D-TX-30]</fullName>
        <middleName>BERNICE</middleName>
        <identifiers>
          <bioguideId>J000126</bioguideId>
          <gpoId>8186</gpoId>
          <lisID>599</lisID>
        </identifiers>
        <lastName>JOHNSON</lastName>
        <firstName>EDDIE</firstName>
        <bioguideId>J000126</bioguideId>
        <party>D</party>
        <district>30</district>
        <byRequestType />
        <state>TX</state>
      </item>
    </sponsors>
    <recordedVotes />
    <calendarNumbers />
    <billNumber>64</billNumber>
    <summaries>
      <billSummaries>
        <item>
          <actionDesc>Introduced in House</actionDesc>
          <actionDate>2017-06-14</actionDate>
          <text><![CDATA[
Expresses the sense of Congress that: (1) the United States Capitol Police is an invaluable asset to Congress and the community; (2) its officers deserve the utmost appreciation and respect; and (3) the congressional community is expressly grateful for the innumerable contributions and sacrifices of its officers to secure the U.S. Capitol complex and protect Members of Congress, their staff, and the general public.
]]></text>
          <updateDate>2017-06-14T04:00:00Z</updateDate>
          <versionCode>00</versionCode>
          <lastSummaryUpdateDate>2017-07-05T18:27:47Z</lastSummaryUpdateDate>
          <name>Introduced in House</name>
        </item>
      </billSummaries>
    </summaries>
    <title>Expressing the sense of Congress regarding the United States Capitol Police and their role in securing the United States Capitol complex and protecting Members of Congress, their staff, and the general public.</title>
    <version>1.0.0</version>
    <titles>
      <item>
        <titleType>Official Title as Introduced</titleType>
        <chamberName />
        <parentTitleType />
        <chamberCode />
        <title>Expressing the sense of Congress regarding the United States Capitol Police and their role in securing the United States Capitol complex and protecting Members of Congress, their staff, and the general public.</title>
      </item>
      <item>
        <titleType>Display Title</titleType>
        <chamberName />
        <parentTitleType />
        <chamberCode />
        <title>Expressing the sense of Congress regarding the United States Capitol Police and their role in securing the United States Capitol complex and protecting Members of Congress, their staff, and the general public.</title>
      </item>
    </titles>
    <cboCostEstimates />
    <relatedBills />
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Congress</name>
        </policyArea>
        <legislativeSubjects>
          <item>
            <name>Congressional agencies</name>
          </item>
          <item>
            <name>Congressional officers and employees</name>
          </item>
          <item>
            <name>Congressional tributes</name>
          </item>
          <item>
            <name>Law enforcement officers</name>
          </item>
          <item>
            <name>Members of Congress</name>
          </item>
          <item>
            <name>Protection of officials</name>
          </item>
          <item>
            <name>U.S. Capitol</name>
          </item>
        </legislativeSubjects>
      </billSubjects>
    </subjects>
    <latestAction>
      <actionDate>2017-06-14</actionDate>
      <links />
      <text>Referred to the House Committee on House Administration.</text>
    </latestAction>
    <laws />
    <amendments />
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
#ifndef _COMMON_VERSION_H
#define _COMMON_VERSION_H

#include <common/config.h>

#ifdef  CONFIG_PRODUCT_NAME
#define PRODUCT_NAME    CONFIG_PRODUCT_NAME
#else
#define PRODUCT_NAME    "HAProxy"
#endif

#ifdef  CONFIG_PRODUCT_BRANCH
#define PRODUCT_BRANCH    CONFIG_PRODUCT_BRANCH
#else
#define PRODUCT_BRANCH   "1.5"
#endif

#ifdef  CONFIG_PRODUCT_URL
#define PRODUCT_URL    CONFIG_PRODUCT_URL
#else
#define PRODUCT_URL    "http://www.haproxy.org/"
#endif

#ifdef  CONFIG_PRODUCT_URL_UPD
#define PRODUCT_URL_UPD  CONFIG_PRODUCT_URL_UPD
#else
#define PRODUCT_URL_UPD "http://www.haproxy.org/#down"
#endif

#ifdef  CONFIG_PRODUCT_URL_DOC
#define PRODUCT_URL_DOC  CONFIG_PRODUCT_URL_DOC
#else
#define PRODUCT_URL_DOC "http://www.haproxy.org/#docs"
#endif

#ifdef CONFIG_HAPROXY_VERSION
#define HAPROXY_VERSION CONFIG_HAPROXY_VERSION
#else
#error "Must define CONFIG_HAPROXY_VERSION"
#endif

#ifdef CONFIG_HAPROXY_DATE
#define HAPROXY_DATE    CONFIG_HAPROXY_DATE
#else
#error "Must define CONFIG_HAPROXY_DATE"
#endif

#endif /* _COMMON_VERSION_H */


text:
import Flickr from "@/flickr"

export default function getPhotos(
  { flickr = Flickr, userId = `` } = {},
  {
    safeSearch = 0,
    minUploadDate = ``,
    maxUploadDate = ``,
    minTakenDate = ``,
    maxTakenDate = ``,
    contentType = 0,
    privacyFilter = 0,
    extras = ``,
    page = 1,
    perPage = 100
  } = {}
) {
  return flickr.fetchResource(
    `flickr.people.getPhotos`,
    { userId },
    {
      safeSearch,
      minUploadDate,
      maxUploadDate,
      minTakenDate,
      maxTakenDate,
      contentType,
      privacyFilter,
      extras,
      page,
      perPage
    }
  )
}


text:
file: 'drink-me'
title: 'Drink me'
date: 2015-03-17
license: 'by-sa'
lang_fr: '/fr/img/buvez-moi'
tags:
  - digital painting
  - fantasy
  - characters
  - sexy
  - black
  - brown
  - yellow
made:
  - Krita
---

My participation in the [Krita](https://krita.org/)'s forum [Monthly Drawing Challenge](https://forum.kde.org/viewtopic.php?f=277&t=125203).
This month topic was **Unusual Dinner**...

For the blue nymph, [reference photo by Marcus Ranum, with Amber G. posing](http://mjranum-stock.deviantart.com/art/Suspense-12-76092317).


text:
require "hbc/container/base"

module Hbc
  class Container
    class Zip < Base
      def self.me?(criteria)
        criteria.magic_number(%r{^PK(\003\004|\005\006)}n)
      end

      def extract
        Dir.mktmpdir do |unpack_dir|
          @command.run!("/usr/bin/ditto", args: ["-x", "-k", "--", @path, unpack_dir])

          extract_nested_inside(unpack_dir)
        end
      end
    end
  end
end


text:
package org.apache.ambari.server.bootstrap;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.ambari.server.utils.Closeables;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Runnable class that gets the hoststatus output by looking at the files
 * in a certain directory. Only meant to be useful for bootstrap as of now.
 */
class BSHostStatusCollector {
  private File requestIdDir;
  private List<BSHostStatus> hostStatus;
  public static final String logFileFilter = ".log";
  public static final String doneFileFilter = ".done";
  private static final Logger LOG = LoggerFactory.getLogger(BSHostStatusCollector.class);

  private List<String> hosts;

  public BSHostStatusCollector(File requestIdDir, List<String> hosts) {
    this.requestIdDir = requestIdDir;
    this.hosts = hosts;
  }

  public List<BSHostStatus> getHostStatus() {
    return hostStatus;
  }

  public void run() {
    LOG.info("Request directory " + requestIdDir);
    hostStatus = new ArrayList<>();
    if (hosts == null) {
      return;
    }
    File done;
    File log;
    LOG.info("HostList for polling on " + hosts);
    for (String host : hosts) {
      /* Read through the files and gather output */
      BSHostStatus status = new BSHostStatus();
      status.setHostName(host);
      done = new File(requestIdDir, host + doneFileFilter);
      log = new File(requestIdDir, host + logFileFilter);
      if (LOG.isDebugEnabled()) {
        LOG.debug("Polling bootstrap status for host, requestDir={}, host={}, doneFileExists={}, logFileExists={}", requestIdDir, host, done.exists(), log.exists());
      }
      if (!done.exists()) {
        status.setStatus("RUNNING");
      } else {
        status.setStatus("FAILED");
        try {
          String statusCode = FileUtils.readFileToString(done, Charset.defaultCharset()).trim();
          if (statusCode.equals("0")) {
            status.setStatus("DONE");
          }

          updateStatus(status, statusCode);
        } catch (IOException e) {
          LOG.info("Error reading done file " + done);
        }
      }
      if (!log.exists()) {
        status.setLog("");
      } else {
        String logString = "";
        BufferedReader reader = null;
        try {
          StringBuilder sb = new StringBuilder();
          reader = new BufferedReader(new FileReader(log));

          String line = null;
          while (null != (line = reader.readLine())) {
            if (line.startsWith("tcgetattr:") || line.startsWith("tput:"))
              continue;

            if (0 != sb.length() || 0 == line.length())
              sb.append('\n');

            if (-1 != line.indexOf ("\\n"))
              sb.append(line.replace("\\n", "\n"));
            else
              sb.append(line);
          }

          logString = sb.toString();
        } catch (IOException e) {
          LOG.info("Error reading log file " + log +
                  ". Log file may be have not created yet");
        } finally {
          Closeables.closeSilently(reader);
        }
        status.setLog(logString);
      }
      hostStatus.add(status);
    }
  }

  private void updateStatus(BSHostStatus status, String statusCode) {

    status.setStatusCode(statusCode);

    int reason = -1;
    try {
      reason = Integer.parseInt(statusCode);
    } catch (Exception ignored) {
    }

    switch (reason) {
    // case X: (as we find them)
    case 2:
      status.setStatusAction("Processing could not continue because the file was not found.");
      break;
    case 255:
    default:
      if (null != status.getLog()) {
        String lowerLog = status.getLog().toLowerCase();
        if (-1 != lowerLog.indexOf("permission denied") && -1 != lowerLog.indexOf("publickey")) {
          status.setStatusAction("Use correct SSH key");
        } else if (-1 != lowerLog.indexOf("connect to host")) {
          status.setStatusAction("Please verify that the hostname '" + status.getHostName() + "' is correct.");
        }
      }
      break;
    }

  }
}


text:
package umich.ms.util;

/**
 * Simple holder for an offset and length of an entry.
 *
 * @author Dmitry Avtonomov
 */
public class OffsetLength {

  /**
   * Offset
   */
  public final long offset;
  /**
   * Length
   */
  public final int length;

  public OffsetLength(long offset, int length) {
    this.offset = offset;
    this.length = length;
  }

  @Override
  public String toString() {
    return "[offset: " + offset + ", len: " + length + "]";
  }
}


text:
from simplediary import bcrypt, db
from sqlalchemy.ext.hybrid import hybrid_property
from flask.ext.login import UserMixin

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), nullable=False)
    email = db.Column(db.String(100), unique=True)
    _password = db.Column('password', db.String(140), nullable=False)
    diary = db.relationship("Diary", backref=db.backref('User'))

    @hybrid_property
    def password(self):
        return self._password

    @password.setter
    def _set_password(self, plaintext):
        self._password = bcrypt.generate_password_hash(plaintext).decode('utf-8')

    def is_correct_password(self, plaintext):
        return bcrypt.check_password_hash(self._password, plaintext)

class Pond(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    pondname = db.Column(db.String(140), nullable=False)
    diary = db.relationship("Diary", backref=db.backref('Pond'))

class Season(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    seasonname = db.Column(db.String(140), nullable=True)
    start_date = db.Column(db.Date, nullable=False)
    end_date = db.Column(db.Date)
    note = db.Column(db.Text)
    diary = db.relationship("Diary", backref=db.backref('Season'))

class Diary(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    pond_id = db.Column(db.Integer, db.ForeignKey('pond.id'), nullable=False)
    season_id = db.Column(db.Integer, db.ForeignKey('season.id'), nullable=False)
    stock_number = db.Column(db.Integer)
    feeding = db.Column(db.String(140))
    report = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    date = db.Column(db.Date, nullable=False)
    update_date = db.Column(db.TIMESTAMP(), nullable=False)
    created_date = db.Column(db.DateTime, nullable=False)
    pond = db.relationship("Pond", backref=db.backref('Diary'))
    season = db.relationship("Season", backref=db.backref('Diary'))
    user = db.relationship("User", backref=db.backref('Diary'))


text:
package org.hawkular.apm.api.model.config;

import java.text.NumberFormat;
import java.text.ParseException;

/**
 * This enumerated type defines the reporting levels for trace
 * instance information.
 *
 * @author gbrown
 */
public enum ReportingLevel {

    /* The activity associated with this transaction is not of interest
     * (i.e. long term decision) */
    Ignore,

    /* Don't report any instances of this transaction, but unlike the
     * 'Ignore' level, this may only be a temporary situation, and the
     * trace is of interest */
    None,

    /* Report all information related to instances of this transaction */
    All;

    public static ReportingLevel parse(Object obj) {
        if (obj instanceof ReportingLevel) {
            return (ReportingLevel) obj;
        }

        if (obj instanceof String) {
            return ReportingLevel.valueOf((String)obj);
        } else if (!(obj instanceof Number)) {
            return null;
        }

        int priority;
        try {
            priority = NumberFormat.getInstance().parse(obj.toString()).intValue();
        } catch (ParseException e) {
            return null;
        }

        if (priority >= 1) {
            return ReportingLevel.All;
        }

        return ReportingLevel.None;
    }

}


text:
package com.lambtors.poker_api.module.poker.infrastructure.stub

import com.lambtors.poker_api.module.poker.application.flop.AddFlopCardsToTableCommand

object AddFlopCardsToTableCommandStub {
  def create(gameId: String = GameIdStub.random().gameId.toString): AddFlopCardsToTableCommand =
    AddFlopCardsToTableCommand(gameId)

  def random(): AddFlopCardsToTableCommand = create()
}


text:
package org.springframework.security.config.annotation.web.configurers;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;

import jakarta.servlet.http.HttpSession;
import org.assertj.core.api.Condition;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.annotation.SecurityTestExecutionListeners;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Tests to verify that all the functionality of <logout> attributes is present
 *
 * @author Rob Winch
 * @author Josh Cummings
 */
@ExtendWith({ SpringExtension.class, SpringTestContextExtension.class })
@SecurityTestExecutionListeners
public class NamespaceHttpLogoutTests {

	public final SpringTestContext spring = new SpringTestContext(this);

	@Autowired
	MockMvc mvc;

	/**
	 * http/logout equivalent
	 */
	@Test
	@WithMockUser
	public void logoutWhenUsingDefaultsThenMatchesNamespace() throws Exception {
		this.spring.register(HttpLogoutConfig.class).autowire();
		// @formatter:off
		this.mvc.perform(post("/logout").with(csrf()))
				.andExpect(authenticated(false))
				.andExpect(redirectedUrl("/login?logout"))
				.andExpect(noCookies())
				.andExpect(session(Objects::isNull));
		// @formatter:on
	}

	@Test
	@WithMockUser
	public void logoutWhenDisabledInLambdaThenRespondsWithNotFound() throws Exception {
		this.spring.register(HttpLogoutDisabledInLambdaConfig.class).autowire();
		MockHttpServletRequestBuilder logoutRequest = post("/logout").with(csrf()).with(user("user"));
		this.mvc.perform(logoutRequest).andExpect(status().isNotFound());
	}

	/**
	 * http/logout custom
	 */
	@Test
	@WithMockUser
	public void logoutWhenUsingVariousCustomizationsMatchesNamespace() throws Exception {
		this.spring.register(CustomHttpLogoutConfig.class).autowire();
		// @formatter:off
		this.mvc.perform(post("/custom-logout").with(csrf()))
				.andExpect(authenticated(false))
				.andExpect(redirectedUrl("/logout-success"))
				.andExpect((result) -> assertThat(result.getResponse().getCookies()).hasSize(1))
				.andExpect(cookie().maxAge("remove", 0))
				.andExpect(session(Objects::nonNull));
		// @formatter:on
	}

	@Test
	@WithMockUser
	public void logoutWhenUsingVariousCustomizationsInLambdaThenMatchesNamespace() throws Exception {
		this.spring.register(CustomHttpLogoutInLambdaConfig.class).autowire();
		// @formatter:off
		this.mvc.perform(post("/custom-logout").with(csrf()))
				.andExpect(authenticated(false))
				.andExpect(redirectedUrl("/logout-success"))
				.andExpect((result) -> assertThat(result.getResponse().getCookies()).hasSize(1))
				.andExpect(cookie().maxAge("remove", 0))
				.andExpect(session(Objects::nonNull));
		// @formatter:on
	}

	/**
	 * http/logout@success-handler-ref
	 */
	@Test
	@WithMockUser
	public void logoutWhenUsingSuccessHandlerRefThenMatchesNamespace() throws Exception {
		this.spring.register(SuccessHandlerRefHttpLogoutConfig.class).autowire();
		// @formatter:off
		this.mvc.perform(post("/logout").with(csrf()))
				.andExpect(authenticated(false))
				.andExpect(redirectedUrl("/SuccessHandlerRefHttpLogoutConfig"))
				.andExpect(noCookies())
				.andExpect(session(Objects::isNull));
		// @formatter:on
	}

	@Test
	@WithMockUser
	public void logoutWhenUsingSuccessHandlerRefInLambdaThenMatchesNamespace() throws Exception {
		this.spring.register(SuccessHandlerRefHttpLogoutInLambdaConfig.class).autowire();
		// @formatter:off
		this.mvc.perform(post("/logout").with(csrf()))
				.andExpect(authenticated(false))
				.andExpect(redirectedUrl("/SuccessHandlerRefHttpLogoutConfig"))
				.andExpect(noCookies())
				.andExpect(session(Objects::isNull));
		// @formatter:on
	}

	ResultMatcher authenticated(boolean authenticated) {
		return (result) -> assertThat(Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
				.map(Authentication::isAuthenticated).orElse(false)).isEqualTo(authenticated);
	}

	ResultMatcher noCookies() {
		return (result) -> assertThat(result.getResponse().getCookies()).isEmpty();
	}

	ResultMatcher session(Predicate<HttpSession> sessionPredicate) {
		return (result) -> assertThat(result.getRequest().getSession(false))
				.is(new Condition<>(sessionPredicate, "sessionPredicate failed"));
	}

	@EnableWebSecurity
	static class HttpLogoutConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) {
		}

	}

	@EnableWebSecurity
	static class HttpLogoutDisabledInLambdaConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.logout(AbstractHttpConfigurer::disable);
		}

	}

	@EnableWebSecurity
	static class CustomHttpLogoutConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.logout()
					.deleteCookies("remove") // logout@delete-cookies
					.invalidateHttpSession(false) // logout@invalidate-session=false (default is true)
					.logoutUrl("/custom-logout") // logout@logout-url (default is /logout)
					.logoutSuccessUrl("/logout-success"); // logout@success-url (default is /login?logout)
			// @formatter:on
		}

	}

	@EnableWebSecurity
	static class CustomHttpLogoutInLambdaConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.logout((logout) ->
						logout.deleteCookies("remove")
							.invalidateHttpSession(false)
							.logoutUrl("/custom-logout")
							.logoutSuccessUrl("/logout-success")
				);
			// @formatter:on
		}

	}

	@EnableWebSecurity
	static class SuccessHandlerRefHttpLogoutConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
			logoutSuccessHandler.setDefaultTargetUrl("/SuccessHandlerRefHttpLogoutConfig");
			// @formatter:off
			http
				.logout()
					.logoutSuccessHandler(logoutSuccessHandler);
			// @formatter:on
		}

	}

	@EnableWebSecurity
	static class SuccessHandlerRefHttpLogoutInLambdaConfig extends WebSecurityConfigurerAdapter {

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			SimpleUrlLogoutSuccessHandler logoutSuccessHandler = new SimpleUrlLogoutSuccessHandler();
			logoutSuccessHandler.setDefaultTargetUrl("/SuccessHandlerRefHttpLogoutConfig");
			// @formatter:off
			http
				.logout((logout) -> logout.logoutSuccessHandler(logoutSuccessHandler));
			// @formatter:on
		}

	}

}


text:
[![license](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/polylingo/l20n.cs/blob/master/LICENSE.md)

An implementation of Mozilla's l20n in C#, supporting .NET2 and above.

Tested on:

+ GlenDC's dev machine: `MonoDevelop 4.0.1 - Mono / .NET 2.0`
+ Travis: `mono (latest)`, `mono 3.10.0`, `3.8.0`

## Documentation

Documentation is generated via _Doxygen_.
HTML documentation for the latest _L20n.cs_ release can be found at:

https://polylingo.github.io/l20n.cs/


text:
require 'sqlite3'

class MemMC
	attr_reader :order

	def initialize(order)
		@order = order
		clear
	end

	def add_beginning(state)
		@beg << state
	end

	def add_follow(lead, follow)
		@freq[lead] ||= []
		@freq[lead] << follow
	end

	def single_transaction(&block)
		block.call
	end

	def get_beginning
		len = @beg.size
		return [ @beg[rand(len)] ]
	end

	def get_follow(state)
		possible = @freq[state]
		return nil if possible.nil?
		len = possible.size
		return [ possible[rand(len)] ]
	end

	def clear
		@beg = []
		@freq = {}
	end
end

class SqliteMC
	DB_FILE = "dbs/markov.db"

	attr_reader :order

	def initialize(order)
		@order = order

		@db = SQLite3::Database.new(DB_FILE)
		init_db if db_empty?
		@add_freq_prep = @db.prepare("INSERT INTO freq VALUES(?, ?)")
		@add_beg_prep = @db.prepare("INSERT INTO beginnings VALUES(?)")
	end

	def add_beginning(state)
		@add_beg_prep.execute(state)
	end

	def add_follow(lead, follow)
		@add_freq_prep.execute(lead, follow)
	end

	def single_transaction(&block)
		@db.transaction {
			block.call
		}
	end

	def get_beginning
		return @db.get_first_row(
			"SELECT * FROM beginnings " +
			"ORDER BY RANDOM() " +
			"LIMIT 1").join.split
	end

	def get_follow(state)
		return @db.get_first_row(
			"SELECT follow FROM freq " +
			"WHERE lead = ? " +
			"ORDER BY RANDOM() " +
			"LIMIT 1", state)
	end

	def clear
		drop_tables
		init_db
	end

	def vacuum
		before = File.size(DB_FILE)
		@db.execute("VACUUM beginnings")
		@db.execute("VACUUM freq")
		after = File.size(DB_FILE)
		return before - after
	end

private

	def db_empty?
		begin
			@db.execute("SELECT COUNT(*) FROM freq")
			return false
		rescue
			return true
		end
	end

	def init_db
		@db.execute("CREATE TABLE beginnings(lead varchar(64))")
		@db.execute("CREATE TABLE freq(lead varchar(64), follow varchar(64))")
		@db.execute("CREATE INDEX ilead ON freq (lead)")
	end

	def drop_tables
		@db.execute("DROP TABLE beginnings");
		@db.execute("DROP TABLE freq");
	end

end

# A sentence-parsing markov chain that can generate new sentences.
class EnglishMC
	def initialize(impl)
		@impl = impl
		@order = impl.order
	end

	def add_text(text)
		@impl.single_transaction {
			# Make sure each line ends with some sentence terminator.
			text.gsub!(/[\n\r]+/m, " . ")
			text << "." if text[-1,1] != "."
			seps = /(https?:\/\/\S+|[.!?]($|\s))/
			sentence = ""
			text.split(seps).grep(/\S/).each { |p|
				if seps =~ p
					add_sentence(sentence, p)
					sentence = ""
				else
					sentence += p
				end
			}
		}
	end

	def generate_sentence
		beg = @impl.get_beginning
		return generate_sentence_from(beg) if beg[0]
	end

	def generate_sentence_from(beginning)
		res = beginning
		loop do
			unless nw = next_word_for(res[-@order, @order])
				return res[0..-2].join(' ') + res.last
			end
			res << nw
		end
		return res
	end

private

	def add_sentence(str, terminator)
		words = str.scan(is_word)
		return unless words.size >= @order # Ignore short sentences.
		words[0][0..0] = words[0][0..0].upcase # Capitalize sentence.
		words << terminator
		buf = []
		words.each do |w|
			buf << w
			if buf.size >= @order + 1
				lead = buf[0..-2]
				follow = buf[-1]
				@impl.add_follow(lead.join(' '), follow)
				buf.shift
			end
		end
		beg = words[0, @order]
		@impl.add_beginning(beg.join(' '))
	end

	def next_word_for(words)
		row = @impl.get_follow(words.join(' '))
		if row.nil?
			return nil
		else
			return row.join
		end
	end

	def is_word
		if @order == 1
			return /[a-zA-Z0-9$,'-_]+/
		elsif @order == 2
			return /[a-zA-Z0-9$,'-_:;\/]+/
		else
			return /[a-zA-Z0-9$,'"-_:;\/\(\)]+/
		end
	end
end

class Markov < RubotPlugin
	@@actions = [
		[/^:generate (\d+)/i, :generate_x],
		[/^:generate/i, :generate],
		[/^:populate/i, :populate],
		[/^:vacuum/i, :vacuum],
	]

	def initialize
		super
		@working = false
		@cooldown = IRCCooldown.new(self, 3,
			"Please wait %s more second%s to generate a sentence.")
#		@backend = SqliteMC.new(1)
		@backend = MemMC.new(1)
		@mc = EnglishMC.new(@backend)
	end

	def on_privmsg(user, source, msg)
		return if @working
		jumped = RegexJump::jump(@@actions, self, msg, [user, source])
		@cooldown.trigger_now if jumped # For long operations.
		add_line(rm_nicks(msg)) if not jumped and valid_line(msg)
	end

	def generate(user, source)
		return unless @cooldown.trigger_err(source)
		sent = @mc.generate_sentence
		say(source, put_nicks(sent, user.nick)) if sent
	end

	def generate_x(user, source, x)
		return if @working
		return unless @cooldown.trigger_err(source)
		work {
			track_time(source) {
				x.times { @mc.generate_sentence }
			}
		}
	end

	def populate(user, source)
		work {
			track_time(source) {
				say(source, "Constructing database...")
				@backend.clear
				Dir.glob("privmsg_logs/*.txt").each do |file|
					@mc.add_text(IO.read(file))
				end
				say(source, "Finished.")
			}
		}
	end

	def vacuum(user, source)
		if not @backend.respond_to? :vacuum
			say(source, "Current markov backend does not need vacuuming.")
			return
		end
		work {
			track_time(source) {
				say(source, "Vacuuming database...")
				reduced = @backend.vacuum
				say(source, "Reduced database size by #{reduced} bytes.")
			}
		}
	end

private

	NICK_SUB = "::NICK::"

	def rm_nicks(str)
		Users.each do |nick, user|
			str.gsub!(nick, NICK_SUB)
		end
		return str
	end

	def put_nicks(str, nick)
		return str.gsub(NICK_SUB, nick)
	end

	# Work in a background thread so we don't disconnect if we take too long, and
	# block all other calls to the database.
	def work(&block)
		Thread.new {
			@working = true
			block.call
			@working = false
		}
	end

	# Print the time a possibly long-standing operation takes.
	def track_time(source, &block)
		before = Time.now
		block.call
		after = Time.now
		say(source, "Took #{after-before} seconds.")
	end

	def valid_line(msg)
		# Only accept ASCII lines without NULLs or IRC control characters.
		return !msg.match(/[\x00\x01\x80-\xff]/)
	end

	def add_line(msg)
		open("privmsg_logs/#{@client.nick}.txt", "a") do |f|
			f.puts(msg)
		end
		@mc.add_text(msg)
	end
end


text:
package com.sixrr.stockmetrics.classCalculators;

import com.sixrr.stockmetrics.halstead.HalsteadVisitor;

public class HalsteadLengthClassCalculator extends HalsteadClassCalculator
{

	@Override
	protected double calculateValue(HalsteadVisitor visitor)
	{
		return (double) visitor.getLength();
	}
}


text:
package com.yeahmama.tennis.score;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.assertj.core.api.Assertions.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class TennisScoreTableTest {

    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
    private final PrintStream originalOut = System.out;
    private final PrintStream originalErr = System.err;

    @InjectMocks
    private TennisScoreTable tennisScoreTable;

    @Before
    public void setUp() {
        System.setOut(new PrintStream(outContent));
        System.setErr(new PrintStream(errContent));
    }

    public void should_add_game_over_column_to_game_score_table_when_a_player_wins_4_points() {
        // Arrange
        tennisScoreTable.addPointCol("Player 1", 1, 0);
        tennisScoreTable.addPointCol("Player 1", 2, 0);
        tennisScoreTable.addPointCol("Player 1", 3, 0);

        // Act
        tennisScoreTable.addGameOverCol("Player 1");

        // Assert
        assertThat(tennisScoreTable.getGameScoreHeader().get(4)).isEqualTo("Player 1 wins 1 point");
        assertThat(tennisScoreTable.getGameScorePlayerOneRow().get(4)).isEqualTo("0");
        assertThat(tennisScoreTable.getGameScorePlayerTwoRow().get(4)).isEqualTo("0");
        assertThat(tennisScoreTable.getGameScoreWinnerRow().get(4)).isEqualTo("Player 1 wins the game");
    }

    @Test
    public void should_add_point_column_to_game_score_table_when_it_has_a_point_winner() {
        // Act
        tennisScoreTable.addPointCol("Player 1", 1, 0);

        // Assert
        assertThat(tennisScoreTable.getGameScoreHeader().get(2)).isEqualTo("Player 1 wins 1 point");
        assertThat(tennisScoreTable.getGameScorePlayerOneRow().get(2)).isEqualTo("15");
        assertThat(tennisScoreTable.getGameScorePlayerTwoRow().get(2)).isEqualTo("0");
        assertThat(tennisScoreTable.getGameScoreWinnerRow().get(2)).isEqualTo("");
    }

    @Test
    public void should_have_tennis_game_score_table_initialized() {
        // Act
        tennisScoreTable.display();

        // Assert
        assertThat(displayGameScoreTableInit()).isEqualTo(outContent.toString());
    }

    private String displayGameScoreTableInit() {
        return "Game score\n" +
                "+----------+----------------+\n" +
                "|          | Start the game |\n" +
                "+----------+----------------+\n" +
                "| Player 1 | 0              |\n" +
                "| Player 2 | 0              |\n" +
                "|          |                |\n" +
                "+----------+----------------+\n";
    }

    @Test
    public void should_have_tennis_game_score_table_with_one_point_column_when_adding_one_point() {
        // Arrange
        tennisScoreTable.addPointCol("Player 1", 1, 0);

        // Act
        tennisScoreTable.display();

        // Assert
        assertThat(displayGameScoreTableWithOnePoint()).isEqualTo(outContent.toString());
    }

    private String displayGameScoreTableWithOnePoint() {
        return "Game score\n" +
                "+----------+----------------+-----------------------+\n" +
                "|          | Start the game | Player 1 wins 1 point |\n" +
                "+----------+----------------+-----------------------+\n" +
                "| Player 1 | 0              | 15                    |\n" +
                "| Player 2 | 0              | 0                     |\n" +
                "|          |                |                       |\n" +
                "+----------+----------------+-----------------------+\n";
    }

    @Test
    public void should_have_final_tennis_game_score_table_when_adding_game_over_column() {
        // Arrange
        tennisScoreTable.addPointCol("Player 1", 1, 0);
        tennisScoreTable.addPointCol("Player 1", 2, 0);
        tennisScoreTable.addPointCol("Player 1", 3, 0);
        tennisScoreTable.addGameOverCol("Player 1");

        // Act
        tennisScoreTable.display();

        // Assert
        assertThat(displayFinalGameScoreTable()).isEqualTo(outContent.toString());
    }

    private String displayFinalGameScoreTable() {
        return "Game score\n" +
                "+----------+----------------+-----------------------+-----------------------+-----------------------+------------------------+\n" +
                "|          | Start the game | Player 1 wins 1 point | Player 1 wins 1 point | Player 1 wins 1 point | Player 1 wins 1 point  |\n" +
                "+----------+----------------+-----------------------+-----------------------+-----------------------+------------------------+\n" +
                "| Player 1 | 0              | 15                    | 30                    | 40                    | 0                      |\n" +
                "| Player 2 | 0              | 0                     | 0                     | 0                     | 0                      |\n" +
                "|          |                |                       |                       |                       | Player 1 wins the game |\n" +
                "+----------+----------------+-----------------------+-----------------------+-----------------------+------------------------+\n";
    }

    @After
    public void tearDown() {
        System.setOut(originalOut);
        System.setErr(originalErr);
    }

}