text:
function [costMat,propagationScheme,kalmanFilterInfoFrame2,nonlinkMarker,...
    errFlag] = costMatRandomDirectedSwitchingMotionLink(movieInfo,kalmanFilterInfoFrame1,...
    costMatParam,nnDistFeatures,probDim,prevCost,featLifetime,...
    trackedFeatureIndx,currentFrame)
%costMatRandomDirectedSwitchingMotionLink provides a cost matrix for linking features based on competing linear motion models
%
%SYNOPSIS [costMat,propagationScheme,kalmanFilterInfoFrame2,nonlinkMarker,...
%    errFlag] = costMatRandomDirectedSwitchingMotionLink(movieInfo,kalmanFilterInfoFrame1,...
%    costMatParam,nnDistFeatures,probDim,prevCost,featLifetime,...
%    trackedFeatureIndx,currentFrame)
%
%INPUT  movieInfo             : An nx1 array (n = number of frames in
%                               movie) containing the fields:
%             .allCoord           : x,dx,y,dy,[z,dz] of features collected in one
%                                   matrix.
%             .amp                : Amplitudes of PSFs fitting detected features.
%                                   1st column for values and 2nd column
%                                   for standard deviations.
%             .num                : Number of features in each frame.
%             .nnDist             : Distance from each feature to its nearest
%                                   neighbor. Not needed at the moment.
%      kalmanFilterInfoFrame1 : Structure with at least the following fields:
%             .stateVec           : Kalman filter state vector for each
%                                   feature in 1st frame.
%             .stateCov           : Kalman filter state covariance matrix
%                                   for each feature in 1st frame.
%             .noiseVar           : Variance of state noise for each
%                                   feature in 1st frame.
%      costMatParam           : Structure with fields:
%             .linearMotion       : 0 for only random motion;
%                                   1 for random + directed motion;
%                                   2 for random + directed motion with the
%                                   possibility of instantaneous switching
%                                   to opposite direction (but same speed),
%                                   i.e. something like 1D diffusion.
%             .minSearchRadius    : Minimum allowed search radius.
%             .maxSearchRadius    : Maximum allowed search radius.
%             .brownStdMult       : Factor multiplying Brownian
%                                   displacement std to get search radius.
%             .lftCdf             : Lifetime cumulative density function.
%                                   Column vector, specifying cdf for
%                                   lifetime = 0 to movie length.
%                                   Enter [] if cdf is not to be used.
%                                   Optional. Default: [].
%             .useLocalDensity    : Logical variable indicating whether to use
%                                   local density in search radius estimation.
%             .nnWindow           : Number of past frames for calculating
%                                   nearest neighbor distance.
%             .diagnostics        : Row vector indicating frames at which
%                                   histogram of linking distances (from
%                                   the beginning till that frame) are to
%                                   be plotted. Does not work for 1st or
%                                   last frame of a movie.
%                                   Optional. Default: None.
%      nnDistFeatures         : Matrix of nearest neighbor distances of
%                               features in first frame as well as of
%                               features in previous frames that they are
%                               connected to.
%      probDim                : Problem dimensionality. 2 (for 2D) or 3 (for 3D).
%      prevCost               : Structure with fields:
%             .all                : Matrix of previous linking costs.
%             .max                : Maximum previous linking cost.
%             .allAux             : Matrix of previous linking costs for
%                                   features not linked to current frame.
%      featLifetime           : Lengths of tracks that features in
%                               first frame belong to.
%      trackedFeatureIndx     : The matrix of feature index connectivity up
%                               to current frame.
%                               Currently not used in this cost function.
%      currentFrame           : Current frame that is being linked to the
%                               next frame.
%
%OUTPUT costMat               : Cost matrix.
%       propagationScheme     : Propagation scheme corresponding to each
%                               cost in the cost matrix.
%       kalmanFilterInfoFrame2: Structure with at least the following fields:
%             .stateVec           : Kalman filter prediction of state
%                                   vector in 2nd frame based on all 3
%                                   motion models.
%             .stateCov           : Kalman filter prediction of state
%                                   covariance matrix in 2nd frame based on
%                                   all 3 motion models.
%             .obsVec             : Kalman filter prediction of the
%                                   observed variables in 2nd frame based
%                                   on all 3 motion models.
%       nonlinkMarker         : Value indicating that a link is not allowed.
%       errFlag               : 0 if function executes normally, 1 otherwise.
%
%REMARKS Three competing linear motion models: 1, 2 and 3.
%        1: forward drift, 2: backward drift, 3: zero drift (Brownian).
%
%Khuloud Jaqaman, March 2007
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track.  If not, see <http://www.gnu.org/licenses/>.
%
%

%% Output

costMat = [];
propagationScheme = [];
kalmanFilterInfoFrame2 = [];
nonlinkMarker = [];
errFlag = [];

%% Input

%check whether correct number of input arguments was used
if nargin ~= nargin('costMatRandomDirectedSwitchingMotionLink')
    disp('--costMatRandomDirectedSwitchingMotionLink: Incorrect number of input arguments!');
    errFlag  = 1;
    return
end

%get cost function parameters
linearMotion = costMatParam.linearMotion;
minSearchRadius = costMatParam.minSearchRadius;
maxSearchRadius = costMatParam.maxSearchRadius;
brownStdMult    = costMatParam.brownStdMult;
useLocalDensity = costMatParam.useLocalDensity;
nnWindow = costMatParam.nnWindow;
if useLocalDensity
    closestDistScale = 2;
    maxStdMult = 100;
end
if isfield('costMatParam','lftCdf')
    lftCdf = costMatParam.lftCdf;
else
    lftCdf = [];
end
if isfield(costMatParam,'diagnostics')
    diagnostics = costMatParam.diagnostics;
else
    diagnostics = 0;
end

%calculate nearest neighbor distance given feature history
frameNum = size(nnDistFeatures,2);
tmpNN = max(1,frameNum-nnWindow);
nnDistTracks = min(nnDistFeatures(:,tmpNN:end),[],2);

%extract the two frames of interest from movieInfo
movieInfo = movieInfo(currentFrame:currentFrame+1);

%% Motion propagation

%calculate vector sizes
vecSize = 2 * probDim;

%construct transition matrices
switch linearMotion

    case 0 %only random motion

        transMat(:,:,1) = eye(vecSize); %zero drift transition matrix
        numSchemes = 1;

    case 1 %random motion + directed motion

        transMat(:,:,1) = eye(vecSize) + diag(ones(probDim,1),probDim); %forward drift transition matrix
        transMat(:,:,2) = eye(vecSize); %zero drift transition matrix
        numSchemes = 2;

    case 2 %random motion + directed motion that can switch to opposite direction at any moment

        transMat(:,:,1) = eye(vecSize) + diag(ones(probDim,1),probDim); %forward drift transition matrix
        transMat(:,:,2) = eye(vecSize) + diag(-ones(probDim,1),probDim); %backward drift transition matrix
        transMat(:,:,3) = eye(vecSize); %zero drift transition matrix
        numSchemes = 3;

end

%construct observation matrix
observationMat = [eye(probDim) zeros(probDim)]; %observation matrix

%get number of features in the 2 frames
numFeaturesFrame1 = movieInfo(1).num;
numFeaturesFrame2 = movieInfo(2).num;

%reserve memory for "kalmanFilterInfoframe2"
kalmanFilterInfoFrame2 = struct('stateVec',zeros(numFeaturesFrame1,vecSize,numSchemes),...
    'stateCov',zeros(vecSize,vecSize,numFeaturesFrame1,numSchemes),...
    'obsVec',zeros(numFeaturesFrame1,probDim,numSchemes));

%apply Kalman filters to each feature in 1st frame
for iFeature = 1 : numFeaturesFrame1

    %get state vector and its covariance matrix of feature in 1st frame
    stateOld = kalmanFilterInfoFrame1.stateVec(iFeature,:)';
    stateCovOld = kalmanFilterInfoFrame1.stateCov(:,:,iFeature);
    noiseVar = abs(kalmanFilterInfoFrame1.noiseVar(:,:,iFeature));

    %go over all possible propagation schemes
    for iScheme = 1 : numSchemes

        %predict state vector of feature in 2nd frame
        stateVec = transMat(:,:,iScheme)*stateOld;

        %predict state covariance matrix of feature in 2nd frame
        stateCov = transMat(:,:,iScheme)*stateCovOld*transMat(:,:,iScheme)' ...
            + noiseVar;

        %determine observation vector of feature in 2nd frame (i.e. the
        %propagated position of the feature)
        obsVec = observationMat*stateVec;

        %save information in kalmanFilterInfoFrame2
        kalmanFilterInfoFrame2.stateVec(iFeature,:,iScheme) = stateVec';
        kalmanFilterInfoFrame2.stateCov(:,:,iFeature,iScheme) = stateCov;
        kalmanFilterInfoFrame2.obsVec(iFeature,:,iScheme) = obsVec';

    end

end

%get the propagated positions of features in 1st frame based on the different propagation schemes
propagatedPos = kalmanFilterInfoFrame2.obsVec;

%put the coordinates of features in the 2nd frame in one matrix
coord2 = movieInfo(2).allCoord(:,1:2:end);

%calculate the cost matrices for all propagation schemes
for iScheme = 1 : numSchemes

    %put the propagated x and y coordinates of features from 1st frame in
    %one matrix
    coord1 = propagatedPos(:,:,iScheme);

    %calculate the distances between features
    costMatTmp(:,:,iScheme) = createDistanceMatrix(coord1,coord2);

end

%find the minimum cost for the link between every pair, which also
%determines the best propagation scheme to perform that link
[costMat,propagationScheme] = min(costMatTmp,[],3);

%% Search radius

%determine which features are not first appearances
notFirstAppearance = squeeze(kalmanFilterInfoFrame1.noiseVar(1,1,:)) >= 0;

%get the Kalman standard deviation of all features in frame 1
kalmanStd = sqrt(probDim * abs(squeeze(kalmanFilterInfoFrame1.noiseVar(1,1,:))));

%copy brownStdMult into vector
stdMultInd = repmat(brownStdMult,numFeaturesFrame1,1);

%if local density information is used to expand search radius ...
if useLocalDensity

    %divide each feature's nearest neighbor distance/closestDistScale by kalmanStd
    ratioDist2Std = nnDistTracks./kalmanStd/closestDistScale;

    %make ratios larger than maxStdMult equal to maxStdMult
    ratioDist2Std(ratioDist2Std > maxStdMult) = maxStdMult;

    %expand search radius multiplication factor if possible
    stdMultInd = max([stdMultInd ratioDist2Std],[],2);

end

%get the search radius of each feature in frame 1 and make sure it falls
%within reasonable limits
searchRadius = stdMultInd .* kalmanStd;
searchRadius((searchRadius>maxSearchRadius)&notFirstAppearance) = maxSearchRadius;
searchRadius((searchRadius<minSearchRadius)&notFirstAppearance) = minSearchRadius;

%replicate the search radius to compare to cost matrix
searchRadius = repmat(searchRadius,1,numFeaturesFrame2);

