text:
<?php
namespace Phly\Conduit;

use Exception;
use Phly\Conduit\Http\ResponseInterface as Response;
use Psr\Http\Message\RequestInterface as Request;
use Zend\Escaper\Escaper;

/**
 * Handle incomplete requests
 */
class FinalHandler
{
    /**
     * @var array
     */
    private $options;

    /**
     * @var Request
     */
    private $request;

    /**
     * @var Response
     */
    private $reponse;

    /**
     * @param Request $request
     * @param Response $response
     */
    public function __construct(Request $request, Response $response, array $options = [])
    {
        $this->request  = $request;
        $this->response = $response;
        $this->options  = $options;
    }

    /**
     * Handle incomplete requests
     *
     * This handler should only ever be invoked if Next exhausts its stack.
     * When that happens, we determine if an $err is present, and, if so,
     * create a 500 status with error details.
     *
     * Otherwise, a 404 status is created.
     *
     * @param null|mixed $err
     */
    public function __invoke($err = null)
    {
        if ($err) {
            $this->handleError($err);
            return;
        }

        $this->create404();
    }

    /**
     * Handle an error condition
     *
     * Use the $error to create details for the response.
     *
     * @param mixed $error
     */
    private function handleError($error)
    {
        $status = $this->response->getStatusCode();
        if (! $status || $status < 400) {
            $this->response->setStatusCode(500);
        }

        if ($error instanceof Exception
            && ($error->getCode() >= 400 && $error->getCode() < 600)
        ) {
            $this->response->setStatusCode($error->getCode());
        }

        $escaper = new Escaper();
        $message = $this->response->getReasonPhrase() ?: 'Unknown Error';
        if (! isset($this->options['env'])
            || $this->options['env'] !== 'production'
        ) {
            if ($error instanceof Exception) {
                $message = $error->getTraceAsString();
            } elseif (is_object($error) && ! method_exists($error, '__toString')) {
                $message = sprintf('Error of type "%s" occurred', get_class($error));
            } else {
                $message = (string) $error;
            }
            $message = $escaper->escapeHtml($message);
        }

        if (isset($this->options['onerror'])
            && is_callable($this->options['onerror'])
        ) {
            $onError = $this->options['onerror'];
            $onError($error, $this->request, $this->response);
        }

        $this->response->end($message);
    }

    /**
     * Create a 404 status in the response
     */
    private function create404()
    {
        $this->response->setStatusCode(404);

        $url     = $this->request->originalUrl ?: $this->request->getUrl();
        $escaper = new Escaper();
        $message = sprintf(
            "Cannot %s %s\n",
            $escaper->escapeHtml($this->request->getMethod()),
            $escaper->escapeHtml((string) $url)
        );
        $this->response->end($message);
    }
}


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

<title>$!app_name</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link href="${base}/private/ratifyFollow/css/blue/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="${base}/css/form.css" />

<form name='form1' id="form1" method='post' action="${base}/private/formyy/add">
<input type="hidden" name="formdefid" value="$!formdefid" />
$!body
</form>

		<input type="button" class="button" name="Preview" value="提交" onclick="doSave()" />
		<input type="button" class="button" name="Close" value="关闭"  onclick="window.close()" />

redpajama_set_name: RedPajamaGithub


text:
cd /usr/src
apt-get install -y curl php5-cli
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer


text:
//
//  sort-list.h
//
//  Created by jeswang 27/06/2014.
//

/*
Description:
Sort a linked list in O(n log n) time using constant space complexity.
*/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *sortList(ListNode *head) {

    }
};


text:
from . import bread_spec
import bread
import os
import sys
from . import utils
from .project import Project
from . import blockutils
from .blockutils import BlockReader, BlockWriter, BlockFactory
from . import filepack
import collections
import bitstring
from . import exceptions

from .vendor.six.moves import range

# Start index for data blocks
BLOCKS_START_OFFSET = 0x8000

# The maximum number of files that the .sav can support
NUM_FILES = 0x20

# Constants
EMPTY_BLOCK = 0xff

# By default, SAV file loading doesn't trigger any callback action
def _noop_callback(message, step, total_steps, continuing):
    pass

class ProjectList(object):
    def __init__(self, filename, header_block):
        self.filename = filename
        self.header_block = header_block

        self._projects = {}

    def __eq__(self, other):
        if not isinstance(other, ProjectList):
            return False

        for i in range(NUM_FILES):
            my_proj = self[i]
            other_proj = other[i]

            if my_proj != other_proj:
                return False

        return True

    def __getitem__(self, file_number):
        if file_number not in self._projects:
            with open(self.filename, 'rb') as fp:
                self._projects[file_number] = self._read_project(
                    fp, file_number)

        return self._projects[file_number]

    def __setitem__(self, file_number, proj):
        self._projects[file_number] = proj

    def keys(self):
        return range(NUM_FILES)

    def _read_project(self, fp, file_number):
        # Scan the block allocation table for blocks for this project
        # Block 0 is reserved, so block numbers are assumed off-by-one
        block_numbers = [
            block_number + 1 for block_number, blk_file in
            enumerate(self.header_block.block_alloc_table)
            if blk_file == file_number
        ]

        project_size_blks = len(block_numbers)

        # If a given file number doesn't have any blocks, it doesn't exist
        if project_size_blks == 0:
            return None

        block_map = {}

        for block_number in block_numbers:
            offset = BLOCKS_START_OFFSET + \
                     (block_number * blockutils.BLOCK_SIZE)

            fp.seek(offset, os.SEEK_SET)

            block_data = bytearray(fp.read(blockutils.BLOCK_SIZE))

            block_map[block_number] = blockutils.Block(
                block_number, block_data)

        reader = BlockReader()
        compressed_data = reader.read(block_map)
        raw_data = filepack.decompress(compressed_data)

        project_name = self.header_block.filenames[file_number]
        project_version = self.header_block.file_versions[file_number]

        project = Project(
            name=self.header_block.filenames[file_number],
            version=self.header_block.file_versions[file_number],
            data=raw_data,
            size_blks=project_size_blks)

        return project

class SAVFile(object):
    # Start offset of SAV file contents
    START_OFFSET = 0x8000

    HEADER_EMPTY_SECTION_1 = (0x8120, 0x813d)

    # Offset of SRAM initialization check
    SRAM_INIT_CHECK_OFFSET = 0x813e
    SRAM_INIT_CHECK_LENGTH = 2

    # Offset where active file number appears
    ACTIVE_FILE_NUMBER_OFFSET = 0x8140

    # Start of block allocation table
    BAT_START_OFFSET = 0x8141

    # End of block allocation table
    BAT_END_OFFSET = 0x81ff

    # Max length in bytes of filename
    FILENAME_LENGTH = 8

    # Length in bytes of file version number
    FILE_VERSION_LENGTH = 1

    # Length in bytes of file number
    FILE_NUMBER_LENGTH = 1

    def __init__(self, filename, callback=_noop_callback):
        """Constructor.

        :param filename: the file to open
        :type name: str
        :param callback: a progress callback function
        :type name: function
        """
        self.filename = filename

        with open(filename, 'rb') as fp:
            self._load(fp, callback)

    def _load(self, fp, callback):
        # read preamble + decompress blocks + "all done"
        total_steps = 3
        current_step = 0

        callback("Reading preamble", current_step, total_steps, True)

        self.preamble = fp.read(self.START_OFFSET)

        header_block_data = fp.read(blockutils.BLOCK_SIZE)

        try:
            self.header_block = bread.parse(
                header_block_data, bread_spec.compressed_sav_file)
        except bitstring.ReadError as e:
            raise exceptions.ImportException(e)

        if self.header_block.sram_init_check != b'jk':
            error_msg = (
                "SRAM init check bits incorrect (should be 'jk', was '%s')" %
                (self.header_block.sram_init_check))

            callback(error_msg, current_step, total_steps, False)
            raise ValueError(error_msg)

        self.active_project_number = self.header_block.active_file

        current_step += 1

        callback("Decompressing", current_step, total_steps, True)

        self.projects = ProjectList(self.filename, self.header_block)

        current_step += 1

        callback("Import complete!", total_steps, total_steps, True)

    def __str__(self):
        output_str = ''

        def add_line(line):
            output_str += line + '\n'

        str_stream = StringIO()

        for i in range(NUM_FILES):
            project = self.projects[i]

            if project is not None:
                add_line(str(project), file=str_stream)

        add_line("Active Project: %s" % \
            (self.projects[self.active_project_number]), file=str_stream)

        return output_str

    def __eq__(self, other):
        return self.projects == other.projects

    @property
    def project_list(self):
        """The list of :py:class:`pylsdj.Project` s that the
        .sav file contains"""
        return [(i, self.projects[i]) for i in sorted(self.projects.keys())]

    def _save(self, fp, callback):
        # Marshal 32 possible projects + write preamble + write data + "all
        # done"
        total_steps = 35
        current_step = 0

        writer = BlockWriter()
        factory = BlockFactory()

        # Block allocation table doesn't include header block because it's
        # always in use, so have to add additional block to account for header
        num_blocks = self.BAT_END_OFFSET - self.BAT_START_OFFSET + 2

        header_block = factory.new_block()

        block_table = []

        for i in range(num_blocks):
            block_table.append(None)

        # First block is the header block, so we should ignore it when creating
        # the block allocation table
        block_table[0] = -1

        for i in range(NUM_FILES):
            project = self.projects[i]

            current_step += 1

            if project is None:
                continue

            callback("Marshaling song '%s'" %
                     (utils.name_without_zeroes(project.name)),
                     current_step - 1, total_steps, True)

            raw_data = project.get_raw_data()
            compressed_data = filepack.compress(raw_data)

            project_block_ids = writer.write(compressed_data, factory)

            for b in project_block_ids:
                block_table[b] = i

        callback("Writing preamble and constructing header block",
                 current_step, total_steps, True)
        current_step += 1
        # Bytes up to START_OFFSET will remain the same
        fp.write(self.preamble)

        # Set header block filenames and versions

        empty_project_name = '\0' * self.FILENAME_LENGTH

        for i in range(NUM_FILES):
            project = self.projects[i]

            if project is None:
                self.header_block.filenames[i] = empty_project_name
                self.header_block.file_versions[i] = 0
            else:
                self.header_block.filenames[i] = project.name
                self.header_block.file_versions[i] = project.version

        self.header_block.active_file = self.active_project_number

        # Ignore the header block when serializing the block allocation table
        for i, b in enumerate(block_table[1:]):
            if b is None:
                file_no = EMPTY_BLOCK
            else:
                file_no = b

            self.header_block.block_alloc_table[i] = file_no

        header_block.data = bread.write(
            self.header_block, bread_spec.compressed_sav_file)

        assert len(header_block.data) == blockutils.BLOCK_SIZE, \
            "Header block isn't the expected length; expected 0x%x, got 0x%x" \
            % (blockutils.BLOCK_SIZE, len(header_block.data))

        block_map = factory.blocks

        empty_block_data = []
        for i in range(blockutils.BLOCK_SIZE):
            empty_block_data.append(0)

        callback("Writing data to file", current_step, total_steps, True)
        current_step += 1
        for i in range(num_blocks):
            if i in block_map:
                data_list = block_map[i].data
            else:
                data_list = empty_block_data

            fp.write(bytearray(data_list))

        callback("Save complete!", total_steps, total_steps, True)

    def save(self, filename, callback=_noop_callback):
        """Save this file.

        :param filename: the file to which to save the .sav file
        :type filename: str
        :param callback: a progress callback function
        :type callback: function
        """
        with open(filename, 'wb') as fp:
            self._save(fp, callback)

if __name__ == "__main__":
    sav = SAVFile(sys.argv[1])
    sav.save(sys.argv[2])


