text:
<?php
/**
 * Implements Special:ChangePassword
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 * @ingroup SpecialPage
 */

/**
 * Let users recover their password.
 *
 * @ingroup SpecialPage
 */
class SpecialChangePasswordPreAuthManager extends FormSpecialPage {
	protected $mUserName;
	protected $mDomain;

	// Optional Wikitext Message to show above the password change form
	protected $mPreTextMessage = null;

	// label for old password input
	protected $mOldPassMsg = null;

	public function __construct() {
		parent::__construct( 'ChangePassword', 'editmyprivateinfo' );
		$this->listed( false );
	}

	public function doesWrites() {
		return true;
	}

	/**
	 * Main execution point
	 * @param string|null $par
	 */
	function execute( $par ) {
		$this->getOutput()->disallowUserJs();

		parent::execute( $par );
	}

	protected function checkExecutePermissions( User $user ) {
		parent::checkExecutePermissions( $user );

		if ( !$this->getRequest()->wasPosted() ) {
			$this->requireLogin( 'resetpass-no-info' );
		}
	}

	/**
	 * Set a message at the top of the Change Password form
	 * @since 1.23
	 * @param Message $msg Message to parse and add to the form header
	 */
	public function setChangeMessage( Message $msg ) {
		$this->mPreTextMessage = $msg;
	}

	/**
	 * Set a message at the top of the Change Password form
	 * @since 1.23
	 * @param string $msg Message label for old/temp password field
	 */
	public function setOldPasswordMessage( $msg ) {
		$this->mOldPassMsg = $msg;
	}

	protected function getFormFields() {
		$user = $this->getUser();
		$request = $this->getRequest();

		$oldpassMsg = $this->mOldPassMsg;
		if ( $oldpassMsg === null ) {
			$oldpassMsg = $user->isLoggedIn() ? 'oldpassword' : 'resetpass-temp-password';
		}

		$fields = [
			'Name' => [
				'type' => 'info',
				'label-message' => 'username',
				'default' => $request->getVal( 'wpName', $user->getName() ),
			],
			'Password' => [
				'type' => 'password',
				'label-message' => $oldpassMsg,
			],
			'NewPassword' => [
				'type' => 'password',
				'label-message' => 'newpassword',
			],
			'Retype' => [
				'type' => 'password',
				'label-message' => 'retypenew',
			],
		];

		if ( !$this->getUser()->isLoggedIn() ) {
			$fields['LoginOnChangeToken'] = [
				'type' => 'hidden',
				'label' => 'Change Password Token',
				'default' => LoginForm::getLoginToken()->toString(),
			];
		}

		$extraFields = [];
		Hooks::run( 'ChangePasswordForm', [ &$extraFields ] );
		foreach ( $extraFields as $extra ) {
			list( $name, $label, $type, $default ) = $extra;
			$fields[$name] = [
				'type' => $type,
				'name' => $name,
				'label-message' => $label,
				'default' => $default,
			];
		}

		if ( !$user->isLoggedIn() ) {
			$fields['Remember'] = [
				'type' => 'check',
				'label' => $this->msg( 'remembermypassword' )
						->numParams(
							ceil( $this->getConfig()->get( 'CookieExpiration' ) / ( 3600 * 24 ) )
						)->text(),
				'default' => $request->getVal( 'wpRemember' ),
			];
		}

		return $fields;
	}

	protected function alterForm( HTMLForm $form ) {
		$form->setId( 'mw-resetpass-form' );
		$form->setTableId( 'mw-resetpass-table' );
		$form->setWrapperLegendMsg( 'resetpass_header' );
		$form->setSubmitTextMsg(
			$this->getUser()->isLoggedIn()
				? 'resetpass-submit-loggedin'
				: 'resetpass_submit'
		);
		$form->addButton( [
			'name' => 'wpCancel',
			'value' => $this->msg( 'resetpass-submit-cancel' )->text()
		] );
		$form->setHeaderText( $this->msg( 'resetpass_text' )->parseAsBlock() );
		if ( $this->mPreTextMessage instanceof Message ) {
			$form->addPreText( $this->mPreTextMessage->parseAsBlock() );
		}
		$form->addHiddenFields(
			$this->getRequest()->getValues( 'wpName', 'wpDomain', 'returnto', 'returntoquery' ) );
	}

	public function onSubmit( array $data ) {
		global $wgAuth;

		$request = $this->getRequest();

		if ( $request->getCheck( 'wpLoginToken' ) ) {
			// This comes from Special:Userlogin when logging in with a temporary password
			return false;
		}

		if ( !$this->getUser()->isLoggedIn()
			&& !LoginForm::getLoginToken()->match( $request->getVal( 'wpLoginOnChangeToken' ) )
		) {
			// Potential CSRF (bug 62497)
			return false;
		}

		if ( $request->getCheck( 'wpCancel' ) ) {
			$returnto = $request->getVal( 'returnto' );
			$titleObj = $returnto !== null ? Title::newFromText( $returnto ) : null;
			if ( !$titleObj instanceof Title ) {
				$titleObj = Title::newMainPage();
			}
			$query = $request->getVal( 'returntoquery' );
			$this->getOutput()->redirect( $titleObj->getFullURL( $query ) );

			return true;
		}

		$this->mUserName = $request->getVal( 'wpName', $this->getUser()->getName() );
		$this->mDomain = $wgAuth->getDomain();

		if ( !$wgAuth->allowPasswordChange() ) {
			throw new ErrorPageError( 'changepassword', 'resetpass_forbidden' );
		}

		$status = $this->attemptReset( $data['Password'], $data['NewPassword'], $data['Retype'] );

		return $status;
	}

	public function onSuccess() {
		if ( $this->getUser()->isLoggedIn() ) {
			$this->getOutput()->wrapWikiMsg(
				"
\n$1\n
",
				'changepassword-success'
			);
			$this->getOutput()->returnToMain();
		} else {
			$request = $this->getRequest();
			LoginForm::clearLoginToken();
			$token = LoginForm::getLoginToken()->toString();
			$data = [
				'action' => 'submitlogin',
				'wpName' => $this->mUserName,
				'wpDomain' => $this->mDomain,
				'wpLoginToken' => $token,
				'wpPassword' => $request->getVal( 'wpNewPassword' ),
			] + $request->getValues( 'wpRemember', 'returnto', 'returntoquery' );
			$login = new LoginForm( new DerivativeRequest( $request, $data, true ) );
			$login->setContext( $this->getContext() );
			$login->execute( null );
		}
	}

	/**
	 * Checks the new password if it meets the requirements for passwords and set
	 * it as a current password, otherwise set the passed Status object to fatal
	 * and doesn't change anything
	 *
	 * @param string $oldpass The current (temporary) password.
	 * @param string $newpass The password to set.
	 * @param string $retype The string of the retype password field to check with newpass
	 * @return Status
	 */
	protected function attemptReset( $oldpass, $newpass, $retype ) {
		$isSelf = ( $this->mUserName === $this->getUser()->getName() );
		if ( $isSelf ) {
			$user = $this->getUser();
		} else {
			$user = User::newFromName( $this->mUserName );
		}

		if ( !$user || $user->isAnon() ) {
			return Status::newFatal( $this->msg( 'nosuchusershort', $this->mUserName ) );
		}

		if ( $newpass !== $retype ) {
			Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'badretype' ] );
			return Status::newFatal( $this->msg( 'badretype' ) );
		}

		$throttleInfo = LoginForm::incrementLoginThrottle( $this->mUserName );
		if ( $throttleInfo ) {
			return Status::newFatal( $this->msg( 'changepassword-throttled' )
				->durationParams( $throttleInfo['wait'] )
			);
		}

		// @todo Make these separate messages, since the message is written for both cases
		if ( !$user->checkTemporaryPassword( $oldpass ) && !$user->checkPassword( $oldpass ) ) {
			Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'wrongpassword' ] );
			return Status::newFatal( $this->msg( 'resetpass-wrong-oldpass' ) );
		}

		// User is resetting their password to their old password
		if ( $oldpass === $newpass ) {
			return Status::newFatal( $this->msg( 'resetpass-recycled' ) );
		}

		// Do AbortChangePassword after checking mOldpass, so we don't leak information
		// by possibly aborting a new password before verifying the old password.
		$abortMsg = 'resetpass-abort-generic';
		if ( !Hooks::run( 'AbortChangePassword', [ $user, $oldpass, $newpass, &$abortMsg ] ) ) {
			Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'abortreset' ] );
			return Status::newFatal( $this->msg( $abortMsg ) );
		}

		// Please reset throttle for successful logins, thanks!
		LoginForm::clearLoginThrottle( $this->mUserName );

		try {
			$user->setPassword( $newpass );
			Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'success' ] );
		} catch ( PasswordError $e ) {
			Hooks::run( 'PrefsPasswordAudit', [ $user, $newpass, 'error' ] );
			return Status::newFatal( new RawMessage( $e->getMessage() ) );
		}

		if ( $isSelf ) {
			// This is needed to keep the user connected since
			// changing the password also modifies the user's token.
			$remember = $this->getRequest()->getCookie( 'Token' ) !== null;
			$user->setCookies( null, null, $remember );
		}
		$user->saveSettings();
		$this->resetPasswordExpiration( $user );
		return Status::newGood();
	}

	public function requiresUnblock() {
		return false;
	}

	protected function getGroupName() {
		return 'users';
	}

	/**
	 * For resetting user password expiration, until AuthManager comes along
	 * @param User $user
	 */
	private function resetPasswordExpiration( User $user ) {
		global $wgPasswordExpirationDays;
		$newExpire = null;
		if ( $wgPasswordExpirationDays ) {
			$newExpire = wfTimestamp(
				TS_MW,
				time() + ( $wgPasswordExpirationDays * 24 * 3600 )
			);
		}
		// Give extensions a chance to force an expiration
		Hooks::run( 'ResetPasswordExpiration', [ $this, &$newExpire ] );
		$dbw = wfGetDB( DB_MASTER );
		$dbw->update(
			'user',
			[ 'user_password_expires' => $dbw->timestampOrNull( $newExpire ) ],
			[ 'user_id' => $user->getId() ],
			__METHOD__
		);
	}

	protected function getDisplayFormat() {
		return 'ooui';
	}
}


text:
package io.koff.generator.utils

import scala.concurrent.Future
import scala.util.control.NonFatal
import akka.pattern.pipe