%assign NaN to costs corresponding to distance > searchRadius
costMat(costMat>searchRadius) = NaN;

%square the cost matrix to make the cost = distance squared
costMat = costMat.^2;

%% Amplitude factor

% %put feature amplitudes from both frames in vectors
% amp1 = movieInfo(1).amp(:,1);
% amp2 = movieInfo(2).amp(:,1);
%
% %make a matrix of amplitude costs
% ampCost = repmat(amp1,1,numFeaturesFrame2)./repmat(amp2',numFeaturesFrame1,1);
% ampCost(ampCost<1) = 1./ampCost(ampCost<1);
%
% %multiply distance cost by amplitude cost
% costMat = costMat .* ampCost;

%% Cost scaling

% %scale the cost of each potential link by kalmanStd^2 in order to normalize
% %costs in case of heterogeneously moving particles ...
%
% %first get kalmanStd^2 for each particle
% %use mean(kalmanStd^2) for particles that just appeared
% kalmanVar = kalmanStd.^2;
% meanKalmanVar = mean(kalmanVar(featLifetime>1));
% if ~isnan(meanKalmanVar)
%     kalmanVar(featLifetime==1) = meanKalmanVar;
% end
%
% %then divide costs by kalmanVar
% costMat = costMat ./ repmat(kalmanVar,1,numFeaturesFrame2);

%% Lifetime penalty

if ~isempty(lftCdf)

    %specify 1 - lifetime cumulative probability
    oneMinusLftCdf = 1 - lftCdf;

    %calculate 1 / (lifetime penalty), which is 1 / (1-cumulative probability
    %of lifetime of feature in first frame)
    oneOverLftPen = oneMinusLftCdf(featLifetime+1);

    %multiply each cost by the lifetime penalty
    costMat = costMat ./ repmat(oneOverLftPen,1,numFeaturesFrame2);

    %replace infinite costs by NaN
    costMat(isinf(costMat)) = NaN;

end

%% Birth and death

%append matrix to allow birth and death
% jonas, 10/09: fix for non-sparse tracker
if isstruct(prevCost)
    prevCostMax = prevCost.max;
else
    prevCostMax = max(prevCost(:));
end

% if ~isnan(prevCostMax) && prevCostMax ~= 0
%     maxCost = 1.05*prevCostMax;
% else
    maxCost = 1.05*max(prctile(costMat(:),100),eps);
% end

deathCost = maxCost * ones(numFeaturesFrame1,1);
birthCost = maxCost * ones(numFeaturesFrame2,1);

%generate upper right and lower left block
deathBlock = diag(deathCost); %upper right
deathBlock(deathBlock==0) = NaN;
birthBlock = diag(birthCost); %lower left
birthBlock(birthBlock==0) = NaN;

%get the cost for the lower right block
% costLR = min(min(min(costMat))-1,-1);
costLR = maxCost;
lrBlock = costMat';
lrBlock(~isnan(lrBlock)) = costLR;

%append cost matrix
costMat = [costMat deathBlock; birthBlock lrBlock];

%% nonLinkMarker

%determine the nonlinkMarker
nonlinkMarker = min(floor(min(min(costMat)))-5,-5);

%replace NaN, indicating pairs that cannot be linked, with nonlinkMarker
costMat(isnan(costMat)) = nonlinkMarker;

%% Histogram of linking distances

%get current frame
% jonas, 10/09: fix for non-sparse tracker
if isstruct(prevCost)
    currentFrame = size(prevCost.all,2);
else
    currentFrame = size(prevCost,2);
end

%check whether current frame matches any of the diagnostics frames
if currentFrame ~= 1 && any(diagnostics == currentFrame)

    %get linking distances
    % jonas, 10/09: fix for non-sparse tracker
    if isstruct(prevCost)
        prevCostNoCol1 = [prevCost.all(:,2:end); prevCost.allAux(:,2:currentFrame)];
    else
        prevCostNoCol1 = prevCost(:,2:end);
    end
    linkingDistances = sqrt(prevCostNoCol1(~isnan(prevCostNoCol1)));

    %plot histogram
    figure('Name',['frame # ' num2str(currentFrame)]); %,'NumberTitle','off');
    try
        histogram(linkingDistances,[],0);
        xlabel('Linking distance');
        ylabel('Counts');
    catch
        disp('histogram plot failed');
    end

end

%% ~~~ the end ~~~


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<script src="../../bower_components/page/page.js"></script>
<script>
  window.addEventListener('WebComponentsReady', function() {

    // We use Page.js for routing. This is a Micro
    // client-side router inspired by the Express router
    // More info: https://visionmedia.github.io/page.js/
    page('/', function () {
    	app.route = 'home';
    	app.mainMenu = true;
    });

    page('/companies', function () {
    	app.route = 'companies';
    	app.mainMenu = true;
    });

    page('/companies/:name', function (data) {
    	app.route = 'company-details';
    	app.params = data.params;
    	app.mainMenu = false;
    	app.companyMenu = true;
    });

    page('/companies/:name/products', function (data) {
    	app.route = 'company-products';
    	app.params = data.params;
    	app.mainMenu = false;
    	app.companyMenu = true;
    });

    page('/people', function () {
    	app.route = 'people';
    });

    page('/people/:name', function (data) {
    	app.route = 'person-details';
    	app.params = data.params;
    });

    page('/books', function () {
    	app.route = 'books';
    });

    page('/books/:title', function (data) {
    	app.route = 'book-details';
    	app.params = data.params;
    });

    page('/videos', function () {
    	app.route = 'videos';
    });

    page('/videos/:videoId', function (data) {
    	app.route = 'video-details';
    	app.params = data.params;
    });

    page('/events', function () {
    	app.route = 'events';
    });

    page('/events/:name', function (data) {
    	app.route = 'event-details';
    	app.params = data.params;
    });

    page('/quotes', function () {
    	app.route = 'quotes';
    });

    page('/quotes/:id', function (data) {
    	app.route = 'quote-details';
    	app.params = data.params;
    });

    page('/wiki', function () {
    	app.route = 'wiki';
    });

    page('/wiki/:title', function (data) {
    	app.route = 'wiki-article';
    	app.params = data.params;
    });

  	// ---

    page('/signup', function () {
    	app.route = 'signup';
    });

    page('/signin', function () {
    	app.route = 'signin';
    });

    page('/contact', function () {
    	app.route = 'contact';
    });

    page('/users', function () {
    	app.route = 'users';
    });

    page('/users/:name', function (data) {
    	app.route = 'user-info';
    	app.params = data.params;
    });

    page('/website', function () {
    	app.route = 'website';
    });

  	// ---

    page('/contact', function () {
    	app.route = 'contact';
    });

    page('/test', function () {
    	app.route = 'test';
    });

    // add #! before urls
    page({
      hashbang: true
    });

  });
</script>

redpajama_set_name: RedPajamaGithub


text:
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create renderer stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Pipeline stuff
#
torus = vtk.vtkSuperquadricSource()
torus.SetCenter(0.0,0.0,0.0)
torus.SetScale(1.0,1.0,1.0)
torus.SetPhiResolution(64)
torus.SetThetaResolution(64)
torus.SetPhiRoundness(1.0)
torus.SetThetaRoundness(1.0)
torus.SetThickness(0.5)
torus.SetSize(0.5)
torus.SetToroidal(1)
# The quadric is made of strips, so pass it through a triangle filter as
# the curvature filter only operates on polys
tri = vtk.vtkTriangleFilter()
tri.SetInputConnection(torus.GetOutputPort())
# The quadric has nasty discontinuities from the way the edges are generated
# so let's pass it though a CleanPolyDataFilter and merge any points which
# are coincident, or very close
cleaner = vtk.vtkCleanPolyData()
cleaner.SetInputConnection(tri.GetOutputPort())
cleaner.SetTolerance(0.005)
curve1 = vtk.vtkCurvatures()
curve1.SetInputConnection(cleaner.GetOutputPort())
curve1.SetCurvatureTypeToGaussian()
curve2 = vtk.vtkCurvatures()
curve2.SetInputConnection(cleaner.GetOutputPort())
curve2.SetCurvatureTypeToMean()
lut1 = vtk.vtkLookupTable()
lut1.SetNumberOfColors(256)
lut1.SetHueRange(0.15,1.0)
lut1.SetSaturationRange(1.0,1.0)
lut1.SetValueRange(1.0,1.0)
lut1.SetAlphaRange(1.0,1.0)
lut1.SetRange(-20,20)
lut2 = vtk.vtkLookupTable()
lut2.SetNumberOfColors(256)
lut2.SetHueRange(0.15,1.0)
lut2.SetSaturationRange(1.0,1.0)
lut2.SetValueRange(1.0,1.0)
lut2.SetAlphaRange(1.0,1.0)
lut2.SetRange(0,4)
cmapper1 = vtk.vtkPolyDataMapper()
cmapper1.SetInputConnection(curve1.GetOutputPort())
cmapper1.SetLookupTable(lut1)
cmapper1.SetUseLookupTableScalarRange(1)
cmapper2 = vtk.vtkPolyDataMapper()
cmapper2.SetInputConnection(curve2.GetOutputPort())
cmapper2.SetLookupTable(lut2)
cmapper2.SetUseLookupTableScalarRange(1)
cActor1 = vtk.vtkActor()
cActor1.SetMapper(cmapper1)
cActor1.SetPosition(-0.5,0.0,0.0)
cActor2 = vtk.vtkActor()
cActor2.SetMapper(cmapper2)
cActor2.SetPosition(0.5,0.0,0.0)
# Add the actors to the renderer
#
ren1.AddActor(cActor1)
ren1.AddActor(cActor2)
ren1.SetBackground(0.5,0.5,0.5)
renWin.SetSize(300,200)
camera = vtk.vtkCamera()
ren1.SetActiveCamera(camera)
camera.SetPosition(0.0,2.0,2.1)
camera.SetFocalPoint(0.0,0.0,0.0)
camera.SetViewAngle(30)
ren1.ResetCameraClippingRange()
iren.Initialize()
# render the image
#
# prevent the tk window from showing up then start the event loop
renWin.Render()
# --- end of script --


text:
import sys
from os import makedirs

def input_process(in_question):
    return input(in_question) if sys.version_info >= (3,0) else raw_input(in_question)

def create_index_file(site_name, author):
    file_name = '%s/index.html' % site_name

    try:
        with open(file_name, 'w') as f:
            f.write('<title>%s</title>\n' % site_name)
            f.write('<meta>author:%s</meta>' % author)
    except:
        print ('File does not created.')
        exit()

if __name__ == '__main__':
    site_name = str(input_process('Site name: '))
    author = str(input_process('Author: '))
    create_js_dir = str(input_process('Do you want a folder for JavaScript?(y) '))
    create_css_dir = str(input_process('Do you want a folder for CSS?(y) '))

    makedirs(site_name)
    create_index_file(site_name, author)

    if create_js_dir.upper() == 'Y':
        makedirs('%s/js' % site_name)

    if create_css_dir.upper() == 'Y':
        makedirs('%s/css' % site_name)

    print ('Website skeleton was created.')