text:
USeaCraftVehicleWeaponComponent::USeaCraftVehicleWeaponComponent(const class FPostConstructInitializeProperties& PCIP)
	: Super(PCIP)
{
	bWantsInitializeComponent = true;

	bWantsToFire = false;
	CurrentState = EVWeaponState::Idle;

	LastActiveTurretBarrel = 0;

	MaxAmmo = 100;
	CurrentAmmo = MaxAmmo;
	TimeBetweenShots = 0.2f;
	LastFireTime = 0.0f;
}

void USeaCraftVehicleWeaponComponent::InitializeComponent()
{
	Super::InitializeComponent();
}

//////////////////////////////////////////////////////////////////////////
// Input

void USeaCraftVehicleWeaponComponent::StartFire()
{
	AActor* Owner = GetOwner();
	if (Owner == NULL)
	{
		return;
	}

	if (Owner->Role < ROLE_Authority)
	{
		ServerStartFire();
	}

	if (!bWantsToFire)
	{
		bWantsToFire = true;
		DetermineWeaponState();
	}
}

void USeaCraftVehicleWeaponComponent::StopFire()
{
	AActor* Owner = GetOwner();
	if (Owner == NULL)
	{
		return;
	}

	if (Owner->Role < ROLE_Authority)
	{
		ServerStopFire();
	}

	if (bWantsToFire)
	{
		bWantsToFire = false;
		DetermineWeaponState();
	}
}

bool USeaCraftVehicleWeaponComponent::ServerStartFire_Validate()
{
	return true;
}

void USeaCraftVehicleWeaponComponent::ServerStartFire_Implementation()
{
	StartFire();
}

bool USeaCraftVehicleWeaponComponent::ServerStopFire_Validate()
{
	return true;
}

void USeaCraftVehicleWeaponComponent::ServerStopFire_Implementation()
{
	StopFire();
}

//////////////////////////////////////////////////////////////////////////
// Control

bool USeaCraftVehicleWeaponComponent::CanFire() const
{
	// @TODO Check fire conditions
	// 1. check we have alive vehicle
	// 2. check we're idle or firing (else we can't fire)
	// 3. check we have no pending reload

	return true;
}

//////////////////////////////////////////////////////////////////////////
// Ammo

void USeaCraftVehicleWeaponComponent::GiveAmmo(int AddAmount)
{
	// @TODO Check max ammo capacity reached
	CurrentAmmo += AddAmount;
}

void USeaCraftVehicleWeaponComponent::UseAmmo()
{
	if (!HasInfiniteAmmo())
	{
		CurrentAmmo--;
	}
}

//////////////////////////////////////////////////////////////////////////
// Weapon usage

void USeaCraftVehicleWeaponComponent::HandleFiring()
{
	APawn* MyPawn = Cast<APawn>(GetOwner());

	if ((CurrentAmmo > 0 || HasInfiniteAmmo()) && CanFire())
	{
		if (MyPawn && MyPawn->IsLocallyControlled())
		{
			FireWeapon();

			UseAmmo();

			// Change barrel
			LastActiveTurretBarrel++;
			if (LastActiveTurretBarrel >= TurretSockets.Num())
			{
				LastActiveTurretBarrel = 0;
			}

			// @TODO Send vehicle event to trigger effects
		}
	}
	else if (MyPawn && MyPawn->IsLocallyControlled())
	{
		if (GetCurrentAmmo() == 0 && !bRefiring)
		{
			// TODO Notify out of ammo
		}
	}

	if (MyPawn && MyPawn->IsLocallyControlled())
	{
		// Local client will notify server
		if (MyPawn->Role < ROLE_Authority)
		{
			ServerHandleFiring();
		}

		// Setup refire timer
		bRefiring = (CurrentState == EVWeaponState::Firing && TimeBetweenShots > 0.0f);
		if (bRefiring)
		{
			MyPawn->GetWorldTimerManager().SetTimer(this, &USeaCraftVehicleWeaponComponent::HandleFiring, TimeBetweenShots, false);
		}
	}

	LastFireTime = GetWorld()->GetTimeSeconds();
}

bool USeaCraftVehicleWeaponComponent::ServerHandleFiring_Validate()
{
	return true;
}

void USeaCraftVehicleWeaponComponent::ServerHandleFiring_Implementation()
{
	HandleFiring();

	// @TODO Check we should update ammo
}

void USeaCraftVehicleWeaponComponent::SetWeaponState(EVWeaponState::Type NewState)
{
	const EVWeaponState::Type PrevState = CurrentState;

	if (PrevState == EVWeaponState::Firing && NewState != EVWeaponState::Firing)
	{
		OnBurstFinished();
	}

	CurrentState = NewState;

	if (PrevState != EVWeaponState::Firing && NewState == EVWeaponState::Firing)
	{
		OnBurstStarted();
	}
}

void USeaCraftVehicleWeaponComponent::DetermineWeaponState()
{
	EVWeaponState::Type NewState = EVWeaponState::Idle;

	if ((bWantsToFire == true) && (CanFire() == true))
	{
		NewState = EVWeaponState::Firing;
	}

	SetWeaponState(NewState);
}

void USeaCraftVehicleWeaponComponent::OnBurstStarted()
{
	APawn* MyPawn = Cast<APawn>(GetOwner());
	if (MyPawn == NULL)
	{
		return;
	}

	// Start firing, can be delayed to satisfy TimeBetweenShots
	const float GameTime = GetWorld()->GetTimeSeconds();
	if (LastFireTime > 0 && TimeBetweenShots > 0.0f &&
		LastFireTime + TimeBetweenShots > GameTime)
	{
		MyPawn->GetWorldTimerManager().SetTimer(this, &USeaCraftVehicleWeaponComponent::HandleFiring, LastFireTime + TimeBetweenShots - GameTime, false);
	}
	else
	{
		HandleFiring();
	}
}

void USeaCraftVehicleWeaponComponent::OnBurstFinished()
{
	APawn* MyPawn = Cast<APawn>(GetOwner());
	if (MyPawn == NULL)
	{
		return;
	}

	MyPawn->GetWorldTimerManager().ClearTimer(this, &USeaCraftVehicleWeaponComponent::HandleFiring);
	bRefiring = false;
}

//////////////////////////////////////////////////////////////////////////
// Weapon usage helpers

FVector USeaCraftVehicleWeaponComponent::GetCameraAim() const
{
	APawn* MyPawn = Cast<APawn>(GetOwner());
	ASeaCraftPlayerController* const PlayerController = MyPawn ? Cast<ASeaCraftPlayerController>(MyPawn->Controller) : NULL;
	FVector FinalAim = FVector::ZeroVector;

	if (PlayerController)
	{
		FVector CamLoc;
		FRotator CamRot;
		PlayerController->GetPlayerViewPoint(CamLoc, CamRot);
		FinalAim = CamRot.Vector();
	}
	else if (MyPawn)
	{
		FinalAim = MyPawn->GetBaseAimRotation().Vector();
	}

	return FinalAim;
}

FVector USeaCraftVehicleWeaponComponent::GetAdjustedAim() const
{
	FVector FinalAim = FVector::ZeroVector;

	// We're using socket rotation as targeting vector
	FinalAim = GetMuzzleDirection();

	return FinalAim;
}

FVector USeaCraftVehicleWeaponComponent::GetCameraDamageStartLocation(const FVector& AimDir) const
{
	APawn* MyPawn = Cast<APawn>(GetOwner());
	ASeaCraftPlayerController* PC = MyPawn ? Cast<ASeaCraftPlayerController>(MyPawn->Controller) : NULL;
	FVector OutStartTrace = FVector::ZeroVector;

	if (PC)
	{
		// use player's camera
		FRotator UnusedRot;
		PC->GetPlayerViewPoint(OutStartTrace, UnusedRot);

		// Adjust trace so there is nothing blocking the ray between the camera and the pawn, and calculate distance from adjusted start
		OutStartTrace = OutStartTrace + AimDir * ((MyPawn->GetActorLocation() - OutStartTrace) | AimDir);
	}

	return OutStartTrace;
}

FVector USeaCraftVehicleWeaponComponent::GetMuzzleLocation() const
{
	ASeaCraftVehicle* MyVehicle = Cast<ASeaCraftVehicle>(GetOwner());
	if (MyVehicle)
	{
		return MyVehicle->VehicleMesh->GetSocketLocation(GetLastActiveTurretBarrel());
	}

	return FVector::ZeroVector;
}

FVector USeaCraftVehicleWeaponComponent::GetMuzzleDirection() const
{
	ASeaCraftVehicle* MyVehicle = Cast<ASeaCraftVehicle>(GetOwner());
	if (MyVehicle)
	{
		return MyVehicle->VehicleMesh->GetSocketRotation(GetLastActiveTurretBarrel()).Vector();
	}

	return FVector::UpVector;
}

FHitResult USeaCraftVehicleWeaponComponent::WeaponTrace(const FVector& StartTrace, const FVector& EndTrace) const
{
	static FName WeaponFireTag = FName(TEXT("WeaponTrace"));

	// Perform trace to retrieve hit info
	FCollisionQueryParams TraceParams(WeaponFireTag, true, GetOwner());
	TraceParams.bTraceAsyncScene = true;
	TraceParams.bReturnPhysicalMaterial = true;

	FHitResult Hit(ForceInit);
	GetWorld()->LineTraceSingle(Hit, StartTrace, EndTrace, COLLISION_WEAPON, TraceParams);

	return Hit;
}

//////////////////////////////////////////////////////////////////////////
// Reading data

EVWeaponState::Type USeaCraftVehicleWeaponComponent::GetCurrentState() const
{
	return CurrentState;
}

FName USeaCraftVehicleWeaponComponent::GetWeaponID() const
{
	return WeaponID;
}

FName USeaCraftVehicleWeaponComponent::GetGroupID() const
{
	return GroupID;
}

int32 USeaCraftVehicleWeaponComponent::GetCurrentAmmo() const
{
	return CurrentAmmo;
}

int32 USeaCraftVehicleWeaponComponent::GetMaxAmmo() const
{
	return MaxAmmo;
}

bool USeaCraftVehicleWeaponComponent::HasInfiniteAmmo() const
{
	return bInfiniteAmmo;
}

FName USeaCraftVehicleWeaponComponent::GetLastActiveTurretBarrel() const
{
	if (LastActiveTurretBarrel >= TurretSockets.Num())
	{
		return TEXT("None");
	}

	return TurretSockets[LastActiveTurretBarrel];
}

void USeaCraftVehicleWeaponComponent::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
	Super::GetLifetimeReplicatedProps(OutLifetimeProps);

	DOREPLIFETIME_CONDITION(USeaCraftVehicleWeaponComponent, CurrentAmmo, COND_OwnerOnly);
	DOREPLIFETIME_CONDITION(USeaCraftVehicleWeaponComponent, LastActiveTurretBarrel, COND_SimulatedOnly);
}


text:
namespace ServerLibraryTests
{
    class GamePlayTests
    {
    }
}


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CHROME_BROWSER_MANAGED_MODE_MANAGED_USER_REGISTRATION_SERVICE_H_
#define CHROME_BROWSER_MANAGED_MODE_MANAGED_USER_REGISTRATION_SERVICE_H_

#include <map>
#include <string>

#include "base/callback.h"
#include "base/memory/weak_ptr.h"
#include "base/prefs/pref_change_registrar.h"
#include "base/strings/string16.h"
#include "base/timer.h"
#include "chrome/browser/profiles/profile_downloader.h"
#include "chrome/browser/profiles/profile_downloader_delegate.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "components/browser_context_keyed_service/browser_context_keyed_service.h"
#include "sync/api/syncable_service.h"

