text:
<?php

use League\OAuth2\Server\AuthorizationServer;
use League\OAuth2\Server\Exception\OAuthServerException;
use League\OAuth2\Server\Grant\ImplicitGrant;
use OAuth2ServerExamples\Entities\UserEntity;
use OAuth2ServerExamples\Repositories\AccessTokenRepository;
use OAuth2ServerExamples\Repositories\ClientRepository;
use OAuth2ServerExamples\Repositories\ScopeRepository;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\App;
use Zend\Diactoros\Stream;

include __DIR__ . '/../vendor/autoload.php';

$app = new App([
    'settings'    => [
        'displayErrorDetails' => true,
    ],
    AuthorizationServer::class => function () {
        // Init our repositories
        $clientRepository = new ClientRepository();
        $scopeRepository = new ScopeRepository();
        $accessTokenRepository = new AccessTokenRepository();

        $privateKeyPath = 'file://' . __DIR__ . '/../private.key';

        // Setup the authorization server
        $server = new AuthorizationServer(
            $clientRepository,
            $accessTokenRepository,
            $scopeRepository,
            $privateKeyPath,
            'lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen'
        );
        $server->setEncryptionKey('lxZFUEsBCJ2Yb14IF2ygAHI5N4+ZAUXXaSeeJm6+twsUmIen');

        // Enable the implicit grant on the server with a token TTL of 1 hour
        $server->enableGrantType(new ImplicitGrant(new \DateInterval('PT1H')));

        return $server;
    },
]);

$app->get('/authorize', function (ServerRequestInterface $request, ResponseInterface $response) use ($app) {
    /* @var \League\OAuth2\Server\AuthorizationServer $server */
    $server = $app->getContainer()->get(AuthorizationServer::class);

    try {
        // Validate the HTTP request and return an AuthorizationRequest object.
        // The auth request object can be serialized into a user's session
        $authRequest = $server->validateAuthorizationRequest($request);

        // Once the user has logged in set the user on the AuthorizationRequest
        $authRequest->setUser(new UserEntity());

        // Once the user has approved or denied the client update the status
        // (true = approved, false = denied)
        $authRequest->setAuthorizationApproved(true);

        // Return the HTTP redirect response
        return $server->completeAuthorizationRequest($authRequest, $response);
    } catch (OAuthServerException $exception) {
        return $exception->generateHttpResponse($response);
    } catch (\Exception $exception) {
        $body = new Stream('php://temp', 'r+');
        $body->write($exception->getMessage());

        return $response->withStatus(500)->withBody($body);
    }
});

$app->run();


text:
/* $NetBSD: wdog.c,v 1.7 2003/07/15 02:54:44 lukem Exp $ */

/*
 * Copyright (c) 2002 Wasabi Systems, Inc.
 * All rights reserved.
 *
 * Written by Jason R. Thorpe and Simon Burge for Wasabi Systems, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed for the NetBSD Project by
 *	Wasabi Systems, Inc.
 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Watchdog timer support for the IBM 405GP processor.
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: wdog.c,v 1.7 2003/07/15 02:54:44 lukem Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/properties.h>
#include <sys/wdog.h>

#include <powerpc/spr.h>
#include <powerpc/ibm4xx/dev/opbvar.h>

#include <dev/sysmon/sysmonvar.h>

static int wdog_match(struct device *, struct cfdata *, void *);
static void wdog_attach(struct device *, struct device *, void *);
static int wdog_tickle(struct sysmon_wdog *);
static int wdog_setmode(struct sysmon_wdog *);

struct wdog_softc {
	struct device sc_dev;
	struct sysmon_wdog sc_smw;
	int sc_wdog_armed;
	int sc_wdog_period;
};

CFATTACH_DECL(wdog, sizeof(struct wdog_softc),
    wdog_match, wdog_attach, NULL, NULL);

static int
wdog_match(struct device *parent, struct cfdata *cf, void *aux)
{
	struct opb_attach_args *oaa = aux;

	/* match only watchdog devices */
	if (strcmp(oaa->opb_name, cf->cf_name) != 0)
		return (0);

	return (1);
}

static void
wdog_attach(struct device *parent, struct device *self, void *aux)
{
	struct wdog_softc *sc = (void *)self;
	unsigned int processor_freq;

	if (board_info_get("processor-frequency",
	    &processor_freq, sizeof(processor_freq)) == -1)
		processor_freq = 200 * 1000 * 1000;	/* assume 200MHz */

	sc->sc_wdog_period = (2LL << 29) / processor_freq;
	printf(": %d second period\n", sc->sc_wdog_period);

	sc->sc_smw.smw_name = sc->sc_dev.dv_xname;
	sc->sc_smw.smw_cookie = sc;
	sc->sc_smw.smw_setmode = wdog_setmode;
	sc->sc_smw.smw_tickle = wdog_tickle;
	sc->sc_smw.smw_period = sc->sc_wdog_period;

	if (sysmon_wdog_register(&sc->sc_smw) != 0)
		printf("%s: unable to register with sysmon\n",
		    sc->sc_dev.dv_xname);

}

static int
wdog_tickle(struct sysmon_wdog *smw)
{
	uint32_t tsr;

	tsr = mfspr(SPR_TSR);
	tsr |= TSR_ENW | TSR_WIS;
	mtspr(SPR_TSR, tsr);
	return (0);
}