text:
import {ControllerMixin} from "ember-runtime/controllers/controller";
import ObjectProxy from "ember-runtime/system/object_proxy";

/**
@module ember
@submodule ember-runtime
*/

/**
  `Ember.ObjectController` is part of Ember's Controller layer. It is intended
  to wrap a single object, proxying unhandled attempts to `get` and `set` to the underlying
  content object, and to forward unhandled action attempts to its `target`.

  `Ember.ObjectController` derives this functionality from its superclass
  `Ember.ObjectProxy` and the `Ember.ControllerMixin` mixin.

  @class ObjectController
  @namespace Ember
  @extends Ember.ObjectProxy
  @uses Ember.ControllerMixin
**/
var ObjectController = ObjectProxy.extend(ControllerMixin);
export default ObjectController;


text:
#include <aws/rds/model/ApplyMethod.h>
#include <aws/core/utils/HashingUtils.h>

using namespace Aws::Utils;

static const int immediate_HASH = HashingUtils::HashString("immediate");
static const int pending_reboot_HASH = HashingUtils::HashString("pending-reboot");

namespace Aws
{
namespace RDS
{
namespace Model
{
namespace ApplyMethodMapper
{
ApplyMethod GetApplyMethodForName(const Aws::String& name)
{
  int hashCode = HashingUtils::HashString(name.c_str());

  if (hashCode == immediate_HASH)
  {
    return ApplyMethod::immediate;
  }
  else if (hashCode == pending_reboot_HASH)
  {
    return ApplyMethod::pending_reboot;
  }

  return ApplyMethod::NOT_SET;
}

Aws::String GetNameForApplyMethod(ApplyMethod value)
{
  switch(value)
  {
  case ApplyMethod::immediate:
    return "immediate";
  case ApplyMethod::pending_reboot:
    return "pending-reboot";
  default:
    return "";
  }
}

} // namespace ApplyMethodMapper
} // namespace Model
} // namespace RDS
} // namespace Aws


text:
import './multiline_autocomplete.css';

import debounce from 'lodash/debounce';
import {CancellationToken, CancellationTokenSource} from 'neuroglancer/util/cancellation';
import {BasicCompletionResult, Completion, CompletionWithDescription} from 'neuroglancer/util/completion';
import {RefCounted} from 'neuroglancer/util/disposable';
import {removeChildren, removeFromParent} from 'neuroglancer/util/dom';
import {positionDropdown} from 'neuroglancer/util/dropdown';
import {EventActionMap, KeyboardEventBinder, registerActionListener} from 'neuroglancer/util/keyboard_bindings';
import {longestCommonPrefix} from 'neuroglancer/util/longest_common_prefix';
import {Signal} from 'neuroglancer/util/signal';
import {VirtualList} from 'neuroglancer/widget/virtual_list';
import ResizeObserver from 'resize-observer-polyfill';

export type {Completion, CompletionWithDescription} from 'neuroglancer/util/completion';

const ACTIVE_COMPLETION_CLASS_NAME = 'neuroglancer-multiline-autocomplete-completion-active';

const DEBUG_DROPDOWN = false;

export interface CompletionResult extends BasicCompletionResult {
  showSingleResult?: boolean;
  selectSingleResult?: boolean;
  makeElement?: (this: CompletionResult, completion: Completion) => HTMLElement;
}

export function makeDefaultCompletionElement(completion: Completion) {
  let element = document.createElement('div');
  element.textContent = completion.value;
  return element;
}

function* splitByWordBreaks(value: string) {
  while (value.length > 0) {
    const m = value.match(/[:/_]+/);
    if (m === null) {
      yield value;
      return;
    }
    const endOffset = m.index! + m[0].length;
    yield value.substring(0, endOffset);
    value = value.substring(endOffset);
  }
}

export function makeCompletionElementWithDescription(completion: CompletionWithDescription) {
  let element = document.createElement('div');
  element.className = 'neuroglancer-multiline-autocomplete-completion-with-description';
  element.textContent = completion.value;
  let descriptionElement = document.createElement('div');
  descriptionElement.className = 'neuroglancer-multiline-autocomplete-completion-description';
  descriptionElement.textContent = completion.description || '';
  element.appendChild(descriptionElement);
  return element;
}

const keyMap = EventActionMap.fromObject({
  'arrowdown': {action: 'cycle-next-active-completion'},
  'arrowup': {action: 'cycle-prev-active-completion'},
  'home': {action: 'home'},
  'end': {action: 'end'},
  'tab': {action: 'choose-active-completion-or-prefix', preventDefault: false},
  'enter': {action: 'commit'},
  'escape': {action: 'cancel', preventDefault: false, stopPropagation: false},
});

export type Completer = (value: string, cancellationToken: CancellationToken) =>
    Promise<CompletionResult>|null;

const DEFAULT_COMPLETION_DELAY = 200;  // milliseconds

export class AutocompleteTextInput extends RefCounted {
  element = document.createElement('div');
  inputElement = document.createElement('span');
  hintElement = document.createElement('span');
  private completionsVirtualList: VirtualList|undefined = undefined;
  onCommit = new Signal<(value: string, explicit: boolean) => void>();
  onInput = new Signal<(value: string) => void>();
  private prevInputValue: string|undefined = '';
  private completionsVisible = false;
  private activeCompletionPromise: Promise<CompletionResult>|null = null;
  private activeCompletionCancellationToken: CancellationTokenSource|undefined = undefined;
  private hasFocus = false;
  private completionResult: CompletionResult|null = null;
  private dropdownContentsStale = true;
  private hasResultForDropdown = false;
  private commonPrefix = '';
  private completionDisabled: number = -1;

  disableCompletion() {
    const selectionRange = this.getSelectionRange();
    this.completionDisabled =
        (selectionRange !== undefined && selectionRange.end === selectionRange.begin) ?
        selectionRange.end :
        -1;
  }

  get placeholder() {
    return this.inputElement.dataset.placeholder || '';
  }

  set placeholder(value: string) {
    this.inputElement.dataset.placeholder = value;
  }

  private getSelectionRange() {
    const s = window.getSelection();
    if (s === null) return undefined;
    if (s.rangeCount === 0) return undefined;
    const startRange = s.getRangeAt(0);
    const {inputElement} = this;
    const beforeRange = document.createRange();
    beforeRange.setStart(inputElement, 0);
    beforeRange.setEnd(startRange.startContainer, startRange.startOffset);
    const begin = beforeRange.toString().length;
    const length = s.toString().length;
    return {begin, end: begin + length};
  }

  setValueAndSelection(
      value: string, selection: {begin: number, end: number}|undefined = undefined) {
    const completionDisabled = this.completionDisabled !== -1;
    this.onInput.dispatch(value);
    const {inputElement} = this;
    removeChildren(inputElement);
    let outputOffset = 0;
    const r = selection !== undefined ? document.createRange() : undefined;
    let isFirst = true;
    for (const text of splitByWordBreaks(value)) {
      if (!isFirst) {
        inputElement.appendChild(document.createElement('wbr'));
      }
      isFirst = false;
      const newOutputOffset = outputOffset + text.length;
      const node = document.createTextNode(text);
      inputElement.appendChild(node);
      if (r !== undefined) {
        const {begin, end} = selection!;
        if (begin >= outputOffset && begin <= newOutputOffset) {
          r.setStart(node, begin - outputOffset);
        }
        if (end >= outputOffset && end <= newOutputOffset) {
          r.setEnd(node, end - outputOffset);
        }
      }
      outputOffset = newOutputOffset;
    };
    if (r !== undefined) {
      if (isFirst) {
        r.setStart(inputElement, 0);
        r.setEnd(inputElement, 0);
      }
      const s = window.getSelection();
      if (s !== null) {
        s.removeAllRanges();
        s.addRange(r);
      }
    }
    this.completionDisabled =
        (completionDisabled && selection !== undefined && selection.end === selection.begin) ?
        selection.end :
        -1;
  }

  /**
   * Index of the active completion.  The active completion is displayed as the hint text and is
   * highlighted in the dropdown.
   */
  private activeIndex = -1;

  private dropdownStyleStale = true;

  private scheduleUpdateCompletions: () => void;
  completer: Completer;

  private resizeHandler = () => {
    if (!this.completionsVisible) return;
    this.updateDropdownStyle();
  };

  private resizeObserver = new ResizeObserver(this.resizeHandler);