class GoogleServiceAuthError;
class ManagedUserRefreshTokenFetcher;
class PrefService;

namespace browser_sync {
class DeviceInfo;
}

namespace user_prefs {
class PrefRegistrySyncable;
}

// Structure to store registration information.
struct ManagedUserRegistrationInfo {
  explicit ManagedUserRegistrationInfo(const string16& name);
  string16 name;
  std::string master_key;
};

// Holds the state necessary for registering a new managed user with the
// management server and associating it with its custodian. It is owned by the
// custodian's profile.
class ManagedUserRegistrationService : public BrowserContextKeyedService,
                                       public syncer::SyncableService,
                                       public ProfileDownloaderDelegate {
 public:
  // Callback for Register() below. If registration is successful, |token| will
  // contain an OAuth2 refresh token for the newly registered managed user,
  // otherwise |token| will be empty and |error| will contain the authentication
  // error for the custodian.
  typedef base::Callback<void(const GoogleServiceAuthError& /* error */,
                              const std::string& /* token */)>
      RegistrationCallback;

  // Callback for DownloadProfile() below. If the GAIA profile download is
  // successful, the profile's full (display) name will be returned.
  typedef base::Callback<void(const string16& /* full name */)>
      DownloadProfileCallback;

  ManagedUserRegistrationService(
      PrefService* prefs,
      scoped_ptr<ManagedUserRefreshTokenFetcher> token_fetcher);
  virtual ~ManagedUserRegistrationService();

  // ProfileDownloaderDelegate:
  virtual bool NeedsProfilePicture() const OVERRIDE;
  virtual int GetDesiredImageSideLength() const OVERRIDE;
  virtual std::string GetCachedPictureURL() const OVERRIDE;
  virtual Profile* GetBrowserProfile() OVERRIDE;
  virtual void OnProfileDownloadSuccess(ProfileDownloader* downloader) OVERRIDE;
  virtual void OnProfileDownloadFailure(
      ProfileDownloader* downloader,
      ProfileDownloaderDelegate::FailureReason reason) OVERRIDE;

  static void RegisterUserPrefs(user_prefs::PrefRegistrySyncable* registry);

  // Registers a new managed user with the server. |info| contains necessary
  // information like the display name of the  the user. |callback| is called
  // with the result of the registration. We use the info here and not the
  // profile, because on Chrome OS the profile of the managed user does
  // not yet exist.
  void Register(const ManagedUserRegistrationInfo& info,
                const RegistrationCallback& callback);

  // Downloads the GAIA account information for the |profile|. This is a best-
  // effort attempt with no error reporting nor timeout. If the download is
  // successful, the profile's full (display) name will be returned via the
  // callback. If the download fails or never completes, the callback will
  // not be called.
  void DownloadProfile(Profile* profile,
                       const DownloadProfileCallback& callback);

  // Cancels any registration currently in progress, without calling the
  // callback or reporting an error. This should be called when the user
  // actively cancels the registration by canceling profile creation.
  void CancelPendingRegistration();

  // ProfileKeyedService implementation:
  virtual void Shutdown() OVERRIDE;

  // SyncableService implementation:
  virtual syncer::SyncMergeResult MergeDataAndStartSyncing(
      syncer::ModelType type,
      const syncer::SyncDataList& initial_sync_data,
      scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
      scoped_ptr<syncer::SyncErrorFactory> error_handler) OVERRIDE;
  virtual void StopSyncing(syncer::ModelType type) OVERRIDE;
  virtual syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const
      OVERRIDE;
  virtual syncer::SyncError ProcessSyncChanges(
      const tracked_objects::Location& from_here,
      const syncer::SyncChangeList& change_list) OVERRIDE;

 private:
  void OnLastSignedInUsernameChange();

  // Called when the Sync server has acknowledged a newly created managed user.
  void OnManagedUserAcknowledged(const std::string& managed_user_id);

  // Fetches the managed user token when we have the device info.
  void FetchToken(const string16& name,
                  const browser_sync::DeviceInfo& device_info);

  // Called when we have received a token for the managed user.
  void OnReceivedToken(const GoogleServiceAuthError& error,
                       const std::string& token);

  // Dispatches the callback and cleans up if all the conditions have been met.
  void CompleteRegistrationIfReady();

  // Aborts any registration currently in progress. If |run_callback| is true,
  // calls the callback specified in Register() with the given |error|.
  void AbortPendingRegistration(bool run_callback,
                                const GoogleServiceAuthError& error);

  // If |run_callback| is true, dispatches the callback with the saved token
  // (which may be empty) and the given |error|. In any case, resets internal
  // variables to be ready for the next registration.
  void CompleteRegistration(bool run_callback,
                            const GoogleServiceAuthError& error);

  void OnProfileDownloadComplete();

  base::WeakPtrFactory<ManagedUserRegistrationService> weak_ptr_factory_;
  PrefService* prefs_;
  PrefChangeRegistrar pref_change_registrar_;
  scoped_ptr<ManagedUserRefreshTokenFetcher> token_fetcher_;

  scoped_ptr<syncer::SyncChangeProcessor> sync_processor_;
  scoped_ptr<syncer::SyncErrorFactory> error_handler_;

  // Provides a timeout during profile creation.
  base::OneShotTimer<ManagedUserRegistrationService> registration_timer_;

  std::string pending_managed_user_id_;
  std::string pending_managed_user_token_;
  bool pending_managed_user_acknowledged_;
  RegistrationCallback callback_;

  Profile* download_profile_;
  scoped_ptr<ProfileDownloader> profile_downloader_;
  DownloadProfileCallback download_callback_;

  DISALLOW_COPY_AND_ASSIGN(ManagedUserRegistrationService);
};

#endif  // CHROME_BROWSER_MANAGED_MODE_MANAGED_USER_REGISTRATION_SERVICE_H_


text:
namespace mojo {

// Type/enum conversions from WebVR data types to Mojo data types
// and vice versa.

template <>
struct TypeConverter<blink::WebVRVector3, content::VRVector3Ptr> {
  static blink::WebVRVector3 Convert(const content::VRVector3Ptr& input);
};

template <>
struct TypeConverter<blink::WebVRVector4, content::VRVector4Ptr> {
  static blink::WebVRVector4 Convert(const content::VRVector4Ptr& input);
};

template <>
struct TypeConverter<blink::WebVRRect, content::VRRectPtr> {
  static blink::WebVRRect Convert(const content::VRRectPtr& input);
};

template <>
struct TypeConverter<blink::WebVRFieldOfView, content::VRFieldOfViewPtr> {
  static blink::WebVRFieldOfView Convert(
      const content::VRFieldOfViewPtr& input);
};

template <>
struct TypeConverter<blink::WebVREyeParameters, content::VREyeParametersPtr> {
  static blink::WebVREyeParameters Convert(
      const content::VREyeParametersPtr& input);
};

template <>
struct TypeConverter<blink::WebVRHMDInfo, content::VRHMDInfoPtr> {
  static blink::WebVRHMDInfo Convert(const content::VRHMDInfoPtr& input);
};

template <>
struct TypeConverter<blink::WebVRDevice, content::VRDeviceInfoPtr> {
  static blink::WebVRDevice Convert(const content::VRDeviceInfoPtr& input);
};

template <>
struct TypeConverter<blink::WebHMDSensorState, content::VRSensorStatePtr> {
  static blink::WebHMDSensorState Convert(
      const content::VRSensorStatePtr& input);
};

}  // namespace mojo

#endif  // CHROME_CONTENT_RENDERER_VR_VR_TYPE_CONVERTERS_H_


text:
require 'contextio/api/resource'
require 'contextio/source_sync_data'

class ContextIO
  class File
    include ContextIO::API::Resource

    self.primary_key = :file_id
    self.association_name = :file

    belongs_to :account

    lazy_attributes :size, :type, :subject, :date, :addresses, :personInfo,
                    :email_message_id, :message_id, :date_indexed,
                    :date_received, :file_name, :file_name_structure,
                    :body_section, :content_disposition, :file_id,
                    :is_tnef_part, :gmail_message_id, :gmail_thread_id,
                    :supports_preview, :is_embedded
    private :date, :addresses, :message_id, :date_indexed, :date_received,
            :is_tnef_part, :is_embedded, :personInfo

    def received_at
      @received_at ||= Time.at(date_received)
    end

    def indexed_at
      @indexed_at ||= Time.at(indexed_at)
    end

    def to
      addresses['to']
    end

    def from
      addresses['from']
    end

    def person_info
      personInfo
    end

    def tnef_part?
      !!is_tnef_part
    end

    def embedded?
      !!is_embedded
    end

    def content
      @content ||= api.raw_request(:get, "#{resource_url}/content")
    end

    def content_link
      @content_link ||= api.raw_request(:get, "#{resource_url}/content", as_link: 1)
    end

    def related_files
      return @related_files if @related_files

      attribute_hashes = api.request(:get, "#{resource_url}/related")

      @related_files = FileCollection.new(api, attribute_hashes: attribute_hashes, account: account)

      return @related_files
    end

    def revisions
      return @revisions if @revisions

      attribute_hashes = api.request(:get, "#{resource_url}/revisions")

      @revisions = FileCollection.new(api, attribute_hashes: attribute_hashes, account: account)

      return @revisions
    end

  end
end


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Sends Braille commands to the Braille API.
 */

goog.provide('cvox.BrailleBackground');

goog.require('cvox.AbstractBraille');
goog.require('cvox.BrailleDisplayManager');
goog.require('cvox.BrailleInputHandler');
goog.require('cvox.BrailleKeyEvent');
goog.require('cvox.BrailleTable');
goog.require('cvox.ChromeVox');
goog.require('cvox.LibLouis');

/**
 * @constructor
 * @param {cvox.BrailleDisplayManager=} opt_displayManagerForTest
 *        Display manager (for mocking in tests).
 * @param {cvox.BrailleInputHandler=} opt_inputHandlerForTest Input handler
 *        (for mocking in tests).
 * @extends {cvox.AbstractBraille}
 */
cvox.BrailleBackground = function(opt_displayManagerForTest,
                                  opt_inputHandlerForTest) {
  goog.base(this);
  /**
   * @type {cvox.BrailleDisplayManager}
   * @private
   */
  this.displayManager_ = opt_displayManagerForTest ||
      new cvox.BrailleDisplayManager();
  cvox.BrailleTable.getAll(goog.bind(function(tables) {
    /**
     * @type {!Array.<cvox.BrailleTable.Table>}
     * @private
     */
    this.tables_ = tables;
    this.initialize_(0);
  }, this));
  this.displayManager_.setCommandListener(
      goog.bind(this.onBrailleKeyEvent_, this));
  /**
   * @type {cvox.NavBraille}
   * @private
   */
  this.lastContent_ = null;
  /**
   * @type {?string}
   * @private
   */
  this.lastContentId_ = null;
  /**
   * @type {!cvox.BrailleInputHandler}
   * @private
   */
  this.inputHandler_ = opt_inputHandlerForTest ||
      new cvox.BrailleInputHandler();
  this.inputHandler_.init();
};
goog.inherits(cvox.BrailleBackground, cvox.AbstractBraille);

/** @override */
cvox.BrailleBackground.prototype.write = function(params) {
  this.lastContentId_ = null;
  this.lastContent_ = null;
  this.inputHandler_.onDisplayContentChanged(params.text);
  this.displayManager_.setContent(
      params, this.inputHandler_.getExpansionType());
};

/** @override */
cvox.BrailleBackground.prototype.setCommandListener = function(func) {
  // TODO(plundblad): Implement when the background page handles commands
  // as well.
};

/**
 * Refreshes the braille translator used for output.  This should be
 * called when something changed (such as a preference) to make sure that
 * the correct translator is used.
 */
