text:
package com.sun.max.ve.fs.image;

import java.io.*;
import java.util.*;

import com.sun.max.annotate.HOSTED_ONLY;
import com.sun.max.io.Files;
import com.sun.max.program.ProgramError;
import com.sun.max.program.Trace;
import com.sun.max.ve.error.VEError;
import com.sun.max.ve.fs.*;
import com.sun.max.vm.MaxineVM;

/**
 * A (read-only) file system that is pre-loaded into a Maxine VE image.
 *
 * @author Mick Jordan
 *
 */
public class BootImageFileSystem extends UnimplementedFileSystemImpl implements VirtualFileSystem {

    public static final String BOOTIMAGE_FILESYSTEM_PROPERTY = "max.ve.bootimage.fs.contents";
    private static BootImageFileSystem _singleton = new BootImageFileSystem();
    private static final int S_IFREG = 0x8000;
    private static final int S_IFDIR = 0x4000;
    @HOSTED_ONLY
    private static Set<File> includeSet = new HashSet<File>();

    private static byte[][] _openFiles = new byte[64][];

    private static String imageFSPrefix = "";
    private static Map<String, byte[]> _fileSystem = new HashMap<String, byte[]>();

    static {
        final String prop = System.getProperty(BOOTIMAGE_FILESYSTEM_PROPERTY);
        if (prop != null) {
            readBootImageFileSystemSpec(new File(prop));
        }
    }

    @HOSTED_ONLY
    private static void readBootImageFileSystemSpec(File specFile) {
        final File parent = specFile.getParentFile();
        includeSet.add(specFile);
        BufferedReader bs = null;
        try {
            bs = new BufferedReader(new FileReader(specFile));
            while (true) {
                final String line = bs.readLine();
                if (line == null) {
                    break;
                }
                if (line.length() == 0 || line.charAt(0) == '#') {
                    continue;
                }
                String argument = null;
                String command;
                final int ix = line.indexOf(' ');
                if (ix > 0) {
                    command = line.substring(0, ix);
                    argument = line.substring(ix + 1).trim();
                } else {
                    command = line;
                }
                if (command.equals("path")) {
                    doImageFile(argument);
                } else if (command.equals("prefix")) {
                    doImagefsPrefix(argument);
                } else if (command.equals("include")) {
                    if (argument != null) {
                        argument = processVars(argument);
                        File f = new File(argument);
                        if (!f.isAbsolute()) {
                            f = new File(parent, argument);
                        }
                        if (!includeSet.contains(f)) {
                            readBootImageFileSystemSpec(f);
                        }
                    }
                } else {
                    error("unknown command: " + command + " in spec file" + specFile);
                }
            }
        } catch (IOException ex) {
            error("error reading spec file: " + specFile + ": " + ex);
        } finally {
            if (bs != null) {
                try {
                    bs.close();
                } catch (IOException ex) {
                }
            }
        }

    }

    @HOSTED_ONLY
    private static void error(String m) {
        VEError.unexpected("BootImageFileSystem: " + m);
    }

    @HOSTED_ONLY
    public static void putImageFile(File file, File asFile) {
        try {
            String path = asFile.getPath();
            if (asFile.isAbsolute() || imageFSPrefix.equals("")) {
                path = imageFSPrefix + path;
            } else {
                path = imageFSPrefix + File.separator + path;
            }
            _fileSystem.put(path, Files.toBytes(file));
            Trace.line(1, "added file " + file.getPath() + " to boot image file system as path " + path);
        } catch (IOException ioException) {
            ProgramError.unexpected("Error reading from " + file + ": " + ioException);
        }
    }

    @HOSTED_ONLY
    protected static void putDirectory(File dir, File asFile) {
        final String[] files = dir.list();
        for (String path : files) {
            final File child = new File(dir, path);
            final File asChild = new File(asFile, path);
            if (child.isDirectory()) {
                putDirectory(child, asChild);
            } else {
                putImageFile(child, asChild);
            }
        }
    }

    @HOSTED_ONLY
    protected static void doImageFile(String argument) {
        String pathName = argument;
        String asName = argument;
        final int ix = argument.lastIndexOf(' ');
        if (ix > 0) {
            pathName = argument.substring(0, ix);
            asName = argument.substring(ix + 1);
        }
        pathName = processVars(pathName);
        asName = processVars(asName);
        final File file = new File(pathName);
        final File asFile = new File(asName);
        if (file.exists()) {
            if (file.isDirectory()) {
                putDirectory(file, asFile);
            } else {
                putImageFile(file, asFile);
            }
        } else {
            ProgramError.unexpected("failed to find file: " + argument);
        }
    }

    @HOSTED_ONLY
    private static String processVars(String s) {
        StringBuilder sb = null;
        int jx = 0;
        int ix = 0;
        while ((ix = s.indexOf("${", jx)) >= 0) {
            if (sb == null) {
                sb = new StringBuilder(s.length());
            }
            sb.append(s.substring(jx, ix));
            jx = s.indexOf('}');
            if (jx < 0) {
                error("malformed variable");
            }
            final String var = s.substring(ix + 2, jx);
            String pvar = System.getProperty(var);
            if (pvar == null) {
                pvar = System.getenv(var);
            }
            if (pvar == null) {
                error("no system property or environment variable: " + var);
            }
            sb.append(pvar);
            jx++;
            ix = jx;
        }
        if (sb == null) {
            return s;
        } else {
            sb.append(s.substring(jx));
            return sb.toString();
        }
    }

    @HOSTED_ONLY
    protected static void doImagefsPrefix(String argument) {
        final int last = argument.length() - 1;
        final String argImageFSPrefix = argument.charAt(last) == File.separatorChar ? argument.substring(0, last) : argument;
        if (imageFSPrefix.length() != 0) {
            if (!imageFSPrefix.equals(argImageFSPrefix)) {
                ProgramError.unexpected("inconsistent definitions of image file system prefix: " + imageFSPrefix + ", " + argImageFSPrefix);
            } else {
                return;
            }
        }
        imageFSPrefix = argImageFSPrefix;
        Trace.line(1, "setting boot image file system prefix to " + imageFSPrefix);
    }

    public static String getPath() {
        return imageFSPrefix;
    }

    @Override
    public void close() {

    }

    private static synchronized int getFd(byte[] data) {
        for (int i = 0; i < _openFiles.length; i++) {
            if (_openFiles[i] == null) {
                _openFiles[i] = data;
                return i;
            }
        }
        return -1;
    }

    public static BootImageFileSystem create() {
        return _singleton;
    }

    @Override
    public String canonicalize0(String path) throws IOException {
        // TODO correct implementation
        return path;
    }

    @Override
    public boolean checkAccess(String path, int access) {
        if (!(_fileSystem.containsKey(path) || isDir(path))) {
            return false;
        }
        switch (access) {
            case ACCESS_READ:
                return true;
            case ACCESS_WRITE:
                return false;
            case ACCESS_EXECUTE:
                return false;
        }
        return false;
    }

    @Override
    public boolean createDirectory(String path) {
        return false;
    }

    @Override
    public boolean createFileExclusively(String path) throws IOException {
        if (MaxineVM.isHosted()) {
            if (_fileSystem.containsKey(path)) {
                return false;
            }
            _fileSystem.put(path, null);
        }

        return false;
    }

    @Override
    public boolean delete0(String path) {
        return false;
    }

    @Override
    public long getLastModifiedTime(String path) {
        // Not recorded
        return 0;
    }

    @Override
    public long getLength(String path) {
        final byte[] data = _fileSystem.get(path);
        return data == null ? 0 : data.length;
    }

    private boolean isDir(String path) {
        final int dirLength = path.length();
        final Set<String> keys = _fileSystem.keySet();
        for (String entry : keys) {
            if (entry.startsWith(path)) {
                if (entry.charAt(dirLength) == File.separatorChar) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public int getMode(String path) {
        if (_fileSystem.containsKey(path)) {
            return S_IFREG | S_IREAD;
        }
        // maybe a directory?
        if (isDir(path)) {
            return S_IFDIR | S_IREAD | S_IEXEC;
        }
        return -1;
    }

    @Override
    public long getSpace(String path, int t) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public String[] list(String path) {
        final String dir = path;
        final List<String> results = new ArrayList<String>();
        final int dirLength = dir.length();
        final Set<String> keys = _fileSystem.keySet();
        for (String keyPath : keys) {
            if (keyPath.startsWith(dir)) {
                if (keyPath.charAt(dirLength) == File.separatorChar) {
                    // matches dir exactly
                    final int ix = keyPath.indexOf(File.separatorChar, dirLength + 1);
                    if (ix < 0) {
                        // leaf file
                        results.add(keyPath.substring(dirLength + 1));
                    } else {
                        // subdirectory
                        final String subDir = keyPath.substring(dirLength + 1, ix);
                        boolean isNew = true;
                        for (String s : results) {
                            if (s.equals(subDir)) {
                                isNew = false;
                                break;
                            }
                        }
                        if (isNew) {
                            results.add(subDir);
                        }
                    }
                }
            }
        }
        return results.toArray(new String[results.size()]);
    }

    @Override
    public boolean rename0(String path1, String path2) {
        return false;
    }

    @Override
    public boolean setLastModifiedTime(String path, long time) {
        return false;
    }

    @Override
    public int setMode(String path, int mode) {
        return -ErrorDecoder.Code.EROFS.getCode();
    }

    // FileInputStream, FileOutputStream

    @Override
    public int read(int fd, long fileOffset) {
        final byte[] data = _openFiles[fd];
        if ((int) fileOffset >= data.length) {
            return -1;
        }
        return data[(int) fileOffset] & 0xFF;
    }

    @Override
    public int readBytes(int fd, byte[] bytes, int offset, int length, long fileOffset) {
        final byte[] data = _openFiles[fd];
        if ((int) fileOffset >= data.length) {
            return -1;
        }
        if (length > data.length - (int) fileOffset) {
            // CheckStyle: stop parameter assignment check
            length = data.length - (int) fileOffset;
            // CheckStyle: resume parameter assignment check
        }
        System.arraycopy(data, (int) fileOffset, bytes, offset, length);
        return length;

    }

    @Override
    public int write(int fd, int b, long fileOffset) {
        return -ErrorDecoder.Code.EROFS.getCode();

    }

    @Override
    public int writeBytes(int fd, byte[] bytes, int offset, int length, long fileOffset) {
        return -ErrorDecoder.Code.EROFS.getCode();
    }

    @Override
    public int open(String name, int flags) {
        if (flags == VirtualFileSystem.O_RDONLY) {
            final byte[] data = _fileSystem.get(name);
            if (data == null) {
                return -ErrorDecoder.Code.ENOENT.getCode();
            }
            return getFd(data);
        } else {
            return -ErrorDecoder.Code.EROFS.getCode();
        }
    }

    @Override
    public int close0(int fd) {
        _openFiles[fd] = null;
        return 0;
    }

    @Override
    public long getLength(int fd) {
        return _openFiles[fd].length;
    }

    @Override
    public int setLength(int fd, long length) {
        return -ErrorDecoder.Code.EROFS.getCode();
    }

    @Override
    public int available(int fd, long fileOffset) {
        final byte[] data = _openFiles[fd];
        if ((int) fileOffset >= data.length) {
            return 0;
        }
        return data.length - (int) fileOffset;
    }

    @Override
    public long skip(int fd, long n, long fileOffset) {
        // spec allows skip to go past end of file
        return n;
    }

}


text:
import React from 'react'
import ReactDOM from 'react-dom'

import TextEditorContainer from './TextEditorContainer'
import PythonContainer from './PythonContainer'
import TerminalContainer from './TerminalContainer'
import MarkdownContainer from './MarkdownContainer'

import DraggableDiv from '../components/DraggableDiv'

import '../../css/style.css'

class EditorContainer extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      width: 0,
      height: 0
    }
  }