  constructor(options: {completer: Completer, delay?: number}) {
    super();
    this.completer = options.completer;
    const {delay = DEFAULT_COMPLETION_DELAY} = options;

    let debouncedCompleter = this.scheduleUpdateCompletions = debounce(() => {
      const cancellationToken = this.activeCompletionCancellationToken =
          new CancellationTokenSource();
      let activeCompletionPromise = this.activeCompletionPromise =
          this.completer(this.value, cancellationToken);
      if (activeCompletionPromise !== null) {
        activeCompletionPromise.then(completionResult => {
          if (this.activeCompletionPromise === activeCompletionPromise) {
            this.setCompletions(completionResult);
            this.activeCompletionPromise = null;
          }
        });
      }
    }, delay);
    this.registerDisposer(() => {
      debouncedCompleter.cancel();
    });

    const {element, inputElement, hintElement} = this;
    element.classList.add('neuroglancer-multiline-autocomplete');
    this.registerEventListener(window, 'resize', this.resizeHandler);

    this.resizeObserver.observe(element);
    this.registerDisposer(() => this.resizeObserver.unobserve(inputElement));

    inputElement.contentEditable = 'true';
    inputElement.spellcheck = false;
    element.appendChild(document.createTextNode('\u200b'));  // Prevent input area from collapsing
    element.appendChild(inputElement);
    element.appendChild(hintElement);
    inputElement.classList.add('neuroglancer-multiline-autocomplete-input');
    hintElement.classList.add('neuroglancer-multiline-autocomplete-hint');
    inputElement.addEventListener('input', () => {
      this.completionDisabled = -1;
      this.setValueAndSelection(this.value, this.getSelectionRange());
      this.debouncedUpdateHintState();
    });
    inputElement.addEventListener('copy', event => {
      // Ensure selected text is copied as plain text.
      const {clipboardData} = event;
      if (clipboardData !== null) {
        const selection = window.getSelection();
        if (selection !== null && !selection.isCollapsed &&
            selection.containsNode(inputElement, /*allowPartialContainment=*/ true)) {
          clipboardData.setData('text/plain', selection.toString());
        }
      }
      event.preventDefault();
      event.stopPropagation();
    });
    this.registerEventListener(document, 'selectionchange', () => {
      const newSelection = this.getSelectionRange();
      const {completionDisabled} = this;
      if (newSelection !== undefined && newSelection.begin === completionDisabled &&
          newSelection.end === completionDisabled) {
        return;
      }
      this.completionDisabled = -1;
      this.debouncedUpdateHintState();
    });
    this.setValueAndSelection('');
    this.updateHintState();

    element.addEventListener('pointerdown', (event: PointerEvent) => {
      const {target} = event;
      if (target instanceof Node) {
        if (inputElement.contains(target)) return;
        const {completionsVirtualList} = this;
        if (completionsVirtualList !== undefined &&
            completionsVirtualList.element.contains(target)) {
          return;
        }
      }
      if (inputElement === document.activeElement) {
        this.moveCaretToEndOfInput();
        event.stopPropagation();
        event.preventDefault();
      }
    });

    element.addEventListener('click', () => {
      inputElement.focus();
    });

    this.registerEventListener(this.inputElement, 'focus', () => {
      if (!this.hasFocus) {
        this.hasFocus = true;
        this.dropdownStyleStale = true;
        this.updateDropdown();
        const r = document.createRange();
        const {childNodes} = inputElement;
        r.setStart(inputElement, 0);
        if (childNodes.length === 0) {
          r.setEnd(inputElement, 0);
        } else {
          r.setEndAfter(childNodes[childNodes.length - 1]);
        }
        const s = window.getSelection();
        if (s !== null) {
          s.removeAllRanges();
          s.addRange(r);
        }
        this.debouncedUpdateHintState();
      }
    });
    this.registerEventListener(this.inputElement, 'blur', () => {
      if (this.hasFocus) {
        if (DEBUG_DROPDOWN) return;
        this.hasFocus = false;
        this.updateDropdown();
      }
      this.debouncedUpdateHintState();
      const s = window.getSelection();
      if (s !== null) {
        if (s.containsNode(this.inputElement, true)) {
          s.removeAllRanges();
        }
      }
      this.onCommit.dispatch(this.value, false);
    });
    this.registerEventListener(window, 'resize', () => {
      this.dropdownStyleStale = true;
    });

    this.registerEventListener(window, 'scroll', () => {
      this.dropdownStyleStale = true;
    });

    const keyboardHandler = this.registerDisposer(new KeyboardEventBinder(inputElement, keyMap));
    keyboardHandler.allShortcutsAreGlobal = true;

    registerActionListener(inputElement, 'cycle-next-active-completion', () => {
      this.cycleActiveCompletion(+1);
    });

    registerActionListener(inputElement, 'cycle-prev-active-completion', () => {
      this.cycleActiveCompletion(-1);
    });

    registerActionListener(inputElement, 'home', () => {
      this.moveCaretToBeginningOfInput();
    });

    registerActionListener(inputElement, 'end', () => {
      this.moveCaretToEndOfInput();
    });

    registerActionListener(
        inputElement, 'choose-active-completion-or-prefix', (event: CustomEvent) => {
          if (this.selectActiveCompletion(/*allowPrefix=*/ true)) {
            event.preventDefault();
          }
        });
    registerActionListener(inputElement, 'commit', (event: CustomEvent) => {
      if (this.selectActiveCompletion(/*allowPrefix=*/ false)) {
        event.stopPropagation();
      } else {
        let explicit = !this.completionsVisible;
        this.disableCompletion();
        this.hideCompletions();
        this.onCommit.dispatch(this.value, explicit);
      }
    });
    registerActionListener(inputElement, 'cancel', (event: CustomEvent) => {
      event.stopPropagation();
      if (this.cancel()) {
        event.detail.preventDefault();
        event.detail.stopPropagation();
      }
    });
  }

  private shouldAttemptCompletion() {
    const {inputElement} = this;
    if (document.activeElement !== inputElement) return false;
    const selection = this.getSelectionRange();
    return (
        selection !== undefined && selection.end === selection.begin &&
        selection.end != this.completionDisabled && selection.end === this.value.length);
  }

  hideCompletions() {
    this.cancelActiveCompletion();
    this.clearCompletions();
    this.hintElement.textContent = '';
  }

  private debouncedUpdateHintState =
      this.registerCancellable(debounce(() => this.updateHintState(), 0));

  private updateHintState() {
    this.debouncedUpdateHintState.cancel();
    if (!this.shouldAttemptCompletion()) {
      this.hideCompletions();
      return;
    } else {
      const {value} = this;
      if (value === this.prevInputValue) {
        // Completion already in progress.
        return;
      }
      this.hideCompletions();
      this.prevInputValue = value;
      this.scheduleUpdateCompletions();
    }
  }

  private handleDropdownClick(event: MouseEvent) {
    let {completionsVirtualList} = this;
    if (completionsVirtualList === undefined) return;
    const dropdownElement = completionsVirtualList.element;
    for (let target: EventTarget|null = event.target;
         target instanceof HTMLElement && target !== dropdownElement;
         target = target.parentElement) {
      const completionIndex = target.dataset.completionIndex;
      if (completionIndex !== undefined) {
        this.selectCompletion(Number(completionIndex));
        break;
      }
    }
  }

  cycleActiveCompletion(delta: number) {
    if (this.completionResult === null) {
      return;
    }
    let {activeIndex} = this;
    let numCompletions = this.completionResult.completions.length;
    if (activeIndex === -1) {
      if (delta > 0) {
        activeIndex = 0;
      } else {
        activeIndex = numCompletions - 1;
      }
    } else {
      activeIndex = (activeIndex + delta + numCompletions) % numCompletions;
    }
    this.setActiveIndex(activeIndex);
  }

  private shouldShowDropdown() {
    let {completionResult} = this;
    if (completionResult === null || !this.hasFocus) {
      return false;
    }
    return this.hasResultForDropdown;
  }

  private updateDropdownStyle() {
    const {completionsVirtualList, element} = this;
    if (completionsVirtualList !== undefined) {
      positionDropdown(completionsVirtualList.element, element, {horizontal: false});
    }
    this.dropdownStyleStale = false;
  }

  private updateDropdown() {
    let {completionsVirtualList} = this;
    if (this.shouldShowDropdown()) {
      if (this.dropdownContentsStale) {
        if (completionsVirtualList !== undefined) {
          completionsVirtualList.dispose();
        }
        const completionResult = this.completionResult!;
        const {makeElement = makeDefaultCompletionElement} = completionResult;
        completionsVirtualList = this.completionsVirtualList = new VirtualList({
          source: {
            length: completionResult.completions.length,
            render: (index: number) => {
              const completion = completionResult.completions[index];
              const completionElement = makeElement.call(completionResult, completion);
              completionElement.classList.add('neuroglancer-multiline-autocomplete-completion');
              completionElement.dataset.completionIndex = `${index}`;
              if (this.activeIndex === index) {
                completionElement.classList.add(ACTIVE_COMPLETION_CLASS_NAME);
              }
              return completionElement;
            },
          },
          selectedIndex: this.activeIndex === -1 ? undefined : this.activeIndex,
        });
        completionsVirtualList.element.classList.add(
            'neuroglancer-multiline-autocomplete-dropdown');

        completionsVirtualList.element.addEventListener('mousedown', event => {
          this.inputElement.focus();
          event.preventDefault();
        });
        completionsVirtualList.element.addEventListener(
            'mouseup', this.handleDropdownClick.bind(this));

        this.element.appendChild(completionsVirtualList.element);
        this.dropdownContentsStale = false;
      }
      if (this.dropdownStyleStale) {
        this.updateDropdownStyle();
      }
      if (!this.completionsVisible) {
        this.completionsVisible = true;
      }
      const {activeIndex} = this;
      if (activeIndex !== -1) {
        this.completionsVirtualList!.scrollItemIntoView(activeIndex);
      }
    } else if (this.completionsVisible) {
      if (completionsVirtualList !== undefined) {
        completionsVirtualList.dispose();
        this.completionsVirtualList = undefined;
        this.dropdownContentsStale = true;
      }
      this.completionsVisible = false;
    }
  }

  private setCompletions(completionResult: CompletionResult) {
    this.clearCompletions();
    let {completions} = completionResult;
    if (completions.length === 0) {
      return;
    }
    const value = this.prevInputValue;
    if (value === undefined) return;
    this.completionResult = completionResult;

    if (completions.length === 1) {
      let completion = completions[0];
      if (completionResult.showSingleResult) {
        this.hasResultForDropdown = true;
      } else {
        if (!completion.value.startsWith(value)) {
          this.hasResultForDropdown = true;
        } else {
          this.hasResultForDropdown = false;
        }
      }
      if (completionResult.selectSingleResult) {
        this.setActiveIndex(0);
      } else {
        this.setHintValue(this.getCompletedValueByIndex(0));
      }
    } else {
      this.hasResultForDropdown = true;
      // Check for a common prefix.
      let commonResultPrefix = longestCommonPrefix(function*() {
        for (let completion of completionResult.completions) {
          yield completion.value;
        }
      }());
      let commonPrefix = this.getCompletedValue(commonResultPrefix);
      if (commonPrefix.startsWith(value)) {
        this.commonPrefix = commonPrefix;
        this.setHintValue(commonPrefix);
      }
    }
    this.updateDropdown();
  }

  setHintValue(hintValue: string) {
    const value = this.prevInputValue;
    if (value === undefined) return;
    if (hintValue === value || !hintValue.startsWith(value)) {
      // If the hint value is identical to the current value, there is no need to show it.  Also,
      // if it is not a prefix of the current value, then we cannot show it either.
      hintValue = '';
    }
    hintValue = hintValue.substring(value.length);
    const {hintElement} = this;
    removeChildren(hintElement);
    let isFirst = true;
    for (const text of splitByWordBreaks(hintValue)) {
      if (!isFirst) {
        hintElement.appendChild(document.createElement('wbr'));
      }
      isFirst = false;
      const node = document.createTextNode(text);
      hintElement.appendChild(node);
    }
  }

  /**
   * This sets the active completion, which causes it to be highlighted and displayed as the hint.
   * Additionally, if the user hits tab then it is chosen.
   */
  private setActiveIndex(index: number) {
    if (!this.dropdownContentsStale) {
      let {activeIndex} = this;
      const {completionsVirtualList} = this;
      if (completionsVirtualList !== undefined) {
        if (activeIndex !== -1) {
          const prevElement = completionsVirtualList.getItemElement(activeIndex);
          if (prevElement !== undefined) {
            prevElement.classList.remove(ACTIVE_COMPLETION_CLASS_NAME);
          }
        }
        if (index !== -1) {
          let completionElement = completionsVirtualList.getItemElement(index);
          if (completionElement !== undefined) {
            completionElement.classList.add(ACTIVE_COMPLETION_CLASS_NAME);
          }
          completionsVirtualList.scrollItemIntoView(index);
        }
      }
    }
    if (index !== -1) {
      this.setHintValue(this.getCompletedValueByIndex(index));
    }
    this.activeIndex = index;
  }

  private getCompletedValueByIndex(index: number) {
    return this.getCompletedValue(this.completionResult!.completions[index].value);
  }

  private getCompletedValue(completionValue: string) {
    let completionResult = this.completionResult!;
    let value = this.prevInputValue;
    if (value === undefined) return '';
    return value.substring(0, completionResult.offset) + completionValue;
  }