cvox.BrailleBackground.prototype.refreshTranslator = function() {
  if (!this.liblouis_) {
    return;
  }
  // First, see if we have a braille table set previously.
  var tables = this.tables_;
  var table = cvox.BrailleTable.forId(tables, localStorage['brailleTable']);
  if (!table) {
    // Match table against current locale.
    var currentLocale = chrome.i18n.getMessage('@@ui_locale').split(/[_-]/);
    var major = currentLocale[0];
    var minor = currentLocale[1];
    var firstPass = tables.filter(function(table) {
      return table.locale.split(/[_-]/)[0] == major;
    });
    if (firstPass.length > 0) {
      table = firstPass[0];
      if (minor) {
        var secondPass = firstPass.filter(function(table) {
          return table.locale.split(/[_-]/)[1] == minor;
        });
        if (secondPass.length > 0) {
          table = secondPass[0];
        }
      }
    }
  }
  if (!table) {
    table = cvox.BrailleTable.forId(tables, 'en-US-comp8');
  }
  // TODO(plundblad): ONly update when user explicitly chooses a table
  // so that switching locales changes table by default.
  localStorage['brailleTable'] = table.id;
  if (table.dots == '6') {
    localStorage['brailleTableType'] = 'brailleTable6';
    localStorage['brailleTable6'] = table.id;
  } else {
    localStorage['brailleTableType'] = 'brailleTable8';
    localStorage['brailleTable8'] = table.id;
  }

  // Initialize all other defaults.
  // TODO(plundblad): Stop doing this here.
  if (!localStorage['brailleTable6']) {
    localStorage['brailleTable6'] = 'en-US-g1';
  }
  if (!localStorage['brailleTable8']) {
    localStorage['brailleTable8'] = 'en-US-comp8';
  }

  // If the user explicitly set an 8 dot table, use that when looking
  // for an uncontracted table.  Otherwise, use the current table and let
  // getUncontracted find an appropriate corresponding table.
  var table8Dot = cvox.BrailleTable.forId(tables,
                                          localStorage['brailleTable8']);
  var uncontractedTable = cvox.BrailleTable.getUncontracted(
      tables,
      table8Dot ? table8Dot : table);
  this.liblouis_.getTranslator(table.fileNames, goog.bind(
      function(translator) {
        if (uncontractedTable.id === table.id) {
          this.displayManager_.setTranslator(translator);
          this.inputHandler_.setTranslator(translator);
        } else {
          this.liblouis_.getTranslator(uncontractedTable.fileNames, goog.bind(
              function(uncontractedTranslator) {
                this.displayManager_.setTranslator(
                    translator, uncontractedTranslator);
                this.inputHandler_.setTranslator(
                    translator, uncontractedTranslator);
              }, this));
        }
      }, this));
};

/**
 * Called when a Braille message is received from a page content script.
 * @param {Object} msg The Braille message.
 */
cvox.BrailleBackground.prototype.onBrailleMessage = function(msg) {
  if (msg['action'] == 'write') {
    this.lastContentId_ = msg['contentId'];
    this.lastContent_ = cvox.NavBraille.fromJson(msg['params']);
    this.inputHandler_.onDisplayContentChanged(this.lastContent_.text);
    this.displayManager_.setContent(
        this.lastContent_, this.inputHandler_.getExpansionType());
  }
};

/**
 * @return {cvox.LibLouis} The liblouis instance used by this object, or null
 * if not initialized yet.
 */
cvox.BrailleBackground.prototype.getLibLouisForTest = function() {
  return this.liblouis_;
};

/**
 * Initialization to be done after part of the background page's DOM has been
 * constructed. Currently only used on ChromeOS.
 * @param {number} retries Number of retries.
 * @private
 */
cvox.BrailleBackground.prototype.initialize_ = function(retries) {
  if (retries > 5) {
    console.error(
        'Timeout waiting for document.body; not initializing braille.');
    return;
  }
  if (!document.body) {
    window.setTimeout(goog.bind(this.initialize_, this, ++retries), 500);
  } else {
    /**
     * @type {cvox.LibLouis}
     * @private
     */
    this.liblouis_ = new cvox.LibLouis(
        chrome.extension.getURL(
            'chromevox/background/braille/liblouis_nacl.nmf'),
        chrome.extension.getURL(
            'chromevox/background/braille/tables'));
    this.liblouis_.attachToElement(document.body);
    this.refreshTranslator();
  }
};

/**
 * Handles braille key events by dispatching either to the input handler or
 * a content script.
 * @param {!cvox.BrailleKeyEvent} brailleEvt The event.
 * @param {cvox.NavBraille} content Content of display when event fired.
 * @private
 */
cvox.BrailleBackground.prototype.onBrailleKeyEvent_ = function(
    brailleEvt, content) {
  if (this.inputHandler_.onBrailleKeyEvent(brailleEvt)) {
    return;
  }
  this.sendCommand_(brailleEvt, content);
};

/**
 * Dispatches braille input commands to the content script.
 * @param {!cvox.BrailleKeyEvent} brailleEvt The event.
 * @param {cvox.NavBraille} content Content of display when event fired.
 * @private
 */
cvox.BrailleBackground.prototype.sendCommand_ =
    function(brailleEvt, content) {
  var msg = {
    'message': 'BRAILLE',
    'args': brailleEvt
  };
  if (content === this.lastContent_) {
    msg.contentId = this.lastContentId_;
  }
  cvox.ExtensionBridge.send(msg);
};


text:
//---THIS FILE WAS AUTOMATICALLY GENERATED.  DO NOT EDIT---//

//To change this file, alter the niftools/docsys/gen_niflib.py Python script.

#include "../../include/gen/ArkTexture.h"
#include "../../include/obj/NiTexturingProperty.h"
using namespace Niflib;

//Constructor
ArkTexture::ArkTexture() : unknownInt3((int)0), unknownInt4((int)0), texturingProperty(NULL) {};

//Copy Constructor
ArkTexture::ArkTexture( const ArkTexture & src ) {
	*this = src;
};

//Copy Operator
ArkTexture & ArkTexture::operator=( const ArkTexture & src ) {
	this->textureName = src.textureName;
	this->unknownInt3 = src.unknownInt3;
	this->unknownInt4 = src.unknownInt4;
	this->texturingProperty = src.texturingProperty;
	this->unknownBytes = src.unknownBytes;
	return *this;
};

//Destructor
ArkTexture::~ArkTexture() {};

//--BEGIN MISC CUSTOM CODE--//
//--END CUSTOM CODE--//


text:
require 'descriptive_statistics'

class Account
  include Mongoid::Document
  include Mongoid::Timestamps

  field :used

  field :is_master

  field :login

  has_many :snapshots

  has_many :account_snapshot_clusters, dependent: :destroy

  @recommendation_snapshots = []
  @product_snapshots = []

  # creates class methods to access snapshots
  # and cluster relationships
  items = %w(ad email product recommendation)
  items.map do |item|
    sn_name = "#{item}_snapshot"
    define_method(sn_name.pluralize) { snapshots.where(_type: sn_name.classify) }
    rel_name = "account_#{item}"
    define_method(rel_name.pluralize) { account_snapshot_clusters.where(_type: rel_name.classify) }
  end

  def self.get_amazon_accounts
    ps_label = "ps"
    rs_label = "rs"
    ret_accounts = Hash.new()

    Mongoid.with_tenant("amazon-1") do
      ProductSnapshot.each do |ps|
        acc = ps.account
        if !ret_accounts.include?(acc)
          ret_accounts[acc] = Hash.new()
          ret_accounts[acc][ps_label] = Set.new()
          ret_accounts[acc][rs_label] = Set.new()
        end
        ret_accounts[acc][ps_label].add(ps)
      end
      RecommendationSnapshot.each do |rs|
        acc = rs.account
        if !ret_accounts.include?(acc)
          ret_accounts[acc] = Hash.new()
          ret_accounts[acc][ps_label] = Set.new()
          ret_accounts[acc][rs_label] = Set.new()
        end
        ret_accounts[acc][rs_label].add(rs)
      end
    end
    return ret_accounts
  end

  def self.write_amazon_acc_data(datapath, amazon_accs)
    acc_data = []
    amazon_accs.keys().each do |acc|
      acc_id = acc.id
      ps_count = amazon_accs[acc]["ps"].length
      rs_count = amazon_accs[acc]["rs"].length
      acc_data.push([acc_id, ps_count, rs_count].join(" "))
    end
    data_file = File.open(datapath, "w")
    data_file.write(acc_data.join("\n"))
    data_file.close()

  end

  def self.write_amazon_statistics(datapath, amazon_accs)
    rec_prod = Hash.new()
    amazon_accs.keys().each do |acc|
      ps_count = amazon_accs[acc]["ps"].length
      rs_count = amazon_accs[acc]["rs"].length
      if !rec_prod.include?(ps_count)
        rec_prod[ps_count] = []
      end
      rec_prod[ps_count].push(rs_count)
    end

    stat_data = ["count min q1 median q3 max"]
    rec_prod.keys().each do |ps_count|
      desc_stats = rec_prod[ps_count].descriptive_statistics
      data_line = "#{ps_count} #{desc_stats[:min]} #{desc_stats[:q1]} #{desc_stats[:median]} #{desc_stats[:q3]} #{desc_stats[:max]}"
      stat_data.push(data_line)
    end
    puts stat_data
    data_file = File.open(datapath, "w")
    data_file.write(stat_data.join("\n"))
    data_file.close()

  end

  def self.write_amazon_account_data(pathname=File.join(Rails.root, "data/amazon"))
    xy_filename = "amazon_acc.dat"
    stats_filename = "amazon_acc_stats.dat"
    amazon_accs = Account.get_amazon_accounts

    write_amazon_acc_data(File.join(pathname, xy_filename), amazon_accs)
    write_amazon_statistics(File.join(pathname, stats_filename), amazon_accs)
  end

  def self.get_wish_list_permuations
    combinations = Hash.new()
    amazon_accs = get_amazon_accounts()

    amazon_accs.keys().each do |acc|
      ps_ids = amazon_accs[acc]["ps"].collect{|x| x._id}.sort()
      if !combinations.include?(ps_ids.length)
        combinations[ps_ids.length] = Set.new()
      end
      combinations[ps_ids.length].add(Set.new(ps_ids))
      puts ps_ids
    end
    return combinations
  end

  def get_product_snapshots()
    p_snaps = []
      snapshots.each do |snap|
        if snap.class == ProductSnapshot
          p_snaps.push(snap)
        end
      end
      return p_snaps
  end

  def get_recommendation_snapshots()
    if @recommendation_snapshots == nil || @recommendation_snapshots.length == 0
      @recommendation_snapshots = []
      snapshots.each do |snap|
        if snap.class == RecommendationSnapshot
          @recommendation_snapshots.push(snap)
        end
      end
    end
    return @recommendation_snapshots
  end

  def reset_snapshot_caches()
    @recommendation_snapshots = []
    @product_snapshots = []
  end

  def has_cluster?(cluster_id)
    AccountSnapshotCluster.where( account: self, snapshot_cluster_id: cluster_id ).count > 0
  end

  def self.master_account
    exp = Experiment.where( :name => Mongoid.tenant_name ).first
    if exp == nil
      Account.where(:is_master => true).first
    else
    Account.where( id: exp.master_account ).first
    end
  end
end


text:
package com.badlogicgames.gdx.tests;

import com.badlogic.gdx.backends.iosmoe.IOSApplication;
import com.badlogic.gdx.backends.iosmoe.IOSApplicationConfiguration;
import com.badlogic.gdx.tests.*;
import org.moe.natj.general.Pointer;

import apple.uikit.c.UIKit;

public class IOSTests extends IOSApplication.Delegate {