  componentDidMount() {
    this.terminalDomNode = ReactDOM.findDOMNode(this.refs.terminal)
    this.editorDomNode = ReactDOM.findDOMNode(this.refs.editor)
  }

  render() {
    let display;
    // If language is markdown display markdown container
    // else display editor
    if (this.props.language === 'markdown') {
      display = (
        <MarkdownContainer
          editorText={this.props.editorText}/>
      );
    } else if (this.props.language === 'python') {
      display = (
        <PythonContainer
            language={this.props.language}
            editorText={this.props.editorText}/>
      );
    } else {
        display = (
          <TerminalContainer
            language={this.props.language}
            editorText={this.props.editorText}/>
        );
    }

    return (

          <TextEditorContainer
            theme={this.props.theme}
            language={this.props.language}
            getEditorText={this.props.getEditorText}/>

        <DraggableDiv />

          {display}

    );
  }
}

export default EditorContainer

redpajama_set_name: RedPajamaGithub


text:
/**
 * Indicator window with a spinner and a label
 *
 * @param {Object} args
 */
function createIndicatorWindow(args) {

	var width = 180, height = 50;

	var args = args || {};
	var top = args.top || 140;
	var text = args.text || "Loading...";

	var win = Titanium.UI.createWindow({
		height : height,
		width : width,
		top : top,
		borderRadius : 4,
		touchEnabled : false,
		backgroundColor : '#5E5E5E',
		opacity : 0.8
	});

	var view = Ti.UI.createView({
		width : Ti.UI.SIZE,
		height : Ti.UI.FILL,
		center : {
			x : (width / 2),
			y : (height / 2)
		},
		layout : 'horizontal'
	});

	function osIndicatorStyle() {
		style = Ti.UI.ActivityIndicatorStyle.PLAIN;

		if ('iPhone OS' !== Ti.Platform.name) {
			style = Ti.UI.ActivityIndicatorStyle.DARK;
		}

		return style;
	}

	var activityIndicator;
	if (OS_IOS) {
		activityIndicator = Ti.UI.createActivityIndicator({
			style : osIndicatorStyle(),
			left : 0,
			height : Ti.UI.FILL,
			width : 30
		});
	} else {
		activityIndicator = Ti.UI.Android.createProgressIndicator({
  			message: text,
  			location: Ti.UI.Android.PROGRESS_INDICATOR_DIALOG,
  			type: Ti.UI.Android.PROGRESS_INDICATOR_INDETERMINANT,
  			cancelable: false,
		});
	}

	var label = Titanium.UI.createLabel({
		left : 10,
		width : Ti.UI.FILL,
		height : Ti.UI.FILL,
		text : L(text),
		color : '#fff',
		font : {
            fontSize : 16,
            fontFamily : 'OpenSans-Regular',
            fontWeight : 'Regular'
		},
	});

	view.add(activityIndicator);
	view.add(label);
	win.add(view);

	function openIndicator() {
		if(OS_IOS){
			win.open();
		}

		setTimeout(function() {
			activityIndicator.show();
        }, 100);
	}

	win.openIndicator = openIndicator;

	function closeIndicator() {
		if(OS_IOS){
			win.close();
		}

		setTimeout(function() {
			activityIndicator.hide();
        }, 300);
	}

	win.closeIndicator = closeIndicator;

    function setText(text) {
        if(OS_IOS) {
            label.setText(text);
        } else {
            activityIndicator.setMessage(text);
        }
    }

    win.setText = setText;

	return win;
}

// Public interface
exports.createIndicatorWindow = createIndicatorWindow;


text:
/*
 * Oracle LGPL Disclaimer: For the avoidance of doubt, except that if any license choice
 * other than GPL or LGPL is available it will apply instead, Oracle elects to use only
 * the Lesser General Public License version 2.1 (LGPLv2) at this time for any software where
 * a choice of LGPL license versions is made available with the language indicating
 * that LGPLv2 or any later version may be used, or where a choice of which version
 * of the LGPL is applied is otherwise unspecified.
 */

#ifndef __AUDIOSESSIONTYPES__
#define __AUDIOSESSIONTYPES__

typedef enum _AUDCLNT_SHAREMODE
{
    AUDCLNT_SHAREMODE_SHARED,
    AUDCLNT_SHAREMODE_EXCLUSIVE,
} AUDCLNT_SHAREMODE;

#define AUDCLNT_STREAMFLAGS_CROSSPROCESS 0x00010000
#define AUDCLNT_STREAMFLAGS_LOOPBACK 0x00020000
#define AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000
#define AUDCLNT_STREAMFLAGS_NOPERSIST 0x00080000
#define AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
#define AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED 0x10000000
#define AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000
#define AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000

typedef enum _AudioSessionState
{
    AudioSessionStateInactive = 0,
    AudioSessionStateActive,
    AudioSessionStateExpired,
} AudioSessionState;

#endif


text:
void compile_and_link_test()
{
   check_result<float>(boost::math::cbrt<float>(f));
   check_result<double>(boost::math::cbrt<double>(d));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   check_result<long double>(boost::math::cbrt<long double>(l));
#endif
}


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

<TITLE>
Gazetteer (NASA World Wind)
</TITLE>

<META NAME="date" CONTENT="2010-01-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Index
      Help

NASA World Wind

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nasa.worldwind.poi

Interface Gazetteer

All Known Implementing Classes:
YahooGazetteer

public interface Gazetteer

Interface to gazetteers.

Method Summary

 List<PointOfInterest>
findPlaces(String placeInfo)

          Find places identified in a string of free text.

Method Detail

findPlaces

List<PointOfInterest> findPlaces(String placeInfo)
                                 throws NoItemException,
                                        ServiceException

Find places identified in a string of free text.

Parameters:
placeInfo - a string containing the place description.

Returns:
the points-of-interest that match the place description.

Throws:

NoItemException - if the place description cannot be matched.

ServiceException - if the lookup service is not available or invocation of it fails.

      Overview
      Package
    Class
      Use
      Tree
      Index
      Help

NASA World Wind

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/libcore/luni/src/main/java/java/nio/channels/AlreadyBoundException.java
//

#ifndef _JavaNioChannelsAlreadyBoundException_H_
#define _JavaNioChannelsAlreadyBoundException_H_

#include "J2ObjC_header.h"
#include "java/lang/IllegalStateException.h"

/*!
 @brief An AlreadyBoundException is thrown when an attempt is made to bind a NetworkChannel that
 is already bound.
  Until ready for a public API change
 */
@interface JavaNioChannelsAlreadyBoundException : JavaLangIllegalStateException

#pragma mark Public

- (instancetype)init;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaNioChannelsAlreadyBoundException)

FOUNDATION_EXPORT void JavaNioChannelsAlreadyBoundException_init(JavaNioChannelsAlreadyBoundException *self);

FOUNDATION_EXPORT JavaNioChannelsAlreadyBoundException *new_JavaNioChannelsAlreadyBoundException_init() NS_RETURNS_RETAINED;

J2OBJC_TYPE_LITERAL_HEADER(JavaNioChannelsAlreadyBoundException)

#endif // _JavaNioChannelsAlreadyBoundException_H_


text:
<?php
namespace SpareParts\Overseer;

use SpareParts\Enum\Enum;

/**
 * @method static VotingDecisionEnum ALLOWED()
 * @method static VotingDecisionEnum DENIED()
 */
final class VotingDecisionEnum extends Enum
{
    protected static $values = [
        'ALLOWED',
        'DENIED',
    ];
}


text:
import {
  isPresent,
  stringify
} from 'angular2/src/facade/lang';
import {
  provide,
  Inject,
  Injectable,
  Renderer,
  RenderViewRef,
  RenderElementRef
} from 'angular2/core';
import {
  DefaultRenderView,
} from 'angular2/src/core/render/view';

import {DOCUMENT} from 'angular2/src/platform/dom/dom_tokens';
import {
  DomRenderer,
  DomRenderer_
} from 'angular2/src/platform/dom/dom_renderer';

import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {EventManager} from 'angular2/src/platform/dom/events/event_manager';
import {DomSharedStylesHost} from 'angular2/src/platform/dom/shared_styles_host';
import {DOM} from 'angular2/src/platform/dom/dom_adapter';

import {cssHyphenate} from '../helper';

function resolveInternalDomView(viewRef: RenderViewRef): DefaultRenderView<Node> {
  return <DefaultRenderView<Node>>viewRef;
}

@Injectable()
export class ServerDomRenderer_ extends DomRenderer_ {
  constructor(
    private eventManager: EventManager,
    private domSharedStylesHost: DomSharedStylesHost,
    private animate: AnimationBuilder,
    @Inject(DOCUMENT) document) {
     super(eventManager, domSharedStylesHost, animate, document);
  }

  setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any) {
    if (propertyName === 'value' || (propertyName === 'checked' && propertyValue !== false)) {
      let view: DefaultRenderView<Node> = resolveInternalDomView(location.renderView);
      let element = <Element>view.boundElements[(<any>location).boundElementIndex];
      if (DOM.nodeName(element) === 'input') {
        DOM.setAttribute(element, propertyName, propertyValue);
        return;
      }
    } else if (propertyName === 'src') {
      let view: DefaultRenderView<Node> = resolveInternalDomView(location.renderView);
      let element = <Element>view.boundElements[(<any>location).boundElementIndex];
      DOM.setAttribute(element, propertyName, propertyValue);
      return;
    }
    return super.setElementProperty(location, propertyName, propertyValue);
  }

  setElementStyle(location: RenderElementRef, styleName: string, styleValue: string): void {
    let styleNameCased = cssHyphenate(styleName);
    super.setElementProperty(location, styleNameCased, styleValue);
  }

  invokeElementMethod(location: RenderElementRef, methodName: string, args: any[]) {
    if (methodName === 'focus') {
      let view: DefaultRenderView<Node> = resolveInternalDomView(location.renderView);
      let element = <Element>view.boundElements[(<any>location).boundElementIndex];
      if (DOM.nodeName(element) === 'input') {
        DOM.invoke(element, 'autofocus', null);
        return;
      }

    }
    return super.invokeElementMethod(location, methodName, args);
  }

}


text:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class ModerationUnlockRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
			'password' => 'required',
			'secret_password' => 'required',
			'g-recaptcha-response' => 'required|captcha'
        ];
    }
}


text:
import React, { useState, useEffect } from 'react';
import styled from '@emotion/styled';

import theme from '../theme';

const TocList = styled.ol`
  margin: ${theme.space[2]} 0;
  padding-left: ${theme.space[3]};
  border-left: 2px solid ${theme.colors.lightestGray};
  list-style-type: none;
`;