  private moveCaretToBeginningOfInput() {
    const r = document.createRange();
    const {inputElement} = this;
    r.setStart(inputElement, 0);
    r.setEnd(inputElement, 0);
    const s = window.getSelection();
    if (s !== null) {
      s.removeAllRanges();
      s.addRange(r);
      this.debouncedUpdateHintState();
    }
  }

  private moveCaretToEndOfInput() {
    const r = document.createRange();
    const {inputElement} = this;
    const {childNodes} = inputElement;
    const lastNode = childNodes[childNodes.length - 1];
    if (lastNode === undefined) {
      r.setStart(inputElement, 0);
      r.setEnd(inputElement, 0);
    } else {
      r.setStartAfter(lastNode);
      r.setEndAfter(lastNode);
    }
    const s = window.getSelection();
    if (s !== null) {
      s.removeAllRanges();
      s.addRange(r);
      this.debouncedUpdateHintState();
    }
  }

  selectActiveCompletion(allowPrefix: boolean) {
    let {activeIndex} = this;
    if (activeIndex === -1) {
      if (!allowPrefix) {
        return false;
      }
      let {completionResult} = this;
      if (completionResult !== null && completionResult.completions.length === 1) {
        activeIndex = 0;
      } else {
        let {commonPrefix} = this;
        if (commonPrefix.length > this.value.length) {
          this.value = commonPrefix;
          this.moveCaretToEndOfInput();
          return true;
        }
        return false;
      }
    }
    let newValue = this.getCompletedValueByIndex(activeIndex);
    if (this.value === newValue) {
      return false;
    }
    this.value = newValue;
    this.moveCaretToEndOfInput();
    return true;
  }

  selectCompletion(index: number) {
    this.value = this.getCompletedValueByIndex(index);
    this.moveCaretToEndOfInput();
  }

  /**
   * Called when user presses escape.  Does nothing here, but may be overridden in a subclass.
   */
  cancel() {
    return false;
  }

  private cancelActiveCompletion() {
    this.prevInputValue = undefined;
    const token = this.activeCompletionCancellationToken;
    if (token !== undefined) {
      token.cancel();
    }
    this.activeCompletionCancellationToken = undefined;
    this.activeCompletionPromise = null;
  }

  private clearCompletions() {
    if (this.completionResult !== null) {
      this.activeIndex = -1;
      this.completionResult = null;
      this.dropdownContentsStale = true;
      this.dropdownStyleStale = true;
      this.commonPrefix = '';
      const {completionsVirtualList} = this;
      if (completionsVirtualList !== undefined) {
        completionsVirtualList.dispose();
        this.completionsVirtualList = undefined;
      }
      this.updateDropdown();
    }
  }

  get value() {
    return this.inputElement.textContent || '';
  }

  set value(value: string) {
    if (value !== this.value) {
      this.completionDisabled = -1;
      this.setValueAndSelection(value);
      this.debouncedUpdateHintState();
    }
  }

  disposed() {
    const {completionsVirtualList} = this;
    if (completionsVirtualList !== undefined) {
      completionsVirtualList.dispose();
    }
    removeFromParent(this.element);
    this.cancelActiveCompletion();
    super.disposed();
  }
}


text:
FROM alpine
MAINTAINER Vladislav Shub <vlad6il@gmail.com>