static int
wdog_setmode(struct sysmon_wdog *smw)
{
	struct wdog_softc *sc = smw->smw_cookie;
	uint32_t tcr, tsr;

	if ((smw->smw_mode & WDOG_MODE_MASK) == WDOG_MODE_DISARMED) {
		if (sc->sc_wdog_armed) {
			tsr = mfspr(SPR_TSR);
			tsr &= ~(TSR_ENW | TSR_WIS);
			mtspr(SPR_TSR, tsr);
		}
	} else {
		if (smw->smw_period == WDOG_PERIOD_DEFAULT)
			smw->smw_period = sc->sc_wdog_period;
		else if (smw->smw_period != sc->sc_wdog_period) {
			/*
			 * There's 4 set watchdog periods on the 405GP,
			 * but we only support the longest one (2.684
			 * seconds).
			 */
			return (EOPNOTSUPP);
		}
		sc->sc_wdog_armed = 1;

		tcr = mfspr(SPR_TCR);
		tcr |= TCR_WP_2_29 | TCR_WRC_SYSTEM;
		mtspr(SPR_TCR, tcr);

		/* Arm the watchdog. */
		wdog_tickle(smw);
	}
	return (0);
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
* wpv_show_hide_pagination
*
* We can enable this to hide the Pagination section
*
* @param $sections (array) sections on the editor screen
*
* @return $sections
*
* @since unknown
*/

add_filter('wpv_sections_filter_show_hide', 'wpv_show_hide_pagination', 1,1);

function wpv_show_hide_pagination($sections) {
	$sections['pagination'] = array(
		'name'		=> __('Pagination and Sliders settings', 'wpv-views'),
		);
	return $sections;
}

/**
* add_view_pagination
*
* Creates the pagination section in the edit screen
*
* @param $view_settings
* @param $view_id
*
* @uses $views_edit_help (global)
*
* @since unknown
*/

add_action('view-editor-section-filter', 'add_view_pagination', 10, 2);

function add_view_pagination($view_settings, $view_id) { //TODO review that default values are set before we display any of this
    global $views_edit_help;
	$rollover_effects = array(
		'fade' => __('Fade', 'wpv-views'),
	//	'fadefast' => __('Fade fast', 'wpv-views'),
	//	'fadeslow' => __('Fade slow', 'wpv-views'),
		'slideleft' => __('Slide Left', 'wpv-views'),
		'slideright' => __('Slide Right', 'wpv-views'),
		'slideup' => __('Slide Up', 'wpv-views'),
		'slidedown' => __('Slide Down', 'wpv-views'),
	);
	$ajax_effects = array(
		'fade' => __('Fade', 'wpv-views'),
		'fadefast' => __('Fade fast', 'wpv-views'),
		'fadeslow' => __('Fade slow', 'wpv-views'),
		'slideh' => __('Slide horizontally', 'wpv-views'),
		'slidev' => __('Slide vertically', 'wpv-views'),
	);
	$hide = '';
	if (isset($view_settings['sections-show-hide']) && isset($view_settings['sections-show-hide']['pagination']) && 'off' == $view_settings['sections-show-hide']['pagination']) {
		$hide = ' hidden';
	}?>
	<div class="wpv-setting-container wpv-settings-pagination js-wpv-settings-pagination<?php echo $hide; ?>">

				<?php _e( 'Pagination and Sliders settings', 'wpv-views' ) ?>
				<i class="icon-question-sign js-display-tooltip" data-header="<?php echo $views_edit_help['pagination_and_sliders_settings']['title']; ?>" data-content="<?php echo $views_edit_help['pagination_and_sliders_settings']['content']; ?>">

			<form class="js-pagination-settings-form">
				<?php
				if ( !isset( $view_settings['pagination'][0] ) ) $view_settings['pagination'][0] = 'disable';
				if ( !isset( $view_settings['pagination']['mode'] ) ) $view_settings['pagination']['mode'] = 'none';
				?>
				<input type="hidden" class="js-pagination-zero" name="pagination[]" value="<?php echo $view_settings['pagination'][0]; ?>" />

						<?php $checked = $view_settings['pagination'][0]=='disable' ? ' checked="checked"' : ''; ?>
						<input type="radio" id="wpv-settings-no-pagination" name="pagination[mode]" value="none"<?php echo $checked; ?> />
						<?php _e('No pagination','wpv-views') ?> - <?php _e('All query results will display.','wpv-views') ?>

						<?php $checked = ( $view_settings['pagination'][0]=='enable' && $view_settings['pagination']['mode']=='paged' ) ? ' checked="checked"' : ''; ?>
						<input type="radio" id="wpv-settings-manual-pagination" name="pagination[mode]" value="paged"<?php echo $checked; ?> />
						<?php _e( 'Pagination enabled with manual transition', 'wpv-views' ) ?> - <?php _e( 'The query results will display in pages, which visitors will switch.', 'wpv-views' ) ?>

						<?php $checked = $view_settings['pagination']['mode']=='rollover' ? ' checked="checked"' : ''; ?>
						<input type="radio" id="wpv-settings-ajax-pagination" name="pagination[mode]" value="rollover"<?php echo $checked; ?> />
						<?php _e( 'Pagination enabled with automatic transition', 'wpv-views' ) ?> - <?php _e( 'The query results will display in pages, which will switch automatically (good for sliders).', 'wpv-views' ) ?>

<?php _e('Options for manual pagination','wpv-views'); ?>

							<?php _e('Number of items per page:', 'wpv-views')?>
							<select name="posts_per_page">
								<?php if ( !isset( $view_settings['posts_per_page'] ) ) $view_settings['posts_per_page'] = '10'; ?>
								<?php
								for($i = 1; $i < 50; $i++) {
									$selected = $view_settings['posts_per_page']==(string)$i ? ' selected="selected"' : '';
									echo '<option value="' . $i . '"' . $selected . '>'. $i . '</option>';
								}
								?>
							</select>

							<?php $checked = ( isset( $view_settings['ajax_pagination'][0] ) && $view_settings['ajax_pagination'][0] == 'disable') ? ' checked="checked"' : ''; ?>
							<input type="radio" id="wpv-settings-ajax-pagination-disabled" value="disable" name="ajax_pagination[]"<?php echo $checked; ?> />
							<?php _e('Pagination updates the entire page', 'wpv-views'); ?>

							<?php $checked = ( isset( $view_settings['ajax_pagination'][0] ) && $view_settings['ajax_pagination'][0] == 'enable') ? ' checked="checked"' : ''; ?>
							<input type="radio" id="wpv-settings-ajax-pagination-enabled" value="enable" name="ajax_pagination[]"<?php echo $checked; ?> />
							<?php _e('Pagination updates only the view (use AJAX)', 'wpv-views'); ?>

								<?php _e('Transition effect:', 'wpv-views')?>
								<select name="ajax_pagination[style]">
									<?php if ( !isset( $view_settings['ajax_pagination']['style'] ) ) $view_settings['ajax_pagination']['style'] = 'fade'; ?>
									<option value="fade"<?php if ($view_settings['ajax_pagination']['style'] == 'fade' || $view_settings['ajax_pagination']['style'] == 'fadefast' || $view_settings['ajax_pagination']['style'] == 'fadeslow') { echo ' selected="selected"'; } ?>><?php _e('Fade',  'wpv-views'); ?></option>
									<option value="slideh"<?php if ($view_settings['ajax_pagination']['style'] == 'slideh') { echo ' selected="selected"'; } ?>><?php _e('Slide horizontally',  'wpv-views'); ?></option>
									<option value="slidev"<?php if ($view_settings['ajax_pagination']['style'] == 'slidev') { echo ' selected="selected"'; } ?>><?php _e('Slide vertically',  'wpv-views'); ?></option>
								</select>

									<?php _e('with duration',  'wpv-views'); ?>
									<?php if ( !isset( $view_settings['ajax_pagination']['duration'] ) ) $view_settings['ajax_pagination']['duration'] = 500;
										if ($view_settings['ajax_pagination']['style'] == 'fadefast') $view_settings['ajax_pagination']['duration'] = 1;
										if ($view_settings['ajax_pagination']['style'] == 'fadeslow') $view_settings['ajax_pagination']['duration'] = 1500;
									?>
									<input type="text" class="transition-duration" name="ajax_pagination[duration]" value="<?php echo $view_settings['ajax_pagination']['duration']; ?>" size="5">

								<?php _e('miliseconds', 'wpv-views'); ?>
								← <?php _e('Please add a numeric value', 'wpv-views'); ?>

								<button class="js-pagination-advanced button-secondary" type="button" data-closed="<?php echo esc_attr( __( 'Advanced options', 'wpv-views' ) ); ?>" data-opened="<?php echo esc_attr( __( 'Close advanced options', 'wpv-views' ) ); ?>" data-section="ajax_pagination" data-state="closed"><?php _e( 'Advanced options', 'wpv-views' ); ?></button>

							<?php $checked = (isset($view_settings['pagination']['preload_images']) && $view_settings['pagination']['preload_images']) ? ' checked="checked"' : '';?>

								<input type="checkbox" name="pagination[preload_images]" value="1"<?php echo $checked; ?> />
								<?php _e('Preload images before transition',  'wpv-views'); ?>

<?php _e('Options for automatic pagination', 'wpv-views')?>

							<?php _e('Number of items per page:', 'wpv-views'); ?>
							<select name="rollover[posts_per_page]">
								<?php if ( !isset( $view_settings['rollover']['posts_per_page'] ) ) $view_settings['rollover']['posts_per_page'] = '10'; ?>
								<?php
								for($i = 1; $i < 50; $i++) {
									$selected = $view_settings['rollover']['posts_per_page']==(string)$i ? ' selected="selected"' : '';
									echo '<option value="' . $i . '"' . $selected . '>'. $i . '</option>';
								}
								?>
							</select>

							<?php _e('Show each page for:', 'wpv-views')?>
							<select name="rollover[speed]">
								<?php if ( !isset( $view_settings['rollover']['speed'] ) ) $view_settings['rollover']['speed'] = '5'; ?>
								<?php
								for($i = 1; $i < 20; $i++) {
									$selected = $view_settings['rollover']['speed']==(string)$i ? ' selected="selected"' : '';
									echo '<option value="' . $i . '"' . $selected . '>'. $i . '</option>';
								}
								?>
							</select> <?php _e('seconds', 'wpv-views')?>

							<?php _e('Transition effect:', 'wpv-views')?>
							<select name="rollover[effect]">
								<?php
								if ( !isset( $view_settings['rollover']['effect'] ) ) $view_settings['rollover']['effect'] = 'fade';
								foreach($rollover_effects as $i => $title) {
									$selected = $view_settings['rollover']['effect']==(string)$i ? ' selected="selected"' : '';
									echo '<option value="' . $i . '"' . $selected . '>'. $title . '</option>';
								}
								?>
							</select>
							<?php _e('with duration',  'wpv-views'); ?>
								<?php if ( !isset( $view_settings['rollover']['duration'] ) ) $view_settings['rollover']['duration'] = 500;
								?>
								<input type="text" class="transition-duration" name="rollover[duration]" value="<?php echo $view_settings['rollover']['duration']; ?>" size="5">
							<?php _e('miliseconds', 'wpv-views'); ?>
							<?php _e(' <- Please add a numeric value', 'wpv-views'); ?>

								<button class="js-pagination-advanced button-secondary" type="button" data-closed="<?php _e( 'Advanced options', 'wpv-views' ) ?>" data-opened="<?php _e( 'Close advanced options', 'wpv-views' ) ?>" data-section="rollover" data-state="closed"><?php _e( 'Advanced options', 'wpv-views' ) ?></button>

							<?php $checked = (isset($view_settings['rollover']['preload_images']) && $view_settings['rollover']['preload_images']) ? ' checked="checked"' : '';?>

								<input type="checkbox" name="rollover[preload_images]" value="1"<?php echo $checked; ?> />
								<?php _e('Preload images before transition',  'wpv-views'); ?>

							<?php $checked = (isset($view_settings['pagination']['cache_pages']) && $view_settings['pagination']['cache_pages']) ? ' checked="checked"' : '';?>

									<input type="checkbox" name="pagination[cache_pages]" value="1"<?php echo $checked; ?> />
									<?php _e('Cache pages',  'wpv-views'); ?>

							<?php $checked = (isset($view_settings['pagination']['preload_pages']) && $view_settings['pagination']['preload_pages']) ? ' checked="checked"' : '';?>

									<input type="checkbox" name="pagination[preload_pages]" value="1"<?php echo $checked; ?> />
									<?php _e('Pre-load the next and previous pages - avoids loading delays when users move between pages',  'wpv-views'); ?>

								<?php _e('Pages to pre-load: ',  'wpv-views'); ?>
								<select name="pagination[pre_reach]">
								<?php if ( !isset( $view_settings['pagination']['pre_reach'] ) ) $view_settings['pagination']['pre_reach'] = 1;
									for($i = 1; $i < 20; $i++) {
										$selected = $view_settings['pagination']['pre_reach']== $i ? ' selected="selected"' : '';
										echo '<option value="' . $i . '"' . $selected . '>'. $i . '</option>';
									}
									?>
								</select>

<?php _e('Spinners',  'wpv-views'); ?>

							<?php $checked = ( isset($view_settings['pagination']['spinner']) && $view_settings['pagination']['spinner'] == 'default' ) ? ' checked="checked"' : '';?>

									<input type="radio" name="pagination[spinner]" value="default"<?php echo $checked; ?> />
									<?php _e('Spinner graphics from Views', 'wpv-views'); ?>

								<?php
								if ( isset( $view_settings['pagination']['spinner_image'] ) ) {
									$spinner_image = $view_settings['pagination']['spinner_image'];
								} else {
									$spinner_image = '';
								}
								foreach (glob(WPV_PATH_EMBEDDED . "/res/img/ajax-loader*") as $file) {
								$filename = WPV_URL_EMBEDDED . '/res/img/' . basename($file);
								$filename2 = WPV_URL . '/res/img/' . basename($file);
								?>

										<input type="radio" name="pagination[spinner_image]" value="<?php echo $filename; ?>"<?php if ( $spinner_image == $filename || $spinner_image == $filename2) { echo ' checked="checked"'; } ?> />
										<img style="background-color: #FFFFFF;" src="<?php echo $filename; ?>" title="<?php echo $filename; ?>" />

								<?php } ?>

							<?php $checked = ( isset($view_settings['pagination']['spinner']) && $view_settings['pagination']['spinner'] == 'uploaded' ) ? ' checked="checked"' : '';?>

									<input type="radio" name="pagination[spinner]" value="uploaded"<?php echo $checked; ?> />
									<?php _e('My custom spinner graphics', 'wpv-views'); ?>

								<input id="wpv-pagination-spinner-image" class="js-wpv-pagination-spinner-image" type="text" name="pagination[spinner_image_uploaded]" value="<?php echo isset( $view_settings['pagination']['spinner_image_uploaded'] ) ? $view_settings['pagination']['spinner_image_uploaded'] : ''; ?>" />
								<button class="button-secondary js-code-editor-toolbar-button js-wpv-media-manager" data-content="wpv-pagination-spinner-image" data-id="<?php echo $view_id; ?>"><?php _e('Upload Image', 'wpv-views'); ?></button>
								<?php if ( isset( $view_settings['pagination']['spinner_image_uploaded'] ) && !empty( $view_settings['pagination']['spinner_image_uploaded'] ) ): ?>
									<img id="wpv-pagination-spinner-image-preview" class="js-wpv-pagination-spinner-image-preview" src="<?php echo $view_settings['pagination']['spinner_image_uploaded']; ?>" height="16" />
								<?php endif; ?>

							<?php $checked = ( isset($view_settings['pagination']['spinner']) &&  $view_settings['pagination']['spinner'] == 'no' ) ? ' checked="checked"' : '';?>

									<input type="radio" name="pagination[spinner]" value="no"<?php echo $checked; ?> />
									<?php _e('No spinner graphics', 'wpv-views'); ?>

<?php _e('Callback function', 'wpv-views'); ?>

<?php _e('Javascript function to execute after the pagination transition has been completed:', 'wpv-views'); ?> <input id="wpv-pagination-callback-next" class="js-wpv-pagination-callback-next" type="text" name="pagination[callback_next]" value="<?php echo isset( $view_settings['pagination']['callback_next'] ) ? $view_settings['pagination']['callback_next'] : ''; ?>" />

			</form>

				<button data-success="<?php echo htmlentities( __('Pagination settings updated', 'wpv-views'), ENT_QUOTES ); ?>" data-unsaved="<?php echo htmlentities( __('Pagination settings not saved', 'wpv-views'), ENT_QUOTES ); ?>" data-nonce="<?php echo wp_create_nonce( 'wpv_view_pagination_nonce' ); ?>" class="js-wpv-pagination-update button-secondary" disabled="disabled"><?php _e('Update', 'wpv-views'); ?></button>

	<?php
		wpv_get_view_pagination_hint_data();
		$data = wpv_get_view_pagination_hint_result_data();
		wpv_toolset_help_box($data);
	?>

<?php _e('Would you like to insert transition controls for the pagination?','wpv-views') ?>

				<?php include('wpv-section-pagination-popup-preview.php'); ?>
				<?php // TODO @Juan. I don't know is it a correct way of including re-usable parts of code. ?>

<?php _e('Pagination controls', 'wpv-views'); ?>

					<input type="radio" name="pagination_control" id="pagination-include-page-num" value="page_num" data-target="current-page-number" />
					<?php _e('Current page number','wpv-views'); ?>

					<input type="radio" name="pagination_control" id="pagination-include-page-total" value="page_total" data-target="total-pages" />
					<?php _e('Number of pages','wpv-views'); ?>

					<input type="radio" name="pagination_control" id="pagination-include-page-selector" value="page_selector" data-target="page-selector"/>
					<?php _e('Page selector using','wpv-views'); ?>
					<select name="pagination_controls_type" id="pagination-controls-type" class="js-pagination-control-type">
						<option value="drop_down"><?php _e('dropdown','wpv-views') ?></option>
						<option value="link"><?php _e('links','wpv-views') ?></option>
					</select>

					<input type="radio" name="pagination_control" id="pagination-include-controls" value="page_controls" data-target="next-previous-controls" />
					<?php _e('Next and previous page controls','wpv-views'); ?>

<?php _e('Pagination display', 'wpv-views'); ?>

					<input type="checkbox" name="pagination_display" id="pagination-include-wrapper" />
					<?php _e('Don\'t show pagination controls if there is only one page','wpv-views'); ?>

				<button class="button js-dialog-close"><?php _e('Cancel','wpv-views') ?></button>
				<button class="button button-primary js-insert-pagination"><?php _e('Insert pagination','wpv-views') ?></button>

<?php _e('What pagination controls would you like to insert?','wpv-views') ?>

				<?php include('wpv-section-pagination-popup-preview.php'); ?>

					<input type="checkbox" checked="checked" id="pagination-include-page-num-hint" name="pagination-include-page-num" class="js-pagination-control-hint" value="page_num" data-target="current-page-number"  />
					<?php _e('Current page number','wpv-views'); ?>

					<input type="checkbox" checked="checked" id="pagination-include-page-total-hint" name="pagination-include-page-total" class="js-pagination-control-hint" value="page_total" data-target="total-pages" />
					<?php _e('Number of pages','wpv-views'); ?>

					<input type="checkbox" checked="checked" id="pagination-include-page-selector-hint" name="pagination-include-page-selector" class="js-pagination-control-hint" value="page_selector" data-target="page-selector" />
					<?php _e('Page selector using','wpv-views'); ?>
					<select name="pagination_controls_type_hint" id="pagination-controls-type-hint" class="js-pagination-control-hint-type">
						<option value="drop_down"><?php _e('dropdown','wpv-views') ?></option>
						<option value="link"><?php _e('links','wpv-views') ?></option>
					</select>

					<input type="checkbox" checked="checked" id="pagination-include-controls-hint" name="pagination-include-controls" class="js-pagination-control-hint" value="page_controls" data-target="next-previous-controls" />
					<?php _e('Next and previous page controls','wpv-views'); ?>

				<button class="button js-dialog-close"><?php _e('Cancel','wpv-views') ?></button>
				<button class="button button-primary js-insert-pagination-from-hint" data-content="wpv_filter_meta_html_content"><?php _e('Insert pagination','wpv-views') ?></button>

<?php }

/**
* wpv_pagination_summary_filter
*
* Returns the pagination part when building the summary for a View
*
* @param $summary
* @param $post_id
* @param $view_settings
*
* @returns (string) $summary
*
* @uses wpv_get_pagination_summary
*
* @since unknown
*/

add_filter( 'wpv-view-get-content-summary', 'wpv_pagination_summary_filter', 6, 3 );

function wpv_pagination_summary_filter($summary, $post_id, $view_settings) {
	$summary .= wpv_get_pagination_summary( $view_settings );
    return $summary;
}


text:
using Prism.Commands;
using Prism.Mvvm;
using SimpleHmi.PlcService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace SimpleHmi.ViewModels
{
    class MainPageViewModel : BindableBase
    {
        public string IpAddress
        {
            get { return _ipAddress; }
            set { SetProperty(ref _ipAddress, value); }
        }
        private string _ipAddress;

        public bool HighLimit
        {
            get { return _highLimit; }
            set { SetProperty(ref _highLimit, value); }
        }
        private bool _highLimit;

        public bool LowLimit
        {
            get { return _lowLimit; }
            set { SetProperty(ref _lowLimit, value); }
        }
        private bool _lowLimit;

        public bool PumpState
        {
            get { return _pumpState; }
            set { SetProperty(ref _pumpState, value); }
        }
        private bool _pumpState;

        public int TankLevel
        {
            get { return _tankLevel; }
            set { SetProperty(ref _tankLevel, value); }
        }
        private int _tankLevel;

        public ICommand ConnectCommand { get; private set; }

        public ICommand DisconnectCommand { get; private set; }

        public ICommand StartCommand { get; private set; }

        public ICommand StopCommand { get; private set; }

        IPlcService _plcService;

        public MainPageViewModel(IPlcService s7PlcService)
        {
            _plcService = s7PlcService;
            ConnectCommand = new DelegateCommand(Connect);
            DisconnectCommand = new DelegateCommand(Disconnect);
            StartCommand = new DelegateCommand(async () => { await Start(); });
            StopCommand = new DelegateCommand(async () => { await Stop(); });

            IpAddress = "127.0.0.1";

            OnPlcServiceValuesRefreshed(null, null);
            _plcService.ValuesRefreshed += OnPlcServiceValuesRefreshed;
        }

        private void OnPlcServiceValuesRefreshed(object sender, EventArgs e)
        {
            PumpState = _plcService.PumpState;
            HighLimit = _plcService.HighLimit;
            LowLimit = _plcService.LowLimit;
            TankLevel = _plcService.TankLevel;
        }

        private void Connect()
        {
            _plcService.Connect(IpAddress, 0, 1);
        }

        private void Disconnect()
        {
            _plcService.Disconnect();
        }

        private async Task Start()
        {
            await _plcService.WriteStart();
        }

        private async Task Stop()
        {
            await _plcService.WriteStop();
        }
    }
}


text:
cask "itrash" do
  version "5.3.3.3.202"
  sha256 :no_check

  url "https://www.osxbytes.com/iTrash.dmg?forcedownload"
  name "iTrash"
  desc "Uninstalls all files of an application"
  homepage "https://www.osxbytes.com/itrash.html"

  app "iTrash.app"
end


text:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect
from django.template import Template, Context, RequestContext
from django.core.mail import send_mail

from starl.forms import *
from starl.models import *
from starl.views import *
from forms import *

import re,datetime,time

def assets_server(request):
	if status(request) == 1:
		return render_to_response('login.html',{'error':'链接超时,请重新登陆!!!','alert':'alert-error'})

	assets_server_form = assets_server_add_Form()
	form = Assets_Server.objects.filter()
	a_path = u'设备资产'
	i_user = request.COOKIES.get('starl', '')
	return render_to_response('assets_server.html', {'form':form,'assets_server_form':assets_server_form,'a_path':a_path,'i_user':i_user})

def assets_server_add(request):
	if status(request) == 1:
		return render_to_response('login.html',{'error':'链接超时,请重新登陆!!!','alert':'alert-error'})

	if request.method == 'POST':
		form = assets_server_add_Form(request.POST)
		if form.is_valid():

			assets_server_data                 = Assets_Server()
			assets_server_data.Room            = form.cleaned_data['Room']
			assets_server_data.System          = form.cleaned_data['System']
			assets_server_data.Type            = form.cleaned_data["Type"]
			assets_server_data.Use             = form.cleaned_data["Use"]
			assets_server_data.Brand           = form.cleaned_data["Brand"]
			assets_server_data.Equipment_Model = form.cleaned_data["Equipment_Model"]
			assets_server_data.Weights         = form.cleaned_data["Weights"]
			assets_server_data.Private_IP      = form.cleaned_data["Private_IP"]
			assets_server_data.Public_IP       = form.cleaned_data["Public_IP"]
			assets_server_data.Admin_IP        = form.cleaned_data["Admin_IP"]
			assets_server_data.SN              = form.cleaned_data["SN"]
			assets_server_data.Response        = form.cleaned_data["Response"]
			assets_server_data.expiration      = form.cleaned_data["expiration"]
			assets_server_data.CPU             = form.cleaned_data["CPU"]
			assets_server_data.CPU_NUM         = form.cleaned_data["CPU_NUM"]
			assets_server_data.MEM             = form.cleaned_data["MEM"]
			assets_server_data.MEM_NUM         = form.cleaned_data["MEM_NUM"]
			assets_server_data.MEM_SINGLE      = form.cleaned_data["MEM_SINGLE"]
			assets_server_data.HDD             = form.cleaned_data["HDD"]
			assets_server_data.HDD_NUM         = form.cleaned_data["HDD_NUM"]
			assets_server_data.HDD_SINGLE      = form.cleaned_data["HDD_SINGLE"]
			assets_server_data.RAID_Type       = form.cleaned_data["RAID_Type"]
			assets_server_data.MAC_1           = form.cleaned_data["MAC_1"]
			assets_server_data.MAC_2           = form.cleaned_data["MAC_2"]
			assets_server_data.MAC_3           = form.cleaned_data["MAC_3"]
			assets_server_data.MAC_4           = form.cleaned_data["MAC_4"]

			if assets_server_data.save() == None:
				return render_to_response('assets_server_add.html',{'form':form,'error':'添加成功!!!','alert':'alert-success'})
			else:
				return render_to_response('assets_server_add.html',{'form':form,'error':'添加失败!!!','alert':'alert-error'})
		else:
			return render_to_response('assets_server_add.html',{'form':form,'error':'添加失败!!!','alert':'alert-error'})
	else:
		form = assets_server_add_Form()
		a_path = u'设备资产'
		i_user = request.COOKIES.get('starl', '')
		return render_to_response('assets_server_add.html', {'form':form,'a_path':a_path,'i_user':i_user})

def assets_server_view(request, id):
	if status(request) == 1:
		return render_to_response('login.html',{'error':'链接超时,请重新登陆!!!','alert':'alert-error'})

	return HttpResponse("assets_server_view" + id)

def assets_serverr_edit(request, id):
	if status(request) == 1:
		return render_to_response('login.html',{'error':'链接超时,请重新登陆!!!','alert':'alert-error'})

	return HttpResponse("assets_server_edit" + id)

def assets_server_delete(request, id):
	if status(request) == 1:
		return render_to_response('login.html',{'error':'链接超时,请重新登陆!!!','alert':'alert-error'})

	return HttpResponse("assets_server_delete" + id)


text:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import db.Database;

/**
 *  This servlet sends one picture stored in the table below to the client
 *  who requested the servlet.
 *
 *   picture( photo_id: integer, title: varchar, place: varchar,
 *            sm_image: blob,   image: blob )
 *
 *  The request must come with a query string as follows:
 *    GetOnePic?12:        sends the picture in sm_image with photo_id = 12
 *    GetOnePic?big12: sends the picture in image  with photo_id = 12
 *
 *  @author  Li-Yan Yuan
 *  modified by Andy Yao
 *
 */
public class GetOnePic extends HttpServlet
    implements SingleThreadModel {

    /**
     *    This method first gets the query string indicating PHOTO_ID,
     *    and then executes the query
     *          select image from yuan.photos where photo_id = PHOTO_ID
     *    Finally, it sends the picture to the client
     */

    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

	//  construct the query  from the client's QueryString
	String picid  = request.getQueryString();
	String query;

	if (picid.startsWith("thumbnail")) {
		query = "select thumbnail from pacs_images where image_id ="+ picid.substring(9);
	} else if (picid.startsWith("regular")) {
		query = "select regular_size from pacs_images where image_id ="+ picid.substring(7);
	} else {
		query = "select full_size from pacs_images where image_id ="+ picid;
	}

	ServletOutputStream out = response.getOutputStream();

	/*
	 *   to execute the given query
	 */
	Connection conn = null;
	try {
		Database db = new Database();
	    conn = db.getConnection();
	    Statement stmt = conn.createStatement();
	    ResultSet rset = stmt.executeQuery(query);

	    if ( rset.next() ) {
			response.setContentType("image/gif");
			InputStream input = rset.getBinaryStream(1);
			int imageByte;
			while((imageByte = input.read()) != -1) {
		   		out.write(imageByte);
			}
			input.close();
	    } else {
			out.println("no picture available");
		}
	} catch( Exception ex ) {
	    out.println(ex.getMessage() );
	}
	// to close the connection
	finally {
	    try {
			conn.close();
	    } catch ( SQLException ex) {
			out.println( ex.getMessage() );
	    }
	}
    }
}