const TocLink = styled.a`
  display: block;
  font-size: ${theme.fontsize[2]};
  color: ${theme.colors.gray};
  transition: color 0.2s;
  line-height: ${theme.lineHeight[1]};
  margin: ${theme.space[2]} 0;

  &:hover {
    color: ${theme.colors.darkGreen};
  }
`;

/**
 * Maually get table of contents since tableOfContents from markdown
 * nodes have code added.
 *
 * https://github.com/gatsbyjs/gatsby/issues/5436
 */
function TableOfContents() {
  const [headings, setHeadings] = useState([]);

  useEffect(() => {
    // TODO: we should be generating headings during the build
    const contentHeadings = document.querySelectorAll('[data-docs-content] h2');
    const headings = [];
    contentHeadings.forEach(h => {
      headings.push({
        id: h.id,
        text: h.innerText,
      });
    });

    setHeadings(headings);
  }, []);

  return (
    headings.length > 0 && (
      <TocList>
        {headings.map(h => (
          <li key={h.id}>
            <TocLink href={`#${h.id}`}>{h.text}</TocLink>
          </li>
        ))}
      </TocList>
    )
  );
}

export default TableOfContents;


text:
package li.strolch.service;

import java.util.Locale;
import java.util.ResourceBundle;

public class I18nService {
	private static final String BUNDLE = "strolch-service";

	public static final ResourceBundle i18nService = ResourceBundle.getBundle(BUNDLE);

	public static ResourceBundle getBundle(Locale locale) {
		return ResourceBundle.getBundle(BUNDLE, locale);
	}

	public static String i18n(Locale locale, String key) {
		ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE, locale);
		if (bundle.containsKey(key))
			return bundle.getString(key);
		return key;
	}
}


text:
import os
import unittest

from stamp import License, constants

class TestLicense(unittest.TestCase):
    """

    """
    def setUp(self):
        test_license_file = os.path.join(os.path.dirname(__file__), 'valid_test_license_file.txt')
        self.inst = License.License(test_license_file)

    def test_is_valid_file_extension(self):
        self.assertFalse(self.inst.is_valid_file_extension('blablabla'))
        self.assertFalse(self.inst.is_valid_file_extension(''))

        self.assertTrue(self.inst.is_valid_file_extension(constants.LANG_EXTENSIONS.keys()[0]))
        self.assertTrue(self.inst.is_valid_file_extension('c'))
        self.assertTrue(self.inst.is_valid_file_extension('C'))

    def test_get_lang_from_extension(self):
        self.assertRaises(IndexError, self.inst.get_lang_from_extension, ('papadoudou'))
        self.assertRaises(IndexError, self.inst.get_lang_from_extension, (' '))

        self.assertIsNotNone(self.inst.get_lang_from_extension('c'))
        self.assertEqual(self.inst.get_lang_from_extension('c'), 'c')

        self.assertIsNotNone(self.inst.get_lang_from_extension('py'))
        self.assertEqual(self.inst.get_lang_from_extension('py'), 'python')

        self.assertIsNotNone(self.inst.get_lang_from_extension('PY'))
        self.assertEqual(self.inst.get_lang_from_extension('PY'), 'python')

    def test_as_dict(self):
        self.assertIsNotNone(self.inst.as_dict())
        self.assertIsInstance(self.inst.as_dict(), dict)
        self.assertIn('content', self.inst.as_dict())
        self.assertIn('size', self.inst.as_dict())

    def test_format_as(self):
        self.assertRaises(KeyError, self.inst.format_as, ('papdoudou'))

        self.assertIsNotNone(self.inst.format_as('C'))
        self.assertIsNotNone(self.inst.format_as('c'))

        self.assertIsInstance(self.inst.format_as('C'), list)
        self.assertEqual(self.inst.format_as('C')[0], constants.LANG_COMMENT_STYLE["stars"][0] + '\n')
        self.assertEqual(self.inst.format_as('C')[-1], constants.LANG_COMMENT_STYLE["stars"][-1] + '\n')

    def test_get_license_as(self):
        self.inst.get_license_as('C')

        self.assertIsNotNone(self.inst.buffered_licenses)
        self.assertIn('c', self.inst.buffered_licenses)  # buffer stores lowercase keys
        self.assertEqual(self.inst.buffered_licenses['c'],
                         self.inst.format_as('c'))

        self.assertNotIn('papadou', self.inst.buffered_licenses)
        self.assertNotIn('python', self.inst.buffered_licenses)

suite = unittest.TestLoader().loadTestsFromTestCase(TestLicense)
unittest.TextTestRunner(verbosity=2).run(suite)


text: <script src="lib/bootstrap-3.2.0/js/bootstrap.min.js"></script>


text:
<!doctype html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html>
<head>
  <meta charset="UTF-8">
  <title>paper-slider test</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

  <script src="../../webcomponentsjs/webcomponents-lite.js"></script>
  <script src="../../web-component-tester/browser.js"></script>
  <script src="../../iron-test-helpers/mock-interactions.js"></script>

  <link rel="import" href="../paper-slider.html">
</head>
<body>

  <test-fixture id="trivialProgress">
    <template>
      <paper-slider></paper-slider>
    </template>
  </test-fixture>

  <script>
    suite('<paper-slider>', function() {
      var slider;

      setup(function() {
        slider = fixture('trivialProgress');
      });

      test('check default', function() {
        assert.equal(slider.min, 0);
        assert.equal(slider.max, 100);
        assert.equal(slider.value, 0);
      });

      test('set value', function(done) {
        slider.value = 50;
        flush(function() {
          assert.equal(slider.value, 50);
          // test clamp value
          slider.value = 60.1;
          flush(function() {
            assert.equal(slider.value, 60);
            done();
          });
        });
      });

      test('set max', function(done) {
        slider.max = 10;
        slider.value = 11;
        flush(function() {
          assert.equal(slider.value, slider.max);
          done();
        });
      });

      test('ratio', function(done) {
        slider.max = 10;
        slider.value = 5;
        flush(function() {
          assert.equal(slider.ratio, 0.5);
          done();
        });
      });

      test('snaps', function(done) {
        slider.snaps = true;
        slider.step = 10;
        slider.max = 100;
        slider.value = 25;
        flush(function() {
          assert.equal(slider.value, 30);

          slider.value = 51.1;

          flush(function() {
            assert.equal(slider.value, 50);
            slider.snaps = false;
            slider.step = 1;
            done();
          });
        });
      });

      test('secondary progress', function(done) {
        slider.max = 10;
        slider.secondaryProgress = 50;
        flush(function() {
          assert.equal(slider.secondaryProgress, slider.max);
          done();
        });
      });

      test('increment', function(done) {
        slider.min = 0;
        slider.max = 10;
        slider.step = 2;
        slider.value = 0;
        slider.increment();

        flush(function() {
          assert.equal(slider.value, slider.step);
            slider.step = 1;
            done();
        });
      });

      test('decrement', function(done) {
        slider.min = 0;
        slider.max = 10;
        slider.step = 2;
        slider.value = 8;
        slider.decrement();

        flush(function() {
          assert.equal(slider.value, 6);
            slider.step = 1;
            done();
        });
      });

      test('editable', function(done) {
        slider.min = 0;
        slider.max = 10;
        slider.step = 1;
        slider.editable = true;

        flush(function() {
          slider.value = 2;
          assert.equal(slider.$$('#input').value, slider.value);
          done();
        });
      });

      test('decimal values', function(done) {
        slider.min = 0;
        slider.max = 1;
        slider.value = slider.min;
        slider.step = 0.1;

        slider.increment();

        flush(function() {
          assert.equal(slider.value, slider.step);
          assert.equal(slider.$.sliderBar.value, slider.step);
          done();
        });
      });

      test('snap to the correct value on tapping', function(done) {
        var cursor = MockInteractions.topLeftOfNode(slider.$.sliderBar);
        cursor.x += slider.$.sliderBar.getBoundingClientRect().width * 0.9;

        slider.min = 0;
        slider.max = 2;
        slider.step = 1;
        slider.value = 0;

        MockInteractions.down(slider.$.sliderBar, cursor);

        flush(function() {
          assert.equal(slider.value, slider.max);
            slider.step = 1;
            done();
        });
      });

      test('value should notify', function(done) {
        var targetValue = 10;

        slider.addEventListener('value-changed', onValueChanged);

        slider.min = 0;
        slider.max = 100;
        slider.value = targetValue;

        function onValueChanged(e) {
          assert.equal(e.detail.value, targetValue);
          done();
          slider.removeEventListener('value-changed', onValueChanged);
        }
      });

      test('immediateValue should notify', function(done) {
        var targetValue = 50;

        slider.addEventListener('immediate-value-changed', function(e) {
          assert.equal(e.detail.value, targetValue);
          assert.equal(slider.immediateValue, targetValue);
          done();
        });

        var cursor = MockInteractions.topLeftOfNode(slider.$.sliderBar);
        cursor.x += slider.$.sliderBar.getBoundingClientRect().width * targetValue/100;

        slider.min = 0;
        slider.max = 100;
        MockInteractions.down(slider.$.sliderBar, cursor);
      });

      test('max markers', function(done) {
        slider.min = 0;
        slider.max = 100;
        slider.snap = true;
        slider.step = 4;
        slider.maxMarkers = 10;
        flush(function() {
          assert.equal(slider.markers.length, 10);
          done();
        });
      });

      test('decimal markers', function(done) {
        slider.min = 0;
        slider.max = 0.7;
        slider.snap = true;
        slider.step = 0.1;
        slider.maxMarkers = 10;
        flush(function() {
          assert.equal(slider.markers.length, 7);
          done();
        });
      });

      test('min greater than max', function(done) {
        slider.min = 101;
        flush(function() {
          assert.equal(slider.markers.length, 0);
          done();
        });
      });

      test('min is NaN', function(done) {
        slider.min = NaN;
        flush(function() {
          assert.equal(slider.markers.length, 0);
          done();
        });
      });

      test('min is Infinity', function(done) {
        slider.min = Infinity;
        flush(function() {
          assert.equal(slider.markers.length, 0);
          done();
        });
      });

      test('max is NaN', function(done) {
        slider.max = NaN;
        flush(function() {
          assert.equal(slider.markers.length, 0);
          done();
        });
      });

      test('max is Infinity', function(done) {
        slider.max = Infinity;
        flush(function() {
          assert.equal(slider.markers.length, 0);
          done();
        });
      });
    });

  </script>

</body>
</html>


text:
from ceilometerclient import client as cc
from ceilometerclient import exc
from ceilometerclient.openstack.common.apiclient import exceptions as api_exc

from heat.engine.clients import client_plugin