ENV PYTHONIOENCODING utf-8
RUN apk add --no-cache --update \
    python \
    python-dev \
    py-pip \
    build-base \
    git \
    openssl-dev \
    libxml2-dev \
    libxslt \
    libxslt-dev \
    py-libxslt \
    py-libxml2 \
    py-lxml \
    libssl1.0 \
    ca-certificates \
    wget \
  && pip install --upgrade pip \
  && pip install virtualenv \
  && update-ca-certificates \
  && rm -rf /var/cache/apk/*


text:
layout: page
title: About
lang: ru-RU
---

The Underhanded Rust Contest is an offical
[Rust Language](https://rust-lang.org) competition to discover and document the
best ways to subtly subvert Rust code. This is intended to be an annual
competition, with a different theme for each year.

# Contest Organizers

This contest is organized by the [Rust Community Team](https://community.rs)
and other volunteers in the Rust community.

# Code of Conduct

We are committed to providing a friendly, safe and welcoming environment for
all, regardless of gender, sexual orientation, disability, ethnicity, religion,
or similar personal characteristic. Our
[code of conduct](https://www.rust-lang.org/en-US/conduct.html) sets the
standards for behavior in all official Rust forums.

If you feel you have been or are being harassed or made uncomfortable by a
community member, please contact any of the
[Rust Moderation Team](https://www.rust-lang.org/en-US/team.html#Moderation-team)
immediately.  Whether you are a regular contributor or a newcomer, we care
about making the community a safe space for you.

# Sponsoring

If you are interested in sponsoring the contest by providing prizes or
financial support, please contact us via email:
<mailto:underhanded@rust-lang.org>.


text:
[assembly: global::Android.Runtime.ResourceDesignerAttribute("KittenView.Droid.Resource", IsApplication=true)]

namespace KittenView.Droid
{

	[System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Android.Build.Tasks", "1.0.0.0")]
	public partial class Resource
	{

		static Resource()
		{
			global::Android.Runtime.ResourceIdManager.UpdateIdValues();
		}

		public static void UpdateIdValues()
		{
		}

		public partial class Attribute
		{

			// aapt resource value: 0x7f010000
			public const int MvxBind = 2130771968;

			// aapt resource value: 0x7f010004
			public const int MvxDropDownItemTemplate = 2130771972;

			// aapt resource value: 0x7f010003
			public const int MvxItemTemplate = 2130771971;

			// aapt resource value: 0x7f010001
			public const int MvxLang = 2130771969;

			// aapt resource value: 0x7f010005
			public const int MvxSource = 2130771973;

			// aapt resource value: 0x7f010002
			public const int MvxTemplate = 2130771970;

			static Attribute()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Attribute()
			{
			}
		}

		public partial class Drawable
		{

			// aapt resource value: 0x7f020000
			public const int Icon = 2130837504;

			// aapt resource value: 0x7f020001
			public const int splash = 2130837505;

			static Drawable()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Drawable()
			{
			}
		}

		public partial class Id
		{

			// aapt resource value: 0x7f040000
			public const int MvxBindingTagUnique = 2130968576;

			static Id()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Id()
			{
			}
		}

		public partial class Layout
		{

			// aapt resource value: 0x7f030000
			public const int FirstView = 2130903040;

			// aapt resource value: 0x7f030001
			public const int Item_Kitten = 2130903041;

			// aapt resource value: 0x7f030002
			public const int SplashScreen = 2130903042;

			static Layout()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Layout()
			{
			}
		}

		public partial class String
		{

			// aapt resource value: 0x7f060001
			public const int ApplicationName = 2131099649;

			// aapt resource value: 0x7f060000
			public const int Hello = 2131099648;

			static String()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private String()
			{
			}
		}

		public partial class Style
		{

			// aapt resource value: 0x7f050000
			public const int Theme_Splash = 2131034112;

			static Style()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Style()
			{
			}
		}

		public partial class Styleable
		{

			public static int[] MvxBinding = new int[] {
					2130771968,
					2130771969};

			// aapt resource value: 0
			public const int MvxBinding_MvxBind = 0;

			// aapt resource value: 1
			public const int MvxBinding_MvxLang = 1;

			public static int[] MvxControl = new int[] {
					2130771970};

			// aapt resource value: 0
			public const int MvxControl_MvxTemplate = 0;

			public static int[] MvxImageView = new int[] {
					2130771973};

			// aapt resource value: 0
			public const int MvxImageView_MvxSource = 0;

			public static int[] MvxListView = new int[] {
					2130771971,
					2130771972};

			// aapt resource value: 1
			public const int MvxListView_MvxDropDownItemTemplate = 1;

			// aapt resource value: 0
			public const int MvxListView_MvxItemTemplate = 0;

			static Styleable()
			{
				global::Android.Runtime.ResourceIdManager.UpdateIdValues();
			}

			private Styleable()
			{
			}
		}
	}
}
#pragma warning restore 1591


text:
	<form class="ui form" autocomplete="off" novalidate>

修改个人设置

			    姓名

			            <input type="text" name="firstName" data-ng-model="user.firstName" placeholder="姓">

			            <input type="text" name="lastName" data-ng-model="user.lastName" placeholder="名">

	        	Email

					<input type="email" id="email" name="email" class="form-control" data-ng-model="user.email" placeholder="邮箱">

		        username

		            <input type="text" id="username" name="username" class="form-control" data-ng-model="user.username" placeholder="会员用户名默认为会员卡号">

 保  存

			Profile Saved Successfully

	</form>


text:
module Shirtsio
  class ShirtsioObject
    include Enumerable

    attr_accessor :api_key
    @@permanent_attributes = Set.new([:api_key, :id])

    # The default :id method is deprecated and isn't useful to us
    if method_defined?(:id)
      undef :id
    end

    def initialize(id=nil, api_key=nil)
      # parameter overloading!
      if id.kind_of?(Hash)
        @retrieve_options = id.dup
        @retrieve_options.delete(:id)
        id = id[:id]
      else
        @retrieve_options = {}
      end

      @api_key = api_key
      @values = {}
      # This really belongs in APIResource, but not putting it there allows us
      # to have a unified inspect method
      @unsaved_values = Set.new
      @transient_values = Set.new
      self.id = id if id
    end

    def self.construct_from(values, api_key=nil)
      obj = self.new(values[:id], api_key)
      obj.refresh_from(values, api_key)
      obj
    end

    def to_s(*args)
      ShirtsioObject::JSON.dump(@values, :pretty => true)
    end

    def inspect()
      id_string = (self.respond_to?(:id) && !self.id.nil?) ? " id=#{self.id}" : ""
      "#<#{self.class}:0x#{self.object_id.to_s(16)}#{id_string}> JSON: " + ShirtsioObject::JSON.dump(@values, :pretty => true)
    end

    def refresh_from(values, api_key, partial=false)
      @api_key = api_key

      removed = partial ? Set.new : Set.new(@values.keys - values.keys)
      added = Set.new(values.keys - @values.keys)
      # Wipe old state before setting new.  This is useful for e.g. updating a
      # customer, where there is no persistent card parameter.  Mark those values
      # which don't persist as transient

      instance_eval do
        remove_accessors(removed)
        add_accessors(added)
      end
      removed.each do |k|
        @values.delete(k)
        @transient_values.add(k)
        @unsaved_values.delete(k)
      end
      values.each do |k, v|
        @values[k] = Util.convert_to_shirtsio_object(v, api_key)
        @transient_values.delete(k)
        @unsaved_values.delete(k)
      end
    end

    def [](k)
      @values[k.to_sym]
    end

    def []=(k, v)
      send(:"#{k}=", v)
    end

    def keys
      @values.keys
    end

    def values
      @values.values
    end

    def to_json(*a)
      ShirtsioObject::JSON.dump(@values)
    end

    def as_json(*a)
      @values.as_json(*a)
    end

    def to_hash
      @values
    end

    def each(&blk)
      @values.each(&blk)
    end

    protected

    def metaclass
      class << self; self; end
    end

    def remove_accessors(keys)
      metaclass.instance_eval do
        keys.each do |k|
          next if @@permanent_attributes.include?(k)
          k_eq = :"#{k}="
          remove_method(k) if method_defined?(k)
          remove_method(k_eq) if method_defined?(k_eq)
        end
      end
    end

    def add_accessors(keys)
      metaclass.instance_eval do
        keys.each do |k|
          next if @@permanent_attributes.include?(k)
          k_eq = :"#{k}="
          define_method(k) { @values[k] }
          define_method(k_eq) do |v|
            @values[k] = v
            @unsaved_values.add(k)
          end
        end
      end
    end

    def method_missing(name, *args)
      # TODO: only allow setting in updateable classes.
      if name.to_s.end_with?('=')
        attr = name.to_s[0...-1].to_sym
        @values[attr] = args[0]
        @unsaved_values.add(attr)
        add_accessors([attr])
        return
      else
        return @values[name] if @values.has_key?(name)
      end

      begin
        super
      rescue NoMethodError => e
        if @transient_values.include?(name)
          raise NoMethodError.new(e.message + ".  HINT: The '#{name}' attribute was set in the past, however.  It was then wiped when refreshing the object with the result returned by Shirtsio's API, probably as a result of a save().  The attributes currently available on this object are: #{@values.keys.join(', ')}")
        else
          raise
        end
      end
    end
  end
end


text:
namespace boost { namespace geometry
{

// Internal struct to uniquely identify a segment
// on a linestring,ring
// or polygon (needs ring_index)
// or multi-geometry (needs multi_index)
struct segment_identifier
{
    inline segment_identifier()
        : source_index(-1)
        , multi_index(-1)
        , ring_index(-1)
        , segment_index(-1)
        , piece_index(-1)
    {}

    inline segment_identifier(signed_size_type src,
                              signed_size_type mul,
                              signed_size_type rin,
                              signed_size_type seg)
        : source_index(src)
        , multi_index(mul)
        , ring_index(rin)
        , segment_index(seg)
        , piece_index(-1)
    {}

    inline bool operator<(segment_identifier const& other) const
    {
        return source_index != other.source_index ? source_index < other.source_index
            : multi_index !=other.multi_index ? multi_index < other.multi_index
            : ring_index != other.ring_index ? ring_index < other.ring_index
            : piece_index != other.piece_index ? piece_index < other.piece_index
            : segment_index < other.segment_index
            ;
    }

    inline bool operator==(segment_identifier const& other) const
    {
        return source_index == other.source_index
            && segment_index == other.segment_index
            && ring_index == other.ring_index
            && piece_index == other.piece_index
            && multi_index == other.multi_index
            ;
    }

#if defined(BOOST_GEOMETRY_DEBUG_SEGMENT_IDENTIFIER)
    friend std::ostream& operator<<(std::ostream &os, segment_identifier const& seg_id)
    {
        os
            << "s:" << seg_id.source_index
            << ", v:" << seg_id.segment_index // v:vertex because s is used for source
            ;
        if (seg_id.ring_index >= 0) os << ", r:" << seg_id.ring_index;
        if (seg_id.multi_index >= 0) os << ", m:" << seg_id.multi_index;
        if (seg_id.piece_index >= 0) os << ", p:" << seg_id.piece_index;
        return os;
    }
#endif

    signed_size_type source_index;
    signed_size_type multi_index;
    signed_size_type ring_index;
    signed_size_type segment_index;

    // For buffer - todo: move this to buffer-only
    signed_size_type piece_index;
};

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace overlay
{

// Create a ring identifier from a segment identifier
inline ring_identifier ring_id_by_seg_id(segment_identifier const& seg_id)
{
    return ring_identifier(seg_id.source_index, seg_id.multi_index, seg_id.ring_index);
}

}} // namespace detail::overlay
#endif // DOXYGEN_NO_DETAIL

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_SEGMENT_IDENTIFIER_HPP


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
using Orleans.TestingHost;
using Orleans.TestingHost.Utils;
using Orleans.Transactions.TestKit.Correctnesss;

namespace Orleans.Transactions.TestKit
{
    public class TransactionRecoveryTestsRunner : TransactionTestRunnerBase
    {
        private static readonly TimeSpan RecoveryTimeout = TimeSpan.FromSeconds(60);
        // reduce to or remove once we fix timeouts abort
        private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(1);

        private readonly TestCluster testCluster;
        private readonly ILogger logger;

        protected void Log(string message)
        {
            this.testOutput($"[{DateTime.Now}] {message}");
            this.logger.LogInformation(message);
        }

        private class ExpectedGrainActivity
        {
            public ExpectedGrainActivity(Guid grainId, ITransactionalBitArrayGrain grain)
            {
                this.GrainId = grainId;
                this.Grain = grain;
            }
            public Guid GrainId { get; }
            public ITransactionalBitArrayGrain Grain { get; }
            public BitArrayState Expected { get; } = new BitArrayState();
            public BitArrayState Unambiguous { get; } = new BitArrayState();
            public List<BitArrayState> Actual { get; set; }
            public async Task GetActual()
            {
                try
                {
                    this.Actual = await this.Grain.Get();
                } catch(Exception)
                {
                    // allow a single retry
                    await Task.Delay(TimeSpan.FromSeconds(30));
                    this.Actual = await this.Grain.Get();
                }
            }
        }

        public TransactionRecoveryTestsRunner(TestCluster testCluster, Action<string> testOutput)
            : base(testCluster.GrainFactory, testOutput)
        {
            this.testCluster = testCluster;
            this.logger = this.testCluster.ServiceProvider.GetService<ILogger<TransactionRecoveryTestsRunner>>();
        }

        public virtual Task TransactionWillRecoverAfterRandomSiloGracefulShutdown(string transactionTestGrainClassName, int concurrent)
        {
            return TransactionWillRecoverAfterRandomSiloFailure(transactionTestGrainClassName, concurrent, true);
        }

        public virtual Task TransactionWillRecoverAfterRandomSiloUnGracefulShutdown(string transactionTestGrainClassName, int concurrent)
        {
            return TransactionWillRecoverAfterRandomSiloFailure(transactionTestGrainClassName, concurrent, false);
        }

        protected virtual async Task TransactionWillRecoverAfterRandomSiloFailure(string transactionTestGrainClassName, int concurrent, bool gracefulShutdown)
        {
            var endOnCommand = new[] { false };
            var index = new[] { 0 };
            Func<int> getIndex = () => index[0]++;
            List<ExpectedGrainActivity> txGrains = Enumerable.Range(0, concurrent * 2)
                .Select(i => Guid.NewGuid())
                .Select(grainId => new ExpectedGrainActivity(grainId, TestGrain<ITransactionalBitArrayGrain>(transactionTestGrainClassName, grainId)))
                .ToList();
            //ping all grains to activate them
            await WakeupGrains(txGrains.Select(g=>g.Grain).ToList());
            List<ExpectedGrainActivity>[] transactionGroups = txGrains
                .Select((txGrain, i) => new { index = i, value = txGrain })
                .GroupBy(v => v.index / 2)
                .Select(g => g.Select(i => i.value).ToList())
                .ToArray();
            var txSucceedBeforeInterruption = await AllTxSucceed(transactionGroups, getIndex());
            txSucceedBeforeInterruption.Should().BeTrue();
            await ValidateResults(txGrains, transactionGroups);

            // have transactions in flight when silo goes down
            Task<bool> succeeding = RunWhileSucceeding(transactionGroups, getIndex, endOnCommand);
            await Task.Delay(TimeSpan.FromSeconds(2));

            var siloToTerminate = this.testCluster.Silos[ThreadSafeRandom.Next(this.testCluster.Silos.Count)];
            this.Log($"Warmup transaction succeeded. {(gracefulShutdown ? "Stopping" : "Killing")} silo {siloToTerminate.SiloAddress} ({siloToTerminate.Name}) and continuing");

            if (gracefulShutdown)
                await this.testCluster.StopSiloAsync(siloToTerminate);
            else
                await this.testCluster.KillSiloAsync(siloToTerminate);

            this.Log("Waiting for transactions to stop completing successfully");
            var complete = await Task.WhenAny(succeeding, Task.Delay(TimeSpan.FromSeconds(30)));
            endOnCommand[0] = true;
            bool endedOnCommand = await succeeding;
            if (endedOnCommand) this.Log($"No transactions failed due to silo death.  Test may not be valid");

            this.Log($"Waiting for system to recover. Performed {index[0]} transactions on each group.");
            var transactionGroupsRef = new[] { transactionGroups };
            await TestingUtils.WaitUntilAsync(lastTry => CheckTxResult(transactionGroupsRef, getIndex, lastTry), RecoveryTimeout, RetryDelay);
            this.Log($"Recovery completed. Performed {index[0]} transactions on each group. Validating results.");
            await ValidateResults(txGrains, transactionGroups);
        }

        private Task WakeupGrains(List<ITransactionalBitArrayGrain> grains)
        {
            var tasks =  new List<Task>();
            foreach (var grain in grains)
            {
                tasks.Add(grain.Ping());
            }
            return Task.WhenAll(tasks);
        }

        private async Task<bool> RunWhileSucceeding(List<ExpectedGrainActivity>[] transactionGroups, Func<int> getIndex, bool[] end)
        {
            // Loop until failure, or getTime changes
            while (await AllTxSucceed(transactionGroups, getIndex()) && !end[0])
            {
            }
            return end[0];
        }

        private async Task<bool> CheckTxResult(List<ExpectedGrainActivity>[][] transactionGroupsRef, Func<int> getIndex, bool assertIsTrue)
        {
            // only retry failed transactions
            transactionGroupsRef[0] = await RunAllTxReportFailed(transactionGroupsRef[0], getIndex());
            bool succeed = transactionGroupsRef[0] == null;
            this.Log($"All transactions succeed after interruption : {succeed}");
            if (assertIsTrue)
            {
                //consider it recovered if all tx succeed
                this.Log($"Final check : {succeed}");
                succeed.Should().BeTrue();
                return succeed;
            }
            else
            {
                return succeed;
            }
        }

        // Runs all transactions and returns failed;
        private async Task<List<ExpectedGrainActivity>[]> RunAllTxReportFailed(List<ExpectedGrainActivity>[] transactionGroups, int index)
        {
            List<Task> tasks = transactionGroups
                .Select(p => SetBit(p, index))
                .ToList();
            try
            {
                await Task.WhenAll(tasks);
                return null;
            }
            catch (Exception)
            {
                // Collect the indices of the transaction groups which failed their transactions for diagnostics.
                List<ExpectedGrainActivity>[] failedGroups = tasks.Select((task, i) => new { task, i }).Where(t => t.task.IsFaulted).Select(t => transactionGroups[t.i]).ToArray();
                this.Log($"Some transactions failed. Index: {index}. {failedGroups.Length} out of {tasks.Count} failed. Failed groups: {string.Join(", ", failedGroups.Select(transactionGroup => string.Join(":", transactionGroup.Select(a => a.GrainId))))}");
                return failedGroups;
            }
        }

        private async Task<bool> AllTxSucceed(List<ExpectedGrainActivity>[] transactionGroups, int index)
        {
            // null return indicates none failed
            return (await RunAllTxReportFailed(transactionGroups, index) == null);
        }

        private async Task SetBit(List<ExpectedGrainActivity> grains, int index)
        {
            try
            {
                await this.grainFactory.GetGrain<ITransactionCoordinatorGrain>(Guid.NewGuid()).MultiGrainSetBit(grains.Select(v => v.Grain).ToList(), index);
                grains.ForEach(g =>
                {
                    g.Expected.Set(index, true);
                    g.Unambiguous.Set(index, true);
                });
            }
            catch (OrleansTransactionAbortedException e)
            {
                this.Log($"Some transactions failed. Index: {index}: Exception: {e.GetType().Name}");
                grains.ForEach(g =>
                {
                    g.Expected.Set(index, false);
                    g.Unambiguous.Set(index, true);
                });
                throw;
            }
            catch (Exception e)
            {
                this.Log($"Ambiguous transaction failure. Index: {index}: Exception: {e.GetType().Name}");
                grains.ForEach(g =>
                {
                    g.Expected.Set(index, false);
                    g.Unambiguous.Set(index, false);
                });
                throw;
            }
        }

        private async Task ValidateResults(List<ExpectedGrainActivity> txGrains, List<ExpectedGrainActivity>[] transactionGroups)
        {
            await Task.WhenAll(txGrains.Select(a => a.GetActual()));
            this.Log($"Got all {txGrains.Count} actual values");

            bool pass = true;
            foreach (List<ExpectedGrainActivity> transactionGroup in transactionGroups)
            {
                if (transactionGroup.Count == 0) continue;
                BitArrayState first = transactionGroup[0].Actual.FirstOrDefault();
                foreach (ExpectedGrainActivity activity in transactionGroup.Skip(1))
                {
                    BitArrayState actual = activity.Actual.FirstOrDefault();
                    BitArrayState difference = first ^ actual;
                    if (difference.Value.Any(v => v != 0))
                    {
                        this.Log($"Activity on grain {activity.GrainId} did not match activity on {transactionGroup[0].GrainId}:\n"
                                 + $"{first} ^\n"
                                 + $"{actual} = \n"
                                 + $"{difference}\n"
                                 + $"Activation: {activity.GrainId}");
                        pass = false;
                    }

                }
            }

            int i = 0;
            foreach (ExpectedGrainActivity activity in txGrains)
            {
                BitArrayState expected = activity.Expected;
                BitArrayState unambiguous = activity.Unambiguous;
                BitArrayState unambuguousExpected = expected & unambiguous;
                List<BitArrayState> actual = activity.Actual;
                BitArrayState first = actual.FirstOrDefault();
                if (first == null)
                {
                    this.Log($"No activity for {i} ({activity.GrainId})");
                    pass = false;
                    continue;
                }

                int j = 0;
                foreach (BitArrayState result in actual)
                {
                    // skip comparing first to first.
                    if (ReferenceEquals(first, result)) continue;
                    // Check if each state is identical to the first state.
                    var difference = result ^ first;
                    if (difference.Value.Any(v => v != 0))
                    {
                        this.Log($"Activity on grain {i}, state {j} did not match 'first':\n"
                                 + $"  {first}\n"
                                 + $"^ {result}\n"
                                 + $"= {difference}\n"
                                 + $"Activation: {activity.GrainId}");
                        pass = false;
                    }

                    j++;
                }

                // Check if the unambiguous portions of the first match.
                var unambiguousFirst = first & unambiguous;
                var unambiguousDifference = unambuguousExpected ^ unambiguousFirst;

                if (unambiguousDifference.Value.Any(v => v != 0))
                {
                    this.Log(
                        $"First state on grain {i} did not match 'expected':\n"
                        + $"  {unambuguousExpected}\n"
                        + $"^ {unambiguousFirst}\n"
                        + $"= {unambiguousDifference}\n"
                        + $"Activation: {activity.GrainId}");
                    pass = false;
                }

                i++;
            }
            this.Log($"Report complete : {pass}");
            pass.Should().BeTrue();
        }
    }
}


text:
<?php

namespace Label305\Auja\Page;

use Label305\Auja\AujaItem;

/**
 * An abstract class which represents a page component.
 *
 * @author  Niek Haarman - <niek@label305.com>
 *
 * @package Label305\Auja\Page
 * @license http://www.apache.org/licenses/LICENSE-2.0
 */