	protected IOSTests(Pointer peer) {
		super(peer);
	}

	@Override
	protected IOSApplication createApplication() {
		IOSApplicationConfiguration config = new  IOSApplicationConfiguration();
		config.useAccelerometer = false;
		config.useGL30 = false;
		return new IOSApplication(new SpriteBatchTest(), config);
	}

	public static void main(String[] argv) {
		UIKit.UIApplicationMain(0, null, null, IOSTests.class.getName());
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:propertyName="pathData"
    android:valueFrom="
    M 20,80
    L 50, 80 80, 80
    "
    android:valueTo="
    M 20,80
    L 50, 50 80, 80
    "
    android:valueType="pathType"
    android:interpolator="@android:anim/bounce_interpolator">

</objectAnimator>


text:
const Electron = require('electron');
const Window = require('./Window.js');

// Module to control application life.
const app = Electron.app;

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', Window.onReady);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (Window.isNull()) {
    Window.create();
  }
});


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Leptoglossum pezizaeforme Velen.

### Remarks
null


text:
import sys

#Only really old versions of Python don't have sys.hexversion. We don't support
#them. The logging module was introduced in Python 2.3
if not hasattr(sys, 'hexversion') or sys.hexversion < 0x20300F0:
    sys.stdout.write('Python version: ' + sys.version)
    sys.stdout.write('PyBitmessage requires Python 2.7.3 or greater (but not Python 3)')
    sys.exit()

#We can now use logging so set up a simple configuration
import logging
formatter = logging.Formatter(
    '%(levelname)s: %(message)s'
)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.ERROR)

#We need to check hashlib for RIPEMD-160, as it won't be available if OpenSSL is
#not linked against or the linked OpenSSL has RIPEMD disabled.
def check_hashlib():
    if sys.hexversion < 0x020500F0:
        logger.error('The hashlib module is not included in this version of Python.')
        return False
    import hashlib
    if '_hashlib' not in hashlib.__dict__:
        logger.error('The RIPEMD-160 hash algorithm is not available. The hashlib module is not linked against OpenSSL.')
        return False
    try:
        hashlib.new('ripemd160')
    except ValueError:
        logger.error('The RIPEMD-160 hash algorithm is not available. The hashlib module utilizes an OpenSSL library with RIPEMD disabled.')
        return False
    return True

def check_sqlite():
    if sys.hexversion < 0x020500F0:
        logger.error('The sqlite3 module is not included in this version of Python.')
        return False
    try:
        import sqlite3
    except ImportError:
        logger.error('The sqlite3 module is not available')
        return False

    logger.info('sqlite3 Module Version: ' + sqlite3.version)
    logger.info('SQLite Library Version: ' + sqlite3.sqlite_version)
    #sqlite_version_number formula: https://sqlite.org/c3ref/c_source_id.html
    sqlite_version_number = sqlite3.sqlite_version_info[0] * 1000000 + sqlite3.sqlite_version_info[1] * 1000 + sqlite3.sqlite_version_info[2]

    conn = None
    try:
        try:
            conn = sqlite3.connect(':memory:')
            if sqlite_version_number >= 3006018:
                sqlite_source_id = conn.execute('SELECT sqlite_source_id();').fetchone()[0]
                logger.info('SQLite Library Source ID: ' + sqlite_source_id)
            if sqlite_version_number >= 3006023:
                compile_options = ', '.join(map(lambda row: row[0], conn.execute('PRAGMA compile_options;')))
                logger.info('SQLite Library Compile Options: ' + compile_options)
            #There is no specific version requirement as yet, so we just use the
            #first version that was included with Python.
            if sqlite_version_number < 3000008:
                logger.error('This version of SQLite is too old. PyBitmessage requires SQLite 3.0.8 or later')
                return False
            return True
        except sqlite3.Error:
            logger.exception('An exception occured while checking sqlite.')
            return False
    finally:
        if conn:
            conn.close()

def check_openssl():
    try:
        import ctypes
    except ImportError:
        logger.error('Unable to check OpenSSL. The ctypes module is not available.')
        return False

    #We need to emulate the way PyElliptic searches for OpenSSL.
    if sys.platform == 'win32':
        paths = ['libeay32.dll']
        if getattr(sys, 'frozen', False):
            import os.path
            paths.insert(0, os.path.join(sys._MEIPASS, 'libeay32.dll'))
    else:
        paths = ['libcrypto.so']
    if sys.platform == 'darwin':
        paths.extend([
            'libcrypto.dylib',
            '/usr/local/opt/openssl/lib/libcrypto.dylib',
            './../Frameworks/libcrypto.dylib'
        ])
    import re
    if re.match(r'linux|darwin|freebsd', sys.platform):
        try:
            import ctypes.util
            path = ctypes.util.find_library('ssl')
            if path not in paths:
                paths.append(path)
        except:
            pass

    SSLEAY_VERSION = 0
    SSLEAY_CFLAGS = 2

    cflags_regex = re.compile(r'(?:OPENSSL_NO_)(AES|EC|ECDH|ECDSA)(?!\w)')

    for path in paths:
        logger.info('Checking OpenSSL at ' + path)
        try:
            library = ctypes.CDLL(path)
        except OSError:
            continue
        logger.info('OpenSSL Name: ' + library._name)
        try:
            library.SSLeay.restype = ctypes.c_long
            library.SSLeay_version.restype = ctypes.c_char_p
            library.SSLeay_version.argtypes = [ctypes.c_int]
        except AttributeError:
            logger.error('Cannot determine version of this OpenSSL library.')
            return False
        logger.info('OpenSSL Version: ' + library.SSLeay_version(SSLEAY_VERSION))
        compile_options = library.SSLeay_version(SSLEAY_CFLAGS)
        logger.info('OpenSSL Compile Options: ' + compile_options)
        openssl_hexversion = library.SSLeay()
        #PyElliptic uses EVP_CIPHER_CTX_new and EVP_CIPHER_CTX_free which were
        #introduced in 0.9.8b.
        if openssl_hexversion < 0x90802F:
            logger.error('This OpenSSL library is too old. PyBitmessage requires OpenSSL 0.9.8b or later with AES, Elliptic Curves (EC), ECDH, and ECDSA enabled.')
            return False
        matches = cflags_regex.findall(compile_options)
        if len(matches) > 0:
            logger.error('This OpenSSL library is missing the following required features: ' + ', '.join(matches) + '. PyBitmessage requires OpenSSL 0.9.8b or later with AES, Elliptic Curves (EC), ECDH, and ECDSA enabled.')
            return False
        return True
    return False

#TODO: The minimum versions of pythondialog and dialog need to be determined
def check_curses():
    if sys.hexversion < 0x20600F0:
        logger.error('The curses interface requires the pythondialog package and the dialog utility.')
        return False
    try:
        import curses
    except ImportError:
        logger.error('The curses interface can not be used. The curses module is not available.')
        return False
    logger.info('curses Module Version: ' + curses.version)
    try:
        import dialog
    except ImportError:
        logger.error('The curses interface can not be used. The pythondialog package is not available.')
        return False
    logger.info('pythondialog Package Version: ' + dialog.__version__)
    dialog_util_version = dialog.Dialog().cached_backend_version
    #The pythondialog author does not like Python2 str, so we have to use
    #unicode for just the version otherwise we get the repr form which includes
    #the module and class names along with the actual version.
    logger.info('dialog Utility Version' + unicode(dialog_util_version))
    return True

def check_pyqt():
    try:
        import PyQt4.QtCore
    except ImportError:
        logger.error('The PyQt4 package is not available. PyBitmessage requires PyQt 4.8 or later and Qt 4.7 or later.')
        return False
    logger.info('PyQt Version: ' + PyQt4.QtCore.PYQT_VERSION_STR)
    logger.info('Qt Version: ' + PyQt4.QtCore.QT_VERSION_STR)
    passed = True
    if PyQt4.QtCore.PYQT_VERSION < 0x40800:
        logger.error('This version of PyQt is too old. PyBitmessage requries PyQt 4.8 or later.')
        passed = False
    if PyQt4.QtCore.QT_VERSION < 0x40700:
        logger.error('This version of Qt is too old. PyBitmessage requries Qt 4.7 or later.')
        passed = False
    return passed

def check_dependencies(verbose = False, optional = False):
    if verbose:
        logger.setLevel(logging.INFO)

    has_all_dependencies = True

    #Python 2.7.3 is the required minimum. Python 3+ is not supported, but it is
    #still useful to provide information about our other requirements.
    logger.info('Python version: %s', sys.version)
    if sys.hexversion < 0x20703F0:
        logger.error('PyBitmessage requires Python 2.7.3 or greater (but not Python 3+)')
        has_all_dependencies = False
    if sys.hexversion >= 0x3000000:
        logger.error('PyBitmessage does not support Python 3+. Python 2.7.3 or greater is required.')
        has_all_dependencies = False

    check_functions = [check_hashlib, check_sqlite, check_openssl]
    if optional:
        check_functions.extend([check_pyqt, check_curses])

    #Unexpected exceptions are handled here
    for check in check_functions:
        try:
            has_all_dependencies &= check()
        except:
            logger.exception(check.__name__ + ' failed unexpectedly.')
            has_all_dependencies = False

    if not has_all_dependencies:
        logger.critical('PyBitmessage cannot start. One or more dependencies are unavailable.')
        sys.exit()

if __name__ == '__main__':
    check_dependencies(True, True)


text:
using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]
public class MicrophoneInput : MonoBehaviour
{
    public float sensitivity = 100;
    public float loudness = 0;

    void Start()
    {
        GetComponent<AudioSource>().clip = Microphone.Start(null, true, 2, 44100);
        GetComponent<AudioSource>().loop = true; // Set the AudioClip to loop
        GetComponent<AudioSource>().mute = true; // Mute the sound, we don't want the player to hear it
                                                 // while (!(Microphone.GetPosition<AudioSource>() > 0)) { } // Wait until the recording has started

        GetComponent<AudioSource>().Play(); // Play the audio source!
    }

    void Update()
    {
        loudness = GetAveragedVolume() * sensitivity;
    }

    float GetAveragedVolume()
    {
        float[] data = new float[256];
        float a = 0;
        GetComponent<AudioSource>().GetOutputData(data, 0);
        foreach (float s in data)
        {
            a += Mathf.Abs(s);
        }
        return a / 256;
    }
}


text:
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from proxy import *
from version import *
from local import *
from base import *


text:
package io.github.ratismal.felineutilities.client.core.proxy;

import cpw.mods.fml.client.registry.RenderingRegistry;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import io.github.ratismal.felineutilities.client.render.RenderEyePlunder;
import io.github.ratismal.felineutilities.common.entity.EntityEyePlunder;
import io.github.ratismal.felineutilities.common.core.proxy.CommonProxy;

public class ClientProxy extends CommonProxy {

    @Override
    public void preInit(FMLPreInitializationEvent event) {
        super.preInit(event);
    }

    @Override
    public void init(FMLInitializationEvent event) {
        super.init(event);
        registerRendering();
    }

    @Override
    public void postInit(FMLPostInitializationEvent event) {
        super.postInit(event);

    }

    public void registerRendering() {

        RenderingRegistry.registerEntityRenderingHandler(EntityEyePlunder.class, new RenderEyePlunder());

    }
}


text:
/* eslint-disable-next-line no-unused-vars */
import { Component, ChangeDetectionStrategy, Input } from '@angular/core'

