text:
Package('Browse.Controllers', {
	Browse : new  Class({
		Extends: Sapphire.Controller,

		initialize : function()
		{
			this.parent();
			SAPPHIRE.application.listen('start', this.onStart.bind(this));
			SAPPHIRE.application.listen('ready', this.onReady.bind(this));
		},

		onStart : function(callback)
		{
			BROWSE.service.start();
			callback();
		},

		onReady : function()
		{
			this.view = new Browse.Views.Browse();
			SAPPHIRE.application.showPage('catalog');
			BROWSE.service.message('karaoke/catalog/listenUpdate', {});
		}
	})
});

SAPPHIRE.application.registerController('browse', new Browse.Controllers.Browse());


text:
package connect.ui.activity.login;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import connect.ui.activity.R;
import connect.ui.activity.home.HomeActivity;
import connect.ui.activity.login.bean.UserBean;
import connect.ui.activity.login.contract.CodeLoginContract;
import connect.ui.activity.login.presenter.CodeLoginPresenter;
import connect.ui.activity.set.PatternActivity;
import connect.ui.base.BaseActivity;
import connect.utils.ActivityUtil;
import connect.utils.DialogUtil;
import connect.utils.ProgressUtil;
import connect.utils.RegularUtil;
import connect.utils.glide.GlideUtil;
import connect.view.TopToolBar;
import connect.view.roundedimageview.RoundedImageView;

/**
 * Login phone number verification
 * Created by john on 2016/11/29.
 */
public class CodeLoginActivity extends BaseActivity implements CodeLoginContract.View {

    @Bind(R.id.toolbar_top)
    TopToolBar toolbarTop;
    @Bind(R.id.userhead_img)
    RoundedImageView userheadImg;
    @Bind(R.id.nickname_et)
    TextView nicknameEt;
    @Bind(R.id.password_et)
    EditText passwordEt;
    @Bind(R.id.passwordhint_tv)
    TextView passwordhintTv;
    @Bind(R.id.next_btn)
    Button nextBtn;
    @Bind(R.id.passwordedit_tv)
    TextView passwordeditTv;

    private CodeLoginActivity mActivity;
    private CodeLoginContract.Presenter presenter;
    private UserBean userBean;
    private String token = "";

    public static void startActivity(Activity activity, UserBean userBean) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", userBean);
        ActivityUtil.next(activity, CodeLoginActivity.class, bundle);
    }

    public static void startActivity(Activity activity, UserBean userBean, String token) {
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", userBean);
        bundle.putString("token", token);
        ActivityUtil.next(activity, CodeLoginActivity.class, bundle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_code);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    public void initView() {
        mActivity = this;
        toolbarTop.setLeftImg(R.mipmap.back_black);
        toolbarTop.setTitleImg(R.mipmap.logo_black_middle);
        Bundle bundle = getIntent().getExtras();
        userBean = (UserBean) bundle.getSerializable("user");
        token = bundle.getString("token", "");
        setPresenter(new CodeLoginPresenter(this));

        passwordEt.addTextChangedListener(textWatcher);
        nicknameEt.setText(userBean.getName());
        GlideUtil.loadAvater(userheadImg, userBean.getAvatar());
        if (TextUtils.isEmpty(token)) {
            if (!TextUtils.isEmpty(userBean.getPassHint())) {
                passwordhintTv.setText(getString(R.string.Login_Password_Hint, userBean.getPassHint()));
            }
            passwordeditTv.setVisibility(View.GONE);
            passwordEt.setHint(R.string.Login_Password);
        } else {
            passwordhintTv.setText(getString(R.string.Login_Password_Hint, getString(R.string.Login_Not_set)));
            nextBtn.setText(R.string.Login_Reset_Password_And_Login);
        }
    }

    @Override
    public Activity getActivity() {
        return mActivity;
    }

    @Override
    public void setPresenter(CodeLoginContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @OnClick(R.id.left_img)
    void goBack(View view) {
        ActivityUtil.goBack(mActivity);
    }

    @OnClick(R.id.next_btn)
    void nextBtn(View view) {
        if (TextUtils.isEmpty(token)) {//Login password directly
            ProgressUtil.getInstance().showProgress(mActivity);
            presenter.checkTalkKey(userBean.getTalkKey(), passwordEt.getText().toString(),userBean);
        } else {//Scan the private key to log in
            if(RegularUtil.matches(passwordEt.getText().toString(), RegularUtil.PASSWORD)){
                ProgressUtil.getInstance().showProgress(mActivity);
                presenter.requestSetPassword(passwordEt.getText().toString(),userBean,token);
            }else{
                DialogUtil.showAlertTextView(mActivity, getString(R.string.Set_tip_title),
                        getString(R.string.Login_letter_number_and_character_must_be_included_in_your_login_password),
                        "", "", true, new DialogUtil.OnItemClickListener() {
                            @Override
                            public void confirm(String value) {

                            }

                            @Override
                            public void cancel() {

                            }
                        });
            }
        }
    }

    @OnClick(R.id.passwordedit_tv)
    void editPasswordHint(View view){
        DialogUtil.showEditView(mActivity, mActivity.getResources().getString(R.string.Login_Login_Password_Hint_Title),"", "", "", "", "",
                false,15,new DialogUtil.OnItemClickListener() {
            @Override
            public void confirm(String value) {
                presenter.setPasswordHintData(value);
                passwordhintTv.setText(getString(R.string.Login_Password_Hint,value));
            }

            @Override
            public void cancel() {

            }
        });
    }

    @Override
    public void setNextBtnEnable(boolean isEnable) {
        nextBtn.setEnabled(isEnable);
    }

    @Override
    public void setPasswordhint(String text) {
        passwordhintTv.setText(text);
    }

    @Override
    public void goinHome(boolean isBack) {
        if(isBack){
            HomeActivity.startActivity(mActivity);
        }else{
            PatternActivity.startActivity(mActivity,PatternActivity.LOGIN_STYPE);
        }
        mActivity.finish();
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            presenter.passEditChange(passwordEt.getText().toString(), nicknameEt.getText().toString());
        }
    };
}

redpajama_set_name: RedPajamaGithub


text:
(project created ca. March 2014)

A minimalistic image viewer that supports animated .gifs and transparency.
One of my earliest projects and thus one of my worst in terms of code quality.
To open an image, either drag it onto the executable or use the "Open with..." dialog. Once the program is started, press CTRL + H for help.


text:
/*
 * Created on 8-Jan-2004
 *
 * To change this generated comment go to
 * Window>Preferences>Java>Code Generation>Code Template
 */
package org.eclipse.releng;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Properties;
import java.io.PrintWriter;

/**
 * @author SDimitrov
 *
 * This class finds an available build machine by reading a registry of build
 * machines and their status.
 *
 */
public class BuildMachineManager extends Thread {
	// registry mapping of machines being used by a given build
	//list is the path to the configuration of build machines available for a
	// given build type
	// waitInterval is the number of seconds to wait if no machines are
	// available for a given build purpose
	// findKey represents the key in cfg from which which to obtain the list of
	// machines
	// createKey is written to the registry with the machine name that is
	// available

	private String markerContainer;
	private int waitInterval;
	private String markerName;
	private String markerKey="0";
	private String cfgKey;
	private String cfg;

	public BuildMachineManager() {
		super();
	}
	public BuildMachineManager(
		String cfg,
		String markerContainer,
		int waitInterval,
		String markerName,
		String markerKey,
		String cfgKey) {
		this.waitInterval = waitInterval;
		this.cfg = cfg;
		this.markerContainer = markerContainer;
		this.markerName = markerName;
		this.markerKey = markerKey;
		this.cfgKey = cfgKey;
		this.run();
	}