abstract class PageComponent extends AujaItem {

}


text:
import sys, os
print("imported sys & os")

# try:
#     from rich import pretty as _pp
#     _pp.install()
#     _pp = print
# except ImportError:
#     from pprint import pprint as _pp

# def __displayhook(value):
#     if value is None:
#         return
#     __builtins__._ = value
#     _pp(value)

# sys.displayhook = __displayhook

try:
    __IPYTHON__
    running_under_ipython = True
except NameError:
    running_under_ipython = False

if running_under_ipython:
    from IPython.core.magic import register_line_magic

    @register_line_magic("rev")
    def lmagic(line):
        "Rev line"
        return line[::-1]


text:
module Aerogel::Admin

  def self.registered(app)
    setup_reloader(app) if Aerogel.config.aerogel.reloader?

    # module initialization
  end

  def self.setup_reloader(app)
    app.use Aerogel::Reloader, :routes, before: true do
      Aerogel::Admin::Menu.reset!
    end
  end
end # module Aerogel::Admin


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

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

    <title>psycopg2.pool – Connections pooling — Psycopg 2.4.5 documentation</title>

    <link rel="stylesheet" href="_static/psycopg.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Psycopg 2.4.5 documentation" href="index.html" />
    <link rel="next" title="psycopg2.extras – Miscellaneous goodies for Psycopg 2" href="extras.html" />
    <link rel="prev" title="psycopg2.tz – tzinfo implementations for Psycopg 2" href="tz.html" />

Navigation

          index

          modules |

          next |

          previous |

Psycopg 2.4.5 documentation »

<tt class="xref py py-obj docutils literal">psycopg2.pool</tt> – Connections pooling¶

Creating new PostgreSQL connections can be an expensive operation.  This
module offers a few pure Python classes implementing simple connection pooling
directly in the client application.

class <tt class="descclassname">psycopg2.pool.</tt><tt class="descname">AbstractConnectionPool</tt><big>(</big>minconn, maxconn, *args, **kwargs<big>)</big>¶

Base class implementing generic key-based pooling code.

New minconn connections are created automatically. The pool will support
a maximum of about maxconn connections.  *args and **kwargs are
passed to the <tt class="xref py py-obj docutils literal">connect()</tt> function.

The following methods are expected to be implemented by subclasses:

<tt class="descname">getconn</tt><big>(</big>key=None<big>)</big>¶

Get a free connection and assign it to key if not <tt class="xref py py-obj docutils literal">None</tt>.

<tt class="descname">putconn</tt><big>(</big>conn, key=None, close=False<big>)</big>¶

Put away a connection.

If close is <tt class="xref py py-obj docutils literal">True</tt>, discard the connection from the pool.

<tt class="descname">closeall</tt><big>(</big><big>)</big>¶

Close all the connections handled by the pool.

Note that all the connections are closed, including ones
eventually in use by the application.

The following classes are <tt class="xref py py-obj docutils literal">AbstractConnectionPool</tt> subclasses ready to
be used.

class <tt class="descclassname">psycopg2.pool.</tt><tt class="descname">SimpleConnectionPool</tt><big>(</big>minconn, maxconn, *args, **kwargs<big>)</big>¶

A connection pool that can’t be shared across different threads.

Note

This pool class is useful only for single-threaded applications.

class <tt class="descclassname">psycopg2.pool.</tt><tt class="descname">ThreadedConnectionPool</tt><big>(</big>minconn, maxconn, *args, **kwargs<big>)</big>¶

A connection pool that works with the threading module.

Note

This pool class can be safely used in multi-threaded applications.

class <tt class="descclassname">psycopg2.pool.</tt><tt class="descname">PersistentConnectionPool</tt><big>(</big>minconn, maxconn, *args, **kwargs<big>)</big>¶

A pool that assigns persistent connections to different threads.

Note that this connection pool generates by itself the required keys
using the current thread id.  This means that until a thread puts away
a connection it will always get the same connection object by successive
<tt class="xref py py-obj docutils literal">getconn()</tt> calls. This also means that a thread can’t use more than one
single connection from the pool.

Note

This pool class is mostly designed to interact with Zope and probably
not useful in generic applications.

Previous topic

<tt class="docutils literal docutils literal">psycopg2.tz</tt> –  <tt class="docutils literal docutils literal">tzinfo</tt> implementations for Psycopg 2

Next topic

<tt class="docutils literal docutils literal docutils literal">psycopg2.extras</tt> – Miscellaneous goodies for Psycopg 2

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

Psycopg 2.4.5 documentation »

        © Copyright 2001-2011, Federico Di Gregorio. Documentation by Daniele Varrazzo.
      Created using Sphinx 1.1.3.


text:
<?php
use Tuum\View\Renderer;
use Tuum\Web\View\Value;

/** @var Renderer $this */
/** @var Value $view */

$page_selection = [3 => 3, 5 => 5, 10 => 10, 20 => 20];
?>

Pagination

This page demonstrates the outcome of the WScore/Paginate package.

PaginateFull class

<?= $view->data->page1; ?>

PaginateMini class

<?= $view->data->page2; ?>

Changing Per Page

Please change the number of list per page below to see how pagination changes.

    <form class="form">

            row per page
            <?= $view->forms->select('_limit', $page_selection)
                ->value($view->data->_limit)
                ->class('form-control')->style('width:5em'); ?>
            <input type="submit" value="set per page" class="btn btn-primary">

    </form>


text:
import numpy as np

## Contour data class.
#  Attributes:
#  * segments: list of segment data.
#      - segment: list of points (n x 2 numpy.array).
#  * closing: if True, [p1, ..., pn] -> [p1, ..., pn, p1].
class Contour:
    ## Constructor
    def __init__(self, segments=[], closing=False):
        self._segments = segments
        self._closing = closing

    def setSegments(self, segments):
        self._segments = segments

    def segments(self):
        return self._segments

    def setClosing(self, closing):
        self._closing = closing

    def closing(self):
        return self._closing

    ## Resample contours.
    def resample(self, span=10):
        segments_resampled = []

        for segment in self._segments:
            segment_resampled = list(segment[::span])
            segment_resampled.append(segment[-1])

            segments_resampled.append(np.array(segment_resampled))

        self._segments = segments_resampled

    ## Clip contours by clipping Mask.
    def clipByMask(self, M_8U, endpoints=True):
        if M_8U is None:
            return

        segments_clipped = []

        for segment in self._segments:
            segment_clipped = []

            p_start = None

            for p in segment:
                if M_8U[p[1], p[0]] == 255:
                    p_start = p

                    if len(segment_clipped) > 0:
                        if endpoints:
                            segment_clipped.append(p)

                        segments_clipped.append(np.array(segment_clipped))
                        segment_clipped = []
                        p_start = None

                    continue

                if endpoints:
                    if p_start is not None:
                        segment_clipped.append(p_start)
                        p_start = None

                segment_clipped.append(p)

            if len(segment_clipped) > 0:
                segments_clipped.append(np.array(segment_clipped))

        p = self._segments[0][0]
        if M_8U[p[1], p[0]] == 255:
            self.setClosing(False)

        self._segments = segments_clipped