@Component({
  inputs: ['subCompObj'],
  selector: 'sub-component',
  template: `

            {{subCompObj.name}}

{{subCompObj.name}} details!

id: {{subCompObj.id}}

freq: {{subCompObj.freq}}

    `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TestSubComponent {
  @Input()
  subCompObj: any

  name: string = 'TestSubComponent'
  constructor() {}
}


text:
```bash
docker build -t ponylang/ponyc-ci:openssl-1.1.0 .
```

# Run image to test

Will get you a bash shell in the image to try cloning Pony into where you can test a build to make sure everything will work before pushing

```bash
docker run --name ponyc-ci-openssl-110 --rm -i -t ponylang/ponyc-ci:openssl-1.1.0 bash
```

# Push to dockerhub

You'll need credentials for the ponylang dockerhub account. Talk to @jemc or @seantallen for access

```bash
docker push ponylang/ponyc-ci:openssl-1.1.0
```


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JohnLambe.Util.MathUtilities
{
    public static class FloatingPointUtil
    {
        /// <summary>
        /// Return the number of digits in a number.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="radix"></param>
        /// <returns>The number of digits in the number before the (decimal) point. Always positive.</returns>
        public static int NumberOfDigits(decimal value, int radix = 10)
        {
            decimal maxValue = Decimal.MaxValue / radix;
            value = System.Math.Abs(value);
            decimal digitValue = radix;
            int digits = 1;
            while (digitValue < maxValue)
            {
                if (value < digitValue)
                    return digits;
                digits++;
                digitValue *= radix;
            }
            return digits;
        }

        /// <summary>
        /// Returns the number of digits in a number after the (decimal) point.
        /// </summary>
        /// <param name="value"></param>
        /// <param name="radix"></param>
        /// <returns></returns>
        public static int FractionNumberOfDigits(decimal value, int radix = 10)
        {
            decimal maxValue = Decimal.MaxValue / radix;
            value = System.Math.Abs(value);
            decimal digitValue = radix;
            int digits = 1;
            while (digitValue < maxValue)
            {
                if (value < digitValue)
                    return digits;
                digits++;
                digitValue *= radix;
            }
            return digits;
        }

    }
}


text:
package org.colorcoding.tools.btulz.bobas.transformer;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.colorcoding.tools.btulz.Environment;

/**
 * 业务对象类型加载器
 *
 * @author manager
 *
 */
public class ClassLoader4Transformer extends URLClassLoader {

	public ClassLoader4Transformer(URL[] urls, ClassLoader parent) {
		super(urls, parent);
	}

	public ClassLoader4Transformer(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
		super(urls, parent, factory);
	}

	public ClassLoader4Transformer(URL[] urls) {
		super(urls);
	}

	public Iterable<String> getClassNames() {
		return new Iterable<String>() {

			@Override
			public Iterator<String> iterator() {
				return new Iterator<String>() {
					/**
					 * 类库文件的迭代器
					 */
					private Iterator<URL> urlIterator = new Iterator<URL>() {
						int index = 0;

						@Override
						public boolean hasNext() {
							if (index < getURLs().length) {
								return true;
							}
							return false;
						}

						@Override
						public URL next() {
							URL item = getURLs()[index];
							index++;
							return item;
						}
					};

					private Iterator<String> classNameIterator;

					@Override
					public boolean hasNext() {
						if (this.classNameIterator != null) {
							if (this.classNameIterator.hasNext()) {
								return true;
							}
						}
						if (this.urlIterator.hasNext()) {
							return true;
						}
						return false;
					}

					@Override
					public String next() {
						if (this.classNameIterator != null && this.classNameIterator.hasNext()) {
							return this.classNameIterator.next();
						} else {
							try {
								while (this.urlIterator.hasNext()) {
									ArrayList<String> classNames = new ArrayList<>();
									URL url = this.urlIterator.next();
									File file = new File(java.net.URLDecoder.decode(url.getPath(), "UTF-8"));
									if (file.getName().endsWith(".jar")) {
										JarFile jarFile = new JarFile(file);
										Enumeration<JarEntry> jarEntries = jarFile.entries();
										if (jarEntries != null) {
											while (jarEntries.hasMoreElements()) {
												JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
												if (jarEntry.isDirectory()) {
													continue;
												}
												if (jarEntry.getName().toLowerCase().endsWith(".class")) {
													String name = jarEntry.getName().replace("/", ".");
													name = name.replace(".class", "");
													classNames.add(name);
												}
											}
										}
										jarFile.close();
									}
									this.classNameIterator = classNames.iterator();
									return this.next();
								}
							} catch (Exception e) {
								throw new RuntimeException(e);
							}
						}
						return null;
					}

				};
			}
		};
	}

	protected Class<?> defineClass(String name, InputStream inputStream)
			throws IOException, ClassFormatError, NoClassDefFoundError, ClassNotFoundException {
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		int data = inputStream.read();
		while (data != -1) {
			buffer.write(data);
			data = inputStream.read();
		}
		byte[] bytes = buffer.toByteArray();
		inputStream.close();
		return this.defineClass(name, bytes, 0, bytes.length);
	}

	@Override
	public Class<?> findClass(String name) throws ClassNotFoundException {
		// 首先,查看是否已经加载
		Class<?> type = this.findLoadedClass(name);
		if (type != null) {
			return type;
		}
		try {
			// 父项加载失败,子项加载
			Environment.getLogger().debug(String.format("to find %s by %s.", name, this.getClass().getSimpleName()));
			return super.findClass(name);
		} catch (ClassNotFoundException e) {
			// 没有加载,尝试父项加载
			Environment.getLogger()
					.debug(String.format("to find %s by %s.", name, this.getParent().getClass().getSimpleName()));
			return this.getParent().loadClass(name);
		}
	}
}


text:
package de.neofonie.cinderella.core.config.xml.condition;

import de.neofonie.cinderella.core.RequestUtil;
import de.neofonie.cinderella.core.config.util.PatternTypeAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import java.util.regex.Pattern;

@XmlAccessorType(XmlAccessType.FIELD)
public class HostNameCondition implements Condition {

    @XmlValue
    @NotNull
    @XmlJavaTypeAdapter(PatternTypeAdapter.class)
    private Pattern regex;

    @XmlAttribute(required = false)
    private Boolean ignoreForwardDnsLookup = false;

    @Override
    public boolean matches(HttpServletRequest request) {

        final String hostName = RequestUtil.getHostName(request, ignoreForwardDnsLookup);
        if (hostName == null) {
            return regex.matcher("").find();
        }
        return regex.matcher(hostName).find();
    }

    public Pattern getRegex() {
        return regex;
    }

    public void setRegex(Pattern regex) {
        this.regex = regex;
    }

    public Boolean getIgnoreForwardDnsLookup() {
        return ignoreForwardDnsLookup;
    }

    public void setIgnoreForwardDnsLookup(Boolean ignoreForwardDnsLookup) {
        this.ignoreForwardDnsLookup = ignoreForwardDnsLookup;
    }
}


text:
package com.polidea.hierarchyviewer.internal.model.view;

import android.view.View;
import android.widget.TextView;
import com.google.gson.annotations.SerializedName;
import com.polidea.hierarchyviewer.internal.logic.ConvertersContainer;

public class TextViewModelInfo extends ViewModelInfo {
    interface Metadata {
        String TEXT = "text";
    }

    @SerializedName(Metadata.TEXT)
    String text;

    @Override
    public void setDataFromView(View view, ConvertersContainer convertersContainer) {
        super.setDataFromView(view, convertersContainer);
        TextView textView = (TextView) view;
        text = textView.getText().toString();
    }
}


text:
package parser_test

import (
	_ "embed"
	iofs "io/fs"
	"os"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"sigs.k8s.io/kustomize/kyaml/fn/framework/parser"
)

//go:embed testdata/schema1.json
var schema1String string

//go:embed testdata/schema2.json
var schema2String string

func TestSchemaFiles(t *testing.T) {
	tests := []struct {
		name          string
		paths         []string
		fs            iofs.FS
		expectedCount int
		wantErr       string
	}{
		{
			name:          "parses schema from file",
			paths:         []string{"testdata/schema1.json"},
			expectedCount: 1,
		},
		{
			name:          "accepts multiple inputs",
			paths:         []string{"testdata/schema1.json", "testdata/schema2.json"},
			expectedCount: 2,
		},
		{
			name:          "parses templates from directory",
			paths:         []string{"testdata"},
			expectedCount: 2,
		},
		{
			name:          "can be configured with an alternative FS",
			fs:            os.DirFS("testdata"), // changes the root of the input paths
			paths:         []string{"schema1.json"},
			expectedCount: 1,
		},
		{
			name:    "rejects non-.template.yaml files",
			paths:   []string{"testdata/ignore.yaml"},
			wantErr: "file testdata/ignore.yaml does not have any of permitted extensions [.json]",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			p := parser.SchemaFiles(tt.paths...)
			if tt.fs != nil {
				p = p.FromFS(tt.fs)
			}
			schemas, err := p.Parse()
			if tt.wantErr != "" {
				require.EqualError(t, err, tt.wantErr)
				return
			}
			require.NoError(t, err)
			assert.Equal(t, tt.expectedCount, len(schemas))
		})
	}
}

func TestSchemaStrings(t *testing.T) {
	tests := []struct {
		name          string
		data          []string
		expectedCount int
	}{
		{
			name:          "parses templates from strings",
			data:          []string{schema1String},
			expectedCount: 1,
		},
		{
			name:          "accepts multiple inputs",
			data:          []string{schema1String, schema2String},
			expectedCount: 2,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			p := parser.SchemaStrings(tt.data...)
			schemas, err := p.Parse()
			require.NoError(t, err)
			assert.Equal(t, tt.expectedCount, len(schemas))
		})
	}
}


text:
package lila.tournament

import org.joda.time.DateTime
import reactivemongo.bson._
import reactivemongo.core.commands._

import BSONHandlers._
import lila.db.BSON._
import lila.db.Implicits._
import lila.rating.Perf
import lila.user.{ User, Perfs }

object PlayerRepo {

  private lazy val coll = Env.current.playerColl

  private def selectId(id: String) = BSONDocument("_id" -> id)
  private def selectTour(tourId: String) = BSONDocument("tid" -> tourId)
  private def selectUser(userId: String) = BSONDocument("uid" -> userId)
  private def selectTourUser(tourId: String, userId: String) = BSONDocument(
    "tid" -> tourId,
    "uid" -> userId)
  private val selectActive = BSONDocument("w" -> BSONDocument("$ne" -> true))
  private val selectWithdraw = BSONDocument("w" -> true)
  private val bestSort = BSONDocument("m" -> -1)

  def byId(id: String): Fu[Option[Player]] = coll.find(selectId(id)).one[Player]

  def bestByTour(tourId: String, nb: Int, skip: Int = 0): Fu[List[Player]] =
    coll.find(selectTour(tourId)).sort(bestSort).skip(skip).cursor[Player]().collect[List](nb)

  def bestByTourWithRank(tourId: String, nb: Int, skip: Int = 0): Fu[RankedPlayers] =
    bestByTour(tourId, nb, skip).map { res =>
      res.foldRight(List.empty[RankedPlayer] -> (res.size + skip)) {
        case (p, (res, rank)) => (RankedPlayer(rank, p) :: res, rank - 1)
      }._1
    }

  def bestByTourWithRankByPage(tourId: String, nb: Int, page: Int): Fu[RankedPlayers] =
    bestByTourWithRank(tourId, nb, (page - 1) * nb)

  def countActive(tourId: String): Fu[Int] =
    coll.count(Some(selectTour(tourId) ++ selectActive))

  def count(tourId: String): Fu[Int] = coll.count(Some(selectTour(tourId)))

  def removeByTour(tourId: String) = coll.remove(selectTour(tourId)).void

  def remove(tourId: String, userId: String) =
    coll.remove(selectTourUser(tourId, userId)).void

  def exists(tourId: String, userId: String) =
    coll.count(selectTourUser(tourId, userId).some) map (0!=)