object ActorUtils {
  /**
   * try to evaluate async operation using the by-name parameter.
   * This method will ensure any non-fatal exception is caught and a `Future.failed(...)` is returned.
   */
  def tryIt[T](value: => Future[T]): Future[T] = {
    try{
      value
    } catch {
      case NonFatal(exc) => Future.failed[T](exc)
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
* Netcat - a network mapping tool native to UNIX fully built in python
* Socket server
* Client
* UDP Client


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.mapreduce.lib.db.DBConfiguration (hadoop-mapreduce-client-core 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

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

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.hadoop.mapreduce.lib.db.DBConfiguration

Packages that use DBConfiguration

org.apache.hadoop.mapred.lib.db

org.apache.hadoop.mapreduce.lib.db

Uses of DBConfiguration in org.apache.hadoop.mapred.lib.db

Subclasses of DBConfiguration in org.apache.hadoop.mapred.lib.db

 class
DBConfiguration

Uses of DBConfiguration in org.apache.hadoop.mapreduce.lib.db

Fields in org.apache.hadoop.mapreduce.lib.db declared as DBConfiguration

protected  DBConfiguration
DBInputFormat.dbConf

Methods in org.apache.hadoop.mapreduce.lib.db that return DBConfiguration

 DBConfiguration
DBInputFormat.getDBConf()

protected  DBConfiguration
DBRecordReader.getDBConf()

Constructors in org.apache.hadoop.mapreduce.lib.db with parameters of type DBConfiguration

DataDrivenDBRecordReader(DBInputFormat.DBInputSplit split,
                         Class<T> inputClass,
                         org.apache.hadoop.conf.Configuration conf,
                         Connection conn,
                         DBConfiguration dbConfig,
                         String cond,
                         String[] fields,
                         String table,
                         String dbProduct)

DBRecordReader(DBInputFormat.DBInputSplit split,
               Class<T> inputClass,
               org.apache.hadoop.conf.Configuration conf,
               Connection conn,
               DBConfiguration dbConfig,
               String cond,
               String[] fields,
               String table)

MySQLDataDrivenDBRecordReader(DBInputFormat.DBInputSplit split,
                              Class<T> inputClass,
                              org.apache.hadoop.conf.Configuration conf,
                              Connection conn,
                              DBConfiguration dbConfig,
                              String cond,
                              String[] fields,
                              String table)

MySQLDBRecordReader(DBInputFormat.DBInputSplit split,
                    Class<T> inputClass,
                    org.apache.hadoop.conf.Configuration conf,
                    Connection conn,
                    DBConfiguration dbConfig,
                    String cond,
                    String[] fields,
                    String table)

OracleDataDrivenDBRecordReader(DBInputFormat.DBInputSplit split,
                               Class<T> inputClass,
                               org.apache.hadoop.conf.Configuration conf,
                               Connection conn,
                               DBConfiguration dbConfig,
                               String cond,
                               String[] fields,
                               String table)

OracleDBRecordReader(DBInputFormat.DBInputSplit split,
                     Class<T> inputClass,
                     org.apache.hadoop.conf.Configuration conf,
                     Connection conn,
                     DBConfiguration dbConfig,
                     String cond,
                     String[] fields,
                     String table)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2015 Apache Software Foundation. All Rights Reserved.


text:
// @todo: remove the following line when part imports has been removed from this file
///<reference types="@sanity/types/parts" />

/**
 * @internal INTERNAL! Don't use outside of @sanity/base!
 *
 * Preconfigured, versioned client used for all the
 * internal tooling within @sanity/base.
 */
import type {SanityClient} from '@sanity/client'
import sanityClient from 'part:@sanity/base/client'

/**
 * Only for use inside of @sanity/base
 * Don't import this from external modules.
 *
 * @internal
 */
export const versionedClient = sanityClient.withConfig({
  /**
   * NOTE: CHANGING THIS VERSION MEANS YOU'LL HAVE TO TEST
   * EVERYTHING THAT DEPENDS ON THIS VERSIONED CLIENT WITHIN
   * @sanity/base!
   */
  apiVersion: '1',
})

/**
 * Only for use inside of @sanity/base
 * Don't import this from external modules.
 *
 * Gets a client configured with the passed API version,
 * re-using clients where possible
 *
 * @internal
 */
export const getVersionedClient = (() => {
  const clientMap = new Map<string, SanityClient>()
  return function getVersionedSanityClient(version: string | undefined): SanityClient {
    const apiVersion = version || '1'

    if (!clientMap.has(apiVersion)) {
      clientMap.set(apiVersion, sanityClient.withConfig({apiVersion}))
    }

    return clientMap.get(apiVersion)
  }
})()


text:
/**********************************************************\

  This file is distributed under the MIT License.
  See https://github.com/morzhovets/momo/blob/master/LICENSE
  for details.

  tests/SimpleHashTesterLimP.cpp

\**********************************************************/

#include "pch.h"

#ifdef TEST_SIMPLE_HASH
#ifdef TEST_OLD_HASH_BUCKETS

#include "SimpleHashTester.h"

#include "../../momo/details/HashBucketLimP.h"

#define BUCKET(maxCount, blockCount, usePtrState) \
	momo::HashBucketLimP<maxCount, momo::MemPoolParams<blockCount, (blockCount % 2) * 16>, usePtrState>

static int testSimpleHash = []
{
	SimpleHashTester::TestStrHash<momo::HashBucketLimP<sizeof(void*), momo::MemPoolParams<>, false>>("momo::HashBucketLimP<..., false>");
	SimpleHashTester::TestStrHash<momo::HashBucketLimP<sizeof(void*), momo::MemPoolParams<>,  true>>("momo::HashBucketLimP<...,  true>");
	SimpleHashTester::TestStrHash<momo::HashBucketLimP<1, momo::MemPoolParams<>, false>>("momo::HashBucketLimP<1, ..., false>");
	SimpleHashTester::TestStrHash<momo::HashBucketLimP<1, momo::MemPoolParams<>,  true>>("momo::HashBucketLimP<1, ...,  true>");

	SimpleHashTester::TestTemplHashSet<BUCKET( 1, 16, false), 11, 1>("momo::HashBucketLimP< 1, 16, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 1, 64, false),  1, 1>("momo::HashBucketLimP< 1, 64, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 2, 99, false),  3, 1>("momo::HashBucketLimP< 2, 99, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 2, 88, false),  2, 2>("momo::HashBucketLimP< 2, 88, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 2,  1, false),  8, 4>("momo::HashBucketLimP< 2,  1, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 3,  2, false),  6, 1>("momo::HashBucketLimP< 3,  2, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 3,  3, false),  8, 2>("momo::HashBucketLimP< 3,  3, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 4,  4, false),  4, 4>("momo::HashBucketLimP< 4,  4, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 5,  5, false), 10, 2>("momo::HashBucketLimP< 5,  5, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 6,  8, false),  4, 4>("momo::HashBucketLimP< 6,  8, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 7, 11, false), 16, 4>("momo::HashBucketLimP< 7, 11, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 8, 33, false),  8, 8>("momo::HashBucketLimP< 8, 33, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET(10, 32, false), 32, 8>("momo::HashBucketLimP<10, 32, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET(12, 55, false), 11, 1>("momo::HashBucketLimP<12, 55, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET(14,  1, false), 16, 8>("momo::HashBucketLimP<14,  1, false>");
	SimpleHashTester::TestTemplHashSet<BUCKET(15, 32, false), 16, 8>("momo::HashBucketLimP<15, 32, false>");

	SimpleHashTester::TestTemplHashSet<BUCKET( 1, 16, true), 11, 1>("momo::HashBucketLimP< 1, 16, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 1, 64, true),  1, 1>("momo::HashBucketLimP< 1, 64, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 2, 99, true),  4, 1>("momo::HashBucketLimP< 2, 99, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 2, 88, true),  2, 2>("momo::HashBucketLimP< 2, 88, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 2,  1, true),  8, 4>("momo::HashBucketLimP< 2,  1, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 3,  2, true),  8, 1>("momo::HashBucketLimP< 3,  2, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 3,  3, true),  8, 2>("momo::HashBucketLimP< 3,  3, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 4,  4, true),  4, 4>("momo::HashBucketLimP< 4,  4, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 5,  5, true), 16, 2>("momo::HashBucketLimP< 5,  5, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 6,  8, true),  8, 8>("momo::HashBucketLimP< 6,  8, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 7, 11, true), 16, 4>("momo::HashBucketLimP< 7, 11, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET( 8, 33, true), 16, 8>("momo::HashBucketLimP< 8, 33, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET(10, 32, true), 32, 8>("momo::HashBucketLimP<10, 32, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET(12, 55, true), 32, 1>("momo::HashBucketLimP<12, 55, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET(14,  1, true), 32, 8>("momo::HashBucketLimP<14,  1, true>");
	SimpleHashTester::TestTemplHashSet<BUCKET(15, 32, true), 32, 8>("momo::HashBucketLimP<15, 32, true>");

	return 0;
}();

#endif // TEST_OLD_HASH_BUCKETS
#endif // TEST_SIMPLE_HASH


text:
/**
 * Provides utilities for manipulating common objects such as arrays and
 * strings. This package contains two types of classes: static library classes
 * that contain methods for working with different types of data, and utility
 * objects that provide extended functionality.
 *
 * @author Joseph Fox-Rabinovitz
 * @version 1.0, 04 Mar 2012 - J. Fox-Rabinovitz - Created
 * @version 1.1, 03 Dec 2012 - J. Fox-Rabinovitz - Added PathManager and FilePathManager
 * @version 1.2, 22 Jun 2014 - J. Fox-Rabinovitz - Added TimeUtilities
 * @version 1.3, 17 Jul 2014 - J. Fox-Rabinovitz - Added ReferenceIterator
 * @version 1.4, 24 Jul 2014 - J. Fox-Rabinovitz - Moved FilePathManager to com.madphysicist.tools.io
 * @version 1.5, 01 Aug 2014 - J. Fox-Rabinovitz - Added MathUtilities
 * @version 2.0, 15 Dec 2014 - J. Fox-Rabinovitz - Deleted BackgroundThread: All methods were superfluous.
 * @since 1.0
 */
package com.madphysicist.tools.util;


text:
<?php /** @var \Dms\Core\Form\IFieldOption[] $options */ ?>
<?php /** @var array $value */ ?>
<?php $valuesAsKeys = $value ? array_fill_keys($value, true) : []; ?>
<select
        name="{{ $name }}"
        @if($required) required @endif
        @if($readonly) readonly @endif
        multiple="multiple"
>
    @foreach ($options as $option)
        <option
                value="{{ $option->getValue() }}"
                @if (isset($valuesAsKeys[$option->getValue()]))selected="selected" @endif
        >{{ $option->getLabel() }}</option>
    @endforeach
</select>


text:
package cbft

import (
	"encoding/json"
	"fmt"
	"hash"
	"hash/crc32"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	log "github.com/couchbase/clog"
)

const FILES_FEED_SLEEP_START_MS = 5000
const FILES_FEED_BACKOFF_FACTOR = 1.5
const FILES_FEED_MAX_SLEEP_MS = 1000 * 60 * 5 // 5 minutes.

func init() {
	RegisterFeedType("files", &FeedType{
		Start:      StartFilesFeed,
		Partitions: FilesFeedPartitions,
		Public:     true,
		Description: "general/files" +
			" - files under a dataDir subdirectory tree will be the data source",
		StartSample: &FilesFeedParams{
			RegExps:       []string{".txt$", ".md$"},
			SleepStartMS:  FILES_FEED_SLEEP_START_MS,
			BackoffFactor: FILES_FEED_BACKOFF_FACTOR,
			MaxSleepMS:    FILES_FEED_MAX_SLEEP_MS,
		},
	})
}

// FilesFeed is a feed implementation that that emits file contents
// from a local subdirectory tree.
//
// The subdirectory tree lives under the dataDir...
//
//    <dataDir>/<sourceName/**
//
// FilesFeed supports optional regexp patterns to allow you to filter
// for only the file paths that you want.
//
// Limitations:
//
// - Only a small number of files will work well (hundreds to low
// thousands, not millions).
//
// - FilesFeed uses file modification timestamps as a poor-man's
// approach instead of properly tracking sequence numbers.  That has
// implications such as whenever a FilesFeed (re-)starts (e.g., the
// process restarts), the FilesFeed will re-emits all files and then
// track the max modification timestamp going forwards as it regularly
// polls for file changes.
type FilesFeed struct {
	mgr        *Manager
	name       string
	indexName  string
	sourceName string
	params     *FilesFeedParams
	dests      map[string]Dest
	disable    bool

	m       sync.Mutex
	closeCh chan struct{}
}

type FilesFeedParams struct {
	RegExps       []string `json:"regExps"`
	MaxFileSize   int64    `json:"maxFileSize"`
	NumPartitions int      `json:"numPartitions"`
	SleepStartMS  int      `json:"sleepStartMS"`
	BackoffFactor float32  `json:"backoffFactor"`
	MaxSleepMS    int      `json:"maxSleepMS"`
}

type FileDoc struct {
	Name     string `json:"name"`
	Path     string `json:"path"` // Path relative to the source name.
	Contents string `json:"contents"`
}

func StartFilesFeed(mgr *Manager, feedName, indexName, indexUUID,
	sourceType, sourceName, sourceUUID, params string,
	dests map[string]Dest) error {
	feed, err := NewFilesFeed(mgr, feedName, indexName, sourceName,
		params, dests, mgr.tagsMap != nil && !mgr.tagsMap["feed"])
	if err != nil {
		return fmt.Errorf("feed_files: NewFilesFeed,"+
			" feedName: %s, err: %v", feedName, err)
	}
	err = feed.Start()
	if err != nil {
		return fmt.Errorf("feed_files: could not start,"+
			" feedName: %s, err: %v", feedName, err)
	}
	err = mgr.registerFeed(feed)
	if err != nil {
		feed.Close()
		return err
	}
	return nil
}

func NewFilesFeed(mgr *Manager, name, indexName, sourceName,
	paramsStr string, dests map[string]Dest, disable bool) (
	*FilesFeed, error) {
	if sourceName == "" {
		return nil, fmt.Errorf("feed_files: missing source name")
	}

	if strings.Index(sourceName, "..") >= 0 {
		return nil, fmt.Errorf("feed_files: disallowed source name,"+
			" name: %s, sourceName: %q", name, sourceName)
	}

	params := &FilesFeedParams{}
	if paramsStr != "" {
		err := json.Unmarshal([]byte(paramsStr), params)
		if err != nil {
			return nil, err
		}
	}

	return &FilesFeed{
		mgr:        mgr,
		name:       name,
		indexName:  indexName,
		sourceName: sourceName,
		params:     params,
		dests:      dests,
		disable:    disable,
		closeCh:    make(chan struct{}),
	}, nil
}

func (t *FilesFeed) Name() string {
	return t.name
}

func (t *FilesFeed) IndexName() string {
	return t.indexName
}

func (t *FilesFeed) Start() error {
	if t.disable {
		log.Printf("feed_files: disable, name: %s", t.Name())
		return nil
	}

	startSleepMS := t.params.SleepStartMS
	if startSleepMS <= 0 {
		startSleepMS = FILES_FEED_SLEEP_START_MS
	}

	backoffFactor := t.params.BackoffFactor
	if backoffFactor <= 0 {
		backoffFactor = FILES_FEED_BACKOFF_FACTOR
	}

	maxSleepMS := t.params.MaxSleepMS
	if maxSleepMS <= 0 {
		maxSleepMS = FILES_FEED_MAX_SLEEP_MS
	}

	numPartitions := t.params.NumPartitions
	if numPartitions < 0 {
		numPartitions = 0
	}

	partitions := make([]string, numPartitions)
	for i := 0; i < len(partitions); i++ {
		partitions[i] = strconv.Itoa(i)
	}

	go func() {
		initTime := time.Now()
		initTimeMicroSecs := initTime.UnixNano() / int64(1000)

		// TODO: NOTE: We're assuming (lazily, incorrectly) that this
		// way of initializing a sequence number never goes downwards,
		// even during fast restarts or clock changes or node
		// rebalances/reassignments.
		seqs := map[string]uint64{}
		for partition, _ := range t.dests {
			seqs[partition] = uint64(initTimeMicroSecs)
		}

		var prevStartTime time.Time

		ExponentialBackoffLoop(t.Name(),
			func() int {
				select {
				case <-t.closeCh:
					return -1
				default:
				}

				h := crc32.NewIEEE()

				startTime := time.Now()

				progress := false

				paths, err := FilesFindMatches(t.mgr.DataDir(),
					t.sourceName, t.params.RegExps, prevStartTime,
					t.params.MaxFileSize)
				if err != nil {
					log.Printf("feed_files, FilesFindMatches, err: %v", err)
					return -1
				}

				seqDeltaMax := uint64(0)

				seqEnds := map[string]uint64{}

				for _, path := range paths {
					partition := FilesPathToPartition(h, partitions, path)

					if t.dests[partition] == nil {
						continue
					}

					seq := seqs[partition]

					seqEnd, exists := seqEnds[partition]
					if exists {
						seqEnd = seqEnd + 1
					} else {
						seqEnd = seq
					}
					seqEnds[partition] = seqEnd

					if seqDeltaMax < seqEnd-seq {
						seqDeltaMax = seqEnd - seq
					}
				}

				snapshotSent := map[string]bool{}

				for _, path := range paths {
					select {
					case <-t.closeCh:
						return -1
					default:
					}

					partition := FilesPathToPartition(h, partitions, path)

					dest := t.dests[partition]
					if dest == nil {
						continue
					}

					seqCur := seqs[partition]
					seqs[partition] = seqCur + 1

					buf, err := ioutil.ReadFile(path)
					if err != nil {
						log.Printf("feed_files: read file,"+
							" name: %s, path: %s, err: %v",
							t.Name(), path, err)
						continue
					}

					jbuf, err := json.Marshal(FileDoc{
						Name:     filepath.Base(path),
						Path:     path,
						Contents: string(buf),
					})
					if err != nil {
						log.Printf("feed_files: json marshal file,"+
							" name: %s, path: %s, err: %v",
							t.Name(), path, err)
						continue
					}

					if !snapshotSent[partition] {
						err = dest.SnapshotStart(partition, seqCur,
							seqEnds[partition])
						if err != nil {
							log.Printf("feed_files: SnapshotStart,"+
								" name: %s, partition: %s,"+
								" seqCur: %d, seqEnd: %d, err: %v",
								t.Name(), partition,
								seqCur, seqEnds[partition], err)
							return -1
						}

						snapshotSent[partition] = true
					}

					pathBuf := []byte(path)

					err = dest.DataUpdate(partition, pathBuf, seqCur,
						jbuf, 0, DEST_EXTRAS_TYPE_NIL, nil)
					if err != nil {
						log.Printf("feed_files: DataUpdate,"+
							" name: %s, path: %s, partition: %s,"+
							" seqCur: %d, err: %v",
							t.Name(), path, partition, seqCur, err)
						return -1
					}

					progress = true
				}

				prevStartTime = startTime

				// NOTE: We may need to sleep a certain amount in case
				// there were tons of file updates/mutations, and we
				// want to reduce the window of potentially repeating
				// sequence numbers.  The window still exists if we
				// crash and quickly restart during the sleep, where
				// the restarted process might have a
				// lower-than-wanted initTime.
				wantTime := initTime // Copy, because Add() mutates.
				wantTime.Add(time.Duration(int64(seqDeltaMax)))

				currTime := time.Now()
				if wantTime.After(currTime) {
					time.Sleep(wantTime.Sub(currTime))
				}

				if progress {
					return 1
				}
				return 0
			},
			startSleepMS,
			backoffFactor,
			maxSleepMS)
	}()

	return nil
}

func (t *FilesFeed) Close() error {
	t.m.Lock()
	if t.closeCh != nil {
		close(t.closeCh)
		t.closeCh = nil
	}
	t.m.Unlock()

	return nil
}

func (t *FilesFeed) Dests() map[string]Dest {
	return t.dests
}

func (t *FilesFeed) Stats(w io.Writer) error {
	_, err := w.Write([]byte("{}"))
	return err
}

// -----------------------------------------------------

func FilesFeedPartitions(sourceType, sourceName, sourceUUID, sourceParams,
	server string) ([]string, error) {
	ffp := &FilesFeedParams{}
	if sourceParams != "" {
		err := json.Unmarshal([]byte(sourceParams), ffp)
		if err != nil {
			return nil, fmt.Errorf("feed_files:"+
				" could not parse sourceParams: %s, err: %v",
				sourceParams, err)
		}
	}
	rv := make([]string, ffp.NumPartitions)
	for i := 0; i < ffp.NumPartitions; i++ {
		rv[i] = strconv.Itoa(i)
	}
	return rv, nil
}

// -----------------------------------------------------

func FilesFindMatches(dataDir, sourceName string,
	regExps []string, modTimeGTE time.Time, maxSize int64) (
	[]string, error) {
	walkPath, err := filepath.EvalSymlinks(dataDir +
		string(os.PathSeparator) + "files" +
		string(os.PathSeparator) + sourceName)
	if err != nil {
		return nil, err
	}

	pathsOk := []string(nil)

	err = filepath.Walk(walkPath,
		func(path string, fi os.FileInfo, err error) error {
			if err != nil ||
				fi.IsDir() ||
				fi.ModTime().Before(modTimeGTE) ||
				(maxSize > 0 && fi.Size() > maxSize) {
				return nil
			}

			if len(regExps) <= 0 {
				pathsOk = append(pathsOk, path)
				return nil
			}

			for _, reStr := range regExps {
				matched, err := regexp.MatchString(reStr, path)
				if err != nil {
					return fmt.Errorf("feed_files, MatchString,"+
						" reStr: %s, path: %s, err: %v",
						reStr, path, err)
				}
				if matched {
					pathsOk = append(pathsOk, path)
					return nil
				}
			}

			return nil
		})
	if err != nil {
		return nil, err
	}

	return pathsOk, nil
}

func FilesPathToPartition(h hash.Hash32,
	partitions []string, path string) string {
	if len(partitions) <= 0 {
		return ""
	}

	h.Reset()
	io.WriteString(h, path)
	i := h.Sum32() % uint32(len(partitions))
	return partitions[i]
}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>TailFile</title>

        <link rel="stylesheet" href="../../../../../css/component-usage.css" type="text/css" />

Introduction

			This processor offers a powerful capability, allowing the user to periodically look at a file that is actively being written to by another process.
			When the file changes, the new lines are ingested. This Processor assumes that data in the file is textual.

			Tailing a file from a filesystem is a seemingly simple but notoriously difficult task. This is because we are periodically checking the contents
			of a file that is being written to. The file may be constantly changing, or it may rarely change. The file may be "rolled over" (i.e., renamed)
			and it's important that even after restarting the application (NiFi, in this case), we are able to pick up where we left off. Other additional complexities
			also come into play. For example, NFS mounted drives may indicate that data is readable but then return NUL bytes (Unicode 0) when attempting to read, as
			the actual bytes are not yet known (see the <Reread when NUL encountered> property), and file systems have different timestamp granularities.

			This Processor is designed to handle all of these different cases. This can lead to slightly more complex configuration, but this document should provide
			you with all you need to get started!

Modes

            This processor is used to tail a file or multiple files, depending on the configured mode. The
            mode to choose depends of the logging pattern followed by the file(s) to tail. In any case, if there
            is a rolling pattern, the rolling files must be plain text files (compression is not supported at
            the moment).

Single file: the processor will tail the file with the path given in 'File(s) to tail' property.

Multiple files: the processor will look for files into the 'Base directory'. It will look for file recursively
        	according to the 'Recursive lookup' property and will tail all the files matching the regular expression
        	provided in the 'File(s) to tail' property.

Rolling filename pattern

        	In case the 'Rolling filename pattern' property is used, when the processor detects that the file to tail has rolled over, the
        	processor will look for possible missing messages in the rolled file. To do so, the processor will use the pattern to find the
        	rolling files in the same directory as the file to tail.

        	In order to keep this property available in the 'Multiple files' mode when multiples files to tail are in the same directory,
        	it is possible to use the ${filename} tag to reference the name (without extension) of the file to tail. For example, if we have:

	        	/my/path/directory/my-app.log.1

	        	/my/path/directory/my-app.log

	        	/my/path/directory/application.log.1

	        	/my/path/directory/application.log

       		the 'rolling filename pattern' would be ${filename}.log.*.

Descriptions for different modes and strategies

        	The 'Single file' mode assumes that the file to tail has always the same name even if there is a rolling pattern.
        	Example:

	        	/my/path/directory/my-app.log.2

	        	/my/path/directory/my-app.log.1

	        	/my/path/directory/my-app.log

        	and new log messages are always appended in my-app.log file.

        	In case recursivity is set to 'true'. The regular expression for the files to tail must embrace the possible intermediate directories
        	between the base directory and the files to tail. Example:

	        	/my/path/directory1/my-app1.log

	        	/my/path/directory2/my-app2.log

	        	/my/path/directory3/my-app3.log

	        	Base directory: /my/path

	        	Files to tail: directory[1-3]/my-app[1-3].log

	        	Recursivity: true

        	If the processor is configured with 'Multiple files' mode, two additional properties are relevant:

Lookup frequency: specifies the minimum duration the processor will wait before listing again the files to tail.

Maximum age: specifies the necessary minimum duration to consider that no new messages will be appended in a file
        	regarding its last modification date. If the amount of time that has elapsed since the file was modified is larger than this
        	period of time, the file will not be tailed. For example, if a file was modified 24 hours ago and this property is set to 12 hours,
        	the file will not be tailed. But if this property is set to 36 hours, then the file will continue to be tailed.

        	It is necessary to pay attention to 'Lookup frequency' and 'Maximum age' properties, as well as the frequency at which the processor is
        	triggered, in order to achieve high performance. It is recommended to keep 'Maximum age' > 'Lookup frequency' > processor scheduling
        	frequency to avoid missing data. It also recommended not to set 'Maximum Age' too low because if messages are appended in a file
        	after this file has been considered "too old", all the messages in the file may be read again, leading to data duplication.

        	If the processor is configured with 'Multiple files' mode, the 'Rolling
        	filename pattern' property must be specific enough to ensure that only the rolling files will be listed and not other currently tailed
        	files in the same directory (this can be achieved using ${filename} tag).

Handling Multi-Line Messages

			Most of the time, when we tail a file, we are happy to receive data periodically, however it was written to the file. There are scenarios, though,
			where we may have data written in such a way that multiple lines need to be retained together. Take, for example, the following lines of text that
			might be found in a log file:

2021-07-09 14:12:19,731 INFO [main] org.apache.nifi.NiFi Launching NiFi...
2021-07-09 14:12:19,915 INFO [main] o.a.n.p.AbstractBootstrapPropertiesLoader Determined default application properties path to be '/Users/mpayne/devel/nifi/nifi-assembly/target/nifi-1.14.0-SNAPSHOT-bin/nifi-1.14.0-SNAPSHOT/./conf/nifi.properties'
2021-07-09 14:12:19,919 INFO [main] o.a.nifi.properties.NiFiPropertiesLoader Loaded 199 properties from /Users/mpayne/devel/nifi/nifi-assembly/target/nifi-1.14.0-SNAPSHOT-bin/nifi-1.14.0-SNAPSHOT/./conf/nifi.properties
2021-07-09 14:12:19,925 WARN Line 1 of Log Message
			Line 2: This is an important warning.
			Line 3: Please do not ignore this warning.
			Line 4: These lines of text make sense only in the context of the original message.
2021-07-09 14:12:19,941 INFO [main] Final message in log file

			In this case, we may want to ensure that the log lines are not ingested in such a way that our multi-line log message is not broken up into Lines 1 and 2 in one FlowFile
			and Lines 3 and 4 in another. To accomplish this, the Processor exposes the <Line Start Pattern> property. If we set this Property to a value of
			\d{4}-\d{2}-\d{2}, then we are telling the Processor that each message should begin with 4 digits, followed by a dash, followed by 2 digits, a dash, and 2 digits.
			I.e., we are telling it that each message begins with a timestamp in yyyy-MM-dd format. Because of this, even if the Processor runs and sees only Lines 1 and 2 of our
			multiline log message, it will not ingest the data yet. It will wait until it sees the next message, which starts with a timestamp.

			Note that, because of this, the last message that the Processor will encounter in the above situation is the "Final message in log file" line. At this point, the Processor does
			not know whether the next line of text it encounters will be part of this line or a new message. As such, it will not ingest this data. It will wait until either another message
			is encountered (that matches our regex) or until the file is rolled over (renamed). Because of this, there may be some delay in ingesting the last message in the file, if the process
			that writes to the file just stops writing at this point.

			Additionally, we run the chance of the Regular Expression not matching the data in the file. This could result in buffering all of the file's content, which could cause NiFi
			to run out of memory. To avoid this, the <Max Buffer Size> property limits the amount of data that can be buffered. If this amount of data is buffered, it will be flushed
			to the FlowFile, even if another message hasn't been encountered.


text:
A JavaScript library providing cross-browser support for content selection.

## Building
To build the library you'll need to use Grunt. First install the required node modules ([grunt-cli](http://gruntjs.com/getting-started) must be installed):
```
git clone https://github.com/GetmeUK/ContentSelect.git
cd ContentSelect
npm install
```

Then run `grunt build` to build the project.

## Testing
To test the library you'll need to use Jasmine. First install Jasmine:
```
git clone https://github.com/pivotal/jasmine.git
mkdir ContentSelect/jasmine
mv jasmine/dist/jasmine-standalone-2.0.3.zip ContentSelect/jasmine
cd ContentSelect/jasmine
unzip jasmine-standalone-2.0.3.zip
```

Then open `ContentSelect/SpecRunner.html` in a browser to run the tests.

## Documentation
Full documentation is available at http://getcontenttools.com/api/content-select

## Browser support
- Chrome
- Firefox
- IE9+


text:
begin;

update testset
set test_type='tpc-b'
where info like 'tpc-b%'
;

update testset
set test_type='select'
where info like 'select%'
;

commit;


text:
var http = require('http');

var httpOptions = {
	host: 'psearch-maps.yandex.ru',
	port: 80,
	path: '/1.x/',
	method: 'GET',
	headers: {
		'Content-Type': 'application/json',
		'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.111 Safari/537.36'
	}
};

var httpRequest = function (options, callback) {

	var req = http.request(options, function (res) {
		var output = '';
		//console.log(options.host + ':' + res.statusCode);
		res.setEncoding('utf8');

		res.on('data', function (chunk) {
			output += chunk;
		});

		res.on('end', function() {
			var json = JSON.parse(output);
			callback(res.statusCode, json);
		});
	});

	req.on('error', function(err) {
		//res.send('error: ' + err.message);
		console.error(err);
	});

	req.end();
};

var prepareCoordinates = function (str) {
	return str.split(' ').reverse();
};

var prepareData = function (data) {
	var result = [];
	var objects = data.response.GeoObjectCollection.featureMember;
	objects.map(function (item) {
		result.push({
			name: item.GeoObject.name,
			coordinates: prepareCoordinates(item.GeoObject.Point.pos)
		});
	});
	return result
};

/*
 * Documentation: https://tech.yandex.ru/maps/doc/geocoder/psearch/concepts/input_params-docpage/
 */
var getCoordinates = function (options, callback) {

	httpOptions.path += '?text=' + encodeURIComponent(options.query) +
					 '&ll=' + encodeURIComponent(options.ll) +
					 '&spn=' + encodeURIComponent(options.spn) +
					 '&format=json' +
					 '&rspn=1' +
					 '&results=' + options.count;

	httpRequest(httpOptions, function (status, response) {
		if (status == 200) {
			try {
				var data = prepareData(response);
                if (data != null) {
                    callback(data);
                }
			} catch (e) {
				console.error(e);
			}
		} else {
			console.error(status);
		}
	});
};

module.exports = {
	getCoordinates: getCoordinates
};


text:
import type { Action } from '../actions/types';
import { SET_INDEX } from '../actions/list';

export type State = {
  list: string
};

const initialState = {
  list: [
    'Observation Report 1',
    'Observation Report 2',
    'Observation Report 3',
    'Observation Report 4',
    'Observation Report 5',
    'Observation Report 5'
  ],
  selectedIndex: undefined
};

export default function(state: State = initialState, action: Action): State {
  if (action.type === SET_INDEX) {
    return {
      ...state,
      selectedIndex: action.payload
    };
  }
  return state;
}


text:
Using node-inspector to debug

----------------------------------------------------------------------
## HINT

When things do go wrong, it's always helpful to have a debugging tool.
Fortunately, Node.js applications deployed to Bluemix have built-in
support for `node-inspector`, a full-featured debug tool for Node.js
that is built on top of webkit. All you need to do is enable it:
```
  cf set-env helloworld BLUEMIX_APP_MGMT_ENABLE proxy+devconsole+inspector
  cf restage helloworld
```

When the application comes back up, open your browser and navigate to
`https://helloworld.mybluemix.net/bluemix-debug/manage` and you ought
to be presented with the Bluemix developers console. Click on "Open
Debugger" to launch `node-inspector`

Once you have enabled the `node-inspector`, run `{appname} verify
{bluemix-appname}` to complete this exercise.

----------------------------------------------------------------------

 __»__ To print these instructions again, run: `{appname} print`
 __»__ To view the Bluemix Documentation, run: `{appname} open`
 __»__ To verify your work, run: `{appname} verify {bluemix-appname}`
 __»__ For help run: `{appname} help


text:
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Web;
using RubyODataService.Models;
using System.Collections.Generic;

namespace RubyODataService
{
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
    public class RubyOData : DataService<RubyODataContext>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("*", EntitySetRights.All);
            config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
            config.UseVerboseErrors = true;
        }

        /// <summary>
        /// Cleans the database for testing.
        /// </summary>
        [WebInvoke]
        public void CleanDatabaseForTesting()
        {
            CurrentDataSource.Database.Delete();
            CurrentDataSource.Database.CreateIfNotExists();
        }

        [WebGet]
        public IQueryable<Category> EntityCategoryWebGet()
        {
            return CurrentDataSource.Categories;
        }

        [WebGet]
        public IQueryable<string> CategoryNames()
        {
            return CurrentDataSource.Categories.Select(c => c.Name);
        }

        [WebGet]
        public int? FirstCategoryId()
        {
            return CurrentDataSource.Categories.Select(c => c.Id).FirstOrDefault();
        }

        [WebGet]
        public Category EntitySingleCategoryWebGet(int id)
        {
            return CurrentDataSource.Categories.FirstOrDefault(c => c.Id == id);
        }
    }
}


text:
#ifndef _KR_REFERENCE_COUNTED_H_
#define _KR_REFERENCE_COUNTED_H_

namespace kroll
{
	class KROLL_API ReferenceCounted
	{
		private:
		Poco::AtomicCounter count;

		public:
		ReferenceCounted() : count(1) { }
		virtual ~ReferenceCounted() { }

		virtual void duplicate()
		{
			++count;
		}

		virtual void release()
		{
			int value = --count;
			if (value <= 0) {
				delete this;
			}
		}

		virtual int referenceCount() const
		{
			return count.value();
		}
	};
}
#endif


text:
package org.apache.sshd.common.forward;

import org.apache.sshd.common.session.Session;
import org.apache.sshd.common.util.SshdEventListener;
import org.apache.sshd.common.util.net.SshdSocketAddress;

public interface PortForwardingEventListener extends SshdEventListener
{
    default void establishedDynamicTunnel(Session p0, SshdSocketAddress p1, SshdSocketAddress p2, Throwable p3){}
    default void establishedExplicitTunnel(Session p0, SshdSocketAddress p1, SshdSocketAddress p2, boolean p3, SshdSocketAddress p4, Throwable p5){}
    default void establishingDynamicTunnel(Session p0, SshdSocketAddress p1){}
    default void establishingExplicitTunnel(Session p0, SshdSocketAddress p1, SshdSocketAddress p2, boolean p3){}
    default void tearingDownDynamicTunnel(Session p0, SshdSocketAddress p1){}
    default void tearingDownExplicitTunnel(Session p0, SshdSocketAddress p1, boolean p2, SshdSocketAddress p3){}
    default void tornDownDynamicTunnel(Session p0, SshdSocketAddress p1, Throwable p2){}
    default void tornDownExplicitTunnel(Session p0, SshdSocketAddress p1, boolean p2, SshdSocketAddress p3, Throwable p4){}
    static <L extends PortForwardingEventListener> L validateListener(L p0){ return null; }
    static PortForwardingEventListener EMPTY = null;
}


text:
FactoryGirl.define do
  factory :animal_handbook_creature do
    animal_handbook nil
    creature nil
  end
end


text:
package moul

import (
	"encoding/json"

	"github.com/parnurzeal/gorequest"
	"github.com/patrickmn/go-cache"
)

func init() {
	RegisterAction("tumblr", GetLatestBlogPostsAction)
}

const TumblrFeedURL = "https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://manfredtouron.tumblr.com/rss"

type TumblrEntry struct {
	Title          string
	Link           string
	Author         string
	PublishedDate  string
	ContentSnippet string
	Content        string
	Categories     []string
}

type TumblrResponse struct {
	ResponseData struct {
		Feed struct {
			FeedURL     string
			Title       string
			Link        string
			Author      string
			Description string
			Type        string
			Entries     []TumblrEntry
		}
	}
	// ResponseDetails
	ResponseStatus int
}

func GetLatestBlogPostsAction(args []string) (interface{}, error) {
	if posts, found := moulCache.Get("tumblr-posts"); found {
		return posts, nil
	}
	posts, err := GetLatestBlogPosts()
	if err != nil {
		return nil, err
	}
	moulCache.Set("tumblr-posts", posts, cache.DefaultExpiration)
	return posts, nil
}

func GetLatestBlogPosts() (*TumblrResponse, error) {
	_, body, errs := gorequest.New().Get(TumblrFeedURL).End()
	if len(errs) > 0 {
		return nil, errs[0]
	}

	var response TumblrResponse
	err := json.Unmarshal([]byte(body), &response)
	return &response, err
}


text:
/*************************************************************************/
/*  subviewport_container.h                                              */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifndef SUBVIEWPORT_CONTAINER_H
#define SUBVIEWPORT_CONTAINER_H

#include "scene/gui/container.h"

class SubViewportContainer : public Container {
	GDCLASS(SubViewportContainer, Container);

	bool stretch = false;
	int shrink = 1;
	void _notify_viewports(int p_notification);

protected:
	void _notification(int p_what);
	static void _bind_methods();

public:
	void set_stretch(bool p_enable);
	bool is_stretch_enabled() const;

	virtual void input(const Ref<InputEvent> &p_event) override;
	virtual void unhandled_input(const Ref<InputEvent> &p_event) override;
	void set_stretch_shrink(int p_shrink);
	int get_stretch_shrink() const;

	virtual Size2 get_minimum_size() const override;

	virtual Vector<int> get_allowed_size_flags_horizontal() const override;
	virtual Vector<int> get_allowed_size_flags_vertical() const override;

	PackedStringArray get_configuration_warnings() const override;

	SubViewportContainer();
};

#endif // SUBVIEWPORT_CONTAINER_H


text:
import ToggleOption from '../index';

import expect from 'expect';
import { shallow } from 'enzyme';
import { IntlProvider, defineMessages } from 'react-intl';
import React from 'react';

describe('<ToggleOption />', () => {
  it('should render default language messages', () => {
    const defaultEnMessage = 'someContent';
    const message = defineMessages({
      enMessage: {
        id: 'app.components.LocaleToggle.en',
        defaultMessage: defaultEnMessage,
      },
    });
    const renderedComponent = shallow(
      <IntlProvider locale="en">
        <ToggleOption value="en" message={message.enMessage} />
      </IntlProvider>
    );
    expect(renderedComponent.contains(<ToggleOption value="en" message={message.enMessage} />)).toEqual(true);
  });
});


text:
/**
 * Components for decoding, post-processing and -validation of
 * csv columns into bean fields.
 * <p>
 * The {@link com.github.kahalemakai.opencsv.beans.processing.DecoderManager}
 * does all the bookkeeping. For every bean field, a
 * {@link com.github.kahalemakai.opencsv.beans.processing.DecoderPropertyEditor}
 * can be added, that keeps track of
 * {@link com.github.kahalemakai.opencsv.beans.processing.Decoder}s,
 * {@link com.github.kahalemakai.opencsv.beans.processing.PostProcessor}s and
 * {@link com.github.kahalemakai.opencsv.beans.processing.PostValidator}s.
 */
package com.github.kahalemakai.opencsv.beans.processing;


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

<TITLE>
LocationJsonConverter
</TITLE>

<META NAME="date" CONTENT="2014-04-08">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

ca.ualberta.cmput301w14t08.geochan.json

Class LocationJsonConverter

java.lang.Object
  ca.ualberta.cmput301w14t08.geochan.json.LocationJsonConverter

All Implemented Interfaces:
com.google.gson.JsonDeserializer<android.location.Location>, com.google.gson.JsonSerializer<android.location.Location>

public class LocationJsonConverter
extends java.lang.Object
implements com.google.gson.JsonSerializer<android.location.Location>, com.google.gson.JsonDeserializer<android.location.Location>

Handles the serialization and deserialization of useful data in a Location
 to and from JSON format.

Author:

Artem Chikin

Constructor Summary

LocationJsonConverter()

Method Summary

 android.location.Location
deserialize(com.google.gson.JsonElement je,
            java.lang.reflect.Type type,
            com.google.gson.JsonDeserializationContext jdc)

          Deserializes data into a Location from JSON format.

 com.google.gson.JsonElement
serialize(android.location.Location location,
          java.lang.reflect.Type type,
          com.google.gson.JsonSerializationContext jsc)

          Serializes data from a Location into JSON format.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

LocationJsonConverter

public LocationJsonConverter()

Method Detail

serialize

public com.google.gson.JsonElement serialize(android.location.Location location,
                                             java.lang.reflect.Type type,
                                             com.google.gson.JsonSerializationContext jsc)

Serializes data from a Location into JSON format.

 (Some of this code is taken from a stackOverflow user
 Brian Roach, for details, see: http://stackoverflow.com/a/13997920)

Specified by:
serialize in interface com.google.gson.JsonSerializer<android.location.Location>

Parameters:
location - the Location to serialize
type - the Type
jsc - the JSON serialization context

Returns:
A JsonElement representing the serialized Location.

deserialize

public android.location.Location deserialize(com.google.gson.JsonElement je,
                                             java.lang.reflect.Type type,
                                             com.google.gson.JsonDeserializationContext jdc)
                                      throws com.google.gson.JsonParseException

Deserializes data into a Location from JSON format.

 (Some of this code is taken from a stackOverflow user
 Brian Roach, for details, see: http://stackoverflow.com/a/13997920)

Specified by:
deserialize in interface com.google.gson.JsonDeserializer<android.location.Location>

Parameters:
je - the JSON element to deserialize
type - the Type
jdc - the JSON deserialization context

Returns:
The deserialized Location object.

Throws:

com.google.gson.JsonParseException

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?php

namespace Lib\Manifest\Type;

use Lib\Manifest\Field\AbstractField;

abstract class AbstractType
{

    protected $default;
    protected $value;

    /**
     * Field default value
     *
     * @param mixed $default The default value to set
     */
    public function setDefault($default)
    {
        $this->default = $default;
        return $this;
    }

    /**
     * Get field default value
     */
    public function getDefault()
    {
        return $this->default;
    }

    /**
     * Field entry value
     *
     * @param mixed $value The value to set
     */
    public function setValue($value)
    {
        $this->value = $value;
        return $this;
    }

    /**
     * get field entry value
     */
    public function getValue()
    {
        return $this->value;
    }

    abstract public function parse(AbstractField $objField = null);

}

// Endfile


text:
namespace {

const char kShutdownPath[] = "shutdown";

}  // namespace

HttpRequest::HttpRequest(HttpMethod method,
                         const std::string& path,
                         const std::string& body)
    : method(method), path(path), body(body) {}

HttpRequest::~HttpRequest() {}

CommandMapping::CommandMapping(HttpMethod method,
                               const std::string& path_pattern,
                               const std::string& name)
    : method(method), path_pattern(path_pattern), name(name) {}

CommandMapping::~CommandMapping() {}

// static
scoped_ptr<HttpHandler::CommandMap> HttpHandler::CreateCommandMap() {
  CommandMapping commands[] = {
      CommandMapping(kPost, "session", internal::kNewSessionIdCommand),
      CommandMapping(kGet, "session/:sessionId", CommandNames::kNewSession),
      CommandMapping(kDelete, "session/:sessionId", CommandNames::kQuit),
      CommandMapping(kGet, "session/:sessionId/window_handle",
                     CommandNames::kGetCurrentWindowHandle),
      CommandMapping(kGet, "session/:sessionId/window_handles",
                     CommandNames::kGetWindowHandles),
      CommandMapping(kPost, "session/:sessionId/url", CommandNames::kGet),
      CommandMapping(kGet, "session/:sessionId/alert", CommandNames::kGetAlert),
      CommandMapping(kPost, "session/:sessionId/dismiss_alert",
                     CommandNames::kDismissAlert),
      CommandMapping(kPost, "session/:sessionId/accept_alert",
                     CommandNames::kAcceptAlert),
      CommandMapping(kGet, "session/:sessionId/alert_text",
                     CommandNames::kGetAlertText),
      CommandMapping(kPost, "session/:sessionId/alert_text",
                     CommandNames::kSetAlertValue),
      CommandMapping(kPost, "session/:sessionId/forward",
                     CommandNames::kGoForward),
      CommandMapping(kPost, "session/:sessionId/back", CommandNames::kGoBack),
      CommandMapping(kPost, "session/:sessionId/refresh",
                     CommandNames::kRefresh),
      CommandMapping(kPost, "session/:sessionId/execute",
                     CommandNames::kExecuteScript),
      CommandMapping(kPost, "session/:sessionId/execute_async",
                     CommandNames::kExecuteAsyncScript),
      CommandMapping(kGet, "session/:sessionId/url",
                     CommandNames::kGetCurrentUrl),
      CommandMapping(kGet, "session/:sessionId/title", CommandNames::kGetTitle),
      CommandMapping(kGet, "session/:sessionId/source",
                     CommandNames::kGetPageSource),
      CommandMapping(kGet, "session/:sessionId/screenshot",
                     CommandNames::kScreenshot),
      CommandMapping(kPost, "session/:sessionId/visible",
                     CommandNames::kSetBrowserVisible),
      CommandMapping(kGet, "session/:sessionId/visible",
                     CommandNames::kIsBrowserVisible),
      CommandMapping(kPost, "session/:sessionId/element",
                     CommandNames::kFindElement),
      CommandMapping(kPost, "session/:sessionId/elements",
                     CommandNames::kFindElements),
      CommandMapping(kPost, "session/:sessionId/element/active",
                     CommandNames::kGetActiveElement),
      CommandMapping(kPost, "session/:sessionId/element/:id/element",
                     CommandNames::kFindChildElement),
      CommandMapping(kPost, "session/:sessionId/element/:id/elements",
                     CommandNames::kFindChildElements),
      CommandMapping(kPost, "session/:sessionId/element/:id/click",
                     CommandNames::kClickElement),
      CommandMapping(kPost, "session/:sessionId/element/:id/clear",
                     CommandNames::kClearElement),
      CommandMapping(kPost, "session/:sessionId/element/:id/submit",
                     CommandNames::kSubmitElement),
      CommandMapping(kGet, "session/:sessionId/element/:id/text",
                     CommandNames::kGetElementText),
      CommandMapping(kPost, "session/:sessionId/element/:id/value",
                     CommandNames::kSendKeysToElement),
      CommandMapping(kPost, "session/:sessionId/file",
                     CommandNames::kUploadFile),
      CommandMapping(kGet, "session/:sessionId/element/:id/value",
                     CommandNames::kGetElementValue),
      CommandMapping(kGet, "session/:sessionId/element/:id/name",
                     CommandNames::kGetElementTagName),
      CommandMapping(kGet, "session/:sessionId/element/:id/selected",
                     CommandNames::kIsElementSelected),
      CommandMapping(kGet, "session/:sessionId/element/:id/enabled",
                     CommandNames::kIsElementEnabled),
      CommandMapping(kGet, "session/:sessionId/element/:id/displayed",
                     CommandNames::kIsElementDisplayed),
      CommandMapping(kPost, "session/:sessionId/element/:id/hover",
                     CommandNames::kHoverOverElement),
      CommandMapping(kGet, "session/:sessionId/element/:id/location",
                     CommandNames::kGetElementLocation),
      CommandMapping(kGet, "session/:sessionId/element/:id/location_in_view",
                     CommandNames::kGetElementLocationOnceScrolledIntoView),
      CommandMapping(kGet, "session/:sessionId/element/:id/size",
                     CommandNames::kGetElementSize),
      CommandMapping(kGet, "session/:sessionId/element/:id/attribute/:name",
                     CommandNames::kGetElementAttribute),
      CommandMapping(kGet, "session/:sessionId/element/:id/equals/:other",
                     CommandNames::kElementEquals),
      CommandMapping(kGet, "session/:sessionId/cookie",
                     CommandNames::kGetCookies),
      CommandMapping(kPost, "session/:sessionId/cookie",
                     CommandNames::kAddCookie),
      CommandMapping(kDelete, "session/:sessionId/cookie",
                     CommandNames::kDeleteAllCookies),
      CommandMapping(kDelete, "session/:sessionId/cookie/:name",
                     CommandNames::kDeleteCookie),
      CommandMapping(kPost, "session/:sessionId/frame",
                     CommandNames::kSwitchToFrame),
      CommandMapping(kPost, "session/:sessionId/window",
                     CommandNames::kSwitchToWindow),
      CommandMapping(kGet, "session/:sessionId/window/:windowHandle/size",
                     CommandNames::kGetWindowSize),
      CommandMapping(kGet, "session/:sessionId/window/:windowHandle/position",
                     CommandNames::kGetWindowPosition),
      CommandMapping(kPost, "session/:sessionId/window/:windowHandle/size",
                     CommandNames::kSetWindowSize),
      CommandMapping(kPost, "session/:sessionId/window/:windowHandle/position",
                     CommandNames::kSetWindowPosition),
      CommandMapping(kPost, "session/:sessionId/window/:windowHandle/maximize",
                     CommandNames::kMaximizeWindow),
      CommandMapping(kDelete, "session/:sessionId/window",
                     CommandNames::kClose),
      CommandMapping(kPost, "session/:sessionId/element/:id/drag",
                     CommandNames::kDragElement),
      CommandMapping(kGet, "session/:sessionId/element/:id/css/:propertyName",
                     CommandNames::kGetElementValueOfCssProperty),
      CommandMapping(kPost, "session/:sessionId/timeouts/implicit_wait",
                     CommandNames::kImplicitlyWait),
      CommandMapping(kPost, "session/:sessionId/timeouts/async_script",
                     CommandNames::kSetScriptTimeout),
      CommandMapping(kPost, "session/:sessionId/timeouts",
                     CommandNames::kSetTimeout),
      CommandMapping(kPost, "session/:sessionId/execute_sql",
                     CommandNames::kExecuteSQL),
      CommandMapping(kGet, "session/:sessionId/location",
                     CommandNames::kGetLocation),
      CommandMapping(kPost, "session/:sessionId/location",
                     CommandNames::kSetLocation),
      CommandMapping(kGet, "session/:sessionId/application_cache/status",
                     CommandNames::kGetStatus),
      CommandMapping(kGet, "session/:sessionId/browser_connection",
                     CommandNames::kIsBrowserOnline),
      CommandMapping(kPost, "session/:sessionId/browser_connection",
                     CommandNames::kSetBrowserOnline),
      CommandMapping(kGet, "session/:sessionId/local_storage/key/:key",
                     CommandNames::kGetLocalStorageItem),
      CommandMapping(kDelete, "session/:sessionId/local_storage/key/:key",
                     CommandNames::kRemoveLocalStorageItem),
      CommandMapping(kGet, "session/:sessionId/local_storage",
                     CommandNames::kGetLocalStorageKeys),
      CommandMapping(kPost, "session/:sessionId/local_storage",
                     CommandNames::kSetLocalStorageItem),
      CommandMapping(kDelete, "session/:sessionId/local_storage",
                     CommandNames::kClearLocalStorage),
      CommandMapping(kGet, "session/:sessionId/local_storage/size",
                     CommandNames::kGetLocalStorageSize),
      CommandMapping(kGet, "session/:sessionId/session_storage/key/:key",
                     CommandNames::kGetSessionStorageItem),
      CommandMapping(kDelete, "session/:sessionId/session_storage/key/:key",
                     CommandNames::kRemoveSessionStorageItem),
      CommandMapping(kGet, "session/:sessionId/session_storage",
                     CommandNames::kGetSessionStorageKey),
      CommandMapping(kPost, "session/:sessionId/session_storage",
                     CommandNames::kSetSessionStorageItem),
      CommandMapping(kDelete, "session/:sessionId/session_storage",
                     CommandNames::kClearSessionStorage),
      CommandMapping(kGet, "session/:sessionId/session_storage/size",
                     CommandNames::kGetSessionStorageSize),
      CommandMapping(kGet, "session/:sessionId/orientation",
                     CommandNames::kGetScreenOrientation),
      CommandMapping(kPost, "session/:sessionId/orientation",
                     CommandNames::kSetScreenOrientation),
      CommandMapping(kPost, "session/:sessionId/click",
                     CommandNames::kMouseClick),
      CommandMapping(kPost, "session/:sessionId/doubleclick",
                     CommandNames::kMouseDoubleClick),
      CommandMapping(kPost, "session/:sessionId/buttondown",
                     CommandNames::kMouseButtonDown),
      CommandMapping(kPost, "session/:sessionId/buttonup",
                     CommandNames::kMouseButtonUp),
      CommandMapping(kPost, "session/:sessionId/moveto",
                     CommandNames::kMouseMoveTo),
      CommandMapping(kPost, "session/:sessionId/keys",
                     CommandNames::kSendKeysToActiveElement),
      CommandMapping(kGet, "session/:sessionId/ime/available_engines",
                     CommandNames::kImeGetAvailableEngines),
      CommandMapping(kGet, "session/:sessionId/ime/active_engine",
                     CommandNames::kImeGetActiveEngine),
      CommandMapping(kGet, "session/:sessionId/ime/activated",
                     CommandNames::kImeIsActivated),
      CommandMapping(kPost, "session/:sessionId/ime/deactivate",
                     CommandNames::kImeDeactivate),
      CommandMapping(kPost, "session/:sessionId/ime/activate",
                     CommandNames::kImeActivateEngine),
      CommandMapping(kPost, "session/:sessionId/touch/click",
                     CommandNames::kTouchSingleTap),
      CommandMapping(kPost, "session/:sessionId/touch/down",
                     CommandNames::kTouchDown),
      CommandMapping(kPost, "session/:sessionId/touch/up",
                     CommandNames::kTouchUp),
      CommandMapping(kPost, "session/:sessionId/touch/move",
                     CommandNames::kTouchMove),
      CommandMapping(kPost, "session/:sessionId/touch/scroll",
                     CommandNames::kTouchScroll),
      CommandMapping(kPost, "session/:sessionId/touch/doubleclick",
                     CommandNames::kTouchDoubleTap),
      CommandMapping(kPost, "session/:sessionId/touch/longclick",
                     CommandNames::kTouchLongPress),
      CommandMapping(kPost, "session/:sessionId/touch/flick",
                     CommandNames::kTouchFlick),
      CommandMapping(kPost, "session/:sessionId/log", CommandNames::kGetLog),
      CommandMapping(kGet, "session/:sessionId/log/types",
                     CommandNames::kGetAvailableLogTypes),
      CommandMapping(kPost, "logs", CommandNames::kGetSessionLogs),
      CommandMapping(kGet, "status", CommandNames::kStatus),

      // Custom Chrome commands:
      // Allow quit all to be called with GET or POST.
      CommandMapping(kGet, kShutdownPath, CommandNames::kQuitAll),
      CommandMapping(kPost, kShutdownPath, CommandNames::kQuitAll),
  };
  return scoped_ptr<CommandMap>(
      new CommandMap(commands, commands + arraysize(commands)));
}

HttpHandler::HttpHandler(scoped_ptr<CommandExecutor> executor,
                         scoped_ptr<CommandMap> command_map,
                         const std::string& url_base)
    : executor_(executor.Pass()),
      command_map_(command_map.Pass()),
      url_base_(url_base) {
  executor_->Init();
}

HttpHandler::~HttpHandler() {}

void HttpHandler::Handle(const HttpRequest& request,
                         HttpResponse* response) {
  std::string path = request.path;
  if (!StartsWithASCII(path, url_base_, true)) {
    *response = HttpResponse(HttpResponse::kBadRequest);
    response->set_body("unhandled request");
    return;
  }

  path.erase(0, url_base_.length());

  if (!HandleWebDriverCommand(request, path, response)) {
    *response = HttpResponse(HttpResponse::kNotFound);
    response->set_body("unknown command: " + path);
    return;
  }
}

bool HttpHandler::ShouldShutdown(const HttpRequest& request) {
  return request.path == url_base_ + kShutdownPath;
}

bool HttpHandler::HandleWebDriverCommand(
    const HttpRequest& request,
    const std::string& trimmed_path,
    HttpResponse* response) {
  base::DictionaryValue params;
  std::string session_id;
  CommandMap::const_iterator iter = command_map_->begin();
  while (true) {
    if (iter == command_map_->end()) {
      return false;
    }
    if (internal::MatchesCommand(
            request.method, trimmed_path, *iter, &session_id, &params)) {
      break;
    }
    ++iter;
  }

  if (iter->name == internal::kNewSessionIdCommand) {
    // Creating a session involves a HTTP request to /session, which is
    // supposed to redirect to /session/:sessionId, which returns the
    // session info. Thus, the create new session command actually is split
    // between two HTTP requests. For this first request, we just redirect
    // to a new unique session ID. On the second request the create new
    // session command will be invoked.
    *response = HttpResponse(HttpResponse::kSeeOther);
    response->AddHeader("Location", url_base_ + "session/" + GenerateId());
    return true;
  }

  if (request.method == kPost && request.body.length()) {
    base::DictionaryValue* body_params;
    scoped_ptr<base::Value> parsed_body(base::JSONReader::Read(request.body));
    if (!parsed_body || !parsed_body->GetAsDictionary(&body_params)) {
      *response = HttpResponse(HttpResponse::kBadRequest);
      response->set_body("missing command parameters");
      return true;
    }
    params.MergeDictionary(body_params);
  }

  StatusCode status = kOk;
  scoped_ptr<base::Value> value;
  std::string out_session_id;
  executor_->ExecuteCommand(
      iter->name, params, session_id, &status, &value, &out_session_id);

  if (status == kUnknownCommand) {
    *response = HttpResponse(HttpResponse::kNotImplemented);
    response->set_body("unimplemented command: " + iter->name);
    return true;
  }

  base::DictionaryValue body_params;
  body_params.SetInteger("status", status);
  body_params.Set("value", value.release());
  body_params.SetString("sessionId", out_session_id);
  std::string body;
  base::JSONWriter::Write(&body_params, &body);
  *response = HttpResponse(HttpResponse::kOk);
  response->SetMimeType("application/json; charset=utf-8");
  response->set_body(body);
  return true;
}

namespace internal {

const char kNewSessionIdCommand[] = "chromedriver:newSessionIdCommand";

bool MatchesCommand(HttpMethod method,
                    const std::string& path,
                    const CommandMapping& command,
                    std::string* session_id,
                    base::DictionaryValue* out_params) {
  if (method != command.method)
    return false;

  std::vector<std::string> path_parts;
  base::SplitString(path, '/', &path_parts);
  std::vector<std::string> command_path_parts;
  base::SplitString(command.path_pattern, '/', &command_path_parts);
  if (path_parts.size() != command_path_parts.size())
    return false;

  base::DictionaryValue params;
  for (size_t i = 0; i < path_parts.size(); ++i) {
    CHECK(command_path_parts[i].length());
    if (command_path_parts[i][0] == ':') {
      std::string name = command_path_parts[i];
      name.erase(0, 1);
      CHECK(name.length());
      if (name == "sessionId")
        *session_id = path_parts[i];
      else
        params.SetString(name, path_parts[i]);
    } else if (command_path_parts[i] != path_parts[i]) {
      return false;
    }
  }
  out_params->MergeDictionary(&params);
  return true;
}

}  // namespace


text:
$('.datepicker').pickadate({
  format: 'dd mmm yyyy',
  selectMonths: true, // Creates a dropdown to control month
  selectYears: 15 // Creates a dropdown of 15 years to control year
});


text:
try {
	$packageName = 'pdfedit'
	$installerType = 'msi'
	$partialInstallArgs = '/quiet /qn /norestart TARGETDIR='
	$is64bit = (Get-WmiObject Win32_Processor).AddressWidth -eq 64
	if ($is64bit) {$installPath = ${Env:ProgramFiles(x86)}} else {$installPath = $Env:ProgramFiles}
	$installArgs = $($partialInstallArgs + '"' + $installPath + '"')
	# due to limitations of Ketarin/chocopkgup when using repos like sf.net:
	# 1. url is partly hardcoded and 2. DownloadUrlx64 is used to pass non-compatible nuget version number
	$url = 'http://sourceforge.net/projects/pdfedit/files/pdfedit-win32/pdfedit-20140526_1531.msi/download'
	$validExitCodes = @(0)
	Install-ChocolateyPackage "$packageName" "$installerType" "$installArgs" "$url" -validExitCodes "$validExitCodes"
  Write-ChocolateySuccess $packageName
} catch {
	Write-ChocolateyFailure $packageName $($_.Exception.Message)
	throw
}


text:
<launch>

  <!-- This file makes it easy to include the settings for sensor managers -->

  <!-- Params for the octomap monitor -->
  <!--  <param name="octomap_frame" type="string" value="some frame in which the robot moves" /> -->
  <param name="octomap_resolution" type="double" value="0.025" />
  <param name="max_range" type="double" value="2.0" />

  <!-- Load the robot specific sensor manager; this sets the moveit_sensor_manager ROS parameter -->
  <arg name="moveit_sensor_manager" default="pedestal_pi_no_gripper" />
  <include file="$(find pedestal_pi_no_gripper_moveit_config)/launch/$(arg moveit_sensor_manager)_moveit_sensor_manager.launch.xml" />

</launch>


text:
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url]

A modern application framework for NodeJS.

## Introduction
Vicegrip is a modern web application framework written in Typescript. Using all the handy new bits and pieces coming to JavaScript.
The idea is to make node web application development easier and support user who like a batteries included framework and even developers who just want to use bits and pieces of this framework.

## Getting started
A simple hello world example: (for more examples look in the examples folder in the current project)

```ts
import {
  ServiceCollection,
  ApplicationBuilder,
  bootstrap,
  Injectable
} from 'vicegrip/core';

@Injectable()
export class Startup {

  configure(services: ServiceCollection): void {
    // configure your services here
  }

  run(app: ApplicationBuilder): void {

    app.use((req: any, res: any) => res.send('hello express'));

  }

}

bootstrap(Startup);
```

More info and howtos coming soon!

[npm-url]: https://www.npmjs.com/package/vicegrip
[npm-image]: https://badge.fury.io/js/vicegrip.svg

[travis-url]: https://travis-ci.org/nickvdyck/vicegrip
[travis-image]: https://travis-ci.org/nickvdyck/vicegrip.svg?branch=master


text:
START_ATF_NAMESPACE
    #pragma pack(push, 2)
    struct  _gravity_stone_fix_position_zocl
    {
        unsigned __int16 wObjIndex;
        unsigned __int16 wRecIndex;
        unsigned int dwObjSerial;
        __int16 zPos[3];
    };
    #pragma pack(pop)
END_ATF_NAMESPACE


text:
package roshanTest

import akka.actor.ActorSystem
import akka.testkit.{TestActorRef, TestKit, ImplicitSender}
import org.scalatest.{BeforeAndAfterEach, WordSpec, BeforeAndAfterAll}
import org.scalatest.matchers.{ShouldMatchers, MustMatchers}
import roshan.buffer.Msg.ACTION._
import roshan.buffer.Msg.ITEM_ATTR._
import roshan.model.Direction
import roshan.protocols.CharacterProtocol.Action
import roshan.protocols.MapProtocol.DirAction
import roshan.{Useful, Character}

class ItemTest(_system: ActorSystem) extends TestKit(_system)
with ImplicitSender with WordSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach with ShouldMatchers {

  def this() = this(Useful.testing)
  var characterRef:TestActorRef[Character] = _
  var character:Character = _
  override def afterAll() {
    system.shutdown()
  }

  override def beforeEach() {
    characterRef = TestActorRef(new Character(self))
    character = characterRef.underlyingActor
    character.map = self
  }

  "Item Factory" should {
    "Activate Items" in {
    }
  }

  "Character" should {
    "Use Items" in {
      // Sword Attr provides sword action
      character.my.items = List(List(SWORDATTR))
      characterRef ! Action(SWORD, Direction.S, null)
      val attack = expectMsgClass(classOf[DirAction])
      attack.action should be === SWORD
      attack.damage should be === 0
      // No List to make sure it at least works
      character.my.items = List(List())
      characterRef ! Action(SWORD, Direction.S, null)
      // Heal
      character.my.items = List(List(HEALATTR))
      characterRef ! Action(SWORD, Direction.S, null)
      val heal = expectMsgClass(classOf[DirAction])
      heal.action should be === HEAL
      // Basic
      character.my.items = List(List(SWORDATTR, BASIC_DMG))
      characterRef ! Action(SWORD, Direction.S, null)
      val attack2 = expectMsgClass(classOf[DirAction])
      attack2.action should be === SWORD
      attack2.damage should be === 1
    }
  }
}


text:
package handlers

import (
	bccsp "github.com/IBM/idemix/bccsp/schemes"
	"github.com/pkg/errors"
)

// CredentialRequestSigner produces credential requests
type CredentialRequestSigner struct {
	// CredRequest implements the underlying cryptographic algorithms
	CredRequest CredRequest
}

func (c *CredentialRequestSigner) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) ([]byte, error) {
	userSecretKey, ok := k.(*UserSecretKey)
	if !ok {
		return nil, errors.New("invalid key, expected *userSecretKey")
	}
	credentialRequestSignerOpts, ok := opts.(*bccsp.IdemixCredentialRequestSignerOpts)
	if !ok {
		return nil, errors.New("invalid options, expected *IdemixCredentialRequestSignerOpts")
	}
	if credentialRequestSignerOpts.IssuerPK == nil {
		return nil, errors.New("invalid options, missing issuer public key")
	}
	issuerPK, ok := credentialRequestSignerOpts.IssuerPK.(*issuerPublicKey)
	if !ok {
		return nil, errors.New("invalid options, expected IssuerPK as *issuerPublicKey")
	}

	return c.CredRequest.Sign(userSecretKey.Sk, issuerPK.pk, credentialRequestSignerOpts.IssuerNonce)
}

// CredentialRequestVerifier verifies credential requests
type CredentialRequestVerifier struct {
	// CredRequest implements the underlying cryptographic algorithms
	CredRequest CredRequest
}

func (c *CredentialRequestVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (bool, error) {
	issuerPublicKey, ok := k.(*issuerPublicKey)
	if !ok {
		return false, errors.New("invalid key, expected *issuerPublicKey")
	}
	credentialRequestSignerOpts, ok := opts.(*bccsp.IdemixCredentialRequestSignerOpts)
	if !ok {
		return false, errors.New("invalid options, expected *IdemixCredentialRequestSignerOpts")
	}

	err := c.CredRequest.Verify(signature, issuerPublicKey.pk, credentialRequestSignerOpts.IssuerNonce)
	if err != nil {
		return false, err
	}

	return true, nil
}

type CredentialSigner struct {
	Credential Credential
}

func (s *CredentialSigner) Sign(k bccsp.Key, digest []byte, opts bccsp.SignerOpts) (signature []byte, err error) {
	issuerSecretKey, ok := k.(*issuerSecretKey)
	if !ok {
		return nil, errors.New("invalid key, expected *issuerSecretKey")
	}
	credOpts, ok := opts.(*bccsp.IdemixCredentialSignerOpts)
	if !ok {
		return nil, errors.New("invalid options, expected *IdemixCredentialSignerOpts")
	}

	signature, err = s.Credential.Sign(issuerSecretKey.sk, digest, credOpts.Attributes)
	if err != nil {
		return nil, err
	}

	return
}

type CredentialVerifier struct {
	Credential Credential
}

func (v *CredentialVerifier) Verify(k bccsp.Key, signature, digest []byte, opts bccsp.SignerOpts) (valid bool, err error) {
	userSecretKey, ok := k.(*UserSecretKey)
	if !ok {
		return false, errors.New("invalid key, expected *userSecretKey")
	}
	credOpts, ok := opts.(*bccsp.IdemixCredentialSignerOpts)
	if !ok {
		return false, errors.New("invalid options, expected *IdemixCredentialSignerOpts")
	}
	if credOpts.IssuerPK == nil {
		return false, errors.New("invalid options, missing issuer public key")
	}
	ipk, ok := credOpts.IssuerPK.(*issuerPublicKey)
	if !ok {
		return false, errors.New("invalid issuer public key, expected *issuerPublicKey")
	}
	if len(signature) == 0 {
		return false, errors.New("invalid signature, it must not be empty")
	}

	err = v.Credential.Verify(userSecretKey.Sk, ipk.pk, signature, credOpts.Attributes)
	if err != nil {
		return false, err
	}

	return true, nil
}


text:
"""Defines the application configuration for the batch application"""
from __future__ import unicode_literals

from django.apps import AppConfig

class BatchConfig(AppConfig):
    """Configuration for the batch app"""
    name = 'batch'
    label = 'batch'
    verbose_name = 'Batch'

    def ready(self):
        """Registers components related to batches"""

        # Register batch message types
        from batch.messages.create_batch_recipes import CreateBatchRecipes
        from batch.messages.update_batch_metrics import UpdateBatchMetrics
        from messaging.messages.factory import add_message_type

        add_message_type(CreateBatchRecipes)
        add_message_type(UpdateBatchMetrics)


text:
package org.jetbrains.plugins.scala
package format

import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.plugins.scala.lang.refactoring.util.ScalaNamesUtil

/**
 * Pavel Fatin
 */

object InterpolatedStringFormatter extends StringFormatter {
  def format(parts: Seq[StringPart]) = {
    val toMultiline = parts.exists {
      case Text(s) => s.contains("\n")
      case i: Injection => i.value == "\n"
      case _ => false
    }
    format(parts, toMultiline)
  }

  def format(parts: Seq[StringPart], toMultiline: Boolean) = {
    val content = formatContent(parts, toMultiline)
    val prefix = {
      val formattingRequired = parts.exists {
        case it: Injection => it.isFormattingRequired
        case _ => false
      }
      if (formattingRequired) "f" else "s"
    }
    val quote = if (toMultiline) "\"\"\"" else "\""
    s"$prefix$quote$content$quote"
  }

  def formatContent(parts: Seq[StringPart], toMultiline: Boolean = false): String = {
    val strings = parts.collect {
      case Text(s) if toMultiline => s.replace("\r", "")
      case Text(s) => StringUtil.escapeStringCharacters(s.replaceAll("\\$", "\\$\\$"))
      case it: Injection =>
        val text = it.value
        if (it.isLiteral && !it.isFormattingRequired) text else {
          val presentation =
            if ((it.isComplexBlock || (!it.isLiteral && it.isAlphanumericIdentifier)) && noBraces(parts, it)) "$" + text else "${" + text + "}"
          if (it.isFormattingRequired) presentation + it.format else presentation
        }
    }
    strings.mkString
  }

  def noBraces(parts: Seq[StringPart], it: Injection): Boolean =  {
    val ind = parts.indexOf(it)
    if (ind + 1 < parts.size) {
      parts(ind + 1) match {
        case Text(s) =>
          return s.isEmpty || !ScalaNamesUtil.isIdentifier(it.text + s.charAt(0)) ||
                s.startsWith("`") || s.exists(_ == '$')
        case _ =>  true
      }
    }
    true
  }
}


text:
using JetBrains.Annotations;
using JsonApiDotNetCore.Configuration;
using TestBuildingBlocks;

namespace JsonApiDotNetCoreTests.Startups;

[UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)]
public sealed class RelativeLinksNoNamespaceStartup<TDbContext> : TestableStartup<TDbContext>
    where TDbContext : TestableDbContext
{
    protected override void SetJsonApiOptions(JsonApiOptions options)
    {
        base.SetJsonApiOptions(options);

        options.Namespace = null;
        options.UseRelativeLinks = true;
    }
}


text:
package net.mostlyoriginal.game.system.dilemma;

import com.artemis.Aspect;
import com.artemis.E;
import com.artemis.utils.IntBag;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.math.Interpolation;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.Json;
import net.mostlyoriginal.api.component.basic.Pos;
import net.mostlyoriginal.api.component.graphics.Tint;
import net.mostlyoriginal.api.system.graphics.RenderBatchingSystem;
import net.mostlyoriginal.api.system.render.AnimRenderSystem;
import net.mostlyoriginal.game.component.*;
import net.mostlyoriginal.game.component.ui.Clickable;
import net.mostlyoriginal.game.screen.GameScreen;
import net.mostlyoriginal.game.system.AchievementSystem;
import net.mostlyoriginal.game.system.common.FluidIteratingSystem;
import net.mostlyoriginal.game.system.logic.TransitionSystem;
import net.mostlyoriginal.game.system.view.GameScreenAssetSystem;

import java.security.Key;

import static com.artemis.E.E;
import static net.mostlyoriginal.api.operation.JamOperationFactory.moveBetween;
import static net.mostlyoriginal.api.operation.JamOperationFactory.moveTo;
import static net.mostlyoriginal.api.operation.JamOperationFactory.scaleBetween;
import static net.mostlyoriginal.api.operation.OperationFactory.*;

/**
 * Responsible for serving and processing cards.
 *
 * @author Daan van Yperen
 */
public class CardSystem extends FluidIteratingSystem {

    private static TransitionSystem transitionSystem;
    private CardLibrary cardLibrary;
    private GameScreenAssetSystem gameScreenAssetSystem;
    private RenderBatchingSystem renderBatchingSystem;
    CardSortSystem cardSortSystem;
    private AchievementSystem achievementSystem;

    public CardSystem() {
        super(Aspect.all(Pos.class, PlayableCard.class, Clickable.class));
    }

    @Override
    protected void initialize() {
        super.initialize();
        loadCards();
        //spawnCard("HOLLOWEARTH");
    }

    private void loadCards() {
        final Json json = new Json();
        cardLibrary = json.fromJson(CardLibrary.class, Gdx.files.internal("cards.json"));
        dealRandomCards(3);
    }

    private void dealRandomCards(int count) {
        for (int i = 0; i < count; i++) {
            CardData card = cardLibrary.random();
            spawnCard(card);
        }
    }

    public void dealResetCard() {
        clearDeck();
        spawnCard(cardLibrary.getById("RESTART"));
    }

    private void clearDeck() {
        IntBag cards = getEntityIds();
        int[] ids = cards.getData();
        for (int i = 0, s = cards.size(); s > i; i++) {
            E e = E.E(ids[i]);
            e.removeClickable().script(sequence(moveBetween(e.posX(), e.posY(), e.posX(), e.posY() - 100, 1f, Interpolation.smooth), deleteFromWorld()));
        }
    }

    @Override
    protected void begin() {
        super.begin();

        if (Gdx.input.isKeyJustPressed(Input.Keys.NUM_0)) {
            //dealRandomCards(1);
            dealResetCard();
        }

        int cards = getEntityIds().size();
        if (cards <= 1 && !achievementSystem.gameEnded) {
            dealRandomCards(3-cards);
        }
    }

    @Override
    protected void process(E e) {

        e.scale(e.clickableState() == Clickable.ClickState.HOVER ? 1.2f : 1.0f);
        int layer = e.clickableState() == Clickable.ClickState.HOVER ? G.LAYER_CARDS_HOVER : G.LAYER_CARDS;
        if (e.renderLayer() != layer) {
            e.renderLayer(layer);
            renderBatchingSystem.sortedDirty = true;
        }
        if (e.clickableState() == Clickable.ClickState.CLICKED) {
            gameScreenAssetSystem.playSfx("LD1_event1");
            e.removeClickable();
            float MOVE_DURATION = 1.5f;
            float FINAL_CARD_SCALE = 0.4f;
            e.physicsVr(500f).physicsFriction(0).angle().tint(Tint.WHITE).renderLayer(G.LAYER_CARDS_FLYING);
            e.script(
                    sequence(
                            parallel(
                                    moveBetween(e.posX(), e.posY(), G.PLANET_CENTER_X - e.boundsCx() * FINAL_CARD_SCALE, G.PLANET_CENTER_Y - e.boundsCy() * FINAL_CARD_SCALE, MOVE_DURATION, Interpolation.smooth),
                                    scaleBetween(1f, FINAL_CARD_SCALE, MOVE_DURATION, Interpolation.smooth),
                                    sequence(
                                            delay(MOVE_DURATION - 0.2f),
                                            tween(Tint.WHITE, Tint.TRANSPARENT, 0.2f)
                                    )),
                            add(new CardScript(e.playableCardCard().script))
                    ));
            cardSortSystem.shouldResort = true;
        }
    }

    private void spawnCard(CardData card) {
        if ( G.DEBUG_NO_CARDS ) return;

        String cardGfx = "card" + card.id;
        gameScreenAssetSystem.add(cardGfx, card.x, card.y, card.width, card.height, 1);
        E()
                .anim(cardGfx)
                .clickable()
                .playableCardCard(card)
                .bounds(0, 0, card.width, card.height)
                .pos(-300, G.CARD_Y)
                .physics()
                .scale(1.0f)
                .renderLayer(G.LAYER_CARDS);
        cardSortSystem.shouldResort = true;
    }

    private static void restartGame() {
        transitionSystem.transition(GameScreen.class, 0f);
    }

    public void spawnCard(String id) {
        spawnCard(cardLibrary.getById(id));
    }
}


text:
{% extends "base.html" %}

{% block head_title %}Home{% endblock %}

{% block content %}
{% include "tabbar.html" %}

Welcome!

    This page will hold a description of what this website does.

    For instance: This is a demonstration of the AIR Toolkit.

{% if ready %}

  Get Started

{% else %}

  login with facebook

{% endif %}

{% endblock %}


text:
using System;

namespace Tamir.SharpSsh.java.util
{
	/// <summary>
	/// Summary description for Arrays.
	/// </summary>
	public class Arrays
	{
		internal static bool equals(byte[] foo, byte[] bar)
		{
			int i=foo.Length;
			if(i!=bar.Length) return false;
			for(int j=0; j<i; j++){ if(foo[j]!=bar[j]) return false; }
			//try{while(true){i--; if(foo[i]!=bar[i])return false;}}catch(Exception e){}
			return true;
		}
	}
}