	public void run() {
		String[] machines = getNames();

		if (new File(markerContainer+"/"+markerName+".marker").exists()){
			System.out.println("Marker already exists: "+markerName+".marker");
			return;
		}

		boolean machineFound = false;
		try {
			while (!machineFound) {
				for (int i = 0; i < machines.length; i++) {
					if (!inUse(machines[i])) {
						if (createNewMarker(machines[i])) {
							machineFound = true;
							return;
						}
					}
				}

				//wait a given interval before re-checking for an available
				// build machine.
				sleep(1000 * waitInterval);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private boolean createNewMarker(String machineName) {
		//create a temporary lock on marker container

		File lock = new File(markerContainer + "/" + "lock");
		if (lock.exists())
			return false;

		try {
			File markerFile =  new File(markerContainer+"/"+markerName+".marker");
			lock.createNewFile();
			markerFile.createNewFile();
			PrintWriter out = new PrintWriter(new FileWriter(markerFile));
			out.println(markerKey+"=" + machineName);
			out.flush();
			out.close();
			lock.delete();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private boolean inUse(String machineName) {

		File container = new File(markerContainer);

		if (container.exists() && container.isDirectory()) {
			Properties properties = null;
			File[] markerFiles = container.listFiles();
			for (int i = 0; i < markerFiles.length; i++) {
				File markerFile = markerFiles[i];
				if (markerFile.getName().endsWith(".marker")) {
					properties = new Properties();
					try {
						FileInputStream in = new FileInputStream(markerFiles[i]);
						properties.load(in);
						in.close();
						if (properties.containsValue(machineName)){
							return true;
						}
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return false;
	}

	private String[] getNames() {
		StringTokenizer tokenizer = new StringTokenizer(getList(), ",");
		String[] names = new String[tokenizer.countTokens()];
		int i = 0;

		while (tokenizer.hasMoreTokens()) {
			names[i++] = tokenizer.nextToken();
		}
		return names;
	}

	private String getList() {
		Properties cfgProperties = new Properties();
		try {
			FileInputStream in = new FileInputStream(new File(cfg));
			cfgProperties.load(in);
			in.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return cfgProperties.getProperty(cfgKey);
	}
}


text:
/* Projector
 * Used to play the staged productions
 */

var Projector = (function(window, document, hyperaudio, Popcorn) {
  var DEBUG = false;

  function Projector(options) {
    this.options = hyperaudio.extend(
      {},
      this.options,
      {
        entity: 'PROJECTOR', // Not really an option... More like a manifest

        target: '#transcript-video', // The selector of element where the video is generated

        trim: 1, // (Seconds) Time added to end word timings.

        players: 2, // Number of Players to use. Mobile: 1, Desktop: 2.

        unit: 0.001, // Unit used if not given in section attr of stage.

        stageChangeDelay: 1000, // (ms) Delay for content update after the stage is changed

        timeAttr: 'data-m',

        music: null, // For the BGM

        gui: true, // True to add a gui.
        async: true // When true, some operations are delayed by a timeout.
      },
      options
    );

    // Properties
    this.target =
      typeof this.options.target === 'string'
        ? document.querySelector(this.options.target)
        : this.options.target;
    this.stage = null;
    this.timeout = {};

    this.player = [];

    this.activePlayer = 0;
    this.nextPlayer = this.options.players > 1 ? 1 : 0;

    this.updateRequired = false;

    this.stageArticle = null;
    this.stageSections = null;
    this.stageIndex = 0; // [Number] The next section
    this.content = []; // [Array] Holding the sections found with content
    this.contentIndex = 0; // [Number] The content that is actually being played.
    this.firstContent = true; // [Boolean] True the first time
    this.endedContent = false; // [Boolean] True when we have no more content

    this.isReadyToPlay = false; // [Boolean] True is the projector is setup and only needs a play to resume.
    this.needsInitVideo = true; // [Boolean] True when the projector is empty and the first video should be loaded in.

    // State Flags
    this.paused = true;

    this.time = {};

    this.iScrollOptions = {
      scrollbars: true,
      mouseWheel: true,
      interactiveScrollbars: true,

      // Options to disable grabbing the page and moving it.
      disableMouse: true,
      disablePointer: true,
      disableTouch: true
    };
    this.iScrollSpeed = 800; // ms
    this.iScrollOffsetY = -20; // pixels
    this.iScroll = null;

    if (this.options.DEBUG) {
      this._debug();
    }

    if (this.target) {
      this.create();
    }
  }

  Projector.prototype = {
    setStage: function(stage) {
      this.stage = stage;
      this.iScroll = new IScroll(this.stage.target, this.iScrollOptions);
    },
    create: function() {
      var self = this;

      if (this.target) {
        var getManager = function(idx) {
          return function(event) {
            // Passing the event context to manager
            //  * The YouTube event object is useless.
            //  * The YouTube event context was fixed in the Player class.
            if (self.activePlayer === idx) {
              self.manager(this, event);
            }
          };
        };

        for (var i = 0; i < this.options.players; i++) {
          var manager = getManager(i);

          var player = document.createElement('div');
          hyperaudio.addClass(player, 'hyperaudio-projector');
          this.player[i] = hyperaudio.Player({
            target: player
          });

          this.player[i].addEventListener('progress', manager); // Important for YT player GUI to update on set/change
          this.player[i].addEventListener('timeupdate', manager);
          this.player[i].addEventListener('play', manager);
          this.player[i].addEventListener('pause', manager);
          this.player[i].addEventListener('ended', manager);

          this.target.appendChild(player);
        }

        this.addHelpers();

        if (this.options.gui) {
          this.GUI = new hyperaudio.PlayerGUI({
            player: this,

            navigation: false, // next/prev buttons
            fullscreen: true, // fullscreen button

            cssClass: this.player[0].options.cssClass
          });
        }
      } else {
        this._error('Target not found : ' + this.options.target);
      }
    },
    addHelpers: function() {
      var fxHelper = document.createElement('div');
      fxHelper.id = 'fxHelper';
      fxHelper.className = 'video-transition-servo';
      fxHelper.appendChild(document.createElement('div'));

      var titleFXHelper = document.createElement('div');
      titleFXHelper.id = 'titleFXHelper';
      titleFXHelper.className = 'title-effect-servo';

      this.target.appendChild(fxHelper);
      this.target.appendChild(titleFXHelper);
    },
    initPopcorn: function(index, player) {
      var self = this;
      var elems, e, eLen;
      var onNewPara = function(parent) {
        self.iScroll.scrollToElement(parent, self.iScrollSpeed, null, self.iScrollOffsetY);
      };

      if (index < this.content.length && player < this.player.length) {
        // Reset the popcorn... Maybe want to only do this if necessary, ie., if any transcript plugins added.
        this.player[player].initPopcorn();
        if (DEBUG) console.log('[Projector|initPopcorn] player[%d].initPopcorn()', player);

        elems = this.content[index].element.getElementsByTagName('a');
        // Setup the Popcorn Transcript Plugin
        for (e = 0, eLen = elems.length; e < eLen; e++) {
          // Might want to move this (behaviour) to the plugin
          // hyperaudio.removeClass(elems[e], 'transcript-grey');

          this.player[player].popcorn.transcript({
            time: elems[e].getAttribute(this.options.timeAttr) * this.content[index].unit, // seconds
            futureClass: 'transcript-grey',
            target: elems[e],
            onNewPara: onNewPara
          });
        }
      }
    },
    load: function(index) {
      var media = this.content[index].media,
        activePlayer = this.which(media);

      this.contentIndex = index;

      if (activePlayer !== false) {
        this.activePlayer = activePlayer;
      } else {
        this.player[this.activePlayer].load(media);
        if (DEBUG)
          console.log('[Projector|load] player[%d].load() | initPopcorn()', this.activePlayer);
      }

      this.initPopcorn(index, this.activePlayer);

      for (var i = 0; i < this.player.length; i++) {
        hyperaudio.removeClass(this.player[i].target, 'active');
      }
      hyperaudio.addClass(this.player[this.activePlayer].target, 'active');

      if (DEBUG)
        console.log(
          '[Projector|load] contentIndex: %d | activePlayer: %d',
          this.contentIndex,
          this.activePlayer
        );
    },
    prepare: function(index) {
      // Used when more than 1 player to prepare the next piece of media.

      // 1. Want to be able to call this method and it deal with preparing the other player.
      // 2. So it should check if the media is already available in a player.
      // 3. If it is available, then do nothing.
      // 4. If not, then setup the next player to play the media.

      // 5. In principle this should support 1, 2 or more players.
      // 6. If 1 player, should do nothing here.
      // 7. If 2 or more players, then setup the next one. ie., The last one ever used before.

      // 8. Normally just 1 or 2 players though, so "keep it real mofo!"

      var media = this.content[index].media;

      // Ignore if we are only using a single Player
      if (media && this.player.length > 1) {
        // See if a player already has it. NB: Zero is falsey, so strong comparison.
        var prepared = this.which(media);
        var alignStart = Math.max(0, this.content[index].start - 1); //
        if (prepared === false) {
          // Get the next free player (Has flaws if more than 2, but still works. Just does not take full advantage of more than 2.)
          this.nextPlayer = this.activePlayer + 1 < this.player.length ? this.activePlayer + 1 : 0;

          if (this.player[this.nextPlayer]) {
            this.player[this.nextPlayer].load(media);
            this.player[this.nextPlayer].pause(alignStart);

            if (DEBUG)
              console.log('[Projector|prepare] player[%d].load() | initPopcorn()', this.nextPlayer);
            if (DEBUG)
              console.log(
                '[Projector|prepare] prepared=false | nextPlayer: %d | alignStart: %d',
                this.nextPlayer,
                alignStart
              );
          }
        } else {
          // Reset popcorn and move the video to the start time.
          if (prepared !== this.activePlayer) {
            this.player[prepared].initPopcorn();
            this.player[prepared].pause(alignStart);

            if (DEBUG) console.log('[Projector|prepare] player[%d].initPopcorn()', prepared);
            if (DEBUG)
              console.log(
                '[Projector|prepare] prepared=' + prepared + ' | nextPlayer: %d | alignStart: %d',
                this.nextPlayer,
                alignStart
              );
          }
        }
      }
    },
    which: function(media) {
      var index = false;

      if (media) {
        for (var i = 0; i < this.player.length; i++) {
          if (!this.player[i].mediaDiff(media)) {
            index = i;
            break;
          }
        }
      }
      if (DEBUG) console.log('[Projector|which] media: %o | index: ' + index, media); // %d no good since index can be boolean.
      return index;
    },

    cue: function(play, jumpTo) {
      var i, iLen, elems, e, eLen;
      /*
			var onNewPara = function(parent) {
				// $("#transcript-content").stop().scrollTo($(parent), 800, {axis:'y',margin:true,offset:{top:0}});
			};
*/
      if (this.stage && this.stage.target) {
        if (this.updateRequired) {
          this.updateContent();
        }

        this._pause();
        this.contentIndex = jumpTo.contentIndex;

        if (this.options.music) {
          this.options.music.pause();
        }

        if (this.contentIndex < this.content.length) {
          this.load(this.contentIndex);
          if (this.content[this.contentIndex + 1]) {
            this.prepare(this.contentIndex + 1);
          }
          // this.effect(this.content[this.contentIndex].effect);

          this.resetEffects(jumpTo);

          if (this.options.gui) {
            this.GUI.setStatus({
              // paused: this.paused,
              currentTime: this.getTotalCurrentTime(jumpTo.start, jumpTo.contentIndex)
            });
          }

          for (i = 0, iLen = this.content.length; i < iLen; i++) {
            elems = this.content[i].element.getElementsByTagName('a');
            for (e = 0, eLen = elems.length; e < eLen; e++) {
              if (i < this.contentIndex) {
                // Remove the class
                hyperaudio.removeClass(elems[e], 'transcript-grey');
              } else if (i > this.contentIndex) {
                // Add the class
                hyperaudio.addClass(elems[e], 'transcript-grey');
              }
            }
          }

          // Believe this is a good place to set this flag
          this.isReadyToPlay = true;
          if (DEBUG) console.log('[Projector|cue] isReadyToPlay = ' + this.isReadyToPlay);

          if (play) {
            this._play(jumpTo.start);
          } else {
            this._pause(jumpTo.start);
          }
        }
      }
    },

    gui_play: function(time) {
      this._trigger(hyperaudio.event.userplay, { msg: 'User clicked play' });
      this.play(time);
    },
    gui_pause: function(time) {
      this._trigger(hyperaudio.event.userpause, { msg: 'User clicked pause' });
      this.pause(time);
    },
    gui_currentTime: function(time, play) {
      this._trigger(hyperaudio.event.usercurrenttime, { msg: 'User clicked the progress bar' });
      this.currentTime(time, play);
    },

    play: function() {
      var resume = false,
        jumpTo;

      if (arguments.length && typeof arguments[0] !== 'undefined') {
        if (typeof arguments[0] === 'object') {
          jumpTo = arguments[0];
          if (DEBUG) console.log('[Projector|play] jumpTo =  %o', jumpTo);
        }
      } else if (this.isReadyToPlay) {
        resume = true;
      }

      if (DEBUG)
        console.log(
          '[Projector|play] resume = ' + resume + ' | content.length = %d | arguments = %o',
          this.content.length,
          arguments
        );

      if (this.content.length) {
        if (resume) {
          this._play();
        } else if (jumpTo) {
          this._pause();
          this.cue(true, {
            contentIndex: jumpTo.contentIndex,
            start: jumpTo.start
          });
          // The effect is not in cue!!!
          // this.effect(this.content[this.contentIndex].effect);
        } else {
          this.cue(true, {
            contentIndex: 0,
            start: this.content[0].start
          });
          this.effect(this.content[0].effect);
        }
      } else {
        if (this.options.gui) {
          this.GUI.setStatus({
            paused: this.paused
          });
        }
      }
    },

    pause: function() {
      // Really need pause to do similar to play by using cue()
      this._pause();
      if (this.options.music) {
        this.options.music.pause();
      }
    },
    _play: function(time) {
      this.paused = false;
      this.player[this.activePlayer].play(time);
    },
    _pause: function(time) {
      this.paused = true;
      this.player[this.activePlayer].pause(time);
    },
    currentTime: function(time, play) {
      var jumpTo = {},
        i,
        len;
      if (this.stage && this.stage.target) {
        if (this.updateRequired) {
          this.updateContent();
        }
        for (i = 0, len = this.content.length; i < len; i++) {
          if (this.content[i].totalStart <= time && time < this.content[i].totalEnd) {
            jumpTo.contentIndex = i;
            jumpTo.start = time - this.content[i].totalStart + this.content[i].start;
            this.cue(!this.paused, jumpTo);
            break;
          }
        }
      }
    },

    playWord: function(sectionElem, wordElem) {
      var jumpTo = {},
        i,
        len;
      if (this.stage && this.stage.target) {
        if (this.updateRequired) {
          this.updateContent();
        }
        for (i = 0, len = this.content.length; i < len; i++) {
          if (this.content[i].element === sectionElem) {
            jumpTo.contentIndex = i;
            jumpTo.start = wordElem.getAttribute(this.options.timeAttr) * this.content[i].unit;
            this._trigger(hyperaudio.event.userplayword, {
              msg: 'User clicked on a word to play from'
            });
            this.play(jumpTo);
            break;
          }
        }
      }
    },

    requestUpdate: function(reset) {
      var self = this,
        delay = this.options.stageChangeDelay;
      if (reset) {
        this.pause();
        if (this.options.gui) {
          this.GUI.setStatus({
            paused: this.paused,
            currentTime: 0,
            duration: 0
          });
        }
        this.needsInitVideo = true;
        delay = 0;
      }
      this.updateRequired = true;
      clearTimeout(this.timeout.updateContent);
      this.timeout.updateContent = setTimeout(function() {
        self.updateContent();
      }, delay);
    },

    updateContent: function() {
      var i,
        len,
        duration = 0;

      this.updateRequired = false;
      clearTimeout(this.timeout.updateContent);

      // Believe this is a good place to unset this flag
      this.isReadyToPlay = false;
      if (DEBUG) console.log('[Projector|updateContent#1] isReadyToPlay = ' + this.isReadyToPlay);

      if (this.stage && this.stage.target) {
        // Refresh the iscroller since mix changed.
        this.iScroll.refresh();

        // Get the staged contents wrapper elem
        this.stageArticle = this.stage.target.getElementsByTagName('article')[0];

        // Get the sections
        this.stageSections = this.stageArticle.getElementsByTagName('section');

        this.stageIndex = 0; // [Number] The next section
        this.content = []; // [Array] Holding the sections found with content
        this.firstContent = true; // [Boolean] True the first time
        this.endedContent = false; // [Boolean] True when we have no more content

        // this.contentIndex = 0; // [Number] The content that is actually being played.

        while (!this.endedContent) {
          this.getContent();
        }

        // Calculate the duration and start/end of this piece of content, compared to to the whole
        for (i = 0, len = this.content.length; i < len; i++) {
          this.content[i].totalStart = duration;
          duration += this.content[i].end + this.content[i].trim - this.content[i].start;
          this.content[i].totalEnd = duration;
        }
        this.time.duration = duration;

        // Update the duration on the GUI
        if (this.options.gui) {
          this.GUI.setStatus({
            duration: this.time.duration
          });
        }

        if (this.needsInitVideo && this.content.length) {
          this.needsInitVideo = false;
          this.cue(false, {
            contentIndex: 0,
            start: this.content[0].start
          });
          //Unset this flag so that any initial effects get played - when play begins.
          this.isReadyToPlay = false;
          if (DEBUG)
            console.log('[Projector|updateContent#2] isReadyToPlay = ' + this.isReadyToPlay);
        }
      }
    },

    getContent: function() {
      var effect = [],
        searching = true,
        section;

      // Search for sections with content and apply sections with effects to that content
      while (searching) {
        section = this.getSection(this.stageIndex);
        // If there is another section
        if (section) {
          // If this section has content
          if (section.media) {
            // Need to add any stored affects here
            section.effect = []; // Init the effect array
            this.effectContent(section, effect);

            // Store the content
            this.content.push(section);

            // The first time we need to get the 1st and 2nd content sections.
            if (this.firstContent) {
              this.firstContent = false;
              effect = []; // reset the effect array
            } else {
              searching = false;
            }
          } else if (section.effect) {
            // Some effects need to be applied to the previous content item

            // Trim affects previous content
            if (section.effect.type === 'trim') {
              // Have we got a previous section to affect?
              if (this.content.length) {
                this.effectContent(this.content[this.content.length - 1], section.effect);
              }

              // Fade effects both previous and next content
            } else if (section.effect.type === 'fade') {
              // Make 2 copies of the fade effect. Out and In.
              var fadeOutEffect = hyperaudio.extend({}, section.effect, { type: 'fadeOut' }),
                fadeInEffect = hyperaudio.extend({}, section.effect, { type: 'fadeIn' });
              // Have we got a previous section to affect?
              if (this.content.length) {
                this.effectContent(this.content[this.content.length - 1], fadeOutEffect);
              }
              // Effect for the next section, so store it for later.
              effect.push(fadeInEffect);
            } else if (section.effect.type === 'title' && section.effect.fullscreen) {
              // Similar to the Fade effect. The FadeFX does the fullscreen title effect

              // Make 2 copies of the fade effect. Out and In.
              var fadeOutEffectTitle = hyperaudio.extend({}, section.effect, {
                type: 'fadeOut',
                duration: 1
              });
              var fadeInEffectTitle = hyperaudio.extend({}, section.effect, {
                type: 'fadeIn',
                duration: 1,
                delay: section.effect.duration
              });

              // Have we got a previous section to affect?
              if (this.content.length) {
                this.effectContent(this.content[this.content.length - 1], fadeOutEffectTitle);
              } else {
                // Effect is on the first section, so store it for later.
                fadeOutEffectTitle.type = 'fadeNow';
                effect.push(fadeOutEffectTitle);
              }
              // Effect for the next section, so store it for later.
              effect.push(fadeInEffectTitle);

              // The rest affect the next content
            } else {
              // Effect for the next section, so store it for later.
              effect.push(section.effect);
            }
          } else {
            // Something is wrong with section structure
            searching = false;
          }
        } else {
          this.endedContent = true;
          searching = false;
        }

        this.stageIndex++;
      }
    },

    getSection: function(index) {
      var stageOptions = this.stage ? this.stage.options : {},
        section = {
          index: index
        };

      if (index < this.stageSections.length) {
        // Get the section
        var el = (section.element = this.stageSections[index]);

        // Get the ID
        section.id = el.getAttribute(stageOptions.idAttr);

        // Get the media
        var mp4 = el.getAttribute(stageOptions.mp4Attr),
          webm = el.getAttribute(stageOptions.webmAttr),
          youtube = el.getAttribute(stageOptions.ytAttr),
          mpeg = el.getAttribute(stageOptions.mpegAttr);

        if (mp4 || webm || youtube || mpeg) {
          section.media = {
            mp4: mp4,
            webm: webm,
            youtube: youtube,
            mpeg: mpeg
          };
        } else {
          section.media = false;
        }

        var unit = 1 * el.getAttribute(stageOptions.unitAttr);
        section.unit = unit = unit > 0 ? unit : this.options.unit;

        // Still have attributes hard coded in here. Would need to pass from the transcript to stage and then to here.
        var words = el.getElementsByTagName('a');
        if (words.length) {
          section.start = words[0].getAttribute(this.options.timeAttr) * unit;
          section.end = words[words.length - 1].getAttribute(this.options.timeAttr) * unit;
          section.trim = this.options.trim;
        }

        // Get the effect details
        section.effect = this.getSectionEffect(el);

        return section;
      } else {
        return false;
      }
    },

    getSectionEffect: function(el) {
      // Get the effect details
      var type = el.getAttribute('data-effect'),
        effect,
        media,
        elem;

      if (type) {
        elem = {
          title: el.querySelector('#effect-title'),
          fullscreen: el.querySelector('#effect-fullscreen'),
          delay: el.querySelector('#effect-delay'),
          start: el.querySelector('#effect-start'),
          duration: el.querySelector('#effect-duration'),
          volume: el.querySelector('#effect-volume')
        };
        media = {
          mp3: el.getAttribute('data-mp3'),
          mp4: el.getAttribute('data-mp4'),
          ogg: el.getAttribute('data-ogg')
        };
        effect = {
          type: type,
          title: elem.title ? elem.title.value : '',
          fullscreen: elem.fullscreen ? elem.fullscreen.checked : false,
          delay: elem.delay ? elem.delay.value * 1 : 0, // Convert to number
          start: elem.start ? elem.start.value * 1 : 0, // Convert to number
          duration: elem.duration ? elem.duration.value * 1 : 0, // Convert to number
          volume: elem.volume ? elem.volume.value / 100 : 0, // Convert to number and ratio from percent
          media: media
        };
      } else {
        effect = false;
      }
      return effect;
    },

    // Maybe this could be its own class?
    bgmFX: function(options) {
      if (this.options.music) {
        this.options.music.bgmFX(options);
      }
    },

    // Obsolete method... Effects are too unique to be classed in such a way
    isPrevEffect: function(effect) {
      // List of the effect types. (Separated by a space.)
      var effectTypes = 'trim',
        flag = false;

      hyperaudio.each(effectTypes.split(/\s+/g), function(i, type) {
        if (effect.type === type) {
          flag = true;
          return false; // exit each
        }
      });
      return flag;
    },

    // Obsolete method... Effects are too unique to be classed in such a way
    isPrevAndNextEffect: function(effect) {
      // List of the effect types. (Separated by a space.)
      var effectTypes = 'fade',
        flag = false;

      hyperaudio.each(effectTypes.split(/\s+/g), function(i, type) {
        if (effect.type === type) {
          flag = true;
          return false; // exit each
        }
      });
      return flag;
    },

    effectContent: function(content, effect) {
      // Allow effect to be a single object, or an array of them. Empty effect arrays do nothing.
      if (effect && !effect.length && effect.length !== 0) {
        effect = [effect];
      }

      for (var i = 0, l = effect.length; i < l; i++) {
        switch (effect[i].type) {
          case 'title':
            content.effect.push(effect[i]);
            break;
          case 'fadeOut':
            content.effect.push(effect[i]);
            break;
          case 'fadeIn':
            content.effect.push(effect[i]);
            break;
          case 'fadeNow':
            content.effect.push(effect[i]);
            break;
          case 'bgm':
            content.effect.push(effect[i]);
            break;
          case 'trim':
            content.trim = effect[i].duration;
            break;
        }
      }
    },

    resetEffects: function(jumpTo) {
      var i, iLen, e, eLen, effect;
      for (i = 0, iLen = this.content.length; i < iLen; i++) {
        effect = this.content[i].effect;
        for (e = 0, eLen = effect.length; e < eLen; e++) {
          if (i < jumpTo.contentIndex) {
            effect[e].init = true;
          } else if (i > jumpTo.contentIndex) {
            effect[e].init = false;
          } else if (effect[e].type === 'fadeOut') {
            // Need an isEndEffect() method
            effect[e].init = false;
          } else {
            // i === jumpTo.contentIndex
            if (this.content[i].start + effect[e].delay < jumpTo.start) {
              effect[e].init = true;
            } else {
              effect[e].init = false;
            }
          }
        }
      }
      // force a fadeIn - as in remove any fadeOuts!
      fadeFX({
        el: '#fxHelper',
        fadeIn: true,
        time: 0
      });
    },

    // Believe that the varous effect start and ends could be refactored into the single method.

    // Effecting the start of the content
    effect: function(effect, time) {
      // time : This is the relative time of the content.
      time = typeof time === 'number' ? time : 0;

      if (effect && effect.length) {
        for (var i = 0, l = effect.length; i < l; i++) {
          if (!effect[i].init && effect[i].delay <= time) {
            switch (effect[i].type) {
              case 'title':
                if (effect[i].title && effect[i].duration) {
                  titleFX({
                    el: '#titleFXHelper',
                    text: effect[i].title,
                    duration: effect[i].duration * 1000
                  });
                  effect[i].init = true;
                }
                break;
              case 'fadeIn':
                if (effect[i].duration) {
                  fadeFX({
                    el: '#fxHelper',
                    fadeIn: true,
                    text: effect[i].title,
                    time: effect[i].duration * 1000
                  });
                  effect[i].init = true;
                }
                break;
              case 'fadeNow':
                fadeFX({
                  el: '#fxHelper',
                  fadeOut: true,
                  text: effect[i].title,
                  time: 0
                });
                effect[i].init = true;
                break;
              case 'bgm':
                if (effect[i].duration) {
                  this.bgmFX({
                    media: {
                      mp3: effect[i].media.mp3,
                      mp4: effect[i].media.mp4,
                      ogg: effect[i].media.ogg
                    },
                    delay: effect[i].delay, // The delay is handled outside the bgmFX
                    start: effect[i].start,
                    duration: effect[i].duration,
                    volume: effect[i].volume
                  });
                  effect[i].init = true;
                }
                break;
            }
          }
        }
      }
    },

    // Effecting the end of the content
    effectEnd: function(effect) {
      if (effect && effect.length) {
        for (var i = 0, l = effect.length; i < l; i++) {
          if (!effect[i].init) {
            switch (effect[i].type) {
              case 'fadeOut':
                if (effect[i].duration) {
                  fadeFX({
                    el: '#fxHelper',
                    fadeOut: true,
                    text: effect[i].title,
                    time: effect[i].duration * 1000
                  });
                  effect[i].init = true;
                }
                break;
            }
          }
        }
      }
    },

    checkEndEffects: function(currentTime, content) {
      // 1. Do we have an end effect?
      // 2. Yes, has it been init?
      // 3. No, well is it time? - Calculate timings
      // 4. Is it time to start it?
      // 5. Yes, well execute the effect.

      var endEffects = this.getEndEffects(content),
        l = endEffects.length,
        i = 0;

      // Check each end effect
      for (; i < l; i++) {
        // Has the effect (not) been initiated?
        if (!endEffects[i].init) {
          // Is it time to start the effect?
          if (currentTime > content.end + content.trim - endEffects[i].duration) {
            // Boomshanka! Wrap it in an Array.
            this.effectEnd([endEffects[i]]);
          }
        }
      }
      // wanna return something?
      // return {buggerAll:true};
    },

    getEndEffects: function(content) {
      // List of the effect types. (Separated by a space.)
      var effectTypes = 'fadeOut',
        endEffects = [];

      hyperaudio.each(content.effect, function(n, effect) {
        hyperaudio.each(effectTypes.split(/\s+/g), function(i, type) {
          if (effect.type === type) {
            endEffects.push(effect);
          }
        });
      });
      // return an array of all the end effects.
      return endEffects;
    },

    getTotalCurrentTime: function(currentTime, index) {
      var start,
        end,
        totalCurrentTime = 0;
      if (index < this.content.length) {
        start = this.content[index].start;
        end = this.content[index].end + this.content[index].trim;

        // Calculte the (total) currentTime to display on the GUI
        totalCurrentTime = this.content[index].totalStart;
        if (start < currentTime && currentTime < end) {
          totalCurrentTime += currentTime - start;
        } else if (currentTime >= end) {
          // totalCurrentTime += end - start;
          totalCurrentTime = this.content[index].totalEnd;
        }
      }
      return totalCurrentTime;
    },

    manager: function(videoElem, event) {
      var self = this;

      this.paused = videoElem.paused;

      if (!this.paused) {
        this.checkEndEffects(videoElem.currentTime, this.content[this.contentIndex]);

        var endTime = this.content[this.contentIndex].end + this.content[this.contentIndex].trim;

        var totalCurrentTime = this.getTotalCurrentTime(videoElem.currentTime, this.contentIndex);

        var relTime = videoElem.currentTime - this.content[this.contentIndex].start;
        /*
				// Paronoid and cleaning up the relTime
				var relEnd = endTime - this.content[this.contentIndex].start;
				if(isNaN(relTime) || relTime < 0) {
					relTime = 0;
				} else if(relTime > relEnd) {
					relTime = relEnd; // Maybe this should be infinity... Since delay greater than the content, and would otherwise never occur.
				}
*/
        if (videoElem.currentTime > endTime) {
          // Goto the next piece of content

          // Flush out any remaining effects. ie., Otherwise delay > duration never happens.
          this.effect(this.content[this.contentIndex].effect, Infinity);

          this._pause(); // Need to stop, otherwise if we switch player, the hidden one keeps playing.

          this.contentIndex++;

          if (this.contentIndex < this.content.length) {
            // this.paused = false;

            this.load(this.contentIndex);
            if (this.content[this.contentIndex + 1]) {
              this.prepare(this.contentIndex + 1);
            }
            this.effect(this.content[this.contentIndex].effect, 0);
            this._play(this.content[this.contentIndex].start);
          } else {
            // Nothing to play
            this.paused = true;
            this.isReadyToPlay = false; // ended so needs a reset to the start
            if (DEBUG) console.log('[Projector|manager] isReadyToPlay = ' + this.isReadyToPlay);
            this.contentIndex = 0; // Reset this since YouTube player (or its Popcorn wrapper) generates the timeupdate all the time.
            this.prepare(this.contentIndex);
            if (this.options.music) {
              this.options.music.pause();
            }
          }
        } else {
          // Doing this every time now.
          this.effect(this.content[this.contentIndex].effect, relTime);
        }

        if (this.options.gui) {
          this.GUI.setStatus({
            paused: this.paused,
            currentTime: totalCurrentTime
          });
        }
      } else {
        if (this.options.gui) {
          this.GUI.setStatus({
            paused: this.paused
          });
        }
      }
    }
  };

  return Projector;
})(window, document, hyperaudio, Popcorn);


text:
<?xml version="1.0" encoding="UTF-8"?>
<RegisterSensor service="SOS" version="1.0.0"
	xmlns="http://www.opengis.net/sos/1.0" xmlns:swe="http://www.opengis.net/swe/1.0.1"
	xmlns:ows="http://www.opengeospatial.net/ows" xmlns:xlink="http://www.w3.org/1999/xlink"
	xmlns:gml="http://www.opengis.net/gml" xmlns:ogc="http://www.opengis.net/ogc"
	xmlns:om="http://www.opengis.net/om/1.0" xmlns:sml="http://www.opengis.net/sensorML/1.0.1"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.opengis.net/sos/1.0
http://schemas.opengis.net/sos/1.0.0/sosRegisterSensor.xsd http://www.opengis.net/om/1.0 http://schemas.opengis.net/om/1.0.0/extensions/observationSpecialization_override.xsd">

	<!-- Sensor Description parameter; Currently, this has to be a sml:System -->
	<SensorDescription>
		<sml:SensorML version="1.0.1">
			<sml:member>
				<sml:System xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

					<!-- last measured position of sensor -->
					<sml:position name="sensorPosition">
						<swe:Position referenceFrame="urn:ogc:def:crs:EPSG::4326">
							<swe:location>
								<swe:Vector gml:id="STATION_LOCATION">
									<swe:coordinate name="easting">
										<swe:Quantity>
											<swe:uom code="degree" />
											<swe:value>7.52</swe:value>
										</swe:Quantity>
									</swe:coordinate>
									<swe:coordinate name="northing">
										<swe:Quantity>
											<swe:uom code="degree" />
											<swe:value>52.9</swe:value>
										</swe:Quantity>
									</swe:coordinate>
									<swe:coordinate name="altitude">
										<swe:Quantity>
											<swe:uom code="m" />
											<swe:value>52.0</swe:value>
										</swe:Quantity>
									</swe:coordinate>
								</swe:Vector>
							</swe:location>
						</swe:Position>
					</sml:position>

					<!-- list containing the input phenomena for this sensor system -->
					<sml:inputs>
						<sml:InputList>
							<sml:input name="Temperature">
								<swe:ObservableProperty
									definition="urn:ogc:def:phenomenon:OGC:1.0.30:temperature" />
							</sml:input>
							<sml:input name="Sunny">
								<swe:ObservableProperty
									definition="urn:ogc:def:phenomenon:OGC:1.0.30:conditions" />
							</sml:input>
							<sml:input name="Position">
								<swe:ObservableProperty
									definition="urn:ogc:def:phenomenon:OGC:1.0.30:position" />
							</sml:input>
						</sml:InputList>
					</sml:inputs>

					<!-- list containing the output phenomena of this sensor system; ATTENTION:
						these phenomena are parsed and inserted into the database; they have to contain
						offering elements to determine the correct offering for the sensors and measured
						phenomena -->
					<sml:outputs>
						<sml:OutputList>
							<sml:output name="active">
								<swe:Boolean definition="urn:ogc:def:phenomenon:OGC:1.0.30:active">
								</swe:Boolean>
							</sml:output>
							<sml:output name="sensors">
								<swe:Count definition="urn:ogc:def:phenomenon:OGC:1.0.30:sensors">
								</swe:Count>
							</sml:output>
							<sml:output name="temperature">
								<swe:Quantity definition="urn:ogc:def:phenomenon:OGC:1.0.30:temperature">
									<swe:uom code="Cel" />
								</swe:Quantity>
							</sml:output>
							<sml:output name="lastCheck">
								<swe:Time definition="urn:ogc:def:phenomenon:OGC:1.0.30:lastCheck">
									<swe:uom code="ISO-8601" />
								</swe:Time>
							</sml:output>
							<sml:output name="conditions">
								<swe:Category definition="urn:ogc:def:phenomenon:OGC:1.0.30:conditions">
								</swe:Category>
							</sml:output>
							<sml:output name="position">
								<swe:Position definition="urn:ogc:def:phenomenon:OGC:1.0.30:position">
								</swe:Position>
							</sml:output>
							<sml:output name="lastCheckDescription">
								<swe:Text
									definition="urn:ogc:def:phenomenon:OGC:1.0.30:lastCheckDescription">
								</swe:Text>
							</sml:output>
							<sml:output name="positionText">
								<swe:Text
									definition="urn:ogc:def:phenomenon:OGC:1.0.30:positionText">
								</swe:Text>
							</sml:output>
							<sml:output name="location">
								<swe:Text
									definition="urn:ogc:def:phenomenon:OGC:1.0.30:location">
								</swe:Text>
							</sml:output>
							<sml:output name="WKT">
								<swe:Text
									definition="urn:ogc:def:phenomenon:OGC:1.0.30:WKT">
								</swe:Text>
							</sml:output>
						</sml:OutputList>
					</sml:outputs>
				</sml:System>
			</sml:member>
		</sml:SensorML>
	</SensorDescription>

	<!-- ObservationTemplate parameter; this has to be an empty measurement
		or category at the moment, as the 52N SOS only supports Measurements or CategoryObservations
		to be inserted -->
	<ObservationTemplate>
		<om:Observation>
			<om:samplingTime />
			<om:procedure />
			<om:observedProperty />
			<om:featureOfInterest></om:featureOfInterest>
			<om:result/>
		</om:Observation>
	</ObservationTemplate>
</RegisterSensor>


text:
{-# LANGUAGE
    DeriveFunctor
  , DeriveFoldable
  , OverloadedStrings
  #-}
module ProjectEuler.Problem128
  ( problem
  ) where

import Data.List
import Data.Maybe
import Math.NumberTheory.Primes

import ProjectEuler.Types

problem :: Problem
problem = pureProblem 128 Solved result

{-
  Idea:

  Let's again begin with what we can do:

  - From center up, we have: 1, 2, 8, 20. next few should be: 38, 62.

  - This gives us: https://oeis.org/A077588

    + f(0) = 1
    + f(n) = 3*n*n - 3*n + 2

  - now let's setup a coordinate system so that when we are
    given a coordinate, the tile numbers of its 6 neighborhoods can be easily computed.

  - Here we'll go with "Axial Coordinate" (flat version) as demonstrated in:

    https://www.redblobgames.com/grids/hexagons/

  - to figure out ring id for a given cell, we can simply compute the distance between it and (0,0)
    (note: the center cell is ring #0, and then we have ring #1 around the center one,
    and ring #2, #3, ... growing outwards)

  - It is too slow to go from tile #1, tile #2, ... all the way up, we got to find some optimizations.

  - Now if we print out 6 differences for each cell for each ring, we can easily spot some patterns:

    (1) we notice that all edge cells *not* next to any corner cells are simply repeating all 6 differences from
        previous cell, this does make sense, say if we are moving from B to B+1:

         A     A+1
       D   D+1     D+2
         B     B+1
       E   E+1     E+2
         C     C+1

      ----- direction of growth ----->

      It is now obvious that this move does not change any of those 6 differences,
      so actually, for each ring, we simply need to test those around corner cells.

    (2) further, we can observe that for the edge cells *not* next to any corner cells,
        there are always two 1s and two pairs of consective numbers
        (so there are exactly 2 even number within those 4 numbers), e.g.:

      - 15: [1,1,9,10,15,16]
      - 17: [1,1,10,11,16,17]
      - 21: [1,1,12,13,18,19]
      - 25: [1,1,13,14,19,20]
      - 31: [1,1,15,16,21,22]

      This allows us to conclude that the PD values for those numbers are always <= 2,
      therefore we can skip them all.

    (3) by excluding those edges described in (2), we have only few cells to check for each ring:

      - all corner cells
      - the cell after corner cell, but it is unnecessary to check this one, due to (2):
        since those edge cells following a corner cell are always a repetition of previous cell,
        that means the cell right next to the corner cell is also one of those cells whose PD value is <= 2.
      - the cell prior to the top corner cell.

      By "prior" and "after" I meant cell with number -1 or +1 to the cell in question.

  - With those discoveries above, we managed to get the correct answer - more optimization could follow.

  - Turns out it is only possible to obtain PD(_) = 3 for the first and last cell of a ring,
    so I optimized my code to only check for that.

 -}

type AxialCoord = (Int, Int)
type AxialDir = (Int, Int)

-- unit directions following tiles' growing direction.
unitDirs :: [] AxialDir
unitDirs =
  [ (-1, 1)
  , (0, 1)
  , (1, 0)
  , (1, -1)
  , (0, -1)
  , (-1, 0)
  ]

plus :: AxialDir -> AxialDir -> AxialDir
plus (x,y) (a,b) = (x+a, y+b)

dist :: AxialCoord -> AxialCoord -> Int
dist (ax, az) (bx, bz) = abs (ax - bx) `max` abs (-ax -az + bx + bz) `max` abs (az - bz)

data HC a = HC !a !a !a !a !a !a deriving (Functor, Foldable)

hcInd :: HC a -> Int -> a
hcInd (HC v0 v1 v2 v3 v4 v5) i = case i of
  0 -> v0
  1 -> v1
  2 -> v2
  3 -> v3
  4 -> v4
  5 -> v5
  _ -> error "out of bound"

{- Compute coords of corner cells of a ring. -}
mkHexCorners :: Int -> HC AxialCoord
mkHexCorners 0 = let z = (0,0) in HC z z z z z z
mkHexCorners n = HC (0,-n) (-n,0) (-n,n) (0,n) (n,0) (n,-n)

{-
  After we got the correct answer, I noticed that it seems true that
  only first and last cell of a ring (first cell is also the top corner of that ring)
  can have PD(_) = 3, perhaps there are proofs but I'll just assume that is true
  and optimize things below.
 -}
checkAroundHexCorners :: Int -> [Int]
checkAroundHexCorners 0 = [1]
checkAroundHexCorners n =
  mapMaybe
    computePdGreaterEqual3
    [ (0,-n) -- first coord of the ring.
    , (1,-n) -- last coord of the ring.
    ]

mkPairs :: (t -> t -> a) -> HC t -> [a]
mkPairs op (HC v0 v1 v2 v3 v4 v5) =
  [op v0 v1, op v1 v2, op v2 v3, op v3 v4, op v4 v5, op v5 v0]

coordToTileNum :: AxialCoord -> Int
coordToTileNum (0,0) = 1
coordToTileNum pt = tileNumBase + offset
  where
    n = dist pt (0,0)
    hcs = mkHexCorners n
    dists = fmap (dist pt) hcs
    Just cornerInd = elemIndex n $ mkPairs (+) dists
    tileNumBase = 3*n*n + (cornerInd - 3)*n + 2
    offset = hcInd dists cornerInd

{- returns tile number n when PD(n) = 3 -}
computePdGreaterEqual3 :: AxialCoord -> Maybe Int
computePdGreaterEqual3 c = case mapMaybe isPrime diffs of
    (_:_:_:_) ->
      {-
        Since we know that PD(_) <= 3, we can stop at 3 and claim PD(c) = 3,
        this pattern just look for that particular shape and avoids some computation.
        (since we don't really care about what exactly is that prime)
       -}
      Just x
    _ -> Nothing
  where
    x = coordToTileNum c
    diffs = fmap ((\y -> abs (y - x)) . coordToTileNum . plus c) unitDirs

result :: Int
result = concatMap checkAroundHexCorners [0..] !! (2000 - 1)


text:
/*!
Peano numbers allow us to do arithmetic at compile time using Rust's type system.

The basic idea of the peano numbers is that we first define the number `Zero`. Then, we
inductively define the rest of the natural numbers. For any non-negative natural number
`N`, define its successor, `Succ<N>`, a positive number. We can now count!

Because we want all the integers and not just the natural numbers, we have to be a
little bit careful with these definitions, which is why it is specified that `N` above
must not be negative. Otherwise, when we define predecessors we could end up with
`Pred<Succ<Zero>>` which should represent the number `Zero` but is a distinct type and
would not be treated as such by the compiler.

We can now define negative numbers: For any non-positive natural number `N`, define
its predecessor, `Pred<N>`, a negative number.

By the definitions of `Pred` and `Succ`, we disallow them to be used together.

Conceptually, we now have access to all integers. In practice, we have access to
the numbers from -63 to 63 unless we use the `#![recursion_limit="N"]` lint to increase
the allowed number of embedded traits.

In addition to the traits created here, the traits `Add`, `Sub`, `Mul`, `Div`, and `Neg`
are all implemented for Peano numbers. Note that these traits are used here very
differently than is typical. The functions that come with them are not used at all (and
will throw an error if you try). Instead, we are using them as operators on *types*,
with the associated type acting as the result of the computation.

# Example
```
use peano::{P2, P3, P4, ToInt};
# use std::ops::{Add, Div};
// 2 + 3 == 5
assert_eq!( 5, <<P2 as Add<P3>>::Output as ToInt>::to_int() );

// 4 / 2 == 2
assert_eq!( 2, <<P4 as Div<P2>>::Output as ToInt>::to_int() );
```

Note that the `ToInt` trait here is only used to get an integer output; it is the only
runtime operation defined for Peano numbers, and exists primarily for debugging
purposes. What is important and generally used is the associated type `Output`.

**Note:** Arithmetic with these numbers is very slow unless the numbers are very small.
It is strongly recommended that you use the [typenum](http://paholg.com/doc/typenum) crate instead.
 */

#![doc(html_root_url = "http://paholg.com/peano/peano/index.html")]
#![warn(missing_docs)]
#![crate_type="lib"]

use std::marker::PhantomData;
use std::ops::{Add, Sub, Mul, Div, Neg};

/// The type corresponding to the Peano number 0.
#[derive(Copy, Clone)]
pub struct Zero;

/// For any non-negative Peano number `N`, we define its successor, `Succ<N>`.
///
/// This gives us positive Peano numbers.
#[derive(Copy, Clone)]
pub struct Succ<N: NonNeg> {
    _marker: PhantomData<N>
}
/// For any non-positive Peano number `N`, we define its predecessor, `Pred<N>`.
///
/// This gives us negative Peano numbers.
#[derive(Copy, Clone)]
pub struct Pred<N: NonPos> {
    _marker: PhantomData<N>
}

/// The Peano number +1; `P1 = Succ<Zero>;`
pub type P1 = Succ<Zero>;
/// The Peano number +2; `P2 = Succ<P1>;`
pub type P2 = Succ<P1>;
/// The Peano number +3; `P3 = Succ<P2>;`
pub type P3 = Succ<P2>;
/// The Peano number +4; `P4 = Succ<P3>;`
pub type P4 = Succ<P3>;
/// The Peano number +5; `P5 = Succ<P4>;`
pub type P5 = Succ<P4>;
/// The Peano number +6; `P6 = Succ<P5>;`
pub type P6 = Succ<P5>;
/// The Peano number +7; `P7 = Succ<P6>;`
pub type P7 = Succ<P6>;
/// The Peano number +8; `P8 = Succ<P7>;`
pub type P8 = Succ<P7>;
/// The Peano number +9; `P9 = Succ<P8>;`
pub type P9 = Succ<P8>;

/// The Peano number -1; `N1 = Pred<Zero>;`
pub type N1 = Pred<Zero>;
/// The Peano number -2; `N2 = Pred<N1>;`
pub type N2 = Pred<N1>;
/// The Peano number -3; `N3 = Pred<N2>;`
pub type N3 = Pred<N2>;
/// The Peano number -4; `N4 = Pred<N3>;`
pub type N4 = Pred<N3>;
/// The Peano number -5; `N5 = Pred<N4>;`
pub type N5 = Pred<N4>;
/// The Peano number -6; `N6 = Pred<N5>;`
pub type N6 = Pred<N5>;
/// The Peano number -7; `N7 = Pred<N6>;`
pub type N7 = Pred<N6>;
/// The Peano number -8; `N8 = Pred<N7>;`
pub type N8 = Pred<N7>;
/// The Peano number -9; `N9 = Pred<N8>;`
pub type N9 = Pred<N8>;

/// All numbers defined in this module belong to the **Peano** trait. It should not be
/// implemented for anything else.
pub trait Peano {}
/// Implemented for all Peano numbers of the form `Succ<M: NonNeg>` or `Pred<N: NonPos>`.
pub trait NonZero: Peano {}
/// Implemented for `Zero` and all numbers of the form `Succ<N: NonNeg>`.
pub trait NonNeg: Peano {}
/// Implemented for `Zero` and all numbers of the form `Pred<N: NonPos>`.
pub trait NonPos: Peano {}

impl Peano for Zero {}
impl NonNeg for Zero {}
impl NonPos for Zero {}

impl<N: NonNeg> Peano for Succ<N> {}
impl<N: NonNeg> NonNeg for Succ<N> {}
impl<N: NonNeg> NonZero for Succ<N> {}

impl<N: NonPos> Peano for Pred<N> {}
impl<N: NonPos> NonPos for Pred<N> {}
impl<N: NonPos> NonZero for Pred<N> {}

// Add
// -------------------------------------------------------------------------------------
/// Add to Zero (e.g. 0 + 3)
impl<Rhs> Add<Rhs> for Zero where Rhs: Peano {
    type Output = Rhs;
    #[allow(unused_variables)]
    fn add(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Add non-negative numbers to positive numbers (e.g. 2 + 3, 2 + 0)
impl<Lhs, Rhs> Add<Rhs> for Succ<Lhs> where Lhs: NonNeg + Add<Rhs>, Rhs: NonNeg, <Lhs as Add<Rhs>>::Output: NonNeg {
    type Output = Succ<<Lhs as Add<Rhs>>::Output>;
    #[allow(unused_variables)]
    fn add(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Add non-positive numbers to negative numbers (e.g. -2 + -3, -2 + 0)
impl<Lhs, Rhs> Add<Rhs> for Pred<Lhs> where Lhs: NonPos + Add<Rhs>, Rhs: NonPos, <Lhs as Add<Rhs>>::Output: NonPos {
    type Output = Pred<<Lhs as Add<Rhs>>::Output>;
    #[allow(unused_variables)]
    fn add(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Add positive and negative numbers (e.g. -2 + 3)
impl<Lhs, Rhs> Add<Succ<Rhs>> for Pred<Lhs> where Lhs: NonPos + Add<Rhs>, Rhs: NonNeg {
    type Output = <Lhs as Add<Rhs>>::Output;
    #[allow(unused_variables)]
    fn add(self, rhs: Succ<Rhs>) -> Self::Output { unreachable!() }
}
/// Add negative and positive numbers (e.g. 2 + -3)
impl<Lhs, Rhs> Add<Pred<Rhs>> for Succ<Lhs> where Lhs: NonNeg + Add<Rhs>, Rhs: NonPos {
    type Output = <Lhs as Add<Rhs>>::Output;
    #[allow(unused_variables)]
    fn add(self, rhs: Pred<Rhs>) -> Self::Output { unreachable!() }
}

// Neg
// -------------------------------------------------------------------------------------
/// The negation of Zero is itself.
impl Neg for Zero {
    type Output = Zero;
    fn neg(self) -> Self::Output { unreachable!() }
}
/// Negate positive numbers (e.g. 5 -> -5)
impl<N> Neg for Succ<N> where N: NonNeg + Neg, <N as Neg>::Output: NonPos {
    type Output = Pred<<N as Neg>::Output>;
    fn neg(self) -> Self::Output { unreachable!() }
}
/// Negate negative numbers (e.g. -5 -> 5)
impl<N> Neg for Pred<N> where N: NonPos + Neg, <N as Neg>::Output: NonNeg {
    type Output = Succ<<N as Neg>::Output>;
    fn neg(self) -> Self::Output { unreachable!() }
}

// Sub
// -------------------------------------------------------------------------------------
/// Subtract from Zero (e.g. 0 - 4)
impl<Rhs> Sub<Rhs> for Zero where Rhs: Neg{
    type Output = <Rhs as Neg>::Output;
    #[allow(unused_variables)]
    fn sub(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Subtract Zero from positive numbers (e.g. 2 - 0)
impl<Lhs> Sub<Zero> for Succ<Lhs> where Lhs: NonNeg {
    type Output = Succ<Lhs>;
    #[allow(unused_variables)]
    fn sub(self, rhs: Zero) -> Self::Output { unreachable!() }
}
/// Subtract Zero from negative numbers (e.g. -2 - 0)
impl<Lhs> Sub<Zero> for Pred<Lhs> where Lhs: NonPos {
    type Output = Pred<Lhs>;
    #[allow(unused_variables)]
    fn sub(self, rhs: Zero) -> Self::Output { unreachable!() }
}
/// Subtract positive numbers from positive numbers (e.g. 3 - 4)
impl<Lhs, Rhs> Sub<Succ<Rhs>> for Succ<Lhs> where Lhs: NonNeg + Sub<Rhs>, Rhs: NonNeg {
    type Output = <Lhs as Sub<Rhs>>::Output;
    #[allow(unused_variables)]
    fn sub(self, rhs: Succ<Rhs>) -> Self::Output { unreachable!() }
}
/// Subtract negative numbers from negative numbers (e.g. -3 - -4)
impl<Lhs, Rhs> Sub<Pred<Rhs>> for Pred<Lhs> where Lhs: NonPos + Sub<Rhs>, Rhs: NonPos {
    type Output = <Lhs as Sub<Rhs>>::Output;
    #[allow(unused_variables)]
    fn sub(self, rhs: Pred<Rhs>) -> Self::Output { unreachable!() }
}
/// Subtract negative numbers from positive numbers (e.g. 3 - -4)
impl<Lhs, Rhs> Sub<Pred<Rhs>> for Succ<Lhs> where Lhs: NonNeg + Sub<Rhs>, Rhs: NonPos, <Lhs as Sub<Rhs>>::Output: NonNeg {
    type Output = Succ<Succ<<Lhs as Sub<Rhs>>::Output>>;
    #[allow(unused_variables)]
    fn sub(self, rhs: Pred<Rhs>) -> Self::Output { unreachable!() }
}
/// Subtract positive numbers from negative numbers (e.g. -3 - 4)
impl<Lhs, Rhs> Sub<Succ<Rhs>> for Pred<Lhs> where Lhs: NonPos + Sub<Rhs>, Rhs: NonNeg, <Lhs as Sub<Rhs>>::Output: NonPos {
    type Output = Pred<Pred<<Lhs as Sub<Rhs>>::Output>>;
    #[allow(unused_variables)]
    fn sub(self, rhs: Succ<Rhs>) -> Self::Output { unreachable!() }
}

// Mul
// -------------------------------------------------------------------------------------
/// Multiply Zero by peano numbers (e.g. 0 * 7)
impl<Rhs> Mul<Rhs> for Zero where Rhs: Peano {
    type Output = Zero;
    #[allow(unused_variables)]
    fn mul(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Multiply positive numbers by integers (e.g. 2 * N)
impl<Lhs, Rhs> Mul<Rhs> for Succ<Lhs> where Lhs: NonNeg + Mul<Rhs>, Rhs: Add<<Lhs as Mul<Rhs>>::Output> {
    type Output = <Rhs as Add<<Lhs as Mul<Rhs>>::Output>>::Output;
    #[allow(unused_variables)]
    fn mul(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Multiply negative numbers by integers (e.g. -2 * N)
impl<Lhs, Rhs> Mul<Rhs> for Pred<Lhs> where Lhs: NonPos + Mul<Rhs>, Rhs: Peano, <Lhs as Mul<Rhs>>::Output: Sub<Rhs> {
    type Output = <<Lhs as Mul<Rhs>>::Output as Sub<Rhs>>::Output;
    #[allow(unused_variables)]
    fn mul(self, rhs: Rhs) -> Self::Output { unreachable!() }
}

// Div
// -------------------------------------------------------------------------------------
/// Divide Zero by a number (e.g. 0 / 5)
impl<Rhs> Div<Rhs> for Zero where Rhs: Peano {
    type Output = Zero;
    #[allow(unused_variables)]
    fn div(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Divide a positive number by a non-zero number (e.g. 4 / 2, 4 / -2).
/// Only defined for numbers that are evenly divisible.
impl<Lhs, Rhs> Div<Rhs> for Succ<Lhs> where Lhs: NonNeg, Succ<Lhs>: DivPrivate<Rhs> {
    type Output = <Succ<Lhs> as DivPrivate<Rhs>>::Output;
    #[allow(unused_variables)]
    fn div(self, rhs: Rhs) -> Self::Output { unreachable!() }
}
/// Divide a negative number by a non-zero number (e.g. -4 / 2, -4 / -2).
/// Only defined for numbers that are evenly divisible.
impl<Lhs, Rhs> Div<Rhs> for Pred<Lhs> where Lhs: NonPos + Neg, Rhs: Neg, Succ<<Lhs as Neg>::Output>: DivPrivate<<Rhs as Neg>::Output>, <Lhs as Neg>::Output: NonNeg {
    type Output = <<Pred<Lhs> as Neg>::Output as DivPrivate<<Rhs as Neg>::Output>>::Output;
    #[allow(unused_variables)]
    fn div(self, rhs: Rhs) -> Self::Output { unreachable!() }
}

mod detail {
    // DivPrivate only supports positive numerators. As division is implemented via repeated
    // subtraction, we can be sure to only support division between divisible numbers by
    // terminating when the numerator is Zero and not allowing it to become negative. We can
    // support negative numerators by mapping e.g. -4 / 2 to 4 / -2, which is what is done
    // in the implementation of `Div`
    pub trait DivPrivate<Rhs>: ::Peano {
        type Output;
    }
}
use detail::DivPrivate;

impl<Rhs: NonZero> DivPrivate<Rhs> for Zero {
    type Output = Zero;
}

// Dividing a positive integer by a positive integer (e.g. 4 / 2)
impl<Lhs, Rhs> DivPrivate<Succ<Rhs>> for Succ<Lhs>
    where Lhs: NonNeg, Rhs: NonNeg,
          Succ<Lhs>: DivPrivate<Succ<Rhs>> + Sub<Succ<Rhs>>,
          <Succ<Lhs> as Sub<Succ<Rhs>>>::Output: DivPrivate<Succ<Rhs>>,
          <<Succ<Lhs> as Sub<Succ<Rhs>>>::Output as DivPrivate<Succ<Rhs>>>::Output: NonNeg
{
    // Lhs / Rhs = 1 + (Lhs - Rhs) / Rhs
    type Output = <P1 as Add<<<Succ<Lhs> as Sub<Succ<Rhs>>>::Output as DivPrivate<Succ<Rhs>>>::Output>>::Output;
}

// Dividing a positive integer by a negative integer (e.g. 4 / -2)
impl<Lhs, Rhs> DivPrivate<Pred<Rhs>> for Succ<Lhs>
    where Lhs: NonNeg, Rhs: NonPos,
          Succ<Lhs>: DivPrivate<Pred<Rhs>> + Add<Pred<Rhs>>,
          <Succ<Lhs> as Add<Pred<Rhs>>>::Output: DivPrivate<Pred<Rhs>>,
          <<Succ<Lhs> as Add<Pred<Rhs>>>::Output as DivPrivate<Pred<Rhs>>>::Output: NonPos
{
    // Lhs / Rhs = -1 + (Lhs + Rhs) / Rhs
    type Output = <N1 as Add<<<Succ<Lhs> as Add<Pred<Rhs>>>::Output as DivPrivate<Pred<Rhs>>>::Output>>::Output;
}

impl<Lhs: Peano> DivPrivate<Zero> for Lhs {
    type Output = P1;
}

/** `Same` is used to ensure that two types are the same. Its `Output` should **always** be that type.

# Example:
```
use peano::{Same, Succ, P1, P2, ToInt};

assert_eq!(2, <<Succ<P1> as Same<P2>>::Output as ToInt>::to_int());
```
*/
pub trait Same<Rhs = Self> {
    /// `Output` should always be `Self`
    type Output;
}

impl<N> Same<N> for N where N: Peano {
    type Output = N;
}

// ToInt
// -------------------------------------------------------------------------------------

/**
Convert a Peano number to the integer it represents.

Once Rust implements associated constants, an associated constant will replace the
function `to_int()`.

# Example:
```
use peano::{P2, ToInt};

assert_eq!(2, <P2 as ToInt>::to_int());
```
*/
pub trait ToInt: Peano {
    #[allow(missing_docs)]
    fn to_int() -> i32;
}
impl ToInt for Zero {
    fn to_int() -> i32 { 0 }
}
impl<N: NonNeg + ToInt> ToInt for Succ<N> {
    fn to_int() -> i32 { 1 + N::to_int() }
}
impl<N: NonPos + ToInt> ToInt for Pred<N> {
    fn to_int() -> i32 { -1 + N::to_int() }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: faustos
 * Date: 31.03.14
 * Time: 21:28
 */

namespace Tixi\ApiBundle\Shared\DataGrid\Tile;

use Tixi\ApiBundle\Shared\DataGrid\DataGridOutputState;
use Tixi\ApiBundle\Tile\AbstractTile;

/**
 * Class DataGridRowTableTile
 * @package Tixi\ApiBundle\Shared\DataGrid\Tile
 */
class DataGridRowTableTile extends AbstractTile{

    protected $dataGridOutputState;

    /**
     * @param DataGridOutputState $dataGridOutputState
     */
    public function __construct(DataGridOutputState $dataGridOutputState) {
        $this->dataGridOutputState = $dataGridOutputState;
    }

    /**
     * @return array
     */
    public function getViewParameters()
    {
        return array('gridState'=>$this->dataGridOutputState);
    }

    /**
     * @return mixed|string
     */
    public function getTemplateName()
    {
        return 'TixiApiBundle:Tile:datagridrowstable.html.twig';
    }

    /**
     * @return mixed|string
     */
    public function getName()
    {
        return 'datagridrowstable';
    }
}


text:
import { describe } from 'riteway'
import { GraphQL } from './index'

describe('GraphQL()', async assert => {
  {
    const actual = GraphQL()()
    const expected = {
      name: '',
      Types: '',
      Query: [],
      Mutation: [],
      Subscription: [],
      Relations: {},
    }

    assert({
      given: 'no name and definition',
      should: 'return an default object',
      actual,
      expected,
    })
  }
})


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you 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.
package com.cloud.network.dao;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import com.cloud.network.rules.FirewallRuleVO;
import com.cloud.network.rules.LoadBalancer;
import com.cloud.utils.net.NetUtils;

/**
 * This VO represent Public Load Balancer
 * It references source ip address by its Id.
 * To get the VO for Internal Load Balancer rule, please refer to LoadBalancerRuleVO
 *
 */
@Entity
@Table(name = ("load_balancing_rules"))
@DiscriminatorValue(value = "LoadBalancing")
@PrimaryKeyJoinColumn(name = "id")
public class LoadBalancerVO extends FirewallRuleVO implements LoadBalancer {

    @Column(name = "name")
    private String name;

    @Column(name = "description", length = 4096)
    private String description;

    @Column(name = "algorithm")
    private String algorithm;

    @Column(name = "default_port_start")
    private int defaultPortStart;

    @Column(name = "default_port_end")
    private int defaultPortEnd;

    @Enumerated(value = EnumType.STRING)
    @Column(name = "scheme")
    Scheme scheme = Scheme.Public;

    @Column(name = "lb_protocol")
    String lbProtocol;

    public LoadBalancerVO() {
    }

    public LoadBalancerVO(String xId, String name, String description, long srcIpId, int srcPort, int dstPort, String algorithm, long networkId, long accountId,
            long domainId, String lbProtocol) {
        super(xId, srcIpId, srcPort, NetUtils.TCP_PROTO, networkId, accountId, domainId, Purpose.LoadBalancing, null, null, null, null);
        this.name = name;
        this.description = description;
        this.algorithm = algorithm;
        this.defaultPortStart = dstPort;
        this.defaultPortEnd = dstPort;
        this.scheme = Scheme.Public;
        this.lbProtocol = lbProtocol;
    }

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

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

    @Override
    public String getAlgorithm() {
        return algorithm;
    }

    @Override
    public int getDefaultPortStart() {
        return defaultPortStart;
    }

    @Override
    public int getDefaultPortEnd() {
        return defaultPortEnd;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getLbProtocol() {
        return lbProtocol;
    }

    public void setLbProtocol(String lbProtocol) {
        this.lbProtocol = lbProtocol;
    }

    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

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

    @Override
    public Scheme getScheme() {
        return scheme;
    }
}


text:
class EasyTag < Formula
  desc "Application for viewing and editing audio file tags"
  homepage "https://projects.gnome.org/easytag"
  url "https://download.gnome.org//sources/easytag/2.4/easytag-2.4.3.tar.xz"
  sha256 "fc51ee92a705e3c5979dff1655f7496effb68b98f1ada0547e8cbbc033b67dd5"

  bottle do
    rebuild 1
    sha256 "bbb4d7b86a05ac2e2d0a1ba275e2fbf828a5a6943203c2dbb077d29675f49268" => :high_sierra
    sha256 "b479d94cdf71aec5b56376397509f3438180d8ac4ba479788b64e3f97b8eda6f" => :sierra
    sha256 "fc36c67da169f09015acc7e91fc2256cc5abaf1ec5539bc382d30fc76f423045" => :el_capitan
  end

  depends_on "pkg-config" => :build
  depends_on "intltool" => :build
  depends_on "itstool" => :build
  depends_on "gtk+3"
  depends_on "hicolor-icon-theme"
  depends_on "adwaita-icon-theme"
  depends_on "id3lib"
  depends_on "libid3tag"
  depends_on "taglib"

  depends_on "libvorbis"
  depends_on "flac"
  depends_on "libogg"
  depends_on "speex"
  depends_on "wavpack"

  # disable gtk-update-icon-cache
  patch :DATA

  def install
    ENV.append_path "PYTHONPATH", "#{Formula["libxml2"].opt_lib}/python2.7/site-packages"
    system "./configure", "--disable-dependency-tracking",
                          "--prefix=#{prefix}",
                          "--disable-schemas-compile"
    system "make"
    ENV.deparallelize # make install fails in parallel
    system "make", "install"
  end

  def post_install
    system "#{Formula["glib"].opt_bin}/glib-compile-schemas", "#{HOMEBREW_PREFIX}/share/glib-2.0/schemas"
    system "#{Formula["gtk+3"].opt_bin}/gtk3-update-icon-cache", "-f", "-t", "#{HOMEBREW_PREFIX}/share/icons/hicolor"
  end

  test do
    system "#{bin}/easytag", "--version"
  end
end

__END__
diff --git a/Makefile.in b/Makefile.in
index 9dbde5f..4ffe52e 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -3960,8 +3960,6 @@ data/org.gnome.EasyTAG.gschema.valid: data/.dstamp
 @ENABLE_MAN_TRUE@		--path $(builddir)/doc --output $(builddir)/doc/ \
 @ENABLE_MAN_TRUE@		http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl $<

-install-data-hook: install-update-icon-cache
-uninstall-hook: uninstall-update-icon-cache

 install-update-icon-cache:
	$(AM_V_at)$(POST_INSTALL)


text:
package br.ufrgs.inf.gar.condo.domain;

import java.io.Serializable;

@SuppressWarnings("serial")
public abstract class AbstractEntity<PK extends Comparable<? super PK>, T extends AbstractEntity<PK, T>>
		implements Serializable, Comparable<T> {

	public abstract PK getId();

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public boolean equals(Object another) {
		Class<? extends AbstractEntity> clazz = this.getClass();
        if (clazz == null || another == null) return false;
        if(!clazz.isAssignableFrom(another.getClass())) return false;

        T obj = null;
		try {
			obj = (T) another.getClass().newInstance();
			return this.getId().equals(obj.getId());
		} catch (Exception e) {
			return false;
		}
    }

	@Override
    public int hashCode() {
        return this.getId().hashCode();
    }

	@Override
	public int compareTo(T o) {
		return this.getId().compareTo(o.getId());
	}
}


text:
package com.intellij.remoteServer.impl.configuration;

import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonShortcuts;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.MasterDetailsComponent;
import com.intellij.openapi.ui.NamedConfigurable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.remoteServer.ServerType;
import com.intellij.remoteServer.configuration.RemoteServer;
import com.intellij.remoteServer.configuration.RemoteServersManager;
import com.intellij.remoteServer.util.CloudBundle;
import com.intellij.ui.TreeSpeedSearch;
import com.intellij.ui.speedSearch.SpeedSearchSupply;
import com.intellij.util.IconUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.text.UniqueNameGenerator;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.*;

/**
 * @author nik
 */
public class RemoteServerListConfigurable extends MasterDetailsComponent implements SearchableConfigurable {

  @NonNls
  public static final String ID = "RemoteServers";

  private final RemoteServersManager myServersManager;
  private RemoteServer<?> myLastSelectedServer;
  private String myInitialSelectedName;
  private final List<ServerType<?>> myDisplayedServerTypes;

  private RemoteServerListConfigurable(@NotNull RemoteServersManager manager,
                                       @NotNull ServerType<?> type,
                                       @Nullable String initialSelectedName) {
    this(manager, Collections.singletonList(type), initialSelectedName);
  }

  protected RemoteServerListConfigurable(@NotNull RemoteServersManager manager,
                                         @NotNull List<ServerType<?>> displayedServerTypes,
                                         @Nullable String initialSelectedName) {
    myServersManager = manager;
    myDisplayedServerTypes = displayedServerTypes;
    initTree();
    myToReInitWholePanel = true;
    myInitialSelectedName = initialSelectedName;
    reInitWholePanelIfNeeded();
  }

  @Nullable
  private ServerType<?> getSingleServerType() {
    List<ServerType<?>> serverTypes = getDisplayedServerTypes();
    return serverTypes.size() == 1 ? serverTypes.get(0) : null;
  }

  @NotNull
  public List<ServerType<?>> getDisplayedServerTypes() {
    // `myDisplayedServerTypes` might be `null` here because overridden `reInitWholePanelIfNeeded()`
    // is executed from `super()` before `myDisplayedServerTypes` is initialized
    return myDisplayedServerTypes != null ? myDisplayedServerTypes : Collections.emptyList();
  }

  @Nullable
  @Override
  protected String getEmptySelectionString() {
    final String typeNames = StringUtil.join(getDisplayedServerTypes(),
                                             type -> type.getPresentableName(), ", ");

    if (typeNames.length() > 0) {
      return CloudBundle.getText("clouds.configure.empty.selection.string", typeNames);
    }
    return null;
  }

  public static RemoteServerListConfigurable createConfigurable(@NotNull ServerType<?> type) {
    return createConfigurable(type, null);
  }

  public static RemoteServerListConfigurable createConfigurable(@NotNull ServerType<?> type, @Nullable String nameToSelect) {
    return new RemoteServerListConfigurable(RemoteServersManager.getInstance(), type, nameToSelect);
  }

  @Nls
  @Override
  public String getDisplayName() {
    ServerType<?> singleServerType = getSingleServerType();
    return singleServerType == null ? "Clouds" : singleServerType.getPresentableName();
  }

  @Override
  public void reset() {
    myRoot.removeAllChildren();
    for (RemoteServer<?> server : getServers()) {
      addServerNode(server, false);
    }
    super.reset();
    if (myInitialSelectedName != null) {
      selectNodeInTree(myInitialSelectedName);
    }
  }

  @NotNull
  private List<? extends RemoteServer<?>> getServers() {
    return ContainerUtil.filter(myServersManager.getServers(), s -> myDisplayedServerTypes.contains(s.getType()));
  }

  private MyNode addServerNode(RemoteServer<?> server, boolean isNew) {
    MyNode node = new MyNode(new SingleRemoteServerConfigurable(server, TREE_UPDATER, isNew));
    addNode(node, myRoot);
    return node;
  }

  @NotNull
  @Override
  public String getId() {
    return ID;
  }

  @Nullable
  @Override
  public Runnable enableSearch(final String option) {
    return () -> ObjectUtils.assertNotNull(SpeedSearchSupply.getSupply(myTree, true)).findAndSelectElement(option);
  }

  @Override
  protected void initTree() {
    super.initTree();
    new TreeSpeedSearch(myTree, treePath -> ((MyNode)treePath.getLastPathComponent()).getDisplayName(), true);
  }

  @Override
  protected void processRemovedItems() {
    Set<RemoteServer<?>> servers = new HashSet<>();
    for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) {
      servers.add(configurable.getEditableObject());
    }

    List<RemoteServer<?>> toDelete = new ArrayList<>();
    for (RemoteServer<?> server : getServers()) {
      if (!servers.contains(server)) {
        toDelete.add(server);
      }
    }
    for (RemoteServer<?> server : toDelete) {
      myServersManager.removeServer(server);
    }
  }

  @Override
  public void apply() throws ConfigurationException {
    super.apply();
    Set<RemoteServer<?>> servers = new HashSet<>(getServers());
    for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) {
      RemoteServer<?> server = configurable.getEditableObject();
      server.setName(configurable.getDisplayName());
      if (!servers.contains(server)) {
        myServersManager.addServer(server);
      }
    }
  }

  @Nullable
  @Override
  protected ArrayList<AnAction> createActions(boolean fromPopup) {
    ArrayList<AnAction> actions = new ArrayList<>();
    ServerType<?> singleServerType = getSingleServerType();
    if (singleServerType == null) {
      actions.add(new AddRemoteServerGroup());
    }
    else {
      actions.add(new AddRemoteServerAction(singleServerType, IconUtil.getAddIcon()));
    }
    actions.add(new MyDeleteAction());
    return actions;
  }

  @Override
  protected boolean wasObjectStored(Object editableObject) {
    return true;
  }

  @Override
  public String getHelpTopic() {
    String result = super.getHelpTopic();
    if (result == null) {
      ServerType<?> singleServerType = getSingleServerType();
      if (singleServerType != null) {
        result = singleServerType.getHelpTopic();
      }
    }
    return result != null ? result : "reference.settings.clouds";
  }

  @Override
  public void disposeUIResources() {
    Object selectedObject = getSelectedObject();
    myLastSelectedServer = selectedObject instanceof RemoteServer<?> ? (RemoteServer)selectedObject : null;
    super.disposeUIResources();
  }

  @Nullable
  public RemoteServer<?> getLastSelectedServer() {
    return myLastSelectedServer;
  }

  private List<NamedConfigurable<RemoteServer<?>>> getConfiguredServers() {
    List<NamedConfigurable<RemoteServer<?>>> configurables = new ArrayList<>();
    for (int i = 0; i < myRoot.getChildCount(); i++) {
      MyNode node = (MyNode)myRoot.getChildAt(i);
      configurables.add((NamedConfigurable<RemoteServer<?>>)node.getConfigurable());
    }
    return configurables;
  }

  private class AddRemoteServerGroup extends ActionGroup implements ActionGroupWithPreselection {
    private AddRemoteServerGroup() {
      super("Add", "", IconUtil.getAddIcon());
      registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
    }

    @NotNull
    @Override
    public AnAction[] getChildren(@Nullable AnActionEvent e) {
      List<ServerType<?>> serverTypes = getDisplayedServerTypes();
      AnAction[] actions = new AnAction[serverTypes.size()];
      for (int i = 0; i < serverTypes.size(); i++) {
        actions[i] = new AddRemoteServerAction(serverTypes.get(i), serverTypes.get(i).getIcon());
      }
      return actions;
    }

    @Override
    public ActionGroup getActionGroup() {
      return this;
    }

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

  private class AddRemoteServerAction extends DumbAwareAction {
    private final ServerType<?> myServerType;

    private AddRemoteServerAction(ServerType<?> serverType, final Icon icon) {
      super(serverType.getPresentableName(), null, icon);
      myServerType = serverType;
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      String name = UniqueNameGenerator.generateUniqueName(myServerType.getPresentableName(), s -> {
        for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) {
          if (configurable.getDisplayName().equals(s)) {
            return false;
          }
        }
        return true;
      });
      MyNode node = addServerNode(myServersManager.createServer(myServerType, name), true);
      selectNodeInTree(node);
    }
  }
}


text:
<title>strlen</title>

strlen

OS/161 Reference Manual

Name

strlen - determine length of string

Library

Standard C Library (libc, -lc)

Synopsis

#include <string.h>

size_t

strlen(const char *string);

Description

strlen returns the length of the string string. The length
does not include the null terminator.


text:
package org.apache.ignite.internal.processors.cache.persistence.snapshot;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.internal.processors.cache.GridCacheSharedContext;
import org.apache.ignite.internal.processors.cache.verify.PartitionHashRecordV2;
import org.apache.ignite.internal.processors.cache.verify.PartitionKeyV2;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;

/**
 * Quick partitions verifier. Warns if partiton counters or size are different among the nodes what can be caused by
 * canceled/failed DataStreamer. Skips checking if the DataStreamer warning is detected.
 */
public class SnapshotPartitionsQuickVerifyHandler extends SnapshotPartitionsVerifyHandler {
    /** */
    public static final String WRN_MSG = "This may happen if DataStreamer with property 'allowOverwrite' set " +
        "to `false` is loading during the snapshot or hadn't successfully finished earlier. However, you will be " +
        "able restore rest the caches from this snapshot.";

    /**
     * @param cctx Shared context.
     */
    public SnapshotPartitionsQuickVerifyHandler(GridCacheSharedContext<?, ?> cctx) {
        super(cctx);
    }

    /** {@inheritDoc} */
    @Override public SnapshotHandlerType type() {
        return SnapshotHandlerType.CREATE;
    }

    /** {@inheritDoc} */
    @Override public Map<PartitionKeyV2, PartitionHashRecordV2> invoke(SnapshotHandlerContext opCtx)
        throws IgniteCheckedException {
        // Return null not to check partitions at all if the streamer warning is detected.
        if (opCtx.streamerWarning())
            return null;

        Map<PartitionKeyV2, PartitionHashRecordV2> res = super.invoke(opCtx);

        assert res != null;

        return res;
    }

    /** {@inheritDoc} */
    @Override public void complete(
        String name,
        Collection<SnapshotHandlerResult<Map<PartitionKeyV2, PartitionHashRecordV2>>> results
    ) throws IgniteCheckedException {
        if (results.stream().anyMatch(r -> r.data() == null))
            return;

        Set<Integer> wrnGrps = new HashSet<>();

        Map<PartitionKeyV2, PartitionHashRecordV2> total = new HashMap<>();

        F.viewReadOnly(results, SnapshotHandlerResult::data).forEach(m -> m.forEach((part, val) -> {
            PartitionHashRecordV2 other = total.putIfAbsent(part, val);

            if (other == null)
                return;

            if (val.size() != other.size() || !val.updateCounter().equals(other.updateCounter()))
                wrnGrps.add(part.groupId());
        }));

        if (!wrnGrps.isEmpty()) {
            throw new SnapshotHandlerWarningException("Cache partitions differ for cache groups " + S.compact(wrnGrps)
                + ". " + WRN_MSG);
        }
    }

    /** {@inheritDoc} */
    @Override protected boolean skipHash() {
        return true;
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <link rel="SHORTCUT ICON" href="../../../img/clover.ico" />

    <link rel="stylesheet" href="../../../aui/css/aui.min.css" media="all"/>
    <link rel="stylesheet" href="../../../aui/css/aui-experimental.min.css" media="all"/>

            <title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>

                    OpenClover

                             Help

                                        ABA Route Transit Number Validator 1.0.1-SNAPSHOT

                    Project overview

            Packages

            <form method="get" action="#" class="aui package-filter-container">
                <input type="text" autocomplete="off" class="package-filter text"
                       placeholder="Type to filter packages..." name="package-filter" id="package-filter"
                       title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
            </form>

                No results found.

 Project Clover database Sat Aug 7 2021 12:29:33 MDT

Package com.cardatechnologies.utils

        Class TraceUnitExtension

            Source file

            Test results

        Class
        Tests
        Fail
        Error

            Time (secs)

        % Tests Success

        TraceUnitExtension
        00
00
00
        0

            Tests

        Started
        Status

            Time (secs)

        Message

                Report generated by OpenClover v 4.4.1
                on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.

OpenClover is free and open-source software.


text:
"""
Contains neural network layers that are composed of multiple sublayer parts.
"""

import logging
from neon.layers.layer import Layer
from neon.util.compat import range
from neon.util.param import req_param

logger = logging.getLogger(__name__)

class CompositeLayer(Layer):
    """
    Generic parent for Branch and List layer that deals with sublayer list

    Attributes:
        sublayers (list of Layer): Individual layers that make up this
                                   compositional layer.
    """
    def initialize(self, kwargs):
        super(CompositeLayer, self).initialize(kwargs)
        req_param(self, ['sublayers'])
        self.has_params = True
        for subl in self.sublayers:
            subl.initialize(kwargs)

    def __str__(self):
        ret = '{} {}: {} nodes'.format(self.__class__.__name__,
                                       self.name, self.nout)
        ret += ':\n'
        for subl in self.sublayers:
            ret += '\t' + str(subl) + '\n'
        return ret

    def update(self, epoch):
        for subl in self.sublayers:
            subl.update(epoch)

    def set_train_mode(self, mode):
        for subl in self.sublayers:
            subl.set_train_mode(mode)

    def get_params(self):
        np_params = dict()
        for i, ll in enumerate(self.sublayers):
            if ll.has_params:
                lkey = self.name + '_' + ll.name + '_' + str(i)
                np_params[lkey] = ll.get_params()
        return np_params

    def set_params(self, params_dict):
        for i, ll in enumerate(self.sublayers):
            if ll.has_params:
                lkey = self.name + '_' + ll.name + '_' + str(i)
                ll.set_params(params_dict[lkey])

class BranchLayer(CompositeLayer):
    """
    Branch layer is composed of a list of other layers concatenated with one
    another.

    During fprop, it concatenates the component outputs and passes it on.
    During bprop, it splits the backward errors into the components and
    accumulates into common deltas
    """

    def __init__(self, **kwargs):
        super(BranchLayer, self).__init__(**kwargs)

    def set_previous_layer(self, pl):
        super(BranchLayer, self).set_previous_layer(pl)
        for subl in self.sublayers:
            subl.set_previous_layer(pl)
        self.nout = reduce(lambda x, y: x + y.nout, self.sublayers, 0)
        if pl is not None:
            self.nin = pl.nout

    def initialize(self, kwargs):
        super(BranchLayer, self).initialize(kwargs)

        self.startidx = [0] * len(self.sublayers)
        self.endidx = [0] * len(self.sublayers)
        self.endidx[0] = self.sublayers[0].nout
        for i in range(1, len(self.sublayers)):
            self.endidx[i] = self.endidx[i - 1] + self.sublayers[i].nout
            self.startidx[i] = self.endidx[i - 1]

        self.allocate_output_bufs()

    def set_deltas_buf(self, delta_pool, offset):
        if self.prev_layer is None:
            return
        if self.prev_layer.is_data:
            return

        self.deltas = self.backend.zeros(self.delta_shape, self.deltas_dtype)
        for subl in self.sublayers:
            subl.set_deltas_buf(delta_pool, offset)

    def fprop(self, inputs):
        for (subl, si, ei) in zip(self.sublayers, self.startidx, self.endidx):
            subl.fprop(inputs)
            self.output[si:ei] = subl.output

    def bprop(self, error):
        if self.deltas is not None:
            self.deltas.fill(0.0)
        for (subl, si, ei) in zip(self.sublayers, self.startidx, self.endidx):
            subl.bprop(error[si:ei])
            if self.deltas is not None:
                self.backend.add(self.deltas, subl.deltas, out=self.deltas)

class ListLayer(CompositeLayer):
    """
    List layer is composed of a list of other layers stacked on top of one
    another.

    During fprop and bprop, it simply operates along the chain.
    """
    def set_previous_layer(self, pl):
        super(ListLayer, self).set_previous_layer(pl)
        for subl in self.sublayers:
            subl.set_previous_layer(pl)
            pl = subl
        self.nout = self.sublayers[-1].nout

    def initialize(self, kwargs):
        super(ListLayer, self).initialize(kwargs)
        self.output = self.sublayers[-1].output
        if self.sublayers[-1].is_local is True:
            self.nofm = self.sublayers[-1].nofm
            self.ofmshape = self.sublayers[-1].ofmshape

    def set_deltas_buf(self, delta_pool, offset):
        self.ninmax = max(map(lambda x: x.nin, self.sublayers))
        delta_shape = (2 * self.ninmax, self.batch_size)
        assert len(self.sublayers) > 1
        delta_type = self.sublayers[1].deltas_dtype
        self.delta_pool = self.backend.zeros(delta_shape, delta_type)
        for idx, subl in enumerate(self.sublayers):
            offset = (idx % 2) * self.ninmax
            subl.set_deltas_buf(self.delta_pool, offset)

        if self.prev_layer is None:
            return
        if self.prev_layer.is_data:
            return
        self.deltas = self.sublayers[0].deltas

    def fprop(self, inputs):
        for subl in self.sublayers:
            subl.fprop(inputs)
            inputs = subl.output

    def bprop(self, error):
        for subl in reversed(self.sublayers):
            subl.bprop(error)
            error = subl.deltas