  def existsActive(tourId: String, userId: String) =
    coll.count(Some(
      selectTourUser(tourId, userId) ++ selectActive
    )) map (0!=)

  def unWithdraw(tourId: String) = coll.update(
    selectTour(tourId) ++ selectWithdraw,
    BSONDocument("$unset" -> BSONDocument("w" -> true)),
    multi = true).void

  def find(tourId: String, userId: String): Fu[Option[Player]] =
    coll.find(selectTourUser(tourId, userId)).one[Player]

  def update(tourId: String, userId: String)(f: Player => Fu[Player]) =
    find(tourId, userId) flatten s"No such player: $tourId/$userId" flatMap f flatMap { player =>
      coll.update(selectId(player._id), player).void
    }

  def playerInfo(tourId: String, userId: String): Fu[Option[PlayerInfo]] = find(tourId, userId) flatMap {
    _ ?? { player =>
      coll.count(Some(selectTour(tourId) ++ BSONDocument(
        "m" -> BSONDocument("$gt" -> player.magicScore))
      )) map { n =>
        PlayerInfo((n + 1), player.withdraw).some
      }
    }
  }

  def join(tourId: String, user: User, perfLens: Perfs => Perf) =
    find(tourId, user.id) flatMap {
      case Some(p) if p.withdraw => coll.update(selectId(p._id), BSONDocument("$unset" -> BSONDocument("w" -> true)))
      case Some(p)               => funit
      case None                  => coll.insert(Player.make(tourId, user, perfLens))
    } void

  def withdraw(tourId: String, userId: String) = coll.update(
    selectTourUser(tourId, userId),
    BSONDocument("$set" -> BSONDocument("w" -> true))).void

  def withPoints(tourId: String): Fu[List[Player]] =
    coll.find(
      selectTour(tourId) ++ BSONDocument("m" -> BSONDocument("$gt" -> 0))
    ).cursor[Player]().collect[List]()

  private def aggregationUserIdList(res: Stream[BSONDocument]): List[String] =
    res.headOption flatMap { _.getAs[List[String]]("uids") } getOrElse Nil

  import coll.BatchCommands.AggregationFramework,
    AggregationFramework.{ Descending, Group, Match, Push, Sort }

  def userIds(tourId: String): Fu[List[String]] =
    coll.aggregate(Match(selectTour(tourId)), List(
      Group(BSONBoolean(true))("uids" -> Push("uid")))).
      map(res => aggregationUserIdList(res.documents.toStream))

  def activeUserIds(tourId: String): Fu[List[String]] =
    coll.aggregate(Match(selectTour(tourId) ++ selectActive), List(
      Group(BSONBoolean(true))("uids" -> Push("uid")))).
      map(res => aggregationUserIdList(res.documents.toStream))

  def winner(tourId: String): Fu[Option[Player]] =
    coll.find(selectTour(tourId)).sort(bestSort).one[Player]

  def ranking(tourId: String): Fu[Ranking] =
    coll.aggregate(Match(selectTour(tourId)), List(Sort(Descending("m")),
      Group(BSONBoolean(true))("uids" -> Push("uid")))).
      map(res => aggregationUserIdList(res.documents.toStream)).
      map { _.zipWithIndex.toMap }

  def byTourAndUserIds(tourId: String, userIds: Iterable[String]): Fu[List[Player]] =
    coll.find(selectTour(tourId) ++ BSONDocument(
      "uid" -> BSONDocument("$in" -> userIds)
    )).cursor[Player]().collect[List]()

  def rankPlayers(players: List[Player], ranking: Ranking): RankedPlayers =
    players.flatMap { p =>
      ranking get p.userId map { RankedPlayer(_, p) }
    }.sortBy(-_.rank)

  def rankedByTourAndUserIds(tourId: String, userIds: Iterable[String], ranking: Ranking): Fu[RankedPlayers] =
    byTourAndUserIds(tourId, userIds) map { rankPlayers(_, ranking) }
}


text:
import { alertConstants } from '../_constants';

export const alertActions = {
    success,
    error,
    clear
};

function success(message) {
    return { type: alertConstants.SUCCESS, message };
}

function error(message) {
    return { type: alertConstants.ERROR, message };
}

function clear() {
    return { type: alertConstants.CLEAR };
}


text:
__author__ = 'rolandh'

NAME = ["givenName", "displayName", "sn"]
STATIC_ORG_INFO = ["c", "o", "co", "norEduOrgAcronym", "schacHomeOrganization"]
OTHER = ["eduPersonPrincipalName", "eduPersonScopedAffiliation", "mail"]

# These give you access to information
RESEARCH_AND_EDUCATION = "http://www.swamid.se/category/research-and-education"
SFS_1993_1153 = "http://www.swamid.se/category/sfs-1993-1153"

# presently these don't by themself
EU = "http://www.swamid.se/category/eu-adequate-protection"
NREN = "http://www.swamid.se/category/nren-service"
HEI = "http://www.swamid.se/category/hei-service"

RELEASE = {
    "": ["eduPersonTargetedID"],
    SFS_1993_1153: ["norEduPersonNIN"],
    (RESEARCH_AND_EDUCATION, EU): NAME + STATIC_ORG_INFO + OTHER,
    (RESEARCH_AND_EDUCATION, NREN): NAME + STATIC_ORG_INFO + OTHER,
    (RESEARCH_AND_EDUCATION, HEI): NAME + STATIC_ORG_INFO + OTHER,
}


text:
package com.facebook.buck.util.versioncontrol;

import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.core.exceptions.HumanReadableException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * * Provides simplified access to settings from the version_control section of a .buckconfig file.
 *
 *
Available keys:
 *
 *
generate_statistics: - Enable or disable the generation of version control statistics -
 * Default value is false. - Currently only Mercurial is supported. hg_cmd: - Override the default
 * Mercurial command used when generating statistics. - Default value is hg
 *
 *
Example config section:
 *
 *
[version_control] hg_cmd = hg3 generate_statistics = true
 */
public class VersionControlBuckConfig {
  static final String VC_SECTION_KEY = "version_control";

  static final String GENERATE_STATISTICS_KEY = "generate_statistics";
  static final boolean GENERATE_STATISTICS_DEFAULT = false;

  static final String HG_CMD_SETTING_KEY = "hg_cmd";
  static final String HG_CMD_DEFAULT = "hg";

  static final String PREGENERATED_CURRENT_REVISION_ID = "pregenerated_current_revision_id";
  static final String PREGENERATED_BASE_BOOKMARKS = "pregenerated_base_bookmarks";
  static final String PREGENERATED_BASE_REVISION_ID = "pregenerated_base_revision_id";
  static final String PREGENERATED_BASE_REVISION_TIMESTAMP = "pregenerated_base_revision_timestamp";

  private final BuckConfig delegate;

  public VersionControlBuckConfig(BuckConfig delegate) {
    this.delegate = delegate;
  }

  public String getHgCmd() {
    return getValue(VC_SECTION_KEY, HG_CMD_SETTING_KEY, HG_CMD_DEFAULT);
  }

  public boolean shouldGenerateStatistics() {
    return delegate.getBooleanValue(
        VC_SECTION_KEY, GENERATE_STATISTICS_KEY, GENERATE_STATISTICS_DEFAULT);
  }

  public Optional<FastVersionControlStats> getPregeneratedVersionControlStats() {
    ImmutableSet<Optional<?>> stats =
        ImmutableSet.of(
            getPregeneratedCurrentRevisionId(),
            getPregeneratedBaseBookmarks(),
            getPregeneratedBaseRevisionId(),
            getPregeneratedBaseRevisionTimestamp());
    if (stats.stream().anyMatch(Optional::isPresent)) {
      if (!stats.stream().allMatch(Optional::isPresent)) {
        throw new HumanReadableException(
            "Specified some of the pregenerated version control stats in the configs, "
                + "but not all: "
                + Stream.of(
                        PREGENERATED_CURRENT_REVISION_ID,
                        PREGENERATED_BASE_BOOKMARKS,
                        PREGENERATED_BASE_REVISION_ID,
                        PREGENERATED_BASE_REVISION_TIMESTAMP)
                    .collect(Collectors.joining(", ")));
      }
      return Optional.of(
          FastVersionControlStats.of(
              getPregeneratedCurrentRevisionId().get(),
              getPregeneratedBaseBookmarks().get(),
              getPregeneratedBaseRevisionId().get(),
              getPregeneratedBaseRevisionTimestamp().get()));
    }
    return Optional.empty();
  }

  private Optional<String> getPregeneratedCurrentRevisionId() {
    return delegate.getValue(VC_SECTION_KEY, PREGENERATED_CURRENT_REVISION_ID);
  }

  private Optional<ImmutableList<String>> getPregeneratedBaseBookmarks() {
    return delegate.getOptionalListWithoutComments(VC_SECTION_KEY, PREGENERATED_BASE_BOOKMARKS);
  }

  private Optional<String> getPregeneratedBaseRevisionId() {
    return delegate.getValue(VC_SECTION_KEY, PREGENERATED_BASE_REVISION_ID);
  }

  private Optional<Long> getPregeneratedBaseRevisionTimestamp() {
    return delegate.getLong(VC_SECTION_KEY, PREGENERATED_BASE_REVISION_TIMESTAMP);
  }

  private String getValue(String section, String key, String defaultValue) {
    Optional<String> optionalValue = delegate.getValue(section, key);
    return optionalValue.orElse(defaultValue);
  }
}


text:
This is an application launcher, which is the mixing of command input and button selection.

You can grep from Miscellaneous list, picked up from the Start menu or the like.
Next, you can execute an item.

this software is suitable for people who come up with words at first, at the time starting the application,

## Forms