class CeilometerClientPlugin(client_plugin.ClientPlugin):

    exceptions_module = [exc, api_exc]

    def _create(self):

        con = self.context
        endpoint_type = self._get_client_option('ceilometer', 'endpoint_type')
        endpoint = self.url_for(service_type='metering',
                                endpoint_type=endpoint_type)
        args = {
            'auth_url': con.auth_url,
            'service_type': 'metering',
            'project_id': con.tenant,
            'token': lambda: self.auth_token,
            'endpoint_type': endpoint_type,
            'ca_file': self._get_client_option('ceilometer', 'ca_file'),
            'cert_file': self._get_client_option('ceilometer', 'cert_file'),
            'key_file': self._get_client_option('ceilometer', 'key_file'),
            'insecure': self._get_client_option('ceilometer', 'insecure')
        }

        return cc.Client('2', endpoint, **args)

    def is_not_found(self, ex):
        return isinstance(ex, (exc.HTTPNotFound, api_exc.NotFound))

    def is_over_limit(self, ex):
        return isinstance(ex, exc.HTTPOverLimit)


text:
\documentclass[12pt,letterpaper,twoside]{article}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{appendix}
\usepackage[figurewithin=section,tablewithin=section]{caption}
\usepackage[usenames,dvipsnames]{color}
\usepackage{graphicx}
\usepackage{longtable}
\usepackage{rotating}
%\usepackage{verbatim}
\usepackage[pdftex,bookmarksopen=false]{hyperref}
%\usepackage[pdftex]{hyperref}
\hypersetup{pdfauthor={John Sibert}}
\hypersetup{pdfsubject={Assessment Model of MHI YFT Stocks}}
\hypersetup{pdftitle={Assessment Models for Hawaiian Islands
Yellowfin Tuna Fishery}}
\hypersetup{pdfkeywords={yellowfin,state space, biomass transfer, model,Hawaii}}