text:
namespace wgt
{
ReflectionSerializer::ReflectionSerializer( ISerializationManager & serializationManager ,
										    IMetaTypeManager & metaTypeManager,
										    IObjectManager & objManager,
											IDefinitionManager & defManager )
	: serializationManager_( serializationManager )
	, metaTypeManager_( metaTypeManager )
	, objManager_( objManager )
	, defManager_( defManager )
	, curDataStream_( nullptr )
{
	typeList.push_back( TypeId::getType<ObjectHandle>() );
}

ReflectionSerializer::~ReflectionSerializer()
{
	curDataStream_ = nullptr;
	typeList.clear();
}

std::vector<TypeId> ReflectionSerializer::getSupportedType()
{
	return typeList;
}

bool ReflectionSerializer::write( IDataStream * dataStream, const Variant & variant )
{
	TypeId type( variant.type()->name() );
	curDataStream_ = dataStream;
	if(!curDataStream_)
	{
		return false;
	}

	if(variant.canCast<ObjectHandle>())
	{
		ObjectHandle provider;
		bool isOk = variant.tryCast( provider );
		assert( isOk );
		if(provider.isValid())
		{
			provider = reflectedRoot( provider, defManager_ );
			const auto classDef = provider.getDefinition( defManager_ );
			if (classDef == nullptr)
			{
				curDataStream_->write("");
				return true;
			}
			curDataStream_->write( classDef->getName() );
			std::string stringId = "";
			RefObjectId id;
			isOk = provider.getId( id );
			if (isOk)
			{
				stringId = id.toString();
			}
			curDataStream_->write( stringId );
			writeProperties( provider );
			return true;
		}
		else
		{
			// write empty string for classdefinition name to handle nullptr
			curDataStream_->write( "" );
			return true;
		}
	}
	else
	{
		assert( false );
	}
	return false;
}

void ReflectionSerializer::writeProperties( const ObjectHandle & provider )
{
	const auto classDef = provider.getDefinition( defManager_ );
	assert( classDef );
	const PropertyIteratorRange& props = classDef->allProperties();
	std::vector< PropertyAccessor > pas;
	for (PropertyIterator pi = props.begin(), end = props.end();
		pi != end; ++pi)
	{
		if (pi->isMethod())
		{
			continue;
		}
		PropertyAccessor pa = classDef->bindProperty(
			pi->getName(), provider );
		assert( pa.isValid() );
		auto metaData = findFirstMetaData<MetaNoSerializationObj>( pa, defManager_ );
		if(metaData != nullptr)
		{
			continue;
		}
		pas.push_back( pa );
	}
	size_t count = pas.size();
	curDataStream_->write( count );
	for(auto & pa : pas)
	{
		writeProperty( pa );
	}
}

void ReflectionSerializer::writeProperty( const PropertyAccessor & property )
{
	assert( property.isValid() );
	const auto & propPath = property.getFullPath();
	curDataStream_->write( propPath );

	Variant value = property.getValue();
	curDataStream_->write( value.type()->name() );
	if(!value.isVoid())
	{
		writePropertyValue( value );
	}

}

void ReflectionSerializer::writeCollection( const Collection & collection )
{
	size_t count = collection.size();
	curDataStream_->write( count );
	for (auto it = collection.begin(), end = collection.end();
		it != end; ++it )
	{
		unsigned int index;
		it.key().tryCast( index );
		//! TODO! how to write the key if we don't know its type?

		std::string strIndex = std::to_string(index);
		curDataStream_->write( strIndex );

		Collection subCollection;
		auto value = it.value();
		curDataStream_->write( value.type()->name() );
		writePropertyValue( value );
	}
}

void ReflectionSerializer::writePropertyValue( const Variant & value )
{
	if( value.typeIs< Collection >() )
	{
		Collection collection;
		bool isCollection = value.tryCast( collection );
		assert( isCollection );
		writeCollection( collection );
	}
	else
	{
		bool hasId = value.typeIs< ObjectHandle >();
		if(hasId)
		{
			ObjectHandle provider;
			bool isOk = value.tryCast( provider );
			assert( isOk );
			if(provider.isValid())
			{
				RefObjectId id;
				hasId = provider.getId( id );
				if(hasId)
				{
					curDataStream_->write( id.toString() );
				}
				else
				{
					hasId = false;
				}
			}
			else
			{
				hasId = false;
			}
		}
		if (!hasId )
		{
			curDataStream_->write( "" );
			serializationManager_.serialize( *curDataStream_, value );
		}
	}
}

bool ReflectionSerializer::read( IDataStream * dataStream, Variant & variant )
{
	curDataStream_ = dataStream;
	if(!curDataStream_)
	{
		return false;
	}

	ObjectHandle provider;
	if(!variant.tryCast( provider ))
	{
		assert( false );
		return false;
	}
	std::string classDefName;
	curDataStream_->read( classDefName );
	if(!classDefName.empty())
	{
		std::string id;
		curDataStream_->read( id );
		if(id.empty())
		{
			if(provider.isValid())
			{
				readProperties( provider );
			}
			else
			{
				auto polyStruct = objManager_.create( classDefName.c_str() );
				readProperties( polyStruct );
				variant = polyStruct;
			}
		}
		else
		{
			auto object =
				objManager_.createObject( RefObjectId( id.c_str() ), classDefName.c_str() );
			readProperties( object );
			variant = object;
		}
	}
	return true;
}

void ReflectionSerializer::readProperties( const ObjectHandle & provider )
{
	assert( provider.isValid() );
	size_t count = 0;
	curDataStream_->read( count );
	for(size_t i = 0; i < count; i++)
	{
		readProperty( provider );
	}
}

void ReflectionSerializer::readProperty( const ObjectHandle & provider )
{
	assert( provider.isValid() );
	std::string propName;
	curDataStream_->read( propName );

	PropertyAccessor prop = provider.getDefinition( defManager_ )->bindProperty(
		propName.c_str(), provider );
	assert( prop.isValid() );

	std::string valueType;
	curDataStream_->read( valueType );
	const MetaType * metaType =
		metaTypeManager_.findType( valueType.c_str() );
	if(metaType == nullptr)
	{
		assert( false );
		return;
	}
	readPropertyValue( valueType.c_str(), prop );
}

void ReflectionSerializer::readCollection( const PropertyAccessor & prop )
{
	assert( prop.isValid() );
	ObjectHandle baseProvider = prop.getRootObject();
	size_t count = 0;
	curDataStream_->read( count );

	Collection collection;
	bool isCollection = prop.getValue().tryCast( collection );
	assert( isCollection );
	if (!collection.empty())
	{
		collection.erase(collection.begin(), collection.end());
	}

	std::string strIndex;
	std::string propName;
	std::string valueType;
	for (size_t i = 0; i < count; i++)
	{
		strIndex.clear();
		curDataStream_->read( strIndex );
		int index = atoi( strIndex.c_str() );
		auto it = collection.insert( index );

		propName = prop.getFullPath();
		propName += '[';
		propName += strIndex;
		propName += ']';

		//TODO: Allow iteration to next element in collection.
		PropertyAccessor pa = baseProvider.getDefinition( defManager_ )->bindProperty(
			propName.c_str(), baseProvider);
		assert( pa.isValid() );
		valueType.clear();
		curDataStream_->read( valueType );
		const MetaType * metaType =
			metaTypeManager_.findType( valueType.c_str() );
		if(metaType == nullptr)
		{
			assert( false );
			return;
		}
		readPropertyValue( valueType.c_str(), pa );
	}
}

void ReflectionSerializer::readPropertyValue( const char * valueType, PropertyAccessor & pa )
{
	const MetaType * metaType =
		metaTypeManager_.findType( valueType );
	if(metaType == nullptr)
	{
		assert( false );
		return;
	}
	Variant value = pa.getValue();

	if (value.typeIs< Collection >())
	{
		readCollection( pa );
		return;
	}
	std::string id;
	curDataStream_->read( id );
	if (ReflectionUtilities::isStruct( pa ))
	{
		read( curDataStream_, value );
	}
	else
	{
		if (!id.empty())
		{
			auto obj = objManager_.getObject( id );
			if(obj == nullptr)
			{
				objManager_.addObjectLinks( id, pa.getProperty(), pa.getRootObject() );
			}
			else
			{
				pa.setValueWithoutNotification( obj );
			}
		}
		else
		{
			Variant variant( metaType );
			if(!variant.isVoid())
			{
				serializationManager_.deserialize( *curDataStream_, variant );
				pa.setValueWithoutNotification( variant );
			}
		}
	}
}
} // end namespace wgt