text:
=pod

=head1 NAME

RC4_set_key, RC4 - RC4 encryption

=head1 SYNOPSIS

 #include <openssl/rc4.h>

 void RC4_set_key(RC4_KEY *key, int len, const unsigned char *data);

 void RC4(RC4_KEY *key, unsigned long len, const unsigned char *indata,
          unsigned char *outdata);

=head1 DESCRIPTION

This library implements the Alleged RC4 cipher, which is described for
example in I<Applied Cryptography>.  It is believed to be compatible
with RC4[TM], a proprietary cipher of RSA Security Inc.

RC4 is a stream cipher with variable key length.  Typically, 128 bit
(16 byte) keys are used for strong encryption, but shorter insecure
key sizes have been widely used due to export restrictions.

RC4 consists of a key setup phase and the actual encryption or
decryption phase.

RC4_set_key() sets up the B<RC4_KEY> B<key> using the B<len> bytes long
key at B<data>.

RC4() encrypts or decrypts the B<len> bytes of data at B<indata> using
B<key> and places the result at B<outdata>.  Repeated RC4() calls with
the same B<key> yield a continuous key stream.

Since RC4 is a stream cipher (the input is XORed with a pseudo-random
key stream to produce the output), decryption uses the same function
calls as encryption.

Applications should use the higher level functions
L<EVP_EncryptInit(3)|EVP_EncryptInit(3)>
etc. instead of calling the RC4 functions directly.

=head1 RETURN VALUES

RC4_set_key() and RC4() do not return values.

=head1 NOTE

Certain conditions have to be observed to securely use stream ciphers.
It is not permissible to perform multiple encryptions using the same
key stream.

=head1 SEE ALSO

L<blowfish(3)|blowfish(3)>, L<des(3)|des(3)>, L<rc2(3)|rc2(3)>

=head1 HISTORY

RC4_set_key() and RC4() are available in all versions of SSLeay and OpenSSL.

=cut


text:
package org.seasar.doma.internal.jdbc.command;

import java.lang.reflect.Method;

import junit.framework.TestCase;

import org.seasar.doma.internal.jdbc.mock.ColumnMetaData;
import org.seasar.doma.internal.jdbc.mock.MockConfig;
import org.seasar.doma.internal.jdbc.mock.MockResultSet;
import org.seasar.doma.internal.jdbc.mock.MockResultSetMetaData;
import org.seasar.doma.internal.jdbc.mock.RowData;
import org.seasar.doma.internal.jdbc.util.SqlFileUtil;
import org.seasar.doma.jdbc.NonUniqueResultException;
import org.seasar.doma.jdbc.SqlLogType;
import org.seasar.doma.jdbc.query.SqlFileSelectQuery;

import example.domain.PhoneNumber;
import example.domain._PhoneNumber;

/**
 * @author taedium
 *
 */
public class DomainSingleResultHandlerTest extends TestCase {

    private final MockConfig runtimeConfig = new MockConfig();

    private Method method;

    @Override
    protected void setUp() throws Exception {
        method = getClass().getMethod(getName());
    }

    public void testHandle() throws Exception {
        MockResultSetMetaData metaData = new MockResultSetMetaData();
        metaData.columns.add(new ColumnMetaData("x"));
        MockResultSet resultSet = new MockResultSet(metaData);
        resultSet.rows.add(new RowData("01-2345-6789"));

        SqlFileSelectQuery query = new SqlFileSelectQuery();
        query.setConfig(runtimeConfig);
        query.setSqlFilePath(SqlFileUtil.buildPath(getClass().getName(),
                getName()));
        query.setCallerClassName("aaa");
        query.setCallerMethodName("bbb");
        query.setMethod(method);
        query.setSqlLogType(SqlLogType.FORMATTED);
        query.prepare();

        DomainSingleResultHandler<String, PhoneNumber> handler = new DomainSingleResultHandler<String, PhoneNumber>(
                _PhoneNumber.getSingletonInternal());
        PhoneNumber result = handler.handle(resultSet, query, (i, next) -> {
        }).get();
        assertEquals("01-2345-6789", result.getValue());
    }

    public void testHandle_NonUniqueResultException() throws Exception {
        MockResultSetMetaData metaData = new MockResultSetMetaData();
        metaData.columns.add(new ColumnMetaData("phoneNumber"));
        MockResultSet resultSet = new MockResultSet(metaData);
        resultSet.rows.add(new RowData("01-2345-6789"));
        resultSet.rows.add(new RowData("02-2345-6789"));

        SqlFileSelectQuery query = new SqlFileSelectQuery();
        query.setConfig(runtimeConfig);
        query.setSqlFilePath(SqlFileUtil.buildPath(getClass().getName(),
                getName()));
        query.setCallerClassName("aaa");
        query.setCallerMethodName("bbb");
        query.setMethod(method);
        query.setSqlLogType(SqlLogType.FORMATTED);
        query.prepare();

        DomainSingleResultHandler<String, PhoneNumber> handler = new DomainSingleResultHandler<String, PhoneNumber>(
                _PhoneNumber.getSingletonInternal());
        try {
            handler.handle(resultSet, query, (i, next) -> {
            });
            fail();
        } catch (NonUniqueResultException expected) {
        }
    }

}


text:
Blocco dati e schemi:

![Schema01](http://i.imgur.com/Rf11RoS.jpg)
--
BASIC AND INFRASTRUCTURE
--
Main Job Families

- Manufacturing and Production (decline)
(Assembly and Factory Workers)
- Architecture and Engineering (decline)
(Chemical Engineers; Civil Engineers)
- Construction and Extraction (decline)
(Mining and Petroleum Extraction Workers; Construction Laborers)
- Management (stable)
(Business Services and Administration Managers; Manufacturing, Mining and Construction Managers)

Ease of recruitment current: HARD
Ease of recruitment 2020: HARDER

--
CONSUMER
--
Main Job Families

- Manufacturing and Production (decline)
(Assembly and Factory Workers; Food Processing and Related Trades Workers);
- Sales and Related (stable)
(Shop Salespersons; Sales Representative, Wholsale and Technical)
- Business and Financial Operatcions (stable)
(Sales and Marketing Professionals; Management and Organisation Analysts)
- Management (decline)
(General and Operations Managers; Business Services and Administration Managers)

Ease of recruitment current: HARD
Ease of recruitment 2020: HARDER

--
ENERGY
--
Main Job Families

- Architecture and Engineering (growth)
(Energy and Petroleum Engineers; Electrotechnology Engineers)
- Manufacturing and Production (decline)
(Assembly and Factory Workers; Petroleum and Natural Gas Refining Plant Operators)
- Management (growth)
(General and Operations Managers; Business Services and Administration Managers)
- Construction and Extraction (decline)
(Mining and Petroleum Extraction Workers; Mining and Petroleum Plant Operators)

Ease of recruitment current: HARD
Ease of recruitment 2020: NEUTRAL

--
FINANCIAL SERVICES AND INVESTORS
--
Main Job Families

- Business and Financial Operations (stable)
(Financial and Investmen Advisers; Investement Fund Managers)
- Computer and Mathematical (growth)
(Data Analusts; Information Security Analysts)
- Sales and Related (stable)
(Securities and Finance Dealers and Brokers; Sales and Purchasing Agents and Brokers)
- Management (growth)
(General and Operations Managers; Business Services and Administration Managers)
Ease of recruitment current: HARD
Ease of recruitment 2020: HARDER

--
HEALTHCARE
--
Main Job Families

- Manufacturing and Production (stable)
(Chemical Processing Plant Operators; Assembly and Factory Workers)
- Life, Physical and Social Sciences (stable)
(Biologist and Geneticists; Chemists and Cemical Laboratory Scientists)
- Sales and Related (decline)
(Shop salespersons; Sales Representatives, Techincal and Scientific)
- Personal Care and Service (-)
(Personal Care Aides)

Ease of recruitment current: HARD
Ease of recruitment 2020: HARDER

--
INFORMATION AND COMMUNICATION TECHNOLOGY
--
Main Job Families

- Computer and Mathematical (growth)
(Database and Network Professionals; Software and Applications Developers and Analysts)
- Sales and Related (growth)
(Telemarketers; Sales Representatives, Wholesale and Technical)
- Installation and Maintenance (decline)
(Mechanics and Machinery Repairers; Electronics and Telecommunications Installer and Repaires)
- Architecture and Engineering (growth)
(Electrotechnology Engineers; Architects and Serveyors)

Ease of recruitment current: HARD
Ease of recruitment 2020: ¬HARDER

--
MEDIA, ENTERTAINMENT AND INFORMATION
--
Main Job Families

- Art, Design, entertainment, Sports and Media (stable)
(Advertising and Public Relations Professionals; Telecommunication and Broadcasting Technicians)
- Computer and Matchematical (strong growth)
(Data Analysts; Software and Applications Developers and Analysts)
- Sales and Related (growth)
(Cashiers and Ticket Clerks; Door-To-Doot Sales Workers, News and Street Vendors)
- Management (growth)
(General and Operations Managers; Business Services and Administration Managers)

Ease of recruitment current: HARD
Ease of recruitment 2020: ¬HARDER

--
MOBILITY
--
Main Job Families

- Manufacturing and Production (decline)
(Manufacturing and Factory Workers; Sheet and Structural Metal Workers)
- Architecture and Engineering (growth)
(Electrotechnology Engineers; Industrial and Product Engineers)
- Transportation and Logistics (growth)
(Supply Chain and Logistics Specialists; Transportation Attendants and Conductors)
- Sales and Related (decline)
(Sales and Marketing Professionals; Sales Representatives, Wholsale and Technical)

Ease of recruitment current: HARD
Ease of recruitment 2020: HARDER

--
PROFESSIONAL SERVICES
--
Main Job Families

- Business and Financial Operations (stable)
(Management and Organisation Analysts; human Resourcers Specialists)
- Computer and Mathematical (strong growth)
(Data Analysts; Software and Applications Developers and Analysts)
- Management (growth)
(General and Operations Managers; Business Services and Administration Managers)
- Sales and Related (decline)
(Sales and Marketing Professionals; Real Estate Sales Agents)

Ease of recruitment current: HARD
Ease of recruitment 2020: ¬HARDER

![Schema01](http://i.imgur.com/Q7j0Ngz.png)