\newcommand\doublespacing{\baselineskip=1.6\normalbaselineskip}
\newcommand\singlespacing{\baselineskip=1.0\normalbaselineskip}
\renewcommand\deg[1]{$^\circ$#1}
\newcommand\SD{SEAPODYM}
\newcommand\MFCL{MULTIFAN-CL}
\newcommand\ADMB{ADModel Builder}
\newcommand\SPC{Secretariat of the Pacific Community}
\newcommand\WCPO{Western Central Pacific Ocean}
\newcommand\WCPFC{Western Central Pacific Fisheries Commission}
\newcommand\SSAP{Skipjack Survey and Assessment Programme}
\newcommand\RTTP{Regional Tuna Tagging Programme}
\newcommand\PTTP{Pacific Tuna Tagging Programme}
\newcommand\FAD{fish aggregating device}
\newcommand\ADRM{advection-diffusion-reaction model}
\newcommand\help[1]{\color{Magenta}{\it #1}\normalcolor}
\newcommand\widebar[1]{\overline{#1}}
\newcommand\EEZ{Exclusive Economic Zone}

\newcommand\None{{N_{1,1}}}
\newcommand\Ntwo{{N_{2,1}}}
\newcommand\Nsum{{N_{1,1}+N_{2,1}}}
\newcommand\peryr{yr$^{-1}$}
\newcommand\prevN[1]{{#1_{t-\Delta t}}}
\newcommand\nextN[1]{{#1_t}}
\newcommand\MSY{\widetilde{Y}}
\newcommand\Fmsy{F_{\MSY}}
\newcommand\MSYFmsy{\MSY\;\Fmsy}
\newcommand\Bd{B_1\; d}

\title{Feasibility of developing a stock assessment model for Main
Hawaiian Islands Yellowfin Tuna Fishery\\
\vspace{2ex}
Part Two}

\author{
John Sibert\thanks{sibert@hawaii.edu}\\
Joint Institute of Marine and Atmospheric Research\\
University of Hawai'i at Manoa\\
Honolulu, HI  96822 U.S.A.\\[0.125in]
\date{\today}
}

\pagestyle{myheadings}
\markboth{John Sibert\hfil MHI Yellowfin Assessment Model
Feasibility --- 2}
{MHI Yellowfin Assessment Model Feasibility --- 2\hfil John Sibert}

\begin{document}
% amsmath package
\numberwithin{equation}{section}
\numberwithin{figure}{section}
\maketitle

%\doublespacing

\begin{abstract}
Single population models with simplified model structure
were developed to test the feasibility of developing a stock
assessment model for the Main Hawaiian Islands yellowfin tuna fishery.
These models are capable of
estimating critical reference points such as maximum sustainable
yield (MSY) and fishing mortality at MSY.
Biomass trends between 1952 and 2012 estimated by using different
model configurations differ in general level, but are
qualitatively consistent across models. All models estimate a period of high
biomass between 1970 and 1990,
including periods where the biomass exceeds the
equilibrium biomass or ``carrying capacity''.
These models are
promising starting points for development of a full-featured stock
assessment model.
\end{abstract}

\section{Introduction}
A previous evaluation of the feasibility of developing a
stock assessment model for the Main Hawaiian Islands (MHI) yellowfin
tuna (YFT)
fishery concluded that such a model is feasible, but that estimation of
fishery management reference points is difficult (Sibert, 2015).
The ambiguity of this
conclusion is unsatisfying, and further research was undertaken to
develop more practical alternative models.
The 2015 model represented
the dynamics of two coupled tuna populations with immigration,
emigration, and fishing and required estimation of approximately 15
parameters. Here I report results of evaluating single
population models with simplified dynamics and fewer parameters.

\section{Methods}
%Model feasibility depends equally on the model and on whether the
%available data contain sufficient information to estimate model
%parameters.  Evaluation of feasibility challenges both the model and
%the available data.

The data used in this analysis are the annual catch data from
five gear types fishing within 200 nm of the Main Hawaiian Islands
(Sibert, 2015).

The basic model is a state-space implementation of the
Schaefer biomass dynamics model (Schaefer, 1954).
The principle model assumptions are:
\begin{enumerate}
\item The dynamics of the population of YFT in the MHI follows a
simple Schaefer model.
\item Fishing mortality is represented by a random walk (Nielsen and
Berg, 2014).
\item The local dynamics are ``forced'' by assuming that the local
abundance is approximately proportional to some ``index'' population.
\end{enumerate}

The basic model was implemented with two different parameter
substitutions in an attempt to find parameter combinations that are
more reliably estimated. Indexing was implemented flexibly to
demonstrate the effects of omitting the index altogether.

Model estimates of yellowfin biomass by \MFCL\ (MFCL)
from the most recent \WCPFC\ stock assessment (Davies et al, 2014) provide
a convenient choice of biomass indices. The MHI straddle the
boundary between MFCL regions 2 and 4. Region 2 is arguably more similar
ecologically to the MHI than the more equatorial region 4. The
YFT population
in region 4 is much larger and exhibits a greater level of depletion than the
population in region 2. Estimated biomass trends from MFCL region 2
were used as the abundance index for most model feasibility evaluations.

Complete details of model structure are presented in Appendix~\ref{sec:models}.

\section{Results}

\begin{table}
\caption{
Model estimates from four different model configurations using the
default prior on $r$.
Model complexity, expressed in number of parameters estimated ($n$)
increases from left to right. Long dashes (---) indicate parameters
not estimated.
{%\small
%$n$ indicates the number of parameters estimated;
$-\log L$ is the negative log likelihood (the smaller the number, the
better the fit);
$|G|_{max}$ is the curvature of the likelihood at the its apparent
minimum (values greater than $0.01$ indicate non-convergence);
other variables are defined in Table~\ref{tab:allvars1}.
}
\label{tag:ests4}}
\begin{center}
\begin{tabular}{|l|rr|rr|}
\hline
Index & \multicolumn{2}{c|}{None}&\multicolumn{2}{c|}{MFCL 2}\\
\cline{2-3}\cline{4-5}
Parameterization&$\MSYFmsy$&$\Bd$&$\MSYFmsy$&$\Bd$\\
Designation& A & B& C& D\\
\hline
\hline
$n$ & 4 & 5 & 5 & 6\\
$-\log L$ & -237.238 & -237.968 & -247.175 & -243.343\\
$|G|_{max}$ & 0.0016409 & 33.1289 & 3.51082e-05 & 3.77653\\
AIC & -466.476 & -465.936 & -484.35 & -474.686\\
\hline
$B_1$ & --- & 1184.2 & --- & 2802.3\\
$d$ & --- & 9.6674 & --- & 2.6348\\
$\MSY$ & 1147.5 & 1199.3 & 1288.7 & 1032.6\\
$\Fmsy$ & 0.82239 & 0.20952 & 0.1668 & 0.2797\\
$r$ & 1.6448 & 0.41904 & 0.3336 & 0.5594\\
$K$ & 2790.8 & 11448 & 15452 & 7383.5\\
$\sigma_P$ & 0.37416 & 0.36757 & 0.2743 & 0.2649\\
$\sigma_Y$ & 0.41693 & 0.43062 & 0.46924 & 0.47614\\
$Q$ & --- & --- & 0.04321 & 0.016535\\
\hline
\end{tabular}
\end{center}
\end{table}

Fitting results are summarized in Table~\ref{tag:ests4}.
Both the indexed and non-indexed configurations of the $\MSYFmsy$
parameterization
appear to converge to a meaningful solution with $|G|_{max}<0.01$
whereas the  $\Bd$ parameterizations appear not to have converged.
Non-indexed models can be considered ``nested'' within indexed
models with the parameter $Q$ constrained to be zero. A likelihood
ratio test is therefore appropriate to test the effect of including
the abundance index in converged $\MSYFmsy$ models.
The change in negative log likelihood
from -237.238 to -247.175 with one degree of freedom is a statistically
significant change with $P<0.005$.

\begin{figure}[h]
\begin{center}
\includegraphics[width=\textwidth]{./graphics/biomass-array.pdf}
\caption{\label{fig:estbiomass}
Estimated biomass trends for the model configurations indicated in
the upper left of each panel.
Blue lines indicate the estimated biomass in metric tons (mt).
The purple line indicates the estimated biomass index using MFCL
region 2 biomass as the index of abundance.
The light blue shaded areas represent the process error as
$\pm 2\sigma_P$.
The equilibrium biomass $K$ is indicated by the blue dot-dash line.
Note that the scale of the ordinate is different in each panel.
}
\end{center}
\end{figure}

Estimated biomass trends for the four models are shown in
Figure~\ref{fig:estbiomass}.
All four models, including the non-indexed models, predict a large
decrease in biomass between 1975 and 2000. The estimated biomass
decrease mimics the MFCL region 2 biomass trend in the
indexed models, and the indexed models amplify the decrease. The
predicted biomass in the both $\MSYFmsy$ models
and the indexed $\Bd$ model exceeds the equilibrium biomass in the 1970s.
\pagebreak

There is an approximate five-fold difference in estimated population size
between the indexed and non-indexed $\MSYFmsy$ models.
The indexed model estimates a larger and slower growing stock than the
non-indexed model as indicated by estimated values of $r$ and $K$.

\begin{figure}[h]
\begin{center}
\includegraphics[width=\textwidth]{./graphics/production-array.pdf}
\caption{\label{fig:estprod}
Catch plotted against fishing mortality (production curves)
for the model configurations indicated in the upper left of each panel.
The green line and dark green dots are estimated catch plotted
against fishing mortality.
The green $+$ symbols are the observed catch annotated with the year.
The dashed red line is the theoretical equilibrium yield.
Note that the scale of the abscissa is different in each panel.
}
\end{center}
\end{figure}

\vbox{ % keeps paragraph from breaking
Production curves for the four models are shown in
Figure~\ref{fig:estprod}.
The peaks of the production curves
are near the highest observed catches
in the two non-indexed models and occur within the range of the
estimated fishing mortality.
In contrast, the peak of the production curve for the indexed models
are greater than the highest observed catches and greater than
the highest estimated fishing mortality.
Catches exceed the production curve between the mid 1970s through the
mid 1990s and drop below the production curve after 2000.
}

\begin{table}[h]
\caption{
Model estimates from four different model configurations omitting the
prior on $r$.
Model complexity, expressed in number of parameters estimated ($n$)
increases from left to right. Long dashes (---) indicate parameters
not estimated.
{%\small
%$n$ indicates the number of parameters estimated;
$-\log L$ is the negative log likelihood (the smaller the number, the
better the fit);
$|G|_{max}$ is the curvature of the likelihood at the its apparent
minimum (values greater than $0.01$ indicate non-convergence);
other variables are defined in Table~\ref{tab:allvars1}.
}
\label{tag:ests4NOprior}}
\begin{center}
\begin{tabular}{|l|rr|rr|}
\hline
Index & \multicolumn{2}{c|}{None}&\multicolumn{2}{c|}{MFCL 2}\\
\cline{2-3}\cline{4-5}
Parameterization&$\MSYFmsy$&$\Bd$&$\MSYFmsy$&$\Bd$\\
Designation& A & B& C& D\\
\hline

\hline
$n$ & 4 & 5 & 5 & 6\\
$-\log L$ & -284.898 & -236.212 & -246.302 & -242.176\\
$|G|_{max}$ & 2.45563 & 151.693 & 1.24795e-05 & 39.9125\\
AIC & 577.796 & 482.424 & 502.604 & 496.352\\
\hline
$B_1$ & --- & 1540.2 & --- & ---\\
$d$ & --- & 12.567 & --- & ---\\
$\MSY$ & --- & 1274.9 & 1579.3 & ---\\
$\Fmsy$ & --- & 0.13174 & 0.1293 & ---\\
$r$ & --- & 0.26347 & 0.25859 & ---\\
$K$ & --- & 19355 & 24430 & ---\\
$\sigma_P$ & --- & 0.35682 & 0.27044 & ---\\
$\sigma_Y$ & --- & 0.43481 & 0.47162 & ---\\
$Q$ & --- & --- & 0.073752 & ---\\
\hline
\end{tabular}
\end{center}
\end{table}

Table~\ref{tag:ests4NOprior} summarizes the effects of omitting the
Bayesian prior on the growth rate parameter, $r$. Only one model
configuration, $\MSYFmsy$, converged to a solution with
$|G|_{max}<0.01$. The negative
log likelihood is slightly higher than the same model configuration
using the default prior, suggesting poorer agreement to the data. The
estimated population dynamics indicates a larger and slower growing
population.

\section{Discussion}
The consistent predictions of high biomass in the 1970s followed by a
persistent decrease in biomass through 2000 in the non-indexed models
is evidence that the catch data provide information on
the relative abundance of YFT in the MHI. The dependency of absolute
biomass estimates on an abundance index is characteristic of
production models \help{(references)} and is cause for caution
in drawing fishery management conclusions from these tentative results.

\begin{figure}[h]
\begin{center}
\begin{tabular}{lr}
\includegraphics[width=0.495\textwidth]{./graphics/est_popB1.pdf}&
\includegraphics[width=0.495\textwidth]{./graphics/est_FB1.pdf}\\
\end{tabular}
\end{center}
\caption{\label{fig:estr4}
Estimated biomass trend and production curve from the $\MSYFmsy$
model indexed to \MFCL\ region 4.
See Figures~\ref{fig:estbiomass} and \ref{fig:estprod} for legends.
}
\end{figure}

The choice of index populations makes a large difference in fishery management
conclusions. Figure~\ref{fig:estr4} shows the biomass trend and
production curve for the MHI population indexed to the MFCL region 4
biomass estimates. This choice of index would lead to completely
different fishery management conclusions.
An alternative to selecting MFCL region
biomass estimates as population indexes would be to use
biomass estimates and predictions from the \SD\ model (Senina et al,
2008) as an index of MHI biomass.

Using the output of one model in another model is sometimes known as
``off-line'' coupling, and is used in \SD\ to couple
ecosystem models to tuna population dynamics
This approach is also sometimes disdained as ``piecemeal''
modeling because the variance structure is not usually propagated from
one model to the next. Such propagation may be possible but was not
examined.

Both \MFCL\ and \SD\ predict age and size structure of tuna stocks.
There are some size data for the MHI YFT landings that could be
incorporated into an age-structured model. No work was undertaken to
develop age-structured models.

The use of a random walk to represent fishing mortality ($F$) is a
unique feature of the model presented here.
This approach avoids the problem
of attempting to contrive an objective measure of fishing effort
along with a time-varying catchability coefficient
on which some estimate of $F$ could be based. The random walk provides
a convenient measure of $F$ that enables the logistic model
to estimate population dynamics parameters from catch data alone.

The imposition of Bayesian priors on Schaefer model growth parameters
is often considered essential (\help{references}).
Both the $\MSYFmsy$ and $\Bd$
parameterizations avoid the problem of estimating $K$ and $r$
simultaneously. The use of a prior on $r$ would appear to offer no
benefit to the $\MSYFmsy$ models, but seems to assist the $\Bd$
models. The great disadvantages of priors are the difficulty of finding
suitable values and the unwanted risk of introducing bias
into the resulting estimates.

The recreational catch of yellowfin tuna in the MHI is thought to be
quite large, approximately the same order of magnitude as the
commercial catch \help{references}.
The lack of readily available accurate estimates of the recreational
catch of YFT makes development of a credible assessment model very
difficult. No attempts were make to evaluate the effects of this
deficiency on estimated model parameters.

\section{Conclusions}
\begin{enumerate}
\item Yellowfin catch data from fleets operating in the Main Hawaiian
Islands waters are sufficiently informative to estimate relative
biomass trends.
\item An index of abundance is required to estimate absolute biomass,
but absolute estimates are sensitive to the choice of index
population.
\item Representing trends in fishing mortality as a random walk is a
convenient and effective approach to accounting for the removal of
biomass from the fish population.
\item Bayesian prior on $r$ are difficult to assign and probably not required.
\end{enumerate}

\vspace{4ex}
%\clearpage
\noindent {\bf Acknowledgements.}
This work was funded by the Western Pacific Regional Fisheries
Managment Council. I thank the Council for its generous support and
Council Staff Paul Dalzell and Eric Kingma for encouraging me to
actually take on this challenging project and for their on-going
collaboration.
Thanks to David Fournier for suggesting the ``$\Bd$''
parameterization of the Schaefer model,
to David Itano for sharing insights into the small-boat
fisheries in Hawaii,
to Reginald Kokubun of the Hawaii Division of Aquatic
Resources for supplying catch report data from the HDAR commercial
fisheries data base,
to Keith Bigelow and Karen Sender of NOAA Pacific
Island Fisheries Science Center for supplying logbook reporting data and
weight-frequency data from the PIFSC data base.
Thanks also to John Hampton of the Secretariat of the Pacific
Community, Oceanic Fisheries Programme, for making available \MFCL\
output files from the latest Western and Central Pacific
Fisheries Commission yellowfin tuna stock assessment, and to Nick
Davies for sharing R scripts and advice on interpreting those files.

\section*{References}
{\parindent=0cm \small
\everypar={\hangindent=2em \hangafter=1}\par
%\doublespacing
Carruthers, T. and M. McAllister. 2011.
Computing prior probability distributions for the
intrinsic rate of increase for atlantic tuna and
billfish using demographic methods.
Collect. Vol. Sci. Pap. ICCAT, 66(5): 2202-2205.

Davies, N., S. Harley, J. Hampton, S. McKechnie. 2014. Stock
assessment of yellowfin tuna in the western and central pacific ocean.
WCPFC-SC10-2014/SA-WP-04.

Fournier, D. A., H.J. Skaug, J. Ancheta, J.Sibert, J. Ianelli,
A. Magnusson, M. N. Maunder, A. Nielsen. 2012. AD Model Builder:
using automatic differentiation for for statistical inference of highly
parameterized complex nonlinear models. Optimization Methods and
Software 27, 233–249.

Nielsen, A., C. Berg. 2014. Estimation of time-varying selectivity
in stock assessments using state-space models. Fisheries Research
158:96-101.

Murray, J. D. 1993. Mathematical biology. Second Edition.
Springer-Verlag. 767pp.

Quinn, T, R. Deriso. 1999. Quantitative fish dynamics. Oxford
University Press, New York.

Schaefer, M. B. 1954. Some aspects of the dynamics of populations
important to the management of the commercial marine fisheries. IATTC
Bull. 1(2):27-56.

Senina, I., J. Sibert, P. Lehodey  2008. Parameter estimation for
basin-scale ecosystem linked population models of large pelagic
predators: Application to skipjack tuna.  Prog. Oceanogr. 78:319-335.

Sibert, J. R. 2015. Feasibility of devloping a stock assessment
model for Main Hawaiian Islands Yellowfin Tuna Fishery.
119th Meeting of the Scientific and Statistical Committee.
Document 7.A.1(1)Rev 1.

Skaug, H., Fournier, D., 2006. Automatic approximation of the marginal
likelihood in non-Gaussian hierarchical models. Computational
Statistics \& Data Analysis 51, 699–709.

Wells, D., J. Rooker, D. Itano. 2012.  Nursery origin of yellowfin
tuna in the Hawaiian Islands. Mar. Ecol. Prog. Ser. 461:187-196.
\par}

\clearpage

\appendix
\section{Model development}
\label{sec:models}
State-space models separate variability in the biological
processes in the system (transition model)
from errors in observing features of interest
in the system (observation model).

{\bf Transition Model $T(\alpha_{t-1})$.}
The general form of the transition model is
\begin{equation}
\alpha_t=T(\alpha_{t-1}) + \eta_t
\end{equation}
where $\alpha_t$ is the state at time $t$ and
the function $T$ embodies the dynamics mediating the
development of the state at time $t$ from the state at the previous
time with random process error, $\eta_t$.

Stock dynamics follow the classic Schaefer differential equation:
\begin{equation}
\label{eqn:ischaefer}
\frac{dN}{dt} = rN(1-\frac{N}{K}) - FN
\end{equation}
where $N$ is the biomass of YFT in the MHI,
$r$ is the logistic growth rate per year,
$K$ is the asymptotic biomass, and
$F$ is the total fishing mortality per year in the MHI.

The state space transition equation for the single population model is
developed by solving \ref{eqn:ischaefer} analytically from one time to
the next (see Appendix \ref{sec:schaefer}).
\begin{equation}
\label{eqn:intschaeferA}
N_t = \frac{K(r-\bar{F}_t)}{\frac{K(r-\bar{F}_t)}{N_{t-\Delta t}}e^{-\Delta
t(r-\bar{F}_t)}-re^{-\Delta t(r-\bar{F}_t)} -r} \cdot e^{\eta_t};
\quad \eta_t\sim N(0,\sigma^2_N)
\end{equation}
where
$\bar{F}_t$ is the total fishing mortality, i. e.,
$$
\bar{F}_t =\sum_{g=1}^n F_{g,t-\Delta t}.
$$
and $\eta_t \sim N(0,\sigma_N)$ is a process error expressing
variability in population dynamics.

Fishing mortality is treated as a random walk.
The logarithm of fishing mortality is assumed to
follow a random walk with normal increments, as suggested by Berg and
Nielsen (2014).
\begin{equation}
\label{eqn:Fwalk}
\log F_{g,t} = \log F_{g,t-1} + \xi_t;\quad \xi_t\sim
N(0,\sigma^2_F)
\end{equation}
where  $\sigma^2_F$ is a process error expressing the year to year
variability in fishing mortality.

The indexed abundance model assumes that the biomass of YFT in the MHI
is approximately proportional to the biomass of an ``index''
population.
\begin{equation}
\log N_t - \log (Q\cdot I_t) = \omega_t;\quad \omega_t\sim N(0,\sigma^2_I)
\label{eqn:index}
\end{equation}
where
$I_t$ is the size of the index population at time $t$,
$Q$ is the estimated ratio of the MHI population size to the index
population,
and $\sigma^2_I$ is a process error representing the difference
between the MHI biomass and the abundance index.

All process errors are assumed to have the same distribution
$N(0,\sigma^2_P)$; $\sigma_N$,$\sigma_F$, and $\sigma_I$ are assumed
to be equal and estimated as a global process error with variance
$\sigma^2_P$.

The logistic parameters $r$ and $K$ are notoriously difficult to estimate
accurately. Two different
alternative parameter substitutions were tested. In the first
alternative, MSY ($\MSY$) and fishing mortality at MSY ($\Fmsy$) were
estimated directly and substituted in \ref{eqn:intschaeferA} as
$r=2F_{\MSY}$ and $K=\frac{4\MSY}{r}$.
In the second alternative, the initial population size $B_1$ and a
proportionality constant $d$ are estimated directly and substituted in
\ref{eqn:intschaeferA} as $K=d\cdot B_1$.

Carruthers and McAllister (2011) recommend use of Bayesian priors for the
logistic growth parameter $r$ in equation~(\ref{eqn:ischaefer}). They
suggest $\tilde{r} = 0.486$ with a standard deviation of $\sigma_r = 0.046$
and coefficient of variation of ${\rm cv}=0.094$ for Atlantic YFT.
A lognormal prior on $r$ was implemented with
$\tilde{r} = 0.486$ and $\sigma_r = 0.8$.
\begin{equation}
\log r - \log \tilde{r} = \rho ;\quad \rho\sim N(0,\sigma^2_r)
\end{equation}
which is a fairly ``loose'' constraint on the estimate of $r$.
$\rho$ becomes a component of the likelihood
(equation~\ref{eqn:likelihood}).

{\bf Observation Model, $O(\alpha)$.}
The general form of the observation model is
\begin{equation}
x_t = O(\alpha_t) + \varepsilon_t
\end{equation}
where the function $O$ describes the measurement process with
error $\varepsilon$ in observing the population.

Predicted catch, $\widehat{C}_{g,t}$, for each gear is the product of
estimated fishing mortality and the total biomass.
\begin{equation}
\widehat{C}_{g,t} = F_{g,t}\cdot\Bigl(\frac{N_{t-\Delta
t}+N_t}{2}\Bigr) \cdot e^{\varepsilon_t}
\label{eqn:obs1}
\end{equation}
where the total biomass is  the average
biomass over the time step (Quinn and Deriso, 1999), and
$\varepsilon_t$ is a ``zero-inflated'' log normal likelihood given by
\begin{equation}
  \log \varepsilon_t = \left\{
    \begin{array}{r@{\;:\quad}l}
       C_{g,t} > 0 &
(1-p_0)\cdot\bigg(\log\frac{1}{\sqrt{2\pi\sigma^2_Y}}
          -\Bigl(\frac{\log
C_{g,t}-\log\widehat{C}_{g,t}}{\sigma_Y}\Bigr)^2\bigg)\\
       C_{g,t} = 0 & p_0 \cdot\log \frac{1}{\sqrt{2\pi\sigma^2_Y}}\\
    \end{array}
  \right.
\end{equation}
where $\sigma_Y$ is the observation error and
$p_0$ is the proportion of observed catch observations equal to zero.
This proportion may be estimated or fixed at a constant value. For
current analysis, it is fixed at $p_0 = 0.15738$ as computed from the data.
% line 186, file issams.cpp, prop_zero =  0.4918 0 0 0.098361 0.19672, tprop_zero = 0.15738

\begin{table}
\caption{Complete list of estimated parameters for two alternative
parameterizations of the state-space single population Schaefer model.
Values of non-estimated model variables, e.g., $K$, are computed by
parameter substitution formulas.}
\label{tab:allvars1}
\begin{center}
\begin{tabular}{lll}
\hline
$\MSY\;\Fmsy$ & $B_1\;d$ & Definition\\
\hline
\hline
$\Fmsy$&  & Fishing mortality at maximum sustainable yield\\
$\MSY$ &  & Maximum sustainable yield\\
    & $r$ & Instantaneous growth rate\\
    & $B_1$ & Biomass at time of first observation\\
    &  $d $ & Constant of proportionality; $B_1=Q\cdot K$\\
$Q$ & $Q$ & Abundance index proportionality constant\\
$\sigma_P$ & $\sigma_P$ & Global process error SD; $\sigma_P=\sigma_N=\sigma_F=\sigma_I$\\
$\sigma_Y$ & $\sigma_Y$ & Observation error SD \\
\hline
$p_0$ & $p_0$ & Proportion of zero catch observations;\\
      &       & fixed at $p_0 = 0.15738$\\
$\tilde{r}$ & $\tilde{r}$ & An {\it a priori} assumed value for $r$\\
            &             & fixed at $\tilde{r}=0.486$ (Carruthers and McAllister, 2011)\\
$\sigma_r$  & $\sigma_r$  & Assumed standard deviation of $r$ around its prior;\\
            &             & fixed at $\sigma_r=0.8$.\\
\hline
\end{tabular}
\end{center}
\end{table}

{\bf Estimation.} The model states, $N_t$ and $F_{gt}$, are assumed to be random
effects (Skaug and Fournier, 2006). Model parameters are estimated by
maximizing the joint likelihood of the random
effects and the observations.
\begin{equation}
\label{eqn:likelihood}
L(\theta,\alpha,x)=
\prod^m_{t=2}\big[\phi\big(\alpha_t-T(\alpha_{t-1}), \Sigma_\eta\big)\big]\cdot
\prod^m_{t=1}\big[\phi\big(x_t-O(\alpha_t),
\Sigma_\varepsilon\big)\big]\cdot\rho
\end{equation}
Here, $m$ is the number of time steps in the catch time series and
$\theta$ is a vector of model parameters (Table~\ref{tab:allvars1}).
The model is implemented in ADMB-RE (Fournier et al, 2012).
The actual number of
parameters to be estimated depends on the model configuration,
specified by phase flags in the input file.
All computer code, data files, and draft reports in support of this
analysis can be found at Github:
\url{https://github.com/johnrsibert/XSSA.git}.

\clearpage
\input{schaefer_section}

\end{document}

\begin{figure}
\begin{center}
\begin{tabular}{lr}
\includegraphics[width=0.495\textwidth]{./graphics/biomass-array.pdf}&
\includegraphics[width=0.495\textwidth]{./graphics/production-array.pdf}\\
\end{tabular}
\end{center}
\caption{\label{fig:estprod}Blah blah}
\end{figure}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>达人游记-<{$setting.SiteName}></title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<link rel="stylesheet" href="<{$mod_path}>css/animate.min.css" />
	<link rel="stylesheet" href="<{$mod_path}>css/bootstrap.css" />
	<link rel="stylesheet" href="<{$mod_path}>css/style.css" />
	<link rel="stylesheet" href="<{$mod_path}>css/flexslider.css" />
	<link rel="stylesheet" href="<{$mod_path}>css/font-awesome.css" />
	<link rel="stylesheet" href="<{$mod_path}>css/prettyPhoto.css" />
	<link rel="stylesheet" href="<{$mod_path}>css/responsive.css" />
	<link rel="stylesheet" href="<{$mod_path}>css/content.css" />

<{include file="common/head.html"}>
<div class="baner_content" style="background:url(<{$baner.imaadd}>) center no-repeat;">

    	<{foreach from=$show.news_list_data item = n_l_d}>

<a href="/youjiview/<{$n_l_d.ID}>.html"><img src="<{$n_l_d.NImg}>" width="440" height="312">

<a href="/youjiview/<{$n_l_d.ID}>.html"><{$n_l_d.Newstitle}>

                    <{$n_l_d.addtime}>

<{$n_l_d.Ndescription|truncate:120:"...":true}>

                <a class="view" href="/youjiview/<{$n_l_d.ID}>.html">查看

        <{/foreach}>

<{$show.showpage}>

<{include file="common/foot.html"}>


text:
package org.diorite.config.exceptions;

import javax.annotation.Nullable;

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

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

import org.diorite.commons.reflections.DioriteReflectionUtils;
import org.diorite.config.Config;
import org.diorite.config.ConfigPropertyTemplate;
import org.diorite.config.ConfigPropertyValue;
import org.diorite.config.ConfigTemplate;

/**
 * Thrown by internal code when validation fails, should not be thrown from validators!
 */
public final class ValidationException extends RuntimeException
{
    private static final ToStringStyle toStringStyle;

    static
    {
        ToStringStyle tmp;
        try
        {
            tmp = ToStringStyle.JSON_STYLE;
        }
        catch (Throwable e)
        {
            tmp = ToStringStyle.SHORT_PREFIX_STYLE;
        }
        toStringStyle = tmp;
    }

    private static final long serialVersionUID = 0;

    private <T> ValidationException(String message, Throwable cause)
    {
        super(message, cause);
    }

    private <T> ValidationException(String message)
    {
        super(message);
    }

    static <T> ValidationException of(ConfigPropertyValue<T> template, @Nullable T value, @Nullable String message, @Nullable Throwable cause)
    {
        if ((message == null) && (cause != null))
        {
            message = cause.getMessage();
        }
        if (message == null)
        {
            message = "unknown error";
        }
        StringBuilder expBuilder = new StringBuilder();
        ConfigPropertyTemplate<T> property = template.getProperty();
        Config declaringConfig = template.getDeclaringConfig();
        ConfigTemplate<?> cfgTemplate = declaringConfig.template();
        expBuilder.append("Failed to validate value for property: '").append(message).append("'\n")
                  .append("    Property name: ").append(template.getName()).append(" (").append(property.getOriginalName()).append(")\n")
                  .append("    Property type: ").append(template.getGenericType()).append("\n")
                  .append("    Config: ").append(declaringConfig.name()).append(" (").append(cfgTemplate.getConfigType().getCanonicalName()).append(")\n");

        List<Exception> suppressed = new ArrayList<>(2);
        try
        {
            T rawValue = template.getRawValue();
            expBuilder.append("    Current value: ").append(rawValue);

            if ((rawValue != null) && ! DioriteReflectionUtils.getPrimitive(rawValue.getClass()).isPrimitive())
            {
                expBuilder.append(" (").append(ReflectionToStringBuilder.toString(template.getRawType(), toStringStyle)).append(")");
            }
            expBuilder.append("\n");
        }
        catch (Exception ignored)
        {
            suppressed.add(ignored);
        }

        expBuilder.append("    Failed value: ").append(value);
        if ((value != null) && ! DioriteReflectionUtils.getPrimitive(value.getClass()).isPrimitive())
        {
            try
            {
                expBuilder.append(" (").append(ReflectionToStringBuilder.toString(value, toStringStyle)).append(")");
            }
            catch (Exception ignored)
            {
                suppressed.add(ignored);
            }
        }
        if (cause != null)
        {
            for (Exception exception : suppressed)
            {
                cause.addSuppressed(exception);
            }
            return new ValidationException(expBuilder.toString(), cause);
        }
        else
        {
            ValidationException validationException = new ValidationException(expBuilder.toString());
            for (Exception exception : suppressed)
            {
                validationException.addSuppressed(exception);
            }
            return validationException;
        }
    }

    public static <T> ValidationException of(ConfigPropertyValue<T> template, @Nullable T value, Throwable cause)
    {
        return of(template, value, cause.getMessage(), cause);
    }

    public static <T> ValidationException of(ConfigPropertyValue<T> template, @Nullable T value, String cause)
    {
        return of(template, value, cause, null);
    }
}


text:
const configs = {
    menu: {
        insertMethod: 'prepend',
        insertSelector: 'body'
    },
    page: {
        nodetype: 'div',
        selector: null,
        noSelector: []
    }
};
export default configs;


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>{{{ $title }}}</title>
        <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>

        @if(isset($style))
            @include($style)
        @else
            @include('admin.styles.global')
        @endif

                {{ \Ngungut\Nccms\Model\Settings::getTitle() }}

                    Toggle navigation

 Libraries

 Upload

                @yield('content')

        @if(isset($script))
            @include($script)
        @else
            @include('admin.scripts.global')
        @endif


text:
package fi.tut.senseback.calibration;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.squareup.otto.Subscribe;

import fi.tut.senseback.R;
import fi.tut.senseback.bleconnection.BLEResponseCodes;
import fi.tut.senseback.bleconnection.ConnectionState;
import fi.tut.senseback.events.BusHandler;
import fi.tut.senseback.events.ReturnBLEResponseEvent;

/*
* Fragment where users can calibrate and start the sensors.
*
* When users press a calibration button, calibration message is sent to RFduino.
* RFduino updates its calibration and sends a response to Android.
* When the response is received, Android user is notified that calibration was successful.
*
 */
public class StartFragment extends Fragment {
    private Button instructionsButton;
    private Button calibrate0Sensor3Button;
    private Button calibrate0Sensor4Button;
    private Button calibrate0Sensor5Button;
    private Button calibrate0Sensor6Button;
    private Button calibrate90Sensor3Button;
    private Button calibrate90Sensor4Button;
    private Button calibrate90Sensor5Button;
    private Button calibrate90Sensor6Button;
    private Button startSensors34Button;
    private Button startSensors56Button;
    private Button stopSensors34Button;
    private Button stopSensors56Button;

    private ProgressDialog progress;
    private WaitForCalibration currentCalibration;

    /*
    * When users press a calibration button, they are given 5 seconds time
    * to position the sensor before calibration message is sent to RFduino via BLE.
    *
    * @param Character code that is sent to RFduino. This tells RFduino which sensor and which angle
    * we are calibrating.
    *
     */
    private class WaitForCalibration extends AsyncTask<Character, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Character... params) {
            long timeStarted = System.currentTimeMillis();
            while(System.currentTimeMillis() - timeStarted < 5000){
                try {
                    Thread.sleep(100);
                    if(isCancelled()){
                        return false;
                    }
                } catch (InterruptedException e) {
                    return false;
                }
            }

            byte[] dataArray = new byte[1];
            char code = params[0];
            dataArray[0] = (byte)code;
            ConnectionState.getRFduinoservice().send(dataArray);
            return true;
        }
        @Override
        protected void onPostExecute(Boolean result) {
            if(progress != null) {
                progress.dismiss();
            }
            if(!result){
                Toast.makeText(getActivity(), "Calibration cancelled", Toast.LENGTH_SHORT).show();
            }
            currentCalibration = null;
        }
    }

    /*
    * If user cancels the dialog during the 5-second wait period, cancel calibration task.
    *
     */
    private DialogInterface.OnCancelListener cancelCalibrationListener = new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if(currentCalibration != null){
                currentCalibration.cancel(true);
            }
        }
    };

    public static StartFragment newInstance() {
        return new StartFragment();
    }

    public StartFragment() {
        // Required empty public constructor
    }

    @Override
    public void onResume(){
        super.onResume();
        BusHandler.getBus().register(this);
    }

    @Override
    public void onPause(){
        super.onPause();
        BusHandler.getBus().unregister(this);
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_start, container, false);

        // Find UI elements and set listeners
        View main = view.findViewById(R.id.scrollView).findViewById(R.id.linearLayout1);
        instructionsButton = (Button)main.findViewById(R.id.instructionsButton);
        calibrate0Sensor3Button = (Button)main.findViewById(R.id.linearLayout2)
                .findViewById(R.id.calibrate0Sensor3Button);
        calibrate0Sensor4Button = (Button)main.findViewById(R.id.linearLayout2)
                .findViewById(R.id.calibrate0Sensor4Button);
        calibrate0Sensor5Button = (Button)main.findViewById(R.id.linearLayout3)
                .findViewById(R.id.calibrate0Sensor5Button);
        calibrate0Sensor6Button = (Button)main.findViewById(R.id.linearLayout3)
                .findViewById(R.id.calibrate0Sensor6Button);
        calibrate90Sensor3Button = (Button)main.findViewById(R.id.linearLayout4)
                .findViewById(R.id.calibrate90Sensor3Button);
        calibrate90Sensor4Button = (Button)main.findViewById(R.id.linearLayout4)
                .findViewById(R.id.calibrate90Sensor4Button);
        calibrate90Sensor5Button = (Button)main.findViewById(R.id.linearLayout5)
                .findViewById(R.id.calibrate90Sensor5Button);
        calibrate90Sensor6Button = (Button)main.findViewById(R.id.linearLayout5)
                .findViewById(R.id.calibrate90Sensor6Button);
        startSensors34Button = (Button)main.findViewById(R.id.linearLayout6)
                .findViewById(R.id.startSensors34Button);
        startSensors56Button = (Button)main.findViewById(R.id.linearLayout6)
                .findViewById(R.id.startSensors56Button);
        stopSensors34Button = (Button)main.findViewById(R.id.linearLayout7)
                .findViewById(R.id.stopSensors34Button);
        stopSensors56Button = (Button)main.findViewById(R.id.linearLayout7)
                .findViewById(R.id.stopSensors56Button);

        instructionsButton.setOnClickListener(new instructionsButtonListener());
        calibrate0Sensor3Button.setOnClickListener(new calibrate0Sensor3ButtonListener());
        calibrate0Sensor4Button.setOnClickListener(new calibrate0Sensor4ButtonListener());
        calibrate0Sensor5Button.setOnClickListener(new calibrate0Sensor5ButtonListener());
        calibrate0Sensor6Button.setOnClickListener(new calibrate0Sensor6ButtonListener());
        calibrate90Sensor3Button.setOnClickListener(new calibrate90Sensor3ButtonListener());
        calibrate90Sensor4Button.setOnClickListener(new calibrate90Sensor4ButtonListener());
        calibrate90Sensor5Button.setOnClickListener(new calibrate90Sensor5ButtonListener());
        calibrate90Sensor6Button.setOnClickListener(new calibrate90Sensor6ButtonListener());
        startSensors34Button.setOnClickListener(new startSensors34ButtonListener());
        startSensors56Button.setOnClickListener(new startSensors56ButtonListener());
        stopSensors34Button.setOnClickListener(new stopSensors34ButtonListener());
        stopSensors56Button.setOnClickListener(new stopSensors56ButtonListener());

        return view;
    }

    /*
     * Called whenever a new BLE response is received via OTTO bus.
     *
     * Used to notify the user that an action was successful.
     *
      */
    @Subscribe
    public void onEvent(ReturnBLEResponseEvent event){
        if(event.getResponse() == BLEResponseCodes.CALIBRATE_0_SENSOR3 ||
                event.getResponse() == BLEResponseCodes.CALIBRATE_90_SENSOR3 ||
                event.getResponse() == BLEResponseCodes.CALIBRATE_0_SENSOR4 ||
                event.getResponse() == BLEResponseCodes.CALIBRATE_90_SENSOR4 ||
                event.getResponse() == BLEResponseCodes.CALIBRATE_0_SENSOR5 ||
                event.getResponse() == BLEResponseCodes.CALIBRATE_90_SENSOR5 ||
                event.getResponse() == BLEResponseCodes.CALIBRATE_0_SENSOR6 ||
                event.getResponse() == BLEResponseCodes.CALIBRATE_90_SENSOR6){
            if(progress != null){
                progress.dismiss();
            }
            Toast.makeText(getActivity(), "Calibration successful", Toast.LENGTH_SHORT).show();
        }
        else {
            switch(event.getResponse()){
                case BLEResponseCodes.START_SENSOR34:
                    Toast.makeText(getActivity(), "Sensors 3 & 4 started", Toast.LENGTH_SHORT).show();
                    break;
                case BLEResponseCodes.START_SENSOR56:
                    Toast.makeText(getActivity(), "Sensors 5 & 6 started", Toast.LENGTH_SHORT).show();
                    break;
                case BLEResponseCodes.STOP_SENSOR34:
                    Toast.makeText(getActivity(), "Sensors 3 & 4 stopped", Toast.LENGTH_SHORT).show();
                    break;
                case BLEResponseCodes.STOP_SENSOR56:
                    Toast.makeText(getActivity(), "Sensors 5 & 6 stopped", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    private class instructionsButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getActivity(), InstructionsActivity.class);
            startActivity(intent);
        }
    }

    private class calibrate0Sensor3ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_0_SENSOR3);
            }
        }
    }

    private class calibrate0Sensor4ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_0_SENSOR4);
            }
        }
    }

    private class calibrate0Sensor5ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_0_SENSOR5);
            }
        }
    }

    private class calibrate0Sensor6ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_0_SENSOR6);
            }
        }
    }

    private class calibrate90Sensor3ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_90_SENSOR3);
            }
        }
    }

    private class calibrate90Sensor4ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_90_SENSOR4);
            }
        }
    }

    private class calibrate90Sensor5ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_90_SENSOR5);
            }
        }
    }

    private class calibrate90Sensor6ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                progress = ProgressDialog.show(getActivity(), "", "Calibrating in 5 seconds...", true);
                progress.setCancelable(true);
                progress.setOnCancelListener(cancelCalibrationListener);
                currentCalibration = new WaitForCalibration();
                currentCalibration.execute(BLEResponseCodes.CALIBRATE_90_SENSOR6);
            }
        }
    }

    private class startSensors34ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                byte[] dataArray = new byte[1];
                dataArray[0] = (byte) BLEResponseCodes.START_SENSOR34;
                ConnectionState.getRFduinoservice().send(dataArray);
            }
        }
    }

    private class startSensors56ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                byte[] dataArray = new byte[1];
                dataArray[0] = (byte)BLEResponseCodes.START_SENSOR56;
                ConnectionState.getRFduinoservice().send(dataArray);
            }
        }
    }

    private class stopSensors34ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                byte[] dataArray = new byte[1];
                dataArray[0] = (byte)BLEResponseCodes.STOP_SENSOR34;
                ConnectionState.getRFduinoservice().send(dataArray);
            }
        }
    }

    private class stopSensors56ButtonListener implements  View.OnClickListener {
        @Override
        public void onClick(View v) {
            if(ConnectionState.getConnectionState() == ConnectionState.STATE_CONNECTED &&
                    ConnectionState.getRFduinoservice() != null){
                byte[] dataArray = new byte[1];
                dataArray[0] = (byte)BLEResponseCodes.STOP_SENSOR56;
                ConnectionState.getRFduinoservice().send(dataArray);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">SimpleTweets</string>
    <string name="title_activity_timeline">Timeline</string>
    <string name="login_label">Connect to Twitter</string>

</resources>


text:
export const SN_CMS_BLOCK = 'cmsBlock'
export const CMS_BLOCK_UPDATE_CMS_BLOCKS = SN_CMS_BLOCK + '/UPDATE_CMS_BLOCKS'
export const CMS_BLOCK_ADD_CMS_BLOCK = SN_CMS_BLOCK + '/ADD_CMS_BLOCK'


text:
module ActiveSupport
  class CustomLogger
    class Railtie < Rails::Railtie
      initializer "before_initialize" do |app|
        app.config.log_tags = [
          lambda { |r| r.uuid[0..7] },
          lambda { |r| Process.pid }
        ]
      end
    end
  end
end


text:
package cern.jet.random;

import cern.colt.list.DoubleArrayList;
import cern.colt.list.IntArrayList;
import cern.jet.random.engine.RandomEngine;
/**
 * Benchmarks random number generation from various distributions as well as PDF and CDF lookups.
 *
 * @author wolfgang.hoschek@cern.ch
 * @version 1.0, 09/24/99
 */
public class Benchmark extends cern.colt.PersistentObject {
	protected RandomEngine randomGenerator;
/**
 * Makes this class non instantiable, but still let's others inherit from it.
 */
protected Benchmark() {
	throw new RuntimeException("Non instantiable");
}
/**
 * Prints the first <tt>size</tt> random numbers generated by the distribution.
 */
public static void demo1() {
// Gamma distribution

// define distribution parameters
double mean = 5;
double variance = 1.5;
double alpha = mean*mean / variance;
double lambda = 1 / (variance / mean);

// for tests and debugging use a random engine with CONSTANT seed --> deterministic and reproducible results
cern.jet.random.engine.RandomEngine engine = new cern.jet.random.engine.MersenneTwister();

// your favourite distribution goes here
cern.jet.random.AbstractDistribution dist = new cern.jet.random.Gamma(alpha,lambda,engine);

// collect random numbers and print statistics
int size = 100000;
cern.colt.list.DoubleArrayList numbers = new cern.colt.list.DoubleArrayList(size);
for (int i=0; i < size; i++) numbers.add(dist.nextDouble());

hep.aida.bin.DynamicBin1D bin = new hep.aida.bin.DynamicBin1D();
bin.addAllOf(numbers);
System.out.println(bin);
}
/**
 * Benchmarks all subclasses
 * @param args[0] the number of random numbers to be generated per subclass.
 * @param args[1] <tt>true</tt> prints each generated number, <tt>false</tt> does not print generated numbers (use this setting for benchmarking).
 */
public static void main(String args[]) {
	int size = Integer.parseInt(args[0]);
	boolean print = new Boolean(args[1]).booleanValue();
	double mean = new Double(args[2]).doubleValue();
	String generatorName = args[3];
	random(size,print,mean,generatorName);
}
/**
 * Benchmarks all subclasses
 * @param size the number of random numbers to be generated per subclass.
 * @param print <tt>true</tt> prints each generated number, <tt>false</tt> does not print generated numbers (use this setting for benchmarking).
 * @param mean the mean for distributions that require a mean.
 */
public static void random(int size, boolean print, double mean, String generatorName) {
	System.out.println("Generating "+size+" random numbers per distribution...\n");

	//int large = 100000000;
	int largeVariance = 100;
	RandomEngine gen; // = new MersenneTwister();
	try {
		gen = (RandomEngine) Class.forName(generatorName).newInstance();
	} catch (Exception exc) {
		throw new InternalError(exc.getMessage());
	}

	/*
	randomInstance(size,print,new Zeta(10.0, 10.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Zeta(1.0, 1.0, (RandomEngine)gen.clone()));
	randomInstance(size,print,new Zeta(mean, mean, (RandomEngine)gen.clone()));
	randomInstance(size,print,new Zeta(mean, 1/mean, (RandomEngine)gen.clone()));
	//randomInstance(size,print,new Zeta(1/mean, mean, (RandomEngine)gen.clone()));
*/

	/*

	randomInstance(size,print,new Beta(10.0, 10.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Beta(1.0, 1.0, (RandomEngine)gen.clone()));
	randomInstance(size,print,new Beta(mean, mean, (RandomEngine)gen.clone()));
	randomInstance(size,print,new Beta(mean, 1/mean, (RandomEngine)gen.clone()));
	randomInstance(size,print,new Beta(1/mean, mean, (RandomEngine)gen.clone()));

	randomInstance(size,print,new Uniform((RandomEngine)gen.clone()));
	*/
	randomInstance(size,print,new Poisson(mean,(RandomEngine)gen.clone()));
	/*
	randomInstance(size,print,new PoissonSlow(mean,(RandomEngine)gen.clone()));

	randomInstance(size,print,new Poisson(3.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new PoissonSlow(3.0,(RandomEngine)gen.clone()));

	randomInstance(size,print,new Binomial(1,0.5,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Binomial(5,0.3,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Binomial((int)mean,0.999999999,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Binomial((int)mean,1.0/mean,(RandomEngine)gen.clone()));

	randomInstance(size,print,new Exponential(1.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Exponential(3.0,(RandomEngine)gen.clone()));

	randomInstance(size,print,new Normal(0.0,1.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Normal(3.0,1.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Normal(mean,largeVariance,(RandomEngine)gen.clone()));

	randomInstance(size,print,new BreitWigner(1.0, 0.2, Double.NEGATIVE_INFINITY, (RandomEngine)gen.clone()));
	randomInstance(size,print,new BreitWigner(1.0, 0.2, 1.0, (RandomEngine)gen.clone()));

	randomInstance(size,print,new BreitWignerMeanSquare(1.0, 0.2, Double.NEGATIVE_INFINITY, (RandomEngine)gen.clone()));
	randomInstance(size,print,new BreitWignerMeanSquare(1.0, 0.2, 1.0, (RandomEngine)gen.clone()));

	randomInstance(size,print,new ChiSquare(1.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new ChiSquare(5.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new ChiSquare(mean,(RandomEngine)gen.clone()));

	randomInstance(size,print,new Gamma(0.2,1.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Gamma(1.0,1.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Gamma(3.0,0.5,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Gamma(mean,0.5,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Gamma(mean,1.0/mean,(RandomEngine)gen.clone()));
	randomInstance(size,print,new Gamma(mean,mean,(RandomEngine)gen.clone()));

	randomInstance(size,print,new StudentT(1.0,(RandomEngine)gen.clone()));
	randomInstance(size,print,new StudentT(2.5,(RandomEngine)gen.clone()));
	randomInstance(size,print,new StudentT(mean,(RandomEngine)gen.clone()));
	randomInstance(size,print,new StudentT(1.0/mean,(RandomEngine)gen.clone()));

	int probs = 10000;
	double[] pdf = new double[probs];
	for (int i=0; i<probs; i++) pdf[i]=i*i; // prepare f(x)=x^2 distrib.
	randomInstance(size,print,new Empirical(pdf,Empirical.NO_INTERPOLATION, (RandomEngine)gen.clone()));
	randomInstance(size,print,new Empirical(pdf,Empirical.LINEAR_INTERPOLATION, (RandomEngine)gen.clone()));
	*/
}
/**
 * generates <size> random numbers from <dist>
 */
public static void randomInstance(int size, boolean print, AbstractDistribution dist) {
	System.out.print("\n"+dist+" ...");
	cern.colt.Timer timer = new cern.colt.Timer().start();

	for (int i=size; --i >= 0;) {
		double rand = dist.nextDouble();
		if (print) {
			if ((size-i-1)%8 == 0) System.out.println();
			System.out.print((float)rand+", ");
		}
	}

	timer.stop();
	System.out.println("\n"+timer);
}
/**
 * Prints the first <tt>size</tt> random numbers generated by the distribution.
 */
public static void test(int size, AbstractDistribution distribution) {
	for (int j=0, i=size; --i>=0; j++) {
		System.out.print(" "+distribution.nextDouble());
		if (j%8==7) System.out.println();
	}
	System.out.println("\n\nGood bye.\n");
}
/**
 * Prints the first <tt>size</tt> random numbers generated by the distribution.
 */
public static void test2(int size, AbstractDistribution distribution) {
	hep.aida.bin.DynamicBin1D bin = new hep.aida.bin.DynamicBin1D();
	for (int j=0, i=size; --i>=0; j++) {
		bin.add(distribution.nextDouble());
	}
	System.out.println(bin);
	System.out.println("\n\nGood bye.\n");
}
/**
 * Prints the first <tt>size</tt> random numbers generated by the distribution.
 */
public static void test2(int size, AbstractDistribution a, AbstractDistribution b) {
	hep.aida.bin.DynamicBin1D binA = new hep.aida.bin.DynamicBin1D();
	hep.aida.bin.DynamicBin1D binB = new hep.aida.bin.DynamicBin1D();
	for (int j=0, i=size; --i>=0; j++) {
		binA.add(a.nextDouble());
		binB.add(b.nextDouble());
	}
	//System.out.println(binA);
	//System.out.println(binB);
	//System.out.println(binA.compareWith(binB));

	System.out.println("\n\nBenchmarking frequencies...\n");
	IntArrayList freq = new IntArrayList();
	DoubleArrayList distinct = new DoubleArrayList();
	cern.colt.Timer timer = new cern.colt.Timer();
	timer.reset();
	timer.start();
	binA.frequencies(distinct,freq);
	timer.stop().display();
	//System.out.println(distinct);
	//System.out.println(freq);

	/*
	timer.reset();
	timer.start();
	binA.xfrequencies2(distinct,freq);
	timer.stop().display();
	//System.out.println(distinct);
	//System.out.println(freq);
	*/

	/*
	distinct.shuffle();
	timer.reset().start();
	distinct.sort();
	timer.stop().display();

	timer.reset().start();
	binA.frequencies(distinct,freq);
	timer.stop().display();
	//System.out.println(distinct);
	//System.out.println(freq);
	*/

	System.out.println("\n\nGood bye.\n");
}
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>My AngularJS App</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
  <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">
  <link rel="stylesheet" href="app.css">
  <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="bower_components/bootstrap/dist/css/bootstrap-theme.css">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Project name

Orders

About

Contact

Login

Register