text:
/** This is generated, do not edit by hand. **/

#include <jni.h>

#include "Proxy.h"

		namespace titanium {

class LocationProviderProxy : public titanium::Proxy
{
public:
	explicit LocationProviderProxy(jobject javaObject);

	static void bindProxy(v8::Handle<v8::Object> exports);
	static v8::Handle<v8::FunctionTemplate> getProxyTemplate();
	static void dispose();

	static v8::Persistent<v8::FunctionTemplate> proxyTemplate;
	static jclass javaClass;

private:
	// Methods -----------------------------------------------------------

	// Dynamic property accessors ----------------------------------------
	static v8::Handle<v8::Value> getter_minUpdateTime(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static void setter_minUpdateTime(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_name(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static void setter_name(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
	static v8::Handle<v8::Value> getter_minUpdateDistance(v8::Local<v8::String> property, const v8::AccessorInfo& info);
	static void setter_minUpdateDistance(v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info);

};

		} // titanium


text:
WebivaExperiment = {
  submitted: false,

  success: function(experiment_id, delay) {
    if(delay) {
      setTimeout( function() { WebivaExperiment.finished(experiment_id); }, delay * 1000 );
    } else {
      WebivaExperiment.finished(experiment_id);
    }
  },

  finished: function(experiment_id) {
    if(! experiment_id || WebivaExperiment.submitted) { return; }
    WebivaExperiment.submitted = true;
    var script = document.createElement('script');
    script.src = '/website/editor/action/exp/' + experiment_id;
    document.documentElement.firstChild.appendChild(script);
  },

  onclick: function(experiment_id, link) {
    WebivaExperiment.finished(experiment_id);
    setTimeout(function() { document.location = link.href; }, 100);
    return false;
  }
};


text:
namespace net {

namespace {

static uint32 WebSocketKeyFingerprint(const std::string& str) {
  std::string result;
  const char* p_char = str.c_str();
  int length = str.length();
  int spaces = 0;
  for (int i = 0; i < length; ++i) {
    if (p_char[i] >= '0' && p_char[i] <= '9')
      result.append(&p_char[i], 1);
    else if (p_char[i] == ' ')
      spaces++;
  }
  if (spaces == 0)
    return 0;
  int64 number = 0;
  if (!base::StringToInt64(result, &number))
    return 0;
  return base::HostToNet32(static_cast<uint32>(number / spaces));
}

class WebSocketHixie76 : public net::WebSocket {
 public:
  static net::WebSocket* Create(HttpServer* server,
                                HttpConnection* connection,
                                const HttpServerRequestInfo& request,
                                size_t* pos) {
    if (connection->read_buf()->GetSize() <
        static_cast<int>(*pos + kWebSocketHandshakeBodyLen))
      return NULL;
    return new WebSocketHixie76(server, connection, request, pos);
  }

  void Accept(const HttpServerRequestInfo& request) override {
    std::string key1 = request.GetHeaderValue("sec-websocket-key1");
    std::string key2 = request.GetHeaderValue("sec-websocket-key2");

    uint32 fp1 = WebSocketKeyFingerprint(key1);
    uint32 fp2 = WebSocketKeyFingerprint(key2);

    char data[16];
    memcpy(data, &fp1, 4);
    memcpy(data + 4, &fp2, 4);
    memcpy(data + 8, &key3_[0], 8);

    base::MD5Digest digest;
    base::MD5Sum(data, 16, &digest);

    std::string origin = request.GetHeaderValue("origin");
    std::string host = request.GetHeaderValue("host");
    std::string location = "ws://" + host + request.path;
    server_->SendRaw(
        connection_->id(),
        base::StringPrintf("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
                           "Upgrade: WebSocket\r\n"
                           "Connection: Upgrade\r\n"
                           "Sec-WebSocket-Origin: %s\r\n"
                           "Sec-WebSocket-Location: %s\r\n"
                           "\r\n",
                           origin.c_str(),
                           location.c_str()));
    server_->SendRaw(connection_->id(),
                     std::string(reinterpret_cast<char*>(digest.a), 16));
  }

  ParseResult Read(std::string* message) override {
    DCHECK(message);
    HttpConnection::ReadIOBuffer* read_buf = connection_->read_buf();
    if (read_buf->StartOfBuffer()[0])
      return FRAME_ERROR;

    base::StringPiece data(read_buf->StartOfBuffer(), read_buf->GetSize());
    size_t pos = data.find('\377', 1);
    if (pos == base::StringPiece::npos)
      return FRAME_INCOMPLETE;

    message->assign(data.data() + 1, pos - 1);
    read_buf->DidConsume(pos + 1);

    return FRAME_OK;
  }

  void Send(const std::string& message) override {
    char message_start = 0;
    char message_end = -1;
    server_->SendRaw(connection_->id(), std::string(1, message_start));
    server_->SendRaw(connection_->id(), message);
    server_->SendRaw(connection_->id(), std::string(1, message_end));
  }

 private:
  static const int kWebSocketHandshakeBodyLen;

  WebSocketHixie76(HttpServer* server,
                   HttpConnection* connection,
                   const HttpServerRequestInfo& request,
                   size_t* pos)
      : WebSocket(server, connection) {
    std::string key1 = request.GetHeaderValue("sec-websocket-key1");
    std::string key2 = request.GetHeaderValue("sec-websocket-key2");

    if (key1.empty()) {
      server->SendResponse(
          connection->id(),
          HttpServerResponseInfo::CreateFor500(
              "Invalid request format. Sec-WebSocket-Key1 is empty or isn't "
              "specified."));
      return;
    }

    if (key2.empty()) {
      server->SendResponse(
          connection->id(),
          HttpServerResponseInfo::CreateFor500(
              "Invalid request format. Sec-WebSocket-Key2 is empty or isn't "
              "specified."));
      return;
    }

    key3_.assign(connection->read_buf()->StartOfBuffer() + *pos,
                 kWebSocketHandshakeBodyLen);
    *pos += kWebSocketHandshakeBodyLen;
  }

  std::string key3_;

  DISALLOW_COPY_AND_ASSIGN(WebSocketHixie76);
};

const int WebSocketHixie76::kWebSocketHandshakeBodyLen = 8;

class WebSocketHybi17 : public WebSocket {
 public:
  static WebSocket* Create(HttpServer* server,
                           HttpConnection* connection,
                           const HttpServerRequestInfo& request,
                           size_t* pos) {
    std::string version = request.GetHeaderValue("sec-websocket-version");
    if (version != "8" && version != "13")
      return NULL;

    std::string key = request.GetHeaderValue("sec-websocket-key");
    if (key.empty()) {
      server->SendResponse(
          connection->id(),
          HttpServerResponseInfo::CreateFor500(
              "Invalid request format. Sec-WebSocket-Key is empty or isn't "
              "specified."));
      return NULL;
    }
    return new WebSocketHybi17(server, connection, request, pos);
  }

  void Accept(const HttpServerRequestInfo& request) override {
    static const char* const kWebSocketGuid =
        "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    std::string key = request.GetHeaderValue("sec-websocket-key");
    std::string data = base::StringPrintf("%s%s", key.c_str(), kWebSocketGuid);
    std::string encoded_hash;
    base::Base64Encode(base::SHA1HashString(data), &encoded_hash);

    server_->SendRaw(connection_->id(),
                     base::StringPrintf(
                         "HTTP/1.1 101 WebSocket Protocol Handshake\r\n"
                         "Upgrade: WebSocket\r\n"
                         "Connection: Upgrade\r\n"
                         "Sec-WebSocket-Accept: %s\r\n"
                         "%s"
                         "\r\n",
                         encoded_hash.c_str(), response_extensions_.c_str()));
  }

  ParseResult Read(std::string* message) override {
    HttpConnection::ReadIOBuffer* read_buf = connection_->read_buf();
    base::StringPiece frame(read_buf->StartOfBuffer(), read_buf->GetSize());
    int bytes_consumed = 0;
    ParseResult result = encoder_->DecodeFrame(frame, &bytes_consumed, message);
    if (result == FRAME_OK)
      read_buf->DidConsume(bytes_consumed);
    if (result == FRAME_CLOSE)
      closed_ = true;
    return result;
  }

  void Send(const std::string& message) override {
    if (closed_)
      return;
    std::string encoded;
    encoder_->EncodeFrame(message, 0, &encoded);
    server_->SendRaw(connection_->id(), encoded);
  }

 private:
  WebSocketHybi17(HttpServer* server,
                  HttpConnection* connection,
                  const HttpServerRequestInfo& request,
                  size_t* pos)
      : WebSocket(server, connection),
        closed_(false) {
    std::string request_extensions =
        request.GetHeaderValue("sec-websocket-extensions");
    encoder_.reset(WebSocketEncoder::CreateServer(request_extensions,
                                                  &response_extensions_));
    if (!response_extensions_.empty()) {
      response_extensions_ =
          "Sec-WebSocket-Extensions: " + response_extensions_ + "\r\n";
    }
  }

  scoped_ptr<WebSocketEncoder> encoder_;
  std::string response_extensions_;
  bool closed_;

  DISALLOW_COPY_AND_ASSIGN(WebSocketHybi17);
};

}  // anonymous namespace

WebSocket* WebSocket::CreateWebSocket(HttpServer* server,
                                      HttpConnection* connection,
                                      const HttpServerRequestInfo& request,
                                      size_t* pos) {
  WebSocket* socket = WebSocketHybi17::Create(server, connection, request, pos);
  if (socket)
    return socket;

  return WebSocketHixie76::Create(server, connection, request, pos);
}

WebSocket::WebSocket(HttpServer* server, HttpConnection* connection)
    : server_(server),
      connection_(connection) {
}

WebSocket::~WebSocket() {
}

}  // namespace net


text:
use strict;
use warnings;

use Bio::EnsEMBL::DBSQL::DBAdaptor;

use Getopt::Long;

#my $LIMIT = ' LIMIT 1000 ';
my $LIMIT = '';

my ($db, $dnadbname);

{
  my ($dbname, $host, $port, $user, $pass);

  GetOptions('dbname=s' => \$dbname,
             'dnadbname=s' => \$dnadbname,
             'user=s'   => \$user,
             'host=s'   => \$host,
             'port=i'   => \$port,
             'pass=s'   => \$pass);

  $port ||= 3306;

  usage() if(!$host || !$user || !$dbname);

  $db = Bio::EnsEMBL::DBSQL::DBAdaptor->new
    (-host => $host,
     -user => $user,
     -pass => $pass,
     -port => $port,
     -dbname => $dbname,
     -dnadbname => $dnadbname);

  if($dnadbname) {
    my $dnadb = Bio::EnsEMBL::DBSQL::DBAdaptor->new
      (-host => $host,
       -user => $user,
       -pass => $pass,
       -port => $port,
       -dbname => $dnadbname);
    $db->dnadb($dnadb);
  } else {
    $dnadbname = $dbname;
  }
}

my @daf_css = get_feat_coord_systems($db, 'dna_align_feature');
my @paf_css = get_feat_coord_systems($db, 'protein_align_feature');

### convert dna align features

my $sth = $db->dbc()->prepare("SHOW CREATE TABLE dna_align_feature");
$sth->execute();
my $create_table = $sth->fetchrow_arrayref()->[1];
$sth->finish();

$create_table =~ s/CREATE TABLE dna_align_feature/CREATE TABLE tmp_dna_align_feature/;
# difference b/w mysql 4 and mysql 3
$create_table =~ s/CREATE TABLE `dna_align_feature`/CREATE TABLE tmp_dna_align_feature/;

$sth = $db->dbc()->prepare($create_table);
$sth->execute();

$sth = $db->dbc()->prepare
    (qq{INSERT INTO tmp_dna_align_feature
        SELECT daf.dna_align_feature_id,
          a.asm_seq_region_id,
          if(a.ori = 1,
            (a.asm_start + daf.seq_region_start - a.cmp_start),
            (a.asm_start + a.cmp_end - daf.seq_region_end))
            as seq_region_start,
          if(a.ori = 1,
            (a.asm_start + daf.seq_region_end - a.cmp_start),
            (a.asm_end   + a.cmp_end - daf.seq_region_start))
            as seq_region_end,
          a.ori * daf.seq_region_strand as seq_region_strand,
          daf.hit_start, daf.hit_end, daf.hit_strand, daf.hit_name,
          daf.analysis_id, daf.score, daf.evalue, daf.perc_ident,
          daf.cigar_line
        FROM $dnadbname.assembly a,
             $dnadbname.seq_region asm_sr,
             $dnadbname.seq_region cmp_sr,
             dna_align_feature daf,
             $dnadbname.seq_region_attrib sra,
             $dnadbname.attrib_type at
        WHERE asm_sr.coord_system_id = ? AND cmp_sr.coord_system_id = ?
        AND   daf.seq_region_id = a.cmp_seq_region_id
        AND   a.asm_seq_region_id = asm_sr.seq_region_id
        AND   a.cmp_seq_region_id = cmp_sr.seq_region_id
        AND   daf.seq_region_start >= a.cmp_start
        AND   daf.seq_region_end <= a.cmp_end
        AND   asm_sr.seq_region_id = sra.seq_region_id
        AND   sra.attrib_type_id = at.attrib_type_id
        AND   at.code = 'toplevel'
        $LIMIT});

foreach my $cs_pair (@daf_css) {
  my ($top_cs, $feat_cs) = @$cs_pair;
  print STDERR "Converting dna align features between from coord system ",
    $feat_cs->name(), " to coord system ", $top_cs->name(), "\n";
  $sth->execute($top_cs->dbID(), $feat_cs->dbID());
}
$sth->finish();

### convert protein align features

$sth = $db->dbc()->prepare("SHOW CREATE TABLE protein_align_feature");
$sth->execute();
$create_table = $sth->fetchrow_arrayref()->[1];
$sth->finish();

$create_table =~ s/CREATE TABLE protein_align_feature/CREATE TABLE tmp_protein_align_feature/;
$create_table =~ s/CREATE TABLE `protein_align_feature`/CREATE TABLE tmp_protein_align_feature/;

$sth = $db->dbc()->prepare($create_table);
$sth->execute();

$sth = $db->dbc()->prepare
    (qq{INSERT INTO tmp_protein_align_feature
        SELECT paf.protein_align_feature_id,
          a.asm_seq_region_id,
          if(a.ori = 1,
            (a.asm_start + paf.seq_region_start - a.cmp_start),
            (a.asm_start + a.cmp_end - paf.seq_region_end))
            as seq_region_start,
          if(a.ori = 1,
            (a.asm_start + paf.seq_region_end - a.cmp_start),
            (a.asm_end   + a.cmp_end - paf.seq_region_start))
            as seq_region_end,
          a.ori * paf.seq_region_strand as seq_region_strand,
          paf.hit_start, paf.hit_end, paf.hit_name, paf.analysis_id,
          paf.score, paf.evalue, paf.perc_ident, paf.cigar_line
        FROM $dnadbname.assembly a,
             $dnadbname.seq_region asm_sr,
             $dnadbname.seq_region cmp_sr,
             protein_align_feature paf,
             $dnadbname.seq_region_attrib sra,
             $dnadbname.attrib_type at
        WHERE asm_sr.coord_system_id = ? AND cmp_sr.coord_system_id = ?
        AND   paf.seq_region_id = a.cmp_seq_region_id
        AND   a.asm_seq_region_id = asm_sr.seq_region_id
        AND   a.cmp_seq_region_id = cmp_sr.seq_region_id
        AND   paf.seq_region_start >= a.cmp_start
        AND   paf.seq_region_end <= a.cmp_end
        AND   asm_sr.seq_region_id = sra.seq_region_id
        AND   sra.attrib_type_id = at.attrib_type_id
        AND   at.code = 'toplevel'
        $LIMIT});

foreach my $cs_pair (@paf_css) {
  my ($top_cs, $feat_cs) = @$cs_pair;
  print STDERR "Converting protein align features between from coord system ",
    $feat_cs->name(), " to coord system ", $top_cs->name(), "\n";
  $sth->execute($top_cs->dbID(), $feat_cs->dbID());
}
$sth->finish();

print STDERR "Replacing existing align feature tables with new tables\n";

$db->dbc->do("drop table protein_align_feature");
$db->dbc->do("drop table dna_align_feature");
$db->dbc->do("alter table tmp_protein_align_feature rename protein_align_feature");
$db->dbc->do("alter table tmp_dna_align_feature rename dna_align_feature");

print STDERR "Updating meta_coord table\n";

$db->dbc->do("delete from meta_coord where table_name = 'dna_align_feature'");
$db->dbc->do("delete from meta_coord where table_name = 'protein_align_feature'");

$sth = $db->dbc->prepare("INSERT INTO meta_coord set table_name = ?, " .
                         "coord_system_id = ?");

my %seen = ();
foreach my $cs_pair (@daf_css) {
  my ($top_cs) = @$cs_pair;
  if(!$seen{$top_cs->dbID()}) {
    $sth->execute('dna_align_feature', $top_cs->dbID());
    $seen{$top_cs->dbID()} = 1;
  }
}

%seen = ();
foreach my $cs_pair (@paf_css) {
  my ($top_cs) = @$cs_pair;
  if(!$seen{$top_cs->dbID()}) {
    $sth->execute('protein_align_feature', $top_cs->dbID());
    $seen{$top_cs->dbID()} = 1;
  }
}

$sth->finish();

sub get_feat_coord_systems {
  my $db = shift;
  my $type = shift;

  my $csa = $db->get_CoordSystemAdaptor();
  my $mcc = $db->get_MetaCoordContainer();

  # determine what coordinate systems have top-level seq_regions

  my $sth = $db->dbc->prepare
    (qq{SELECT distinct(sr.coord_system_id)
        FROM   seq_region sr, seq_region_attrib sra, attrib_type at
        WHERE  sr.seq_region_id = sra.seq_region_id
        AND    sra.attrib_type_id = at.attrib_type_id
        AND    at.code = 'toplevel'});

  $sth->execute();

  my @top_css = map {$csa->fetch_by_dbID($_->[0])}
                @{$sth->fetchall_arrayref()};

  $sth->finish();

  # determine what coord systems features are stored in

  my @feat_css = @{$mcc->fetch_all_CoordSystems_by_feature_type($type)};

  my @css;

  foreach my $feat_cs (@feat_css) {
    foreach my $top_cs (@top_css) {
      if(!$feat_cs->equals($top_cs)) {
        if($feat_cs->rank() > $top_cs->rank()) {
          my @mp = @{$csa->get_mapping_path($top_cs, $feat_cs)};
          if(@mp == 2) {
            if($mp[0]->equals($top_cs)) {
              push @css, \@mp;
            } else {
              die("Unexpected: ". $top_cs->name() .
                  " coord system should not be component of " .
                  $feat_cs->name(), " coord system.");
            }
          }
        } else {
          die("There is no 1 step mapping path between coord systems " .
              $feat_cs->name()." and ".$top_cs->name().". This script " .
              "requires one step mapping paths.");
        }
      }
    }
  }

  if(!@css) {
    die("Nothing to do for ${type}s (or missing meta/assembly info)\n");
  }

  return @css;
}

sub usage {
  print STDERR
qq{
This program will convert the coordinates of alignment features from
their current cooridinate systems to coordinates on toplevel sequence
regions.  This can speed up the retrieval of these features dramatically.

Features which are partially or entirely non-golden portions of
sequence regions will be discarded.

This program is only capable of mapping if there is a direct relationship
between the coordinate systems defined in the assembly and meta tables.

This program can use a different database to obtain the assembly information
but the database must be on the same MySQL instance.  This is useful for
satellite databases such as the est database.

usage:
  perl push_align_features -dbname <dbname> -user <user> -host <host> \
                           [-port <port>] [-pass <pass>] [-dnadbname <dbname>]
};

  exit;
}


text:
<?php declare(strict_types=1);

namespace Terah\RedisCache;

use Terah\Assert\Assert;
use Redis;

/**
 * Class RedisCachePool
 *
 * @package Terah\RedisCache
 * @method CacheInterface setNamespace(string $namespace)
 * @method CacheInterface setDefaultTtl(int $defaultTtl)
 * @method bool set(string $key, $data, int $ttl=null)
 * @method mixed get(string $key)
 * @method bool exists(string $key)
 * @method \DateTime expires(string $key)
 * @method mixed remember(string $key, callable $callback, int $ttl=null)
 * @method bool delete(string $keyOrDirectory)
 * @method string[] allKeys()
 * @method bool flush()
 */
class RedisCachePool
{
    /** @var \Psr\Log\LoggerInterface $logger */
    protected $logger;

    /**
     * Sets a logger.
     *
     * @param \Psr\Log\LoggerInterface $logger
     * @return $this
     */
    public function setLogger($logger)
    {
        $this->logger = $logger;

        return $this;
    }

    /**
     * Gets a logger.
     *
     * @return object
     */
    public function getLogger()
    {
        return $this->logger;
    }

    /**
     * @var CacheInterface[]
     */
    protected $caches       = [];

    /** @var string[] */
    protected $globalFlush  = [];

    /**
     * RedisCachePool constructor.
     *
     * @param array  $config
     * @param Redis[] $redisServers
     * @param \Psr\Log\LoggerInterface $logger
     * @throws \Exception
     */
    public function __construct(array $config=[], array $redisServers, $logger)
    {
        $this->setLogger($logger);

        $servers            = [
            'read'              => [],
            'write'             => [],
            'delete'            => [],
            'all'               => [],
        ];
        $failedServers      = [];
        foreach ( $redisServers['hosts'] as $type => $hosts )
        {
            foreach ( $hosts as $host )
            {
                $parts      = explode(':', $host);
                $hostname   = $parts[0];
                $port       = isset($parts[1]) ? $parts[1] : $redisServers['port'];
                $timeout    = $redisServers['timeout'];
                $password   = $redisServers['password'];
                try
                {
                    if ( ! in_array("{$hostname}:{$port}", $failedServers) )
                    {
                        if ( ! array_key_exists($host, $servers['all']) )
                        {
                            $redis                  = new Redis;
                            $redis->pconnect($hostname, (int)$port, $timeout);
                            $redis->auth($password);
                            $servers['all'][$host]  = $redis;
                        }
                        $servers[$type][$host] = $servers['all'][$host];
                    }
                }
                catch ( \Exception $e )
                {
                    $failedServers[] = "{$hostname}:{$port}";
                    $this->logger->error($e->getMessage(), compact('hostname', 'port', 'timeout'));
                }
            }
        }
        foreach ( ['read', 'write', 'delete'] as $type )
        {
            if ( ! empty($redisServers['hosts'][$type]) && empty($servers[$type]) )
            {
                $this->logger->error("There are no {$type} redis servers online.", ['config' => $redisServers, 'online' => $servers]);
                throw new \Exception("There are no {$type} redis servers online.");
            }
        }

        foreach ( $config as $name => $conf )
        {
            $conf = (object)$conf;
            Assert::that($conf)->propertiesExist(['default_ttl', 'global_flush']);

            $this->caches[$name]        = (new RedisCache($servers, $conf->default_ttl, $name))->setLogger($logger);
            $this->globalFlush[$name]   = $conf->global_flush;
        }
    }

    /**
     * @param string $cache
     * @return CacheInterface
     * @throws \Terah\Assert\AssertionFailedException
     */
    public function getCache(string $cache='default') : CacheInterface
    {
        Assert::that($this->caches)->keyExists($cache, "Could not load cache pool by name ({$cache})");

        return $this->caches[$cache];
    }

    /**
     * @return bool
     */
    public function wipe() : bool
    {
        foreach ( $this->globalFlush as $name => $doFlush )
        {
            if ( $doFlush && array_key_exists($name, $this->caches) && ! empty( $this->caches[$name] ) )
            {
                $this->caches[$name]->flush();
            }
        }

        return true;
    }

    /**
     * @param string $method
     * @param array $arguments
     * @return mixed
     */
    public function __call(string $method, array $arguments)
    {
        return call_user_func_array([$this->getCache('default'), $method], $arguments);
    }

}


text:
//
// This file is part of khmer, https://github.com/dib-lab/khmer/, and is
// Copyright (C) Michigan State University, 2009-2015. It is licensed under
// the three-clause BSD license; see LICENSE.
// Contact: khmer-project@idyll.org
//

#ifndef PRIMES_HH
#define PRIMES_HH

#include <math.h>
#include "hashtable.hh"

/* Primes is a class for generating prime numbers. */

namespace khmer
{
class Primes
{

private:
    HashIntoType n;

    /* Returns true if n is prime, false otherwise */
    bool is_prime()
    {
        if (n < 2) {
            return false;
        }
        if (n == 2) {
            return true;
        }
        if ((n % 2) == 0) {
            return false;
        }

        HashIntoType max = (HashIntoType)pow(n, 0.5);
        for (HashIntoType x = 3; x <= max; x+=2)
            if ((n % x) == 0) {
                return false;
            }
        return true;
    }

public:
    Primes(HashIntoType num)
    {
        /* Make sure that the initial number to start from is odd
         * and strictly greater than num */
        n = ++num;
        if ((n % 2) == 0) {
            n++;
        }
    }

    /* Returns the next prime >= n */
    HashIntoType get_next_prime()
    {
        for (;;) {
            if (is_prime()) {
                /* If n is prime, we need to make sure to increment
                 * n by 2 before returning, otherwise we will always
                 * return the same prime number */
                HashIntoType prime = n;
                n += 2;
                return prime;
            }
            n += 2;
        }
    }
};
};

#endif


text:
layout: post
title: Jasper
date: 2015-10-01 00:00:00
homepage: https://github.com/biomadeira/jasper
download: https://github.com/biomadeira/jasper/archive/master.zip
demo: https://biomadeira.github.io/jasper/
author: biomadeira
thumbnail: jasper.png
license: MIT License
license_link: http://opensource.org/licenses/MIT
---

Jekyll-ready and full featured clone of Ghost's Casper theme.


text:
package apollo.gui;

import java.util.Vector;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import apollo.datamodel.SeqFeatureI;
import apollo.datamodel.SeqFeature;
import apollo.gui.event.BaseFocusEvent;
import apollo.gui.genomemap.StrandedZoomableApolloPanel;

import org.apache.oro.text.regex.*;

/** CallsSeqSelector on separate thread and populates table with
    results */
public class SeqSelectorTable {

  Perl5Compiler p5Compiler;
  Perl5Pattern pattern; //to extract numeric patterns

  private SeqFeatureI sf;
  private String searchSeqString;
  private boolean revComp;
  private Vector columns = new Vector(2);
  private Vector features = new Vector();
  private JTable        resultTable;
  //  private static int tableSize;
  private StrandedZoomableApolloPanel szap;
  private SelectionManager selectionManager;
  private StatusPane statusPane;
  private boolean useRegExp;

  public SeqSelectorTable(SeqFeatureI sf, String searchSeqString,
                          boolean revComp, StrandedZoomableApolloPanel szap,
                          StatusPane statusPane) {
    this(sf, searchSeqString, revComp, szap, statusPane, false);
  }

  public SeqSelectorTable(SeqFeatureI sf, String searchSeqString,
                          boolean revComp, StrandedZoomableApolloPanel szap,
                          StatusPane statusPane, boolean useRegExp) {
    this.sf = sf;
    this.searchSeqString = searchSeqString.toUpperCase();
    this.revComp = revComp;
    this.szap = szap;
    this.useRegExp = useRegExp;
    selectionManager = szap.getSelectionManager();
    this.statusPane = statusPane;
    initTable();
    SeqSelSwingWorker w = new SeqSelSwingWorker();
    w.start();
    // funny - selects all features but nothing selected in table
    // should the whole table be selected or should select not happen?
    selectionManager.select(features, this);

    p5Compiler = new Perl5Compiler();
    try{
      pattern =
	(Perl5Pattern)p5Compiler.compile("([0-9]+)",
					 p5Compiler.CASE_INSENSITIVE_MASK);
    } catch(MalformedPatternException ex){
      System.out.println("couldn't make Perl5 pattern");
    }
  }

  public JTable getTable() {
    return resultTable;
  }

  private void initTable() {
    columns.addElement("Position");
    columns.addElement("Sequence");
    resultTable    = new JTable(new Vector(), columns);
    // Currently doesnt deal with multiselect - might be nice if did
    resultTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    resultTable.getSelectionModel().addListSelectionListener(new TableSelector());
  }

  private class SeqSelSwingWorker extends SwingWorker {
    /**
     * Compute the value to be returned by the get method.
     */
    public Object construct() {
      SequenceSelector sel = new SequenceSelector(sf,
						  searchSeqString,
						  revComp,
						  useRegExp);
      return sel;
    }

    /**
     * Called on the event dispatching thread (not on the worker thread)
     * after the construct method has returned.
     */
    public void finished() {
      // get() is a SwingWorker method that returns an Object that is
      // constructed by construct() which is a SequenceSelector
      SequenceSelector sel = (SequenceSelector)get();

      features = sel.getMatches();
      SequenceMatchModel model = new SequenceMatchModel();
      model.setData(features);
      model.setColumns(columns);
      resultTable.setModel(model);
      if (statusPane != null)
	statusPane.setText("Found sequence " + features.size() + " times");
    }
  }

  private void fireBaseFocusEvent(String posString) {
    int pos = Integer.parseInt(posString);
    //if (revComp)
    //  pos = pos - searchSeqString.length();
    BaseFocusEvent evt = new BaseFocusEvent(this, pos, new SeqFeature());
    selectionManager.getController().handleBaseFocusEvent(evt);
  }

  //modified to extract positions from strings in form "(\d+)-(\d+)"
  private class TableSelector implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) {

      Perl5Matcher matcher = new Perl5Matcher();
      PatternMatcherInput pmInput = null;

      int row = resultTable.getSelectedRow();
      if (row >= 0 && !e.getValueIsAdjusting() ) {
        Object position = resultTable.getValueAt(row, 0);
	pmInput = new PatternMatcherInput(position.toString());
	matcher.contains(pmInput,pattern);
	fireBaseFocusEvent(matcher.getMatch().toString());
        SeqFeature feat = (SeqFeature)features.elementAt(row);
        selectionManager.select(feat,this);
        // zoom in on new selection (with some padding)
	szap.zoomToSelectionWithWindow(feat.length()*2 - 2);
      }
    }
  }

  /**
   * This is the TableModel for the table
   * Takes a Vector of SequenceMatch in setData.
   * Each SequenceMatch represents a row
   */
  protected class SequenceMatchModel extends AbstractTableModel {
    private Vector data;
    private Vector columns;

    protected void setData (Vector data) {
      this.data = data;
    }

    protected void setColumns (Vector columns) {
      this.columns = columns;
    }

    public int getRowCount() {
      return data.size();
    }

    public int getColumnCount() {
      return columns.size();
    }

    public String getColumnName(int column) {
      return (String) columns.elementAt(column);
    }

    public Object getValueAt(int row, int column) {
      SeqFeatureI match = (SeqFeatureI) data.elementAt(row);
      if (column == 0)
        return (match.getLow() + "-" + match.getHigh());
      else
        return match.getResidues();
    }

  } // end SequenceMatchModel inner class

}