![Main Form](https://raw.githubusercontent.com/Rab-Duck/Mutter-Launcher.NET/master/doc/MainForm.png)

## Install and requirements

Download and unzip a MutterLauncherNet_x_x_x.zip file from [release page](https://github.com/Rab-Duck/Mutter-Launcher.NET/releases).
Set files to any folder.

It require .NET Framework 4.5(over 4.5.2 is better).
Windows Vista or later are supported.

## First step

1. When you start the MutterLauncherNet.exe, the icon appears in the task tray.
2. Shift+Space to open main form.
3. If you enter the character at the text box of the top of the form, You can search items by partial match search.
(Searched from Start menu, Desktop, Control panel, PATH, my favorites)
4. When you grep what you want to start, it is to select it using the up and down keys and to started by Enter.

## How to search

Default is partial match search(not case sensitive).
Using regulation charactor, you can use skip-matching, forward/backward/exact match.

example:
- "hoge" -> partial match search of "hoge" (equal to ".*hoge.*" Regex search)
- " hoge" → skip-matching of "hoge" (equal to ".\*h.\*o.\*g.\*e.\*" Regex search)
- "^hoge" → forward match search of "hoge" (equal to "^hoge.\*" Regex search)
- "hoge$" → backward match search of "hoge" (equal to ".\*hoge$" Regex search)
- "\hoge" → exact match search of "hoge" (equal to "^hoge$" Regex search)

## How to exec

- Enter -> Run
- Shift + Enter -> open folder
- ctrl + Enter -> Run as Admin

Double click in the List View is the same action of Enter.

## About User Item

## How to setting
![Setting Form](https://raw.githubusercontent.com/Rab-Duck/Mutter-Launcher.NET/master/doc/SettingForm.png)

## About Update List

## Uninstall

## Lisence

MIT License


text:
using System;
using System.Linq;
using Batcher.Tests.Data;
using Batcher.Tests.Data.Model;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Batcher.Tests.Tests
{
	[TestClass]
	public class DeleteTests
	{
		[TestMethod]
		public void TestDeleteMethod()
		{
			//ensure an unique id
			var uniqueId = Guid.NewGuid();

			var bigData = SqlStore.For<BigData>();

			BigData item = InsertTests.GetBigDataItems(1).First();
			item.UniqueID = uniqueId;

			using (var dbContext = new BatcherDbContext())
			{
				var query = Sql.Insert(bigData).Values(item).Output();
				item = dbContext.GetResult<BigData>(query).First();
				Assert.AreEqual(item.UniqueID, uniqueId);

				query = Sql.Delete(bigData).Where(bigData[d => d.UniqueID] == uniqueId).Output();
				var deletedItem = dbContext.GetResult<BigData>(query).First();
				Assert.AreEqual(item.ID, deletedItem.ID);

				query = Sql.Select(bigData).Columns(Sql.Count()).Where(bigData[d => d.UniqueID] == uniqueId);
				var selectResult = dbContext.GetFirstBase<int>(query);
				Assert.AreEqual(selectResult, 0);
			}
		}
	}
}


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

import org.apache.ignite.cache.CacheAtomicityMode;
import org.apache.ignite.cache.CacheMode;

import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL;
import static org.apache.ignite.cache.CacheMode.PARTITIONED;

/**
 *
 */
public class GridCacheTxPartitionedLocalStoreSelfTest extends GridCacheAbstractLocalStoreSelfTest {
    /** {@inheritDoc} */
    @Override protected CacheAtomicityMode getAtomicMode() {
        return TRANSACTIONAL;
    }

    /** {@inheritDoc} */
    @Override protected CacheMode getCacheMode() {
        return PARTITIONED;
    }
}


text:
package eventstreams.instructions

import core.sysevents.SyseventOps.symbolToSyseventOps
import core.sysevents.WithSyseventPublisher
import core.sysevents.ref.ComponentWithBaseSysevents
import eventstreams.Tools.{configHelper, _}
import eventstreams.instructions.Types.SimpleInstructionType
import eventstreams.{EventFrame, Fail, UUIDTools}
import play.api.libs.json.{JsValue, Json}

import scalaz.Scalaz._
import scalaz._

trait AddTagInstructionSysevents
  extends ComponentWithBaseSysevents {

  val Built = 'Built.trace
  val TagAdded = 'TagAdded.trace

  override def componentId: String = "Instruction.AddTag"
}

trait AddTagInstructionConstants extends InstructionConstants with AddTagInstructionSysevents  {
  val CfgFTagToAdd = "tagToAdd"
}

class AddTagInstruction extends SimpleInstructionBuilder with AddTagInstructionConstants with WithSyseventPublisher {
  val configId = "addtag"

  override def simpleInstruction(props: JsValue, id: Option[String] = None): \/[Fail, SimpleInstructionType] =
    for (
      tagName <- props ~> CfgFTagToAdd orFail s"Invalid $configId instruction. Missing '$CfgFTagToAdd' value. Contents: ${Json.stringify(props)}"
    ) yield {

      val uuid = UUIDTools.generateShortUUID

      Built >> ('Tag ->  tagName, 'InstructionInstanceId -> uuid)

      frame: EventFrame => {

        val fieldName = "tags"
        val fieldType = "as"

        val keyPath = macroReplacement(frame, fieldName)

        val replacement = macroReplacement(frame, tagName)

        val value: EventFrame = setValue(fieldType, replacement, keyPath, frame)

        val eventId = value.eventIdOrNA

        TagAdded >>('Tag -> tagName, 'EventId -> eventId, 'InstructionInstanceId -> uuid)

        List(value)

      }
    }

}


text:
using namespace ofp;

class NullController : public ChannelListener {
 public:
  void onChannelUp(Channel *channel) override {
    log_debug(__PRETTY_FUNCTION__);
  }

  void onMessage(Message *message) override {}

  static ChannelListener *Factory() { return new NullController; }
};

int main(int argc, char **argv) {
  log::configure(log::Level::Debug);

  std::vector<std::string> args{argv + 1, argv + argc};

  IPv6Address addr;
  if (!args.empty()) {
    addr = IPv6Address{args[0]};
  }

  Driver driver;
  driver.installSignalHandlers();

  if (addr.valid()) {
    (void)driver.connect(
        ChannelOptions::FEATURES_REQ, 0,
        IPv6Endpoint{addr, OFPGetDefaultPort()}, ProtocolVersions::All,
        NullController::Factory, [](Channel *channel, std::error_code err) {
          std::cout << "Result: connId=" << channel->connectionId()
                    << " err=" << err << '\n';
        });

  } else {
    std::error_code err;
    (void)driver.listen(ChannelOptions::FEATURES_REQ, 0,
                        IPv6Endpoint{OFPGetDefaultPort()},
                        ProtocolVersions::All, NullController::Factory, err);
  }

  driver.run();
}


text:
package ubic.gemma.persistence.util;

import ubic.gemma.model.common.Describable;

import java.util.Comparator;

/**
 * @author luke
 */
public class DescribableComparator implements Comparator<Describable> {
    private static final DescribableComparator _instance = new DescribableComparator();

    public static DescribableComparator getInstance() {
        return DescribableComparator._instance;
    }

    @Override
    public int compare( Describable d1, Describable d2 ) {
        String s1 = d1.getName();
        String s2 = d2.getName();
        if ( s1 != null ) {
            if ( s2 != null )
                return s1.compareTo( s2 );

            return 1;
        }
        if ( s2 != null )
            return -1;

        return 0;

    }
}


text:
'''Unit tests for grit.node.message'''

import os
import sys
if __name__ == '__main__':
  sys.path[0] = os.path.abspath(os.path.join(sys.path[0], '../..'))

import unittest
import StringIO

from grit import tclib
from grit import util
from grit.node import message

class MessageUnittest(unittest.TestCase):
  def testMessage(self):
    root = util.ParseGrdForUnittest('''
        <messages>
        <message name="IDS_GREETING"
                 desc="Printed to greet the currently logged in user">
        Hello <ph name="USERNAME">%s<ex>Joi</ex></ph>, how are you doing today?
        </message>
        </messages>''')
    msg, = root.GetChildrenOfType(message.MessageNode)
    cliques = msg.GetCliques()
    content = cliques[0].GetMessage().GetPresentableContent()
    self.failUnless(content == 'Hello USERNAME, how are you doing today?')

  def testMessageWithWhitespace(self):
    root = util.ParseGrdForUnittest("""\
        <messages>
        <message name="IDS_BLA" desc="">
        '''  Hello there <ph name="USERNAME">%s</ph>   '''
        </message>
        </messages>""")
    msg, = root.GetChildrenOfType(message.MessageNode)
    content = msg.GetCliques()[0].GetMessage().GetPresentableContent()
    self.failUnless(content == 'Hello there USERNAME')
    self.failUnless(msg.ws_at_start == '  ')
    self.failUnless(msg.ws_at_end == '   ')

  def testConstruct(self):
    msg = tclib.Message(text="   Hello USERNAME, how are you?   BINGO\t\t",
                        placeholders=[tclib.Placeholder('USERNAME', '%s', 'Joi'),
                                      tclib.Placeholder('BINGO', '%d', '11')])
    msg_node = message.MessageNode.Construct(None, msg, 'BINGOBONGO')
    self.failUnless(msg_node.children[0].name == 'ph')
    self.failUnless(msg_node.children[0].children[0].name == 'ex')
    self.failUnless(msg_node.children[0].children[0].GetCdata() == 'Joi')
    self.failUnless(msg_node.children[1].children[0].GetCdata() == '11')
    self.failUnless(msg_node.ws_at_start == '   ')
    self.failUnless(msg_node.ws_at_end == '\t\t')

  def testUnicodeConstruct(self):
    text = u'Howdie \u00fe'
    msg = tclib.Message(text=text)
    msg_node = message.MessageNode.Construct(None, msg, 'BINGOBONGO')
    msg_from_node = msg_node.GetCdata()
    self.failUnless(msg_from_node == text)

if __name__ == '__main__':
  unittest.main()


text:
define([
        '../Core/deprecationWarning',
        '../Core/OrthographicFrustum'
    ], function(
        deprecationWarning,
        OrthographicFrustum) {
    'use strict';

    function DeprecatedOrthographicFrustum(options) {
        deprecationWarning('OrthographicFrustum', 'Scene/OrthographicFrustum is deprecated. It has moved to Core/OrthographicFrustum in 1.36. Scene/OrthographicFrustum will be removed in 1.38.');
        return new OrthographicFrustum(options);
    }

    return DeprecatedOrthographicFrustum;
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d %5p %40.40c:%4L - %m%n</pattern>
        </encoder>
    </appender>

    <logger name="org.springframework" level="error" />
    <logger name="org.springframework.aop.interceptor" level="trace" />

    <logger name="org.hibernate.tool.hbm2ddl" level="debug"/>
    <logger name="org.hibernate.SQL" level="debug"/>
    <logger name="org.hibernate.type" level="info"/>

    <root level="info">
        <appender-ref ref="console" />
    </root>

</configuration>


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Translator;

/**
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class BCLabelTranslatorStrategy implements LabelTranslatorStrategyInterface
{
    public function getLabel($label, $context = '', $type = '')
    {
        if ('breadcrumb' === $context) {
            return sprintf('%s.%s_%s', $context, $type, strtolower($label));
        }

        return ucfirst(strtolower($label));
    }
}


text:
<resources>
    <string name="app_name">Sunshine</string>
    <string name="action_settings">Settings</string>
    <string name="action_refresh">Refresh</string>
    <string name="action_map">Map Location</string>
    <string name="action_share">Share</string>

    <!-- Activity Titles -->
    <string name="title_activity_detail">Details</string>
    <string name="title_activity_setting">Settings</string>

    <!-- Preferences -->
    <string name="pref_location_label">Location</string>
    <string name="pref_location_key">location</string>
    <string name="pref_location_default">94043</string>

    <string name="pref_temp_label">Temperature</string>
    <string name="pref_temp_key">temperature</string>
    <string name="pref_temp_default">Metric</string>
    <string-array name="pref_temp_entries">
        <item>Kelvin</item>
        <item>Celsius</item>
        <item>Fahrenheit</item>
    </string-array>

    <string-array name="pref_temp_entry_values">
        <item> </item>
        <item>metric</item>
        <item>imperial</item>
    </string-array>
</resources>


text:
<?php

namespace Yoh\JasperReportBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class YohJasperReportBundle extends Bundle
{
}


text:
require 'test_helper'

class InstrumentTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` BIGINT AUTO_INCREMENT PRIMARY KEY,
  `first_name` VARCHAR(255) NOT NULL,
  `last_name` VARCHAR(255),
  `age` INTEGER,
  `haunted` BOOLEAN DEFAULT NULL,
  UNIQUE KEY (`first_name`, `last_name`)
);

INSERT INTO `user` (`id`, `first_name`, `last_name`, `age`)
       VALUES (1, 'George', 'Saunders', 54);

INSERT INTO `user` (`id`, `first_name`, `last_name`, `age`)
       VALUES (2, 'Barry', 'Hannah', 71);

INSERT INTO `user` (`id`, `first_name`, `last_name`, `age`)
       VALUES (3, 'Kelly', 'Link', 44);


text:
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Transformation
{
    /// <summary>
    /// The result of a message transformation
    /// </summary>
    /// <typeparam name="TResult"></typeparam>
    public interface TransformResult<out TResult>
    {
        /// <summary>
        /// The transformed message
        /// </summary>
        TResult Value { get; }

        /// <summary>
        /// True if the transform has returned a new value, otherwise false. Some transforms
        /// actually apply to the original message, versus creating a new message leaving the
        /// original message unmodified.
        /// </summary>
        bool IsNewValue { get; }
    }
}