text:
import { tmpdir } from 'os'
import { join } from 'path'
import fs from 'mz/fs'
import uuid from 'uuid'
import del from 'del'
import webpack from './webpack'
import replaceCurrentBuild from './replace'
import md5File from 'md5-file/promise'

export default async function build (dir, conf = null) {
  const buildId = uuid.v4()
  const buildDir = join(tmpdir(), uuid.v4())
  const compiler = await webpack(dir, { buildId, buildDir, conf })

  try {
    await runCompiler(compiler)
    await writeBuildStats(buildDir)
    await writeBuildId(buildDir, buildId)
  } catch (err) {
    console.error(`> Failed to build on ${buildDir}`)
    throw err
  }

  await replaceCurrentBuild(dir, buildDir)

  // no need to wait
  del(buildDir, { force: true })
}

function runCompiler (compiler) {
  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) return reject(err)

      const jsonStats = stats.toJson()

      if (jsonStats.errors.length > 0) {
        const error = new Error(jsonStats.errors[0])
        error.errors = jsonStats.errors
        error.warnings = jsonStats.warnings
        return reject(error)
      }

      resolve(jsonStats)
    })
  })
}

async function writeBuildStats (dir) {
  // Here we can't use hashes in webpack chunks.
  // That's because the "app.js" is not tied to a chunk.
  // It's created by merging a few assets. (commons.js and main.js)
  // So, we need to generate the hash ourself.
  const assetHashMap = {
    'app.js': {
      hash: await md5File(join(dir, '.next', 'app.js'))
    }
  }
  const buildStatsPath = join(dir, '.next', 'build-stats.json')
  await fs.writeFile(buildStatsPath, JSON.stringify(assetHashMap), 'utf8')
}

async function writeBuildId (dir, buildId) {
  const buildIdPath = join(dir, '.next', 'BUILD_ID')
  await fs.writeFile(buildIdPath, buildId, 'utf8')
}


text:
package io.github.stormcloud_dev.stormcloud.frame.itemproc;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

public class ScopeItemProcFrame extends ItemProcFrame {

    private double x;
    private double y;
    private double objectIndex;
    private short mId;

    public ScopeItemProcFrame(double x, double y, double objectIndex, short mId) {
        super((short) 5);
        this.x = x;
        this.y = y;
        this.objectIndex = objectIndex;
        this.mId = mId;
    }

    @Override
    public int getLength() {
        return 29;
    }

    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public double getObjectIndex() {
        return objectIndex;
    }

    public short getMId() {
        return mId;
    }

    @Override
    public void writeData(ByteBuf buf) {
        super.writeData(buf);
        buf.writeDouble(getX());
        buf.writeDouble(getY());
        buf.writeDouble(getObjectIndex());
        buf.writeShort(getMId());
    }

}

redpajama_set_name: RedPajamaGithub


text:
package de.uxnr.tsoexpert.game.communication.vo.guild;

import de.uxnr.amf.v3.AMF3_Object;

public class GuildPlayerPermissionVO extends AMF3_Object {
  private int banner;
  private int description;
  private int guildMail;
  private int invite;
  private int joinRequestAccept;
  private int joinRequestAllow;
  private int kick;
  private int motd;
  private int note;
  private int officerNote;
  private int officersChannel;
  private int ranksAssign;
  private int ranksEdit;

  public int getBanner() {
    return this.banner;
  }

  public int getDescription() {
    return this.description;
  }

  public int getGuildMail() {
    return this.guildMail;
  }

  public int getInvite() {
    return this.invite;
  }

  public int getJoinRequestAccept() {
    return this.joinRequestAccept;
  }

  public int getJoinRequestAllow() {
    return this.joinRequestAllow;
  }

  public int getKick() {
    return this.kick;
  }

  public int getMotd() {
    return this.motd;
  }

  public int getNote() {
    return this.note;
  }

  public int getOfficerNote() {
    return this.officerNote;
  }

  public int getOfficersChannel() {
    return this.officersChannel;
  }

  public int getRanksAssign() {
    return this.ranksAssign;
  }

  public int getRanksEdit() {
    return this.ranksEdit;
  }
}


text:
typedef enum {
    kLKSStreamCameraFocusModeContinuous = 0, // Continunally auto focus and expose in the center but don't monitor subject area for changes
    kLKSStreamCameraFocusModeAuto, // Auto focus and expose - not continuous, and listen for subject area changes
    kLKSStreamCameraFocusModeLocked
} LKSStreamCameraFocusMode;

@interface LKSStreamCamera ()

// Session management.
@property (nonatomic) dispatch_queue_t sessionQueue; // Communicate with the session and other session objects on this queue.
@property (nonatomic) AVCaptureSession *session;
@property (nonatomic) AVCaptureDeviceInput *captureDeviceInput;
@property (nonatomic) AVCaptureStillImageOutput *stillImageOutput;
@property (nonatomic) AVCaptureVideoPreviewLayer *captureVideoPreviewLayer;

@property (nonatomic,assign) BOOL authOK;
@property (nonatomic,assign) BOOL deviceExists;

// Utilities.
@property (nonatomic) id runtimeErrorHandlingObserver;

@property (nonatomic,assign,readwrite) LKSStreamCameraScaleMode scaleMode;
@property (nonatomic,assign) CGRect viewFrame;
@property (nonatomic,assign) BOOL tapToFocusEnabled;

@property (nonatomic,assign,readonly) BOOL isRunning;
@property (nonatomic,assign) BOOL paused;

@end

@implementation LKSStreamCamera

-(id) initWithViewFrame:(CGRect)viewFrame scaleMode:(LKSStreamCameraScaleMode)scaleMode tapToFocusEnabled:(BOOL)tapToFocusEnabled {

    if (self = [super init]){

        self.scaleMode = scaleMode;
        self.viewFrame = viewFrame;
        self.tapToFocusEnabled = tapToFocusEnabled;

    }

    return self;
}

- (void)viewDidLoad {

    [super viewDidLoad];

    self.view.frame = self.viewFrame;

    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;

    [self.view setBackgroundColor:[UIColor clearColor]];

    // Check if camera exists

    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {

        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Camera not found", nil)
                                    message:NSLocalizedString(@"A camera is requried to take photos", nil)
                                   delegate:self
                          cancelButtonTitle:NSLocalizedString(@"OK", nil)
                          otherButtonTitles:nil] show];

        return;
    }

    self.deviceExists = YES;

    dispatch_queue_t sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL);
    self.sessionQueue = sessionQueue;

    // Check auth
    [self checkDeviceAuthorizationStatus];

    dispatch_async(self.sessionQueue, ^{

        // AV Foundation
        // =============
        // https://developer.apple.com/library/ios/documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html

        if ([session canSetSessionPreset:AVCaptureSessionPresetPhoto]) {
            session.sessionPreset = AVCaptureSessionPresetPhoto;
        } else {
            [self onError:@"Ivalid session preset"];
        }

        // Find device
        // -----------

        AVCaptureDevice *device;

        NSArray *devices = [AVCaptureDevice devices];

        for (AVCaptureDevice *aDevice in devices) {
            if ([aDevice hasMediaType:AVMediaTypeVideo]) {
                if ([aDevice position] == AVCaptureDevicePositionBack) {
                    NSLog(@"Device name: %@", [aDevice localizedName]);
                    device = aDevice;
                }
            }
        }

        if (!device) {
            [self onError:@"Back camera not present"];
            return;
        }

        // Configure device
        // ----------------

        // An instance of AVCaptureDevice to represent the input device, such as a camera or microphone

        [self focusAtPoint:CGPointMake(0.5f, 0.5f) mode:kLKSStreamCameraFocusModeContinuous];

        // Flash set to Auto for Still Capture
        [self setFlashMode:AVCaptureFlashModeAuto];

        // An instance of a concrete subclass of AVCaptureInput to configure the ports from the input device

        // Hookup device
        // -------------

        NSError *deviceInputError;
        self.captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&deviceInputError];
        if (!self.captureDeviceInput){
            [self onError:deviceInputError.localizedDescription];
        }
        if ([session canAddInput:self.captureDeviceInput]) {
            [session addInput:self.captureDeviceInput];
        } else {
            [self onError:@"Unable to add device input"];
            return;
        }

        // Create capture output
        // ---------------------

        // An instance of a concrete subclass of AVCaptureOutput to manage the output to a movie file or still image

        self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
        if (self.stillImageOutput.stillImageStabilizationSupported){
            [self.stillImageOutput automaticallyEnablesStillImageStabilizationWhenAvailable];
        }
        self.stillImageOutput.highResolutionStillImageOutputEnabled = YES;
        NSDictionary *outputSettings = @{ AVVideoCodecKey : AVVideoCodecJPEG};
        [self.stillImageOutput setOutputSettings:outputSettings];
        if ([session canAddOutput:self.stillImageOutput]) {
            [session addOutput:self.stillImageOutput];
        } else {
            [self onError:@"Unable to add output"];
            return;
        }

        // Hookup video preview
        // --------------------

        // NOTE: Maybe this goes after auth?

        AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
        self.captureVideoPreviewLayer = captureVideoPreviewLayer;

        dispatch_async(dispatch_get_main_queue(), ^{

            if (self.scaleMode == kLKSStreamCameraModeCrop){
                [self.view.layer setMasksToBounds:YES];
                captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
            } else {
                captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspect;
            }
            captureVideoPreviewLayer.frame = self.view.bounds;
            [self.view.layer addSublayer:captureVideoPreviewLayer];

            if ([captureVideoPreviewLayer.connection isVideoOrientationSupported]){
                [captureVideoPreviewLayer.connection setVideoOrientation:(AVCaptureVideoOrientation)[self interfaceOrientation]];
            }
        });

    });
}

- (void)viewWillAppear:(BOOL)animated {

    if (!self.sessionQueue){
        return;
    }

    dispatch_async(self.sessionQueue, ^{

        if (!self.locked){
            [self listenForFocusEvents:YES];
        }

        // Attempt session reboot
        __weak LKSStreamCamera *weakSelf = self;
        [self setRuntimeErrorHandlingObserver:[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification object:self.session queue:nil usingBlock:^(NSNotification *note) {

            LKSStreamCamera *strongSelf = weakSelf;
            dispatch_async([strongSelf sessionQueue], ^{
                // Manually restarting the session since it must have been stopped due to an error.
                [self.session startRunning];
            });

        }]];

        [self.session startRunning];

    });
}

- (void)viewDidDisappear:(BOOL)animated {

    if (!self.sessionQueue){
        return;
    }

    dispatch_async(self.sessionQueue, ^{

        [self listenForFocusEvents:NO];

        [self.session stopRunning];

        [[NSNotificationCenter defaultCenter] removeObserver:self.runtimeErrorHandlingObserver];

    });
}

-(void) viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Actions

// Returns nil |image| nil |error| when busy
-(BOOL) takeSnapShot: (void (^)(UIImage *image, NSError *error)) handler {

    //CGSize size = CMVideoFormatDescriptionGetPresentationDimensions(camera.activeFormat.formatDescription, YES, YES);

    if (!self.isRunning || self.busy){
        return NO;
    }

    self.busy = YES;

    dispatch_async([self sessionQueue], ^{

        // Update the orientation on the still image output video connection before capturing.
        [[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:  self.captureVideoPreviewLayer.connection.videoOrientation];

        if (self.stillImageOutput.capturingStillImage){
            handler(nil,nil);
            return;
        }

        // Capture a still image.
        [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

            if (error){
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(nil, error);
                    self.busy = NO;
                });
            } else if (imageDataSampleBuffer){

                //CFDictionaryRef exifAttachments = CMGetAttachment(imageDataSampleBuffer, kCGImagePropertyExifDictionary, NULL);
                //if (exifAttachments) {
                    // Do something with the attachments.
                //}

                NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                UIImage *image = [[UIImage alloc] initWithData:imageData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    handler(image, nil);
                    self.busy = NO;
                });

                // [[[ALAssetsLibrary alloc] init] writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:nil];

            }
        }];
    });

    return YES;
}

#pragma mark - Orientation

- (BOOL)shouldAutorotate {

    return YES;

}

- (NSUInteger)supportedInterfaceOrientations {

    return UIInterfaceOrientationMaskLandscape;

}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {

    if ([self.captureVideoPreviewLayer.connection isVideoOrientationSupported]){
        [self.captureVideoPreviewLayer.connection setVideoOrientation:(AVCaptureVideoOrientation)toInterfaceOrientation];
    }

}

#pragma mark - Focus

-(void) listenForFocusEvents:(BOOL)listen {

    // Tap to focus
    // ------------

    for (NSUInteger i = 0; i < self.view.gestureRecognizers.count; i++){
        [self.view removeGestureRecognizer:[self.view.gestureRecognizers objectAtIndex:i]];
        i--;
    }

    if (self.tapToFocusEnabled){

        if (listen){

            UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleFocusTap:)];
            [self.view addGestureRecognizer:singleFingerTap];

        }
    }

    // Subject area changes
    // --------------------

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:self.captureDeviceInput.device];
    if (listen){
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object: self.captureDeviceInput.device];
    }
}

-(void) handleFocusTap: (UITapGestureRecognizer*)recognizer {

    CGPoint location = [recognizer locationInView: recognizer.view];
    CGPoint focalPoint = [self.captureVideoPreviewLayer captureDevicePointOfInterestForPoint:location];

    focalPoint.x = fmaxf(focalPoint.x, 0.0f);
    focalPoint.x = fminf(focalPoint.x, 1.0f);
    focalPoint.y = fmaxf(focalPoint.y, 0.0f);
    focalPoint.y = fminf(focalPoint.y, 1.0f);

    [self focusAtPoint:focalPoint mode:kLKSStreamCameraFocusModeAuto];

}

// |continuousMode| Do not monitor subject area for changes but adjust
// exposure and focus continuously
// !|continuousMode| Auto focus and exposure at point and listen for subject
// matter changes
-(void) focusAtPoint:(CGPoint)focalPoint mode:(LKSStreamCameraFocusMode)mode {

    dispatch_async([self sessionQueue], ^{

        AVCaptureExposureMode exposureMode;
        AVCaptureWhiteBalanceMode whiteBalanceMode;
        AVCaptureFocusMode focusMode;
        BOOL monitorSubjectArea;

        if (mode == kLKSStreamCameraFocusModeContinuous){

            exposureMode = AVCaptureExposureModeContinuousAutoExposure;
            whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
            focusMode = AVCaptureFocusModeContinuousAutoFocus;
            monitorSubjectArea = false;

        } else if (mode == kLKSStreamCameraFocusModeAuto){

            exposureMode = AVCaptureExposureModeAutoExpose;
            whiteBalanceMode = AVCaptureWhiteBalanceModeAutoWhiteBalance;
            focusMode = AVCaptureFocusModeAutoFocus;
            monitorSubjectArea = true;

        } else { // Locked

            exposureMode = AVCaptureExposureModeLocked;
            whiteBalanceMode = AVCaptureWhiteBalanceModeLocked;
            focusMode = AVCaptureFocusModeLocked;
            monitorSubjectArea = false;

        }

        AVCaptureDevice *device = self.captureDeviceInput.device;

        NSError *error = nil;
        if ([device lockForConfiguration:&error]){

            if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:focusMode]){
                [device setFocusMode:focusMode];
                if (mode != kLKSStreamCameraFocusModeLocked){
                    [device setFocusPointOfInterest:focalPoint];
                }
            }

            if ([device isExposurePointOfInterestSupported] && [device isExposureModeSupported:exposureMode]) {
                [device setExposureMode:exposureMode];
                if (mode != kLKSStreamCameraFocusModeLocked){
                    [device setExposurePointOfInterest:focalPoint];
                }
            }

            if ([device isWhiteBalanceModeSupported:whiteBalanceMode]) {
                [device setWhiteBalanceMode:whiteBalanceMode];
            }

            // Indicates whether the device should monitor the subject area for changes.
            [device setSubjectAreaChangeMonitoringEnabled:monitorSubjectArea];

            [device unlockForConfiguration];

        } else {

            [self onError:error.localizedDescription];

        }
    });
}

-(void) pausePreview: (BOOL)pause {

    if (!self.sessionQueue){
        return;
    }

    if (pause && self.isRunning){

        dispatch_async(self.sessionQueue, ^{

            [self listenForFocusEvents:NO];

            [self.session stopRunning];

            [[NSNotificationCenter defaultCenter] removeObserver:self.runtimeErrorHandlingObserver];

        });
    }

    if (!pause && !self.isRunning && self.authOK && self.deviceExists && self.session) {

        dispatch_async(self.sessionQueue, ^{
            if (!self.locked){
                [self listenForFocusEvents:YES];
            }
            // Attempt session reboot
            __weak LKSStreamCamera *weakSelf = self;
            [self setRuntimeErrorHandlingObserver:[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification object:self.session queue:nil usingBlock:^(NSNotification *note) {

                LKSStreamCamera *strongSelf = weakSelf;
                dispatch_async([strongSelf sessionQueue], ^{
                    // Manually restarting the session since it must have been stopped due to an error.
                    [self.session startRunning];
                });

            }]];
            [self.session startRunning];

        });
    }
}

-(void) setLocked:(BOOL)locked {

    if (_locked != locked){
        _locked = locked;

        if (locked){
            [self focusAtPoint:CGPointMake(0.5f, 0.5f) mode:kLKSStreamCameraFocusModeLocked];
        } else {
            [self focusAtPoint:CGPointMake(0.5f, 0.5f) mode:kLKSStreamCameraFocusModeContinuous];
        }

        if (self.isRunning){
            [self listenForFocusEvents:!locked];
        }
    }
}

- (void)subjectAreaDidChange:(NSNotification *)notification {

    [self focusAtPoint:CGPointMake(0.5f, 0.5f) mode:kLKSStreamCameraFocusModeContinuous];

}

-(void)setFlashMode:(AVCaptureFlashMode)flashMode {

    AVCaptureDevice *device = self.captureDeviceInput.device;

    if ([device hasFlash] && [device isFlashModeSupported:flashMode]){

        NSError *error = nil;
        if ([device lockForConfiguration:&error]){
            [device setFlashMode:flashMode];
            [device unlockForConfiguration];
        } else {
            [self onError:error.localizedDescription];
        }

    }
}

#pragma mark - Authorization

- (void)checkDeviceAuthorizationStatus {

    NSString *mediaType = AVMediaTypeVideo;

    [AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {

        if (granted){

            self.authOK = YES;

        } else {

            //Not granted access to mediaType
            dispatch_async(dispatch_get_main_queue(), ^{

                [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Camera access required", nil)
                                            message:NSLocalizedString(@"This app does not have permission to access the camera. Please enable camera access in settings to continue", nil)
                                           delegate:self
                                  cancelButtonTitle:NSLocalizedString(@"OK", nil)
                                  otherButtonTitles:nil] show];

                self.authOK = NO;

            });
        }
    }];
}

#pragma mark - Error handling

-(void) onError:(NSString*)msg {

    // Choose to suppress these or not down the track

    dispatch_async(dispatch_get_main_queue(), ^{

        if (kSupressErrors){

            NSLog(@"ERROR:%@",msg);

        } else {

            [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ERROR", nil)
                                        message:msg
                                       delegate:self
                              cancelButtonTitle:NSLocalizedString(@"OK", nil)
                              otherButtonTitles:nil] show];

        }
    });
}

#pragma mark - Check status

-(BOOL) isRunning {

    return self.authOK && self.deviceExists && self.session && self.session.isRunning;

}

@end


text:
package org.apache.flink.connector.file.table;

import org.apache.flink.annotation.Internal;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;

/** A bin packing implementation. */
@Internal
public class BinPacking {
    private BinPacking() {}

    public static <T> List<List<T>> pack(
            Iterable<T> items, Function<T, Long> weightFunc, long targetWeight) {
        List<List<T>> packed = new ArrayList<>();
        Deque<Bin<T>> bins = new LinkedList<>();

        for (T item : items) {
            long weight = weightFunc.apply(item);
            Bin<T> bin = findBin(bins, weight);

            if (bin != null) {
                bin.add(item, weight);
            } else {
                bin = new Bin<>(targetWeight);
                bin.add(item, weight);
                bins.addLast(bin);

                // avoid n * n algorithm complexity
                if (bins.size() > 10) {
                    packed.add(bins.removeFirst().items());
                }
            }
        }

        bins.forEach(bin -> packed.add(bin.items));
        return packed;
    }

    private static <T> Bin<T> findBin(Iterable<Bin<T>> bins, long weight) {
        for (Bin<T> bin : bins) {
            if (bin.canAdd(weight)) {
                return bin;
            }
        }
        return null;
    }

    private static class Bin<T> {
        private final long targetWeight;
        private final List<T> items = new ArrayList<>();
        private long binWeight = 0L;

        Bin(long targetWeight) {
            this.targetWeight = targetWeight;
        }

        List<T> items() {
            return items;
        }

        boolean canAdd(long weight) {
            return binWeight + weight <= targetWeight;
        }

        void add(T item, long weight) {
            this.binWeight += weight;
            items.add(item);
        }
    }
}


text:
Kirby
=====

BDD for Developers


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerCollision : MonoBehaviour {

    [SerializeField]
    private int m_playerNum;

    [SerializeField]
    private float m_respawnTime = 3.0f;

    [SerializeField]
    private GameObject m_deathParticles;
    [SerializeField]
    private GameObject m_lastParticles;

    private PlayerAudio m_audio;

    void Start()
    {
        m_audio = GetComponent<PlayerAudio>();
    }

    void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Crush")
        {
            if (GameController.Instance.remainingTime <= 0)
                return;

            // Hit
            m_audio.PlayEffect(1);
            GameController.Instance.AddScore(-5, m_playerNum);
            m_lastParticles = Instantiate(m_deathParticles, transform.position, /*transform.Find("Mesh").*/transform.rotation) as GameObject;
            transform.position = GameController.Instance.hidePosition.position;
            StartCoroutine(RespawnCount());
        }

        if(other.tag == "Pickup")
        {
            // Pickup
            m_audio.PlayEffect(0);
            GameController.Instance.AddScore(1, m_playerNum);
            Destroy(other.gameObject);
        }
    }

    private IEnumerator RespawnCount()
    {
        yield return new WaitForSeconds(m_respawnTime / 2);
        m_audio.PlayEffect(2);
        yield return new WaitForSeconds(m_respawnTime / 2);

        if (m_lastParticles != null)
            Destroy(m_lastParticles);

        transform.position = GameController.Instance.GetSpawnPos(m_playerNum).position;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.CMS.Content.Models;
using Kooboo.CMS.Content.Query;
using System.Runtime.Serialization;

namespace Kooboo.CMS.Sites.DataRule
{
    [DataContract(Name = "SchemaDataRule")]
    [KnownTypeAttribute(typeof(SchemaDataRule))]
    public class SchemaDataRule : DataRuleBase
    {
        [DataMember(Order = 13)]
        public string SchemaName { get; set; }

        public override Content.Query.IContentQuery<Content.Models.TextContent> Execute(DataRuleContext dataRuleContext)
        {
            var site = dataRuleContext.Site;
            var repositoryName = site.Repository;
            if (string.IsNullOrEmpty(repositoryName))
            {
                throw new KoobooException("The repository for site is null.");
            }
            var repository = new Repository(repositoryName);
            var schema = new Schema(repository, SchemaName);
            var contentQuery = (IContentQuery<Content.Models.TextContent>)schema.CreateQuery();

            contentQuery.Where(WhereClauses.Parse(schema,dataRuleContext.ValueProvider));

            return contentQuery;
        }
        public override DataRuleType DataRuleType
        {
            get { return DataRuleType.Schema; }
        }

        public override Schema GetSchema(Repository repository)
        {
            return new Schema(repository, SchemaName);
        }
    }
}


text: export { default } from 'ember-handoff/adapters/server-page';


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

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>pandas.Series.aggregate — pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation</title>
    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="pandas.Series.align" href="pandas.Series.align.html" />
    <link rel="prev" title="pandas.Series.agg" href="pandas.Series.agg.html" />

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

pandas.Series »

Table Of Contents

What's New

Installation

Contributing to pandas

Package overview

10 Minutes to pandas

Tutorials

Cookbook

Intro to Data Structures

Essential Basic Functionality

Working with Text Data

Options and Settings

Indexing and Selecting Data

MultiIndex / Advanced Indexing

Computational tools

Working with missing data

Group By: split-apply-combine

Merge, join, and concatenate

Reshaping and Pivot Tables

Time Series / Date functionality

Time Deltas

Categorical Data

Visualization

Styling

IO Tools (Text, CSV, HDF5, …)

Enhancing Performance

Sparse data structures

Frequently Asked Questions (FAQ)

rpy2 / R interface

pandas Ecosystem

Comparison with R / R libraries

Comparison with SQL

Comparison with SAS

Comparison with Stata

API Reference

Input/Output

General functions

Series

Constructor

Attributes

Conversion

Indexing, iteration

Binary operator functions

Function application, GroupBy & Window

pandas.Series.apply

pandas.Series.agg

pandas.Series.aggregate

pandas.Series.transform

pandas.Series.map

pandas.Series.groupby

pandas.Series.rolling

pandas.Series.expanding

pandas.Series.ewm

pandas.Series.pipe

Computations / Descriptive Stats

Reindexing / Selection / Label manipulation

Missing data handling

Reshaping, sorting

Combining / joining / merging

Time series-related

Datetimelike Properties

String handling

Categorical

Plotting

Serialization / IO / Conversion

Sparse

DataFrame

Panel

Index

Numeric Index

CategoricalIndex

IntervalIndex

MultiIndex

DatetimeIndex

TimedeltaIndex

PeriodIndex

Scalars

Frequencies

Window

GroupBy

Resampling

Style

Plotting

General utility functions

Extensions

Developer

Internals

Extending Pandas

Release Notes

Search

                <form class="search" action="../search.html" method="get">
                    <input type="text" name="q" size="18"/>
                    <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.

pandas.Series.aggregate¶

Series.aggregate(func, axis=0, *args, **kwargs)[source]¶

Aggregate using one or more operations over the specified axis.

New in version 0.20.0.

<col class="field-name" />
<col class="field-body" />

Parameters:
func : function, string, dictionary, or list of string/functions

Function to use for aggregating the data. If a function, must either
work when passed a Series or when passed to Series.apply. For
a DataFrame, can pass a dict, if the keys are DataFrame column names.

Accepted combinations are:

string function name.

function.

list of functions.

dict of column names -> functions (or list of functions).

axis : {0 or 'index'}

Parameter needed for compatibility with DataFrame.

*args

Positional arguments to pass to func.

**kwargs

Keyword arguments to pass to func.

Returns:

aggregated : Series

See also

pandas.Series.apply, pandas.Series.transform

Notes

agg is an alias for aggregate. Use the alias.

A passed user-defined-function will be passed a Series for evaluation.

Examples

>>> s = Series(np.random.randn(10))

>>> s.agg('min')
-1.3018049988556679

>>> s.agg(['min', 'max'])
min   -1.301805
max    1.127688
dtype: float64

Navigation

          index

          modules |

          next |

          previous |

pandas 0.24.0.dev0+81.g8d5032a8c.dirty documentation »

API Reference »

pandas.Series »

Scroll To Top


text:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"  xmlns:th="http://www.thymeleaf.org">

	<head th:fragment="pageContent" th:remove="tag" >

		<title th:inline="text"> [[ ${ lifecycle + ":" + csapApp.getName() } ]] </title>

		<script th:replace="~{ csap/fragments/libsAndStyles :: pageContent }"></script>

		<script th:replace="csap/fragments/jqplot-includes :: pageContent"></script>

		<script th:src="@{ ${csapApp.versionedUrl('/js/csapLibs/commonJQ.js')} }"></script>
		<script th:src="@{ ${csapApp.versionedUrl('/js/csapLibs/csapUtils/CsapUser.js')} }"></script>

		<link th:href="@{ ${csapApp.versionedUrl('/js/csapLibs/qtip/jquery.qtip.min.css')} }" rel="stylesheet"  type="text/css" media="screen" />
		<script th:src="@{ ${csapApp.versionedUrl('/js/csapLibs/qtip/jquery.qtip.min.js')} }"></script>

		<link th:href="@{ ${csapApp.versionedUrl('/js/csapLibs/jquery.contextMenu.css')} }" rel="stylesheet"  type="text/css" media="screen" />
		<script th:src="@{ ${csapApp.versionedUrl('/js/csapLibs/jquery.contextMenu.js')} }"></script>

		<script th:inline="javascript">
			var inHostMode = false;
			var contextUrl = [[@{ ${"/"} }]];
			var baseUrl = [[@{ ${ T(org.csap.agent.CsapCoreService).SERVICE_URL}}]];
			var reportUrl = baseUrl + "/report";
			var trendUrl = baseUrl + "/trend";
			var appId = [[${ eventUser }]];
			var agentHostUrlPattern = [[${ agentHostUrlPattern }]];
			var desktopTestProject = "";
			if ([[${csapApp.isRunningOnDesktop()}]]) {
			appId = "csapeng.gen";
			desktopTestProject = "CSAP Engineering";
			}

			var activePackge = [[ ${csapApp.activeModelName}]];
			var analyticsUrl = [[${analyticsUrl}]];
			var activityUrl = baseUrl + "/activityCount";
			var historyUrl = [[${lifeCycleSettings.historyUiUrl}]];
			var eventApiUrl = [[${lifeCycleSettings.eventApiUrl}]];
			// fixed in Thymeleaf 3
			var httpdArray = [[     ${ testUrls }     ]]  ;
		//    for ( i=0; i< httpdArray.length; i++) { console.log("testUrl: " + httpdArray[i]) ; }

			var hostName = [[${T(org.csap.agent.model.Application).HOST_NAME}]];
			var lb = [[${lifeCycleSettings.lbUrl}]];
			var userid = [[${userid}]];
			var deployTimeout = 10000; // default 10s
			var serviceName = "null";
			var defaultLifeCycle = [[${lifecycle}]];
			CsapCommon.configureCsapAlertify();
		</script>

		<script th:src="@{ ${csapApp.versionedUrl('/js/deployment/serviceContext.js')} }"></script>

		<script th:src="@{ ${csapApp.versionedUrl('/js/deployment/menus.js')} }"></script>

		<!--
		<script th:src="@{ ${csapApp.versionedUrl('/js/deployment/services.js')} }"></script> -->

		<script  th:attr="data-main=@{ ${csapApp.requiresUrl('/js/deployment/modules/app-portal-main.js')}   }"
		th:src="@{/webjars/requirejs/2.1.20/require.min.js}"></script>
		<link th:href="@{ ${csapApp.versionedUrl('/js/deployment/services.css')} }" rel="stylesheet"  type="text/css" media="screen" />

		<script th:src="@{ ${csapApp.versionedUrl('/js/deployment/service-dialog-batch.js')} }"></script>
		<link th:href="@{ ${csapApp.versionedUrl('/js/deployment/service-dialog-batch.css')} }" rel="stylesheet"  type="text/css" media="screen" />

	</head>

</html>


text:
<?php defined('SYSPATH') or die('No direct script access.');
/**
 * Created by PhpStorm.
 * User: jinhan
 * Date: 2016/5/13
 * Time: 0:56
 */
class Controller_login extends Controller_Template{
    public $template = 'login.tpl';
    public function action_index(){

    }
    public function action_filter(){

    }
    public function action_loginapi(){
        $this -> auto_render = FALSE;
        //if ($this -> request -> is_ajax()) //判断是否为ajax请求
        {
            $data = $this->request->post();
            $query = Login::loginchack($data);
            if (sizeof($query) == 1)
                echo 'success';
            else
                echo 'false';
            exit;

        }
    }
}


text:
Public-key cryptography refers to a cryptographic system requiring two separate
keys, one of which is secret and one of which is public. Although different, the
two parts of the key pair are mathematically linked. One key locks or encrypts
the plaintext, and the other unlocks or decrypts the cyphertext. Neither key can
perform both functions. One of these keys is published or public, while the
other is kept private.

In zend-crypt, we implement two public key algorithms:

- [Diffie-Hellman](http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange)
  key exchange, and
- [RSA](http://en.wikipedia.org/wiki/RSA_%28algorithm%29).

## Diffie-Hellman

The Diffie-Hellman algorithm is a specific method of exchanging cryptographic
keys. It is one of the earliest practical examples of key exchange implemented
within the field of cryptography. The Diffie–Hellman key exchange method allows
two parties that have no prior knowledge of each other to jointly establish a
shared secret key over an insecure communications channel. This key can then be
used to encrypt subsequent communications using a symmetric key cipher.

The diagram of operation of the Diffie-Hellman algorithm can be defined by the
following picture (taken from the [Diffie-Hellman](http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange)
Wikipedia page):

![Diffie-Hellman algorithm](images/zend.crypt.public-key.diffie-hellman.png)

The schema's colors represent the parameters of the algorithm.

Below is an example demonstrating usage of `Zend\Crypt\PublicKey\DiffieHellman`:

```php
use Zend\Crypt\PublicKey\DiffieHellman;

$aliceOptions = [
    'prime' => '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227'
        . '423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580'
        . '104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925'
        . '984760375594985848253359305585439638443',
    'generator'=> '2',
    'private'  => '992093140665725952364085695919679885571412495614942674862518080355353963322786201435363176'
        . '813127128916726230726309951803243888416814918577455156967890911274095150092503589658166661'
        . '463420498381785213791321533481399080168191962194483101070726325157493390557981225386151351'
        . '04828702523796951800575031871051678091',
];

$bobOptions   = [
    'prime'    => $aliceOptions['prime'],
    'generator'=> '2',
    'private'  => '334117357926395586257336357178925636125481806504021611510774783148414637079488997861035889'
        . '123256347304105519467727528801778689728169635518217403867000760342134081539246925625431179'
        . '634647331566005454845108330724270034742070646507148310833044977371603820970833568760781462'
        . '31616972608703322302585471319261275664',
);

$alice = new DiffieHellman(
    $aliceOptions['prime'],
    $aliceOptions['generator'],
    $aliceOptions['private']
);
$bob = new DiffieHellman(
    $bobOptions['prime'],
    $bobOptions['generator'],
    $bobOptions['private']
);

$alice->generateKeys();
$bob->generateKeys();

$aliceSecretKey = $alice->computeSecretKey(
    $bob->getPublicKey(DiffieHellman::FORMAT_BINARY),
    DiffieHellman::FORMAT_BINARY,
    DiffieHellman::FORMAT_BINARY
);

$bobSecretKey = $bob->computeSecretKey(
    $alice->getPublicKey(DiffieHellman::FORMAT_BINARY),
    DiffieHellman::FORMAT_BINARY,
    DiffieHellman::FORMAT_BINARY
);

if ($aliceSecretKey !== $bobSecretKey) {
    echo "ERROR!\n";
} else {
    printf("The secret key is: %s\n", base64_encode($aliceSecretKey));
}
```

The parameters of the Diffie-Hellman class are:

- a prime number (p),
- a generator (g) that is a primitive root mod p, and
- a private integer number.

The security of the Diffie-Hellman exchange algorithm is related to the choice
of these parameters. To know how to choose secure numbers you can read the
[RFC 3526](http://tools.ietf.org/html/rfc3526) document.

> ### Openssl
>
> The `Zend\Crypt\PublicKey\DiffieHellman` class by default uses the
> [OpenSSL](http://php.net/manual/en/book.openssl.php) extension to generate the
> parameters. If you don't want to use the OpenSSL library, call
> `DiffieHelmman::useOpensslExtension(false)`.

## RSA

RSA is an algorithm for public-key cryptography that is based on the presumed
difficulty of factoring large integers, known as the [factoring
problem](http://en.wikipedia.org/wiki/Factoring_problem). A user of RSA creates
and then publishes the product of two large prime numbers, along with an
auxiliary value, as their public key. The prime factors must be kept secret.
Anyone can use the public key to encrypt a message, but with currently published
methods, if the public key is large enough, only someone with knowledge of the
prime factors can feasibly decode the message. Whether breaking RSA encryption
is as hard as factoring is an open question.

The RSA algorithm can be used to encrypt/decrypt messages, and also to provide
authenticity and integrity by generating a digital signature of a message.

Suppose that Alice wants to send an encrypted message to Bob. Alice must use the
public key of Bob to encrypt the message. Bob can decrypt the message using his
private key. Because Bob is the only one that can access his private key,
he is the only one that can decrypt the message. If Alice wants to provide
authenticity and integrity of a message to Bob she can use her private key to
sign the message. Bob can check the correctness of the digital signature using
the public key of Alice. Alice can provide encryption, authenticity, and
integrity of a message to Bob using the previous schemas in sequence, applying
the encryption first and the digital signature after.

Below are examples of usage of the `Zend\Crypt\PublicKey\Rsa` class in order to:

- generate a public key and a private key;
- encrypt/decrypt a string;
- generate a digital signature of a file.

### Generate a public key and a private key

In order to generate a public and private key, use the following code:

```php
use Zend\Crypt\PublicKey\RsaOptions;

$rsaOptions = new RsaOptions([
    'pass_phrase' => 'test'
]);

$rsaOptions->generateKeys([
    'private_key_bits' => 2048,
]);

file_put_contents('private_key.pem', $rsaOptions->getPrivateKey());
file_put_contents('public_key.pub', $rsaOptions->getPublicKey());
```

This example generates a 2048-bit public and private key, storing the keys in two separate files,
`private_key.pem` for the private key and `public_key.pub` for the public key. You can also
generate the public and private key using OpenSSL from the command line (Unix style syntax):

```bash
$ ssh-keygen -t rsa
```

### Encrypt and decrypt a string

Below is an example demonstrating encryption and decryption of a string using
the RSA algorithm. You can encrypt only small strings. The maximum size of
encryption is given by the length of the public/private key - 88 bits. For
instance, if we use a size of 2048 bit you can encrypt a string with a maximum
size of 1960 bit (245 characters). This limitation is related to the OpenSSL
implementation for a security reason related to the nature of the RSA algorithm.

The normal application of public key encryption algorithm is to store a key or a
hash of the data you want to encrypt or sign. A hash is typically 128-256 bits
(the PHP `sha1()` function returns a 160 bit hash). An AES encryption key is 128
to 256 bits. Either will comfortably fit inside a single RSA encryption.

```php
use Zend\Crypt\PublicKey\Rsa;

$rsa = Rsa::factory([
    'public_key'    => 'public_key.pub',
    'private_key'   => 'private_key.pem',
    'pass_phrase'   => 'test',
    'binary_output' => false,
]);

$text = 'This is the message to encrypt';

$encrypt = $rsa->encrypt($text);
printf("Encrypted message:\n%s\n", $encrypt);

$decrypt = $rsa->decrypt($encrypt);

if ($text !== $decrypt) {
    echo "ERROR\n";
} else {
    echo "Encryption and decryption performed successfully!\n";
}
```

### Generate a digital signature of a file

Below is an example demonstrating generation of a digital file signature.

```php
use Zend\Crypt\PublicKey\Rsa;

$rsa = Rsa::factory([
    'private_key'   => 'path/to/private_key',
    'pass_phrase'   => 'passphrase of the private key',
    'binary_output' => false,
]);

$file = file_get_contents('path/file/to/sign');

$signature = $rsa->sign($file, $rsa->getOptions()->getPrivateKey());
$verify    = $rsa->verify($file, $signature, $rsa->getOptions()->getPublicKey());

if ($verify) {
    echo "The signature is OK\n";
    file_put_contents($filename . '.sig', $signature);
    echo "Signature save in $filename.sig\n";
} else {
     echo "The signature is not valid!\n";
}
```

In this example, we used the Base64 format to encode the digital signature of the file
(`binary_output` is false).

> ## Openssl
>
> The implementation of the `Zend\Crypt\PublicKey\Rsa` algorithm uses PHP's OpenSSL extension.


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/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Lighthouse: lapack/sggsvp.f File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="tabs.css" rel="stylesheet" type="text/css" />
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

lapack

Functions/Subroutines

sggsvp.f File Reference

Functions/Subroutines

subroutine 	sggsvp (JOBU, JOBV, JOBQ, M, P, N, A, LDA, B, LDB, TOLA, TOLB, K, L, U, LDU, V, LDV, Q, LDQ, IWORK, TAU, WORK, INFO)

 	SGGSVP

Function/Subroutine Documentation

          subroutine sggsvp
          (
          character
          JOBU,

          character
          JOBV,

          character
          JOBQ,

          integer
          M,

          integer
          P,

          integer
          N,

          real, dimension( lda, * )
          A,

          integer
          LDA,

          real, dimension( ldb, * )
          B,

          integer
          LDB,

          real
          TOLA,

          real
          TOLB,

          integer
          K,

          integer
          L,

          real, dimension( ldu, * )
          U,

          integer
          LDU,

          real, dimension( ldv, * )
          V,

          integer
          LDV,

          real, dimension( ldq, * )
          Q,

          integer
          LDQ,

          integer, dimension( * )
          IWORK,

          real, dimension( * )
          TAU,

          real, dimension( * )
          WORK,

          integer
          INFO

          )

SGGSVP

 Download SGGSVP + dependencies

 [TGZ]

 [ZIP]

 [TXT]

Purpose:

 SGGSVP computes orthogonal matrices U, V and Q such that

                    N-K-L  K    L
  U**T*A*Q =     K ( 0    A12  A13 )  if M-K-L >= 0;
                 L ( 0     0   A23 )
             M-K-L ( 0     0    0  )

                  N-K-L  K    L
         =     K ( 0    A12  A13 )  if M-K-L < 0;
             M-K ( 0     0   A23 )

                  N-K-L  K    L
  V**T*B*Q =   L ( 0     0   B13 )
             P-L ( 0     0    0  )

 where the K-by-K matrix A12 and L-by-L matrix B13 are nonsingular
 upper triangular; A23 is L-by-L upper triangular if M-K-L >= 0,
 otherwise A23 is (M-K)-by-L upper trapezoidal.  K+L = the effective
 numerical rank of the (M+P)-by-N matrix (A**T,B**T)**T.

 This decomposition is the preprocessing step for computing the
 Generalized Singular Value Decomposition (GSVD), see subroutine
 SGGSVD.

Parameters

[in]	JOBU
          JOBU is CHARACTER*1
          = 'U':  Orthogonal matrix U is computed;
          = 'N':  U is not computed.

[in]	JOBV
          JOBV is CHARACTER*1
          = 'V':  Orthogonal matrix V is computed;
          = 'N':  V is not computed.

[in]	JOBQ
          JOBQ is CHARACTER*1
          = 'Q':  Orthogonal matrix Q is computed;
          = 'N':  Q is not computed.

[in]	M
          M is INTEGER
          The number of rows of the matrix A.  M >= 0.

[in]	P
          P is INTEGER
          The number of rows of the matrix B.  P >= 0.

[in]	N
          N is INTEGER
          The number of columns of the matrices A and B.  N >= 0.

[in,out]	A
          A is REAL array, dimension (LDA,N)
          On entry, the M-by-N matrix A.
          On exit, A contains the triangular (or trapezoidal) matrix
          described in the Purpose section.

[in]	LDA
          LDA is INTEGER
          The leading dimension of the array A. LDA >= max(1,M).

[in,out]	B
          B is REAL array, dimension (LDB,N)
          On entry, the P-by-N matrix B.
          On exit, B contains the triangular matrix described in
          the Purpose section.

[in]	LDB
          LDB is INTEGER
          The leading dimension of the array B. LDB >= max(1,P).

[in]	TOLA
          TOLA is REAL

[in]	TOLB
          TOLB is REAL

          TOLA and TOLB are the thresholds to determine the effective
          numerical rank of matrix B and a subblock of A. Generally,
          they are set to
             TOLA = MAX(M,N)*norm(A)*MACHEPS,
             TOLB = MAX(P,N)*norm(B)*MACHEPS.
          The size of TOLA and TOLB may affect the size of backward
          errors of the decomposition.

[out]	K
          K is INTEGER

[out]	L
          L is INTEGER

          On exit, K and L specify the dimension of the subblocks
          described in Purpose section.
          K + L = effective numerical rank of (A**T,B**T)**T.

[out]	U
          U is REAL array, dimension (LDU,M)
          If JOBU = 'U', U contains the orthogonal matrix U.
          If JOBU = 'N', U is not referenced.

[in]	LDU
          LDU is INTEGER
          The leading dimension of the array U. LDU >= max(1,M) if
          JOBU = 'U'; LDU >= 1 otherwise.

[out]	V
          V is REAL array, dimension (LDV,P)
          If JOBV = 'V', V contains the orthogonal matrix V.
          If JOBV = 'N', V is not referenced.

[in]	LDV
          LDV is INTEGER
          The leading dimension of the array V. LDV >= max(1,P) if
          JOBV = 'V'; LDV >= 1 otherwise.

[out]	Q
          Q is REAL array, dimension (LDQ,N)
          If JOBQ = 'Q', Q contains the orthogonal matrix Q.
          If JOBQ = 'N', Q is not referenced.

[in]	LDQ
          LDQ is INTEGER
          The leading dimension of the array Q. LDQ >= max(1,N) if
          JOBQ = 'Q'; LDQ >= 1 otherwise.

[out]	IWORK
          IWORK is INTEGER array, dimension (N)

[out]	TAU
          TAU is REAL array, dimension (N)

[out]	WORK
          WORK is REAL array, dimension (max(3*N,M,P))

[out]	INFO
          INFO is INTEGER
          = 0:  successful exit
          < 0:  if INFO = -i, the i-th argument had an illegal value.

Author

Univ. of Tennessee

Univ. of California Berkeley

Univ. of Colorado Denver

NAG Ltd.

Date

November 2011

Further Details:

The subroutine uses LAPACK subroutine SGEQPF for the QR factorization with column pivoting to detect the effective numerical rank of the a matrix. It may be replaced by a better rank determination strategy.

<address class="footer">
Generated on Mon Jul 14 2014 18:28:49 for Lighthouse by

 1.8.2
</address>


text:
/**
 * method:
 *
 *  - data api:
 *      data-aside = "hide|show|toggle"
 *  - js:
 *      $(this).aside("toggle"|"show"|"hide")
 *
 * fire aside-show,aside-shown, aside-hide event
 */

;(function ($, window, document) {
    "use strict";
    var Aside = function(element){
        var $btn = $(element);
        this.$el = $($btn.attr("href") || $btn.data("target"));
        if(this.$el.hasClass('aside-push')){

            this.isPush = true;
            var bindEl = this.bindEl = $(this.$el.data("bind"))
                bindEl.addClass('aside-push-obj')
                    .removeClass('aside-push-obj-right')
                    .removeClass('aside-push-obj-left')
                    .removeClass('aside-push-obj-top')
                    .removeClass('aside-push-obj-bottom')

            if (this.$el.hasClass('aside-right')){
                this.bindClass = "aside-push-obj-right"
            }else if (this.$el.hasClass('aside-left')){
                this.bindClass = "aside-push-obj-left"
            }else if (this.$el.hasClass('aside-top')){
                this.bindClass = "aside-push-obj-top"
            }else if (this.$el.hasClass('aside-bottom')){
                this.bindClass = "aside-push-obj-bottom"
            }
            bindEl.addClass(this.bindClass)
        }

    }

    Aside.prototype={
        "show": function(){
            var me = this;
            this.$el
                .removeClass("slideout")
                .addClass("show")
                .addClass("slidein")

            this._apear(this.$el)
            if(this.isPush){
                this.bindEl.removeClass("slideout")
                    .addClass("slidein")
                    .one('click', function(e){
                        me.hide.call(me)
                    })
                    .on('touchmove', this.bindEl, this._preventMove)

            } else { // if $el has class aside-overlay
                this._addBackdrop()
            }
        },
        "hide": function(){
            this.$el
                .removeClass("slidein")
                .addClass("slideout")
                .removeClass("show")

            this._disapear(this.$el)
            if(this.isPush){
                this.bindEl.removeClass("slidein")
                    .addClass("slideout")
                    .off('touchmove', this.bindEl, this._preventMove)
            }else{ // if $el has class aside=-overlay
                this._removeBackdrop()
            }
        },
        "toggle": function(){
            this.$el.hasClass("show") ? this.hide() : this.show();
        },
        "_disapear": function(el){
                setTimeout(function(){
                    el.addClass('disapear');
                },300); //trick for side bar
        },
        "_apear": function(el){
                el.removeClass('disapear');
        },
        "_addBackdrop": function(){
            var me = this;
            this.$el.after("

")
            this.$el.siblings('.aside-backdrop').one('click', function(e){
                e.preventDefault();
                e.stopPropagation();
                this.remove();
                me.hide();
            })
        },
        "_removeBackdrop": function(){
            this.$el.siblings('.aside-backdrop').remove();
        },
        "_preventMove" :function(e){
            e.preventDefault()
        }
    }

    /*
     * ASIDE PLUGIN DEFINITION
     */

    $.fn.aside = function ( option ) {
        return this.each(function () {
            var aside = new Aside(this);
            if (typeof option == 'string') aside[option]();
        });
    }

    /*
     * ASIDE DATA API
     */

    $(document).on('click.data-api', '[data-aside="toggle"]', function (e) {
        e.preventDefault();
        $(this).aside('toggle');
    });

}($, window, document));

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */

;(function (window, document) {
    $(".aside").on("tap",function(){

    });
}(window, document));
;(function ($, window, document) {
    "use strict"; // jshint ;_;
    /**
     * 弹出层和对话框的基础组件
     * 示例:
     *      $(".tips").modal();
     */
    $.fn.Modal = function(options){

    }
    /**
     * 对话框
     * 示例:
     *      $(".dialog").dialog();
     */
    $.fn.Dialog = function(options){
        var me = this;
        this.$el = options.el || $("#dialogPanel");
        if (options){
            if (options.$el) this.$el = $(options.$el);
            if (options.confirm) this.confirm = options.confirm;
        }
        this.$el.find(".btn-confirm").bind("click",function(){
            if(me.confirm){
                me.confirm.call(me,this);
            }
        });
        this.$el.find(".btn-cancel").bind("click",function(){
            me.hide();
        });
    }

    $.fn.Dialog.prototype = {
        pos : function () {
            this.$el.css({
                top     : window.pageYOffset + (window.innerHeight - 85)*0.5 + 'px',
                left    : (window.innerWidth - 216)*0.5 + 'px'
            })
        },
        show : function(options){
            if(this.showed) return;
            this.pos();
            if(options.msg){
                $(".dialog-tip",this.$el).text(options.msg);
            }
            this.$el.addClass("show");
            this.showed = true;
        },
        hide : function(){
            if(!this.showed) return;
            this.$el.removeClass("show");
            this.showed = false;
        }
    };

}($, window, document));
/**
 * nav:
 *     (class)
 *     data-target href
 *
 * content:
 *     (class) tab-content tab-pane
 *
 * methods:
 *     show
 *     activate
 *
 * @todo
 *  动画
 *  绑定 data-api
 *  nav-tab 不在 tab-pane中时 nav-tab的切换
 */
;(function ($, window, document) {

    "use strict";

    /* TAB CLASS DEFINITION */
    var Tab = function (element) {
        this.element = $(element);
    }

    Tab.prototype = {
        show: function () {
            var $this = this.element,
                target_selector = $this.attr('data-target') || $this.attr('href'),
                target = target_selector ? $(target_selector) : $this,
                container = target.closest('.tab-content');

            if ( $this.hasClass('active') ) return;

            var previous = container.find('.tab-pane.active');
            $this.trigger('show', [previous]);
            this.activate(target, container, function () {
                $this.trigger('shown', [previous]);
            })
        },

        activate: function ( element, container, callback) {
            var $active = container.find('.tab-pane.active'),
                transition = callback && $active.hasClass('fade');
            function next() {
                $active.removeClass('active');
                element.addClass('active');
                if (transition) {
                  element[0].offsetWidth; // reflow for transition
                  element.addClass('in');
                } else {
                  element.removeClass('fade');
                }
                callback && callback();
            }
            transition ? $active.one(transition.end, next) : next();
            $active.removeClass('in');
        }
  }

 /*
  * TAB PLUGIN DEFINITION
  */
  $.fn.tab = function ( option ) {
    return this.each(function () {
      var tab = new Tab(this);
      if (typeof option == 'string') tab[option]();
    })
  }

 /*
  * TAB DATA-API
  */

  $(document).on('click.tab.data-api', '[data-toggle="tab"]', function (e) {
    e.preventDefault();
    $(this).tab('show');
  });

}($, window, document));
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */

;(function ($, window, document) {
    "use strict"; // jshint ;_;
    /**
     * 弹出层和对话框的基础组件
     * 示例:
     *      $(".model").modal();
     */
    var Model = function(options){
        var me = this;
        if (!options) return;
        if (typeof options == 'string'){
            this.el = options;
            this.$el = $(this.el);
        }else{
            this.$el = options.$el || $(options.el);
            this.confirm = options.confirm;
        }
        this.$el.find(".btn-confirm").bind("click",function(){
            if(me.confirm){
                me.confirm.call(me,this);
            }
        });
        this.$el.find(".btn-cancel").bind("click",function(){
            me.hide();
        });
    };

    Model.prototype = {
        pos : function () {
            var dialog = this.$el.find('.modal-dialog');
            console.log(dialog);
                dialog.css({
                    //top     : window.pageYOffset + (window.innerHeight - 85)*0.5 + 'px',
                    //left    : (window.innerWidth - 216)*0.5 + 'px'
                })
        },
        show : function(options){
            if(this.showed) return;
            this.pos();
            if(options && options.msg){
                $(".dialog-tip",this.$el).text(options.msg);
            }
            this.$el.removeClass("hide").addClass("show");
            this.showed = true;
            $('body').append('

');
        },
        hide : function(){
            if(!this.showed) return;
            this.$el.removeClass("show").addClass("hide");
            $('.modal-backdrop').remove();
            this.showed = false;
        }
    };

    $.fn.modal = function(options){
        var modal = new Model(options);
        return modal
    }

}($, window, document));

/**
 * nav:
 *     (class)
 *     data-target href
 *
 * content:
 *     (class) tab-content tab-pane
 *
 * methods:
 *     show
 *     activate
 *     hide
 *
 * @todo
 *  动画
 *  绑定 data-api
 *  nav-tab 不在 tab-pane中时 nav-tab的切换
 *  滑动切换
 */
;(function ($, window, document) {

    "use strict";

    /* TAB CLASS DEFINITION */
    var Tab = function (element) {
        this.element = $(element);
    }

    Tab.prototype = {
        show: function () {
            var $this = this.element,
                target_selector = $this.attr('data-target') || $this.attr('href'),
                target = target_selector ? $(target_selector) : $this,
                container = target.closest('.tab-content');

            if ( $this.hasClass('active') ) return;

            var previous = container.find('.tab-pane.active');
            $this.trigger('show', [previous]);
            this.activate(target, container, function () {
                $this.trigger('shown', [previous]);
            })
        },

        activate: function ( element, container, callback) {
            var $active = container.find('.tab-pane.active'),
                transition = callback && $active.hasClass('fade');
            function next() {
                $active.removeClass('active');
                element.addClass('active');
                if (transition) {
                  element[0].offsetWidth; // reflow for transition
                  element.addClass('in');
                } else {
                  element.removeClass('fade');
                }
                callback && callback();
            }
            transition ? $active.one(transition.end, next) : next();
            $active.removeClass('in');
        }
  }

 /*
  * TAB PLUGIN DEFINITION
  */
  $.fn.tab = function ( option ) {
    return this.each(function () {
      var tab = new Tab(this);
      if (typeof option == 'string') tab[option]();
    })
  }

 /*
  * SWIPE PLUGIN
  */

 /*
  * TAB DATA-API
  */

  $(document).on('click.tab.data-api', '[data-toggle="tab"]', function (e) {
    e.preventDefault();
    $(this).tab('show');
  });

}($, window, document));

/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */

// webkit tap highlight color
// -webkit-tap-highlight-color:
// Overrides the highlight color shown when the user taps a link or a JavaScript clickable element in Safari on iPhone.
//
// This property obeys the alpha value, if specified. If you don't specify an alpha value, Safari on iPhone applies a default alpha value to the color. To disable tap highlighting, set the alpha value to 0 (invisible). If you set the alpha value to 1.0 (opaque), the element is not visible when tapped.
// http://stackoverflow.com/questions/2851663/how-do-i-simulate-a-hover-with-a-touch-in-touch-enabled-browsers
// http://phonegap-tips.com/articles/essential-phonegap-css-webkit-tap-highlight-color.html

;(function(){
    // tap 点击延时绑定

    //tap highlight
    if($.os.android){
        $(".tap")
            .live('touchstart',function(){
                $(this).data('background', $(this).css('background'));
                $(this).css('background','#D9E9FF')
            }).live('touchend', function(){
                var background = $(this).data('background');
                if(background){
                    $(this).css('background',background);
                }else{
                    $(this).css('background','transparent')
                }
            })
    }

    //data api

    $(document).on('click.tap', '[data-url]', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var url = $(this).data('url');
        setTimeout(function(){
            location.href = url;
        },300);
    });

    $(document).on('click.tap', '[data-openurl]', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var url = $(this).data('openurl');
        setTimeout(function(){
            window.open(url);
        },300);
    });

}($, window, document));
/* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */

if ($.os.iphone){
    setTimeout(function() {
        window.scrollTo(0, 0);
    },0);
}


text:
package io.netty.handler.codec.http2;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpVersion;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class Http2ClientUpgradeCodecTest {

    @Test
    public void testUpgradeToHttp2ConnectionHandler() throws Exception {
        testUpgrade(new Http2ConnectionHandlerBuilder().server(false).frameListener(new Http2FrameAdapter()).build());
    }

    @Test
    public void testUpgradeToHttp2FrameCodec() throws Exception {
        testUpgrade(Http2FrameCodecBuilder.forClient().build());
    }

    @Test
    public void testUpgradeToHttp2MultiplexCodec() throws Exception {
        testUpgrade(Http2MultiplexCodecBuilder.forClient(new HttpInboundHandler())
            .withUpgradeStreamHandler(new ChannelInboundHandlerAdapter()).build());
    }

    private static void testUpgrade(Http2ConnectionHandler handler) throws Exception {
        FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "*");

        EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
        ChannelHandlerContext ctx = channel.pipeline().firstContext();
        Http2ClientUpgradeCodec codec = new Http2ClientUpgradeCodec("connectionHandler", handler);
        codec.setUpgradeHeaders(ctx, request);
        // Flush the channel to ensure we write out all buffered data
        channel.flush();

        codec.upgradeTo(ctx, null);
        assertNotNull(channel.pipeline().get("connectionHandler"));

        assertTrue(channel.finishAndReleaseAll());
    }

    @ChannelHandler.Sharable
    private static final class HttpInboundHandler extends ChannelInboundHandlerAdapter { }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var data_1 = require("./data");
var moment = require('moment');
function logServer(message) {
    console.log('DMM QUEST: ' + message);
}
exports.logServer = logServer;
function createDefaultAppState(team) {
    var stages = [];
    var appState = {
        bonus: null,
        killer: null,
        stages: stages
    };
    var defaultStages = data_1.defaultData.stages;
    var startFromStage = team.startFromStage;
    var pushNumber = 0;
    for (var i = startFromStage; i < defaultStages.length; i++) {
        var status_1 = i == startFromStage ? 1 /* OPEN */ : 0 /* LOCKED */;
        stages.push({
            id: String(i),
            status: status_1,
            showNumber: pushNumber++
        });
    }
    for (var i = 0; i < startFromStage; i++) {
        var item = {
            id: String(i),
            status: 0 /* LOCKED */,
            showNumber: pushNumber++
        };
        stages.push(item);
    }
    stages[stages.length - 1].last = true;
    appState.bonus = {
        id: 'bonus',
        status: 3 /* BONUS */,
        showNumber: pushNumber++
    };
    appState.killer = {
        id: 'killer',
        status: 6 /* KILLER */,
        showNumber: pushNumber++
    };
    return appState;
}
exports.createDefaultAppState = createDefaultAppState;
function toEkbString(date) {
    return moment(date).tz('Asia/Yekaterinburg').format('YYYY-MM-DD HH:mm');
}
exports.toEkbString = toEkbString;
function toEkbOnlyTimeString(date) {
    return moment(date).tz('Asia/Yekaterinburg').format('HH:mm');
}
exports.toEkbOnlyTimeString = toEkbOnlyTimeString;
function getCloseDate(date, hours, minutes) {
    var add1 = moment(date).add('hours', hours);
    if (minutes !== 0) {
        add1 = add1.add('minutes', minutes);
    }
    return add1.tz('Asia/Yekaterinburg').format('HH:mm');
}
exports.getCloseDate = getCloseDate;
function getDefaultTeams() {
    var teams = [];
    teams.push({
        name: 'Тестовая админская команда',
        secretCode: 'зачемятаквчеранапился',
        tokenId: 'зачемятаквчеранапился',
        admin: true,
        startFromStage: 0
    });
    return teams;
}
exports.getDefaultTeams = getDefaultTeams;
//# sourceMappingURL=utils.js.map


text:
<?php

// classpath
namespace Mimoto\Core\entities;

// Mimoto classes
use Mimoto\Mimoto;
use Mimoto\Core\CoreConfig;
use Mimoto\Core\CoreFormUtils;
use Mimoto\Data\MimotoEntity;
use Mimoto\EntityConfig\EntityConfig;
use Mimoto\EntityConfig\MimotoEntityPropertyValueTypes;

/**
 * PathElement
 *
 * @author Sebastian Kersten (@supertaboo)
 */
class PathElement
{

    public static function getStructure()
    {
        return (object) array(
            'id' => CoreConfig::MIMOTO_PATH_ELEMENT,
            // ---
            'name' => CoreConfig::MIMOTO_PATH_ELEMENT,
            'extends' => null,
            'forms' => [CoreConfig::MIMOTO_PATH_ELEMENT],
            'properties' => [
                (object) array(
                    'id' => CoreConfig::MIMOTO_PATH_ELEMENT.'--type',
                    // ---
                    'name' => 'type',
                    'type' => CoreConfig::PROPERTY_TYPE_VALUE,
                    'settings' => [
                        'type' => (object) array(
                            'key' => 'type',
                            'type' => MimotoEntityPropertyValueTypes::VALUETYPE_TEXT,
                            'value' => CoreConfig::DATA_VALUE_TEXTLINE
                        )
                    ]
                ),
                (object) array(
                    'id' => CoreConfig::MIMOTO_PATH_ELEMENT.'--staticValue',
                    // ---
                    'name' => 'staticValue',
                    'type' => CoreConfig::PROPERTY_TYPE_VALUE,
                    'settings' => [
                        'type' => (object) array(
                            'key' => 'type',
                            'type' => MimotoEntityPropertyValueTypes::VALUETYPE_TEXT,
                            'value' => CoreConfig::DATA_VALUE_TEXTLINE
                        )
                    ]
                ),
                (object) array(
                    'id' => CoreConfig::MIMOTO_PATH_ELEMENT.'--varName',
                    // ---
                    'name' => 'varName',
                    'type' => CoreConfig::PROPERTY_TYPE_VALUE,
                    'settings' => [
                        'type' => (object) array(
                            'key' => 'type',
                            'type' => MimotoEntityPropertyValueTypes::VALUETYPE_TEXT,
                            'value' => CoreConfig::DATA_VALUE_TEXTLINE
                        )
                    ]
                ),
            ]
        );
    }

    public static function getData()
    {

    }

    // ----------------------------------------------------------------------------
    // --- Form -------------------------------------------------------------------
    // ----------------------------------------------------------------------------

    /**
     * Get form structure
     */
    public static function getFormStructure()
    {
        return (object) array(
            'id' => CoreConfig::MIMOTO_PATH_ELEMENT,
            'name' => CoreConfig::MIMOTO_PATH_ELEMENT,
            'class' => get_class(),
            'inputFieldIds' => [
                CoreFormUtils::composeFieldName(CoreConfig::MIMOTO_PATH_ELEMENT, 'type'),
                CoreFormUtils::composeFieldName(CoreConfig::MIMOTO_PATH_ELEMENT, 'value')
            ]
        );
    }

    /**
     * Get form
     */
    public static function getForm()
    {
        // init
        $form = CoreFormUtils::initForm(CoreConfig::MIMOTO_PATH_ELEMENT, true);

        // setup
        CoreFormUtils::addField_title($form, 'Path element', '', "The core element of data is called an 'entity'. Entities are the data objects that contain a certain set of properties, for instance Person containing a name and a date of birth");
        CoreFormUtils::addField_groupStart($form);

        $form->addValue('fields', self::getField_type());

        $field = CoreFormUtils::addField_textline
        (
            $form, 'staticValue', CoreConfig::MIMOTO_PATH_ELEMENT.'--staticValue',
            'Static part of the path', 'Enter the path`s element'
        );
        //self::setStaticValueValidation($field);

        $field = CoreFormUtils::addField_textline
        (
            $form, 'varName', CoreConfig::MIMOTO_PATH_ELEMENT.'--varName',
            'Variable name', 'The variable`s name', "The variable`s name should be unique"
        );
        //self::setVarNameValidation($field);

        CoreFormUtils::addField_groupEnd($form);

        // send
        return $form;
    }

    // ----------------------------------------------------------------------------
    // --- private methods---------------------------------------------------------
    // ----------------------------------------------------------------------------

    /**
     * Get field: type
     */
    private static function getField_type()
    {
        // 1. create and setup field
        $field = CoreFormUtils::createField(CoreConfig::MIMOTO_FORM_INPUT_RADIOBUTTON, CoreConfig::MIMOTO_PATH_ELEMENT, 'type');
        $field->setValue('label', 'Type');

        // 2. connect value
        $field = CoreFormUtils::addValueToField($field, CoreConfig::MIMOTO_PATH_ELEMENT, 'type');

        $option = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_OPTION);
        $option->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--type_value_options-var');
        $option->setValue('label', 'Static');
        $option->setValue('value', 'static');
        $field->addValue('options', $option);

        $option = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_OPTION);
        $option->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--type_value_options-var');
        $option->setValue('label', 'Slash');
        $option->setValue('value', 'slash');
        $field->addValue('options', $option);

        $option = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_OPTION);
        $option->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--type_value_options-static');
        $option->setValue('label', 'Variable');
        $option->setValue('value', 'var');
        $field->addValue('options', $option);

        // validation rule #1
        $validationRule = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_VALIDATION);
        $validationRule->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--type_value_validation1');
        $validationRule->setValue('type', 'regex_custom');
        $validationRule->setValue('value', '^(static|slash|var)$');
        $validationRule->setValue('errorMessage', 'Select one of the types above');
        $validationRule->setValue('trigger', 'submit');
        $field->addValue('validation', $validationRule);

        // send
        return $field;
    }

    /**
     * Set validation for staticValue
     */
    private static function setStaticValueValidation(MimotoEntity $field)
    {

        // 1. activate only when type = 'static'
        // 2. conditional validation

        // validation rule #1
        $validationRule = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_VALIDATION);
        $validationRule->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--staticValue_value_validation2');
        $validationRule->setValue('type', 'minchars');
        $validationRule->setValue('value', 1);
        $validationRule->setValue('errorMessage', 'The value can`t be empty');
        $validationRule->setValue('trigger', 'submit');
        $field->addValue('validation', $validationRule);

        // validation rule #2
        $validationRule = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_VALIDATION);
        $validationRule->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--staticValue_value_validation1');
        $validationRule->setValue('type', 'regex_custom');
        $validationRule->setValue('value', '^[a-z][a-zA-Z0-9_-]*$');
        $validationRule->setValue('errorMessage', 'Name should be in lowerCamelCase, starting with a letter followed by [a-zA-Z0-9-_]');
        $validationRule->setValue('trigger', 'submit');
        $field->addValue('validation', $validationRule);

        // send
        return $field;
    }

    /**
     * Set validation for varName
     */
    private static function setVarNameValidation(MimotoEntity $field)
    {
        // validation rule #1
        $validationRule = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_VALIDATION);
        $validationRule->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--name_value_validation2');
        $validationRule->setValue('type', 'minchars');
        $validationRule->setValue('value', 1);
        $validationRule->setValue('errorMessage', "The var name can't be empty");
        $validationRule->setValue('trigger', 'submit');
        $field->addValue('validation', $validationRule);

        // validation rule #2
        $validationRule = Mimoto::service('data')->create(CoreConfig::MIMOTO_FORM_FIELD_VALIDATION);
        $validationRule->setId(CoreConfig::MIMOTO_PATH_ELEMENT.'--name_value_validation1');
        $validationRule->setValue('type', 'regex_custom');
        $validationRule->setValue('value', '^[a-z][a-zA-Z0-9_-]*$');
        $validationRule->setValue('errorMessage', 'The variable`s name should be in lowerCamelCase, starting with a letter followed by [a-zA-Z0-9-_]');
        $validationRule->setValue('trigger', 'submit');
        $field->addValue('validation', $validationRule);

        // send
        return $field;
    }

}


text:
extern NSString* const kDataFromChromeSyncAccessibilityIdentifier;

// Accessibility identifier for Manage Sync table view.
extern NSString* const kManageSyncTableViewAccessibilityIdentifier;

// Sections used in Sync Settings page.
typedef NS_ENUM(NSInteger, SyncSettingsSectionIdentifier) {
  // Section for all the sync settings.
  SyncDataTypeSectionIdentifier = kSectionIdentifierEnumZero,
  // Sign out options.
  SignOutSectionIdentifier,
  // Advanced settings.
  AdvancedSettingsSectionIdentifier,
  // Sync errors.
  SyncErrorsSectionIdentifier,
};

// Item types used per Sync Setting section.
// Types are used to uniquely identify SyncSwitchItem items.
typedef NS_ENUM(NSInteger, SyncSettingsItemType) {
  // SyncDataTypeSectionIdentifier section.
  // Sync everything item.
  SyncEverythingItemType = kItemTypeEnumZero,
  // kSyncAutofill.
  AutofillDataTypeItemType,
  // kSyncBookmarks.
  BookmarksDataTypeItemType,
  // kSyncOmniboxHistory.
  HistoryDataTypeItemType,
  // kSyncOpenTabs.
  OpenTabsDataTypeItemType,
  // kSyncPasswords
  PasswordsDataTypeItemType,
  // kSyncReadingList.
  ReadingListDataTypeItemType,
  // kSyncPreferences.
  SettingsDataTypeItemType,
  // Item for kAutofillWalletImportEnabled.
  AutocompleteWalletItemType,
  // Sign out item,
  SignOutItemType,
  // AdvancedSettingsSectionIdentifier section.
  // Encryption item.
  EncryptionItemType,
  // Google activity controls item.
  GoogleActivityControlsItemType,
  // Data from Chrome sync.
  DataFromChromeSync,
  // Sync errors.
  ReauthDialogAsSyncIsInAuthErrorItemType,
  ShowPassphraseDialogErrorItemType,
  SyncNeedsTrustedVaultKeyErrorItemType,
  SyncTrustedVaultRecoverabilityDegradedErrorItemType,
  SyncDisabledByAdministratorErrorItemType,
  // Sign out item footer.
  SignOutItemFooterType,
};

#endif  // IOS_CHROME_BROWSER_UI_SETTINGS_GOOGLE_SERVICES_MANAGE_SYNC_SETTINGS_CONSTANTS_H_


text:
package docker

import (
	"errors"
	"fmt"
	"net/http"
)

// RestartPolicy represents the policy for automatically restarting a container.
//
// Possible values are:
//
//   - always: the docker daemon will always restart the container
//   - on-failure: the docker daemon will restart the container on failures, at
//     most MaximumRetryCount times
//   - unless-stopped: the docker daemon will always restart the container except
//     when user has manually stopped the container
//   - no: the docker daemon will not restart the container automatically
type RestartPolicy struct {
	Name              string `json:"Name,omitempty" yaml:"Name,omitempty" toml:"Name,omitempty"`
	MaximumRetryCount int    `json:"MaximumRetryCount,omitempty" yaml:"MaximumRetryCount,omitempty" toml:"MaximumRetryCount,omitempty"`
}

// AlwaysRestart returns a restart policy that tells the Docker daemon to
// always restart the container.
func AlwaysRestart() RestartPolicy {
	return RestartPolicy{Name: "always"}
}

// RestartOnFailure returns a restart policy that tells the Docker daemon to
// restart the container on failures, trying at most maxRetry times.
func RestartOnFailure(maxRetry int) RestartPolicy {
	return RestartPolicy{Name: "on-failure", MaximumRetryCount: maxRetry}
}

// RestartUnlessStopped returns a restart policy that tells the Docker daemon to
// always restart the container except when user has manually stopped the container.
func RestartUnlessStopped() RestartPolicy {
	return RestartPolicy{Name: "unless-stopped"}
}

// NeverRestart returns a restart policy that tells the Docker daemon to never
// restart the container on failures.
func NeverRestart() RestartPolicy {
	return RestartPolicy{Name: "no"}
}

// RestartContainer stops a container, killing it after the given timeout (in
// seconds), during the stop process.
//
// See https://goo.gl/MrAKQ5 for more details.
func (c *Client) RestartContainer(id string, timeout uint) error {
	path := fmt.Sprintf("/containers/%s/restart?t=%d", id, timeout)
	resp, err := c.do(http.MethodPost, path, doOptions{})
	if err != nil {
		var e *Error
		if errors.As(err, &e) && e.Status == http.StatusNotFound {
			return &NoSuchContainer{ID: id}
		}
		return err
	}
	resp.Body.Close()
	return nil
}


text:
import { Injectable } from '@angular/core';
import { of as observableOf, Observable } from 'rxjs';
import { LiveUpdateChart, PieChart, EarningData } from '../data/earning';

@Injectable()
export class EarningService extends EarningData {

  private currentDate: Date = new Date();
  private currentValue = Math.random() * 1000;
  private ONE_DAY = 24 * 3600 * 1000;

  private pieChartData = [
    {
      value: 50,
      name: 'Bitcoin',
    },
    {
      value: 25,
      name: 'Tether',
    },
    {
      value: 25,
      name: 'Ethereum',
    },
  ];

  private liveUpdateChartData = {
    bitcoin: {
      liveChart: [],
      delta: {
        up: true,
        value: 4,
      },
      dailyIncome: 45895,
    },
    tether: {
      liveChart: [],
      delta: {
        up: false,
        value: 9,
      },
      dailyIncome: 5862,
    },
    ethereum: {
      liveChart: [],
      delta: {
        up: false,
        value: 21,
      },
      dailyIncome: 584,
    },
  };

  getDefaultLiveChartData(elementsNumber: number) {
    this.currentDate = new Date();
    this.currentValue = Math.random() * 1000;

    return Array.from(Array(elementsNumber))
      .map(item => this.generateRandomLiveChartData());
  }

  generateRandomLiveChartData() {
    this.currentDate = new Date(+this.currentDate + this.ONE_DAY);
    this.currentValue = this.currentValue + Math.random() * 20 - 11;

    if (this.currentValue < 0) {
      this.currentValue = Math.random() * 100;
    }

    return {
      value: [
        [
          this.currentDate.getFullYear(),
          this.currentDate.getMonth(),
          this.currentDate.getDate(),
        ].join('/'),
        Math.round(this.currentValue),
      ],
    };
  }

  getEarningLiveUpdateCardData(currency): Observable<any[]> {
    const data = this.liveUpdateChartData[currency.toLowerCase()];
    const newValue = this.generateRandomLiveChartData();

    data.liveChart.shift();
    data.liveChart.push(newValue);

    return observableOf(data.liveChart);
  }

  getEarningCardData(currency: string): Observable<LiveUpdateChart> {
    const data = this.liveUpdateChartData[currency.toLowerCase()];

    data.liveChart = this.getDefaultLiveChartData(150);

    return observableOf(data);
  }

  getEarningPieChartData(): Observable<PieChart[]> {
    return observableOf(this.pieChartData);
  }
}


text:
require 'linkedin'

class LinkedinController < ApplicationController

  # reauthorize linkedin user with scope r_basicprofile r_network rw_nus
  # that is - allow gofreerev to post on linkedin wall if user wants it
  # http://developer.linkedin.com/documents/authentication
  # http://railscarma.com/blog/rails-3/how-to-use-linkedin-api-in-rails-applications/
  # signatures:
  # 1) callback with rw_nus:
  #    Parameters: {"oauth_token"=>"75--62450be1-6396-45a9-b26f-050a2b471a9d", "oauth_verifier"=>"15521"}
  def index
    # linkedin oauth client was saved in util.post_on_linkedin after "(403): Access to posting shares denied" error
    api_client = get_linkedin_api_client
    if !api_client
      # linkedin client temporary saved in task queue in util.post_on_linkedin was not found
      # maybe client was deleted by cleanup rutine (clients older than 10 minutes are deleted)
      # maybe used has reloaded this page after an exception
      save_flash_key '.no_client', :apiname => provider_downcase('linkedin'), :appname => APP_NAME
      redirect_to :controller => :gifts
      return
    end
    begin
      token = api_client.authorize_from_request(api_client.request_token.token, api_client.request_token.secret, params[:oauth_verifier])
      # note. minor change to linkedin-0.4.4 gem. expires_in is saved in a instance variable
      expires_in = api_client.instance_variable_get('@auth_expires_in') # seconds from now
      if expires_in.to_s == ''
        logger.error2 "expires_at timestamp was not received from linkedin gem authorize_from_request method."
        logger.debug2 "add line \"@auth_expires_in = access_token.instance_variable_get('@params')[:oauth_expires_in]\" to authorize_from_request method"
        logger.debug2 "expires_at was set to 2 months from now"
        expires_at = 2.months.from_now.to_i
      else
        expires_at = expires_in.to_i.seconds.from_now.to_i # unix timestamp
      end
      logger.debug2 "expires_in = #{expires_in}, expires_at = #{expires_at}"
    rescue => e
      logger.debug2 "Exception: #{e.message} (#{e.class})"
      save_flash_key '.auth_failed', :apiname => provider_downcase('linkedin'), :appname => APP_NAME, :error => e.message
      raise
    end
    # logger.debug2  "x = #{token} (#{token.class})"
    if token.class == Array and token.length == 2 and token[0].class == String and token[1].class == String and token[0] != "" and token[1] != ''
      logger.debug2  "login ok. Get name, .... from linkedin"
      # get basic user information from linkedin before 2. login with write permission (rw_nus) to linkedin wall
      api_client = init_api_client_linkedin(token) # token and secret
      res1 = api_client.profile(:fields => %w(id,first-name,last-name,picture-url,public-profile-url))
      logger.debug2 "res1.public_profile_url = #{res1.public_profile_url}"
      # index: res1.public_profile_url = http://www.linkedin.com/pub/jan-test-account-roslind/87/b08/27a
      # new login with write permission to linkedin wall
      res2 = login :provider => provider,
                  :token => token,
                  :expires_at => expires_at,
                  :uid => res1.id,
                  :name => "#{res1.first_name} #{res1.last_name}",
                  :image => res1.picture_url,
                  :country => nil,
                  :language => nil,
                  :profile_url => res1.public_profile_url,
                  :permissions => 'r_basicprofile,r_network,rw_nus'
      # logger.debug2  "res2 = #{res2}"
      if !res2
        # login ok with extra rw_nus priv
        user_id = "#{res1.id}/#{provider}"
        user = User.find_by_user_id(user_id)
        # user.permissions = "r_basicprofile,r_network,rw_nus"
        # user.save!
        save_flash_key ".ok_rw_nus", user.app_and_apiname_hash
        redirect_to :controller => :gifts
      else
        # login failed
        key, options = res2
        begin
          save_flash_key key, options
        rescue => e
          logger.debug2  "invalid response from login. Must be nil or a valid input to translate. Response: #{res2}"
          save_flash_key '.find_or_create_from_auth_hash', :response => res2, :exception => e.message.to_s
        end
        redirect_to :controller => :auth
      end

    else
      # todo: add error and redirect to gifts/index page
      logger.debug2  "login not ok."
    end

  end # index

  private
  def provider
    "linkedin"
  end

end


text:
package com.dataapi.dao;

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.authentication.UserCredentials;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

@Configuration
public class MongoConfig {

	@Value("${db.host}")
	String host;
	@Value("${db.dbname}")
	String dbName;
	@Value("${db.username}")
	String userName;
	@Value("${db.password}")
	String password;
	@Value("${db.port}")
	int port;

	 public @Bean MongoClientFactoryBean mongoDbFactory() throws Exception {
	        MongoClientFactoryBean clientFactoryBean = new MongoClientFactoryBean();
	        clientFactoryBean.setHost(host);
	        clientFactoryBean.setPort(port);
	        System.out.println("Creating MongoClientFactoryBean | Port: " + port + " | host: " + host);
	        MongoCredential credential = MongoCredential.createScramSha1Credential(userName, dbName, password.toCharArray());
	        clientFactoryBean.setCredentials(new MongoCredential[]{credential});
	        return clientFactoryBean;
	    }

	    public @Bean MongoTemplate mongoTemplate(Mongo mongo) throws Exception {
	        MongoTemplate mongoTemplate = new MongoTemplate(mongo, dbName);
	        System.out.println("Created MongoTemplateBean with " + mongo.toString());
	        return mongoTemplate;

	    }

}


text:
import numpy as np
from abc import ABC, abstractmethod

class AbstractEnvRunner(ABC):
    def __init__(self, *, env, model, nsteps):
        self.env = env
        self.model = model
        self.nenv = nenv = env.num_envs if hasattr(env, 'num_envs') else 1
        self.batch_ob_shape = (nenv*nsteps,) + env.observation_space.shape
        self.obs = np.zeros((nenv,) + env.observation_space.shape, dtype=env.observation_space.dtype.name)
        self.obs[:] = env.reset()
        self.nsteps = nsteps
        self.states = model.initial_state
        self.dones = [False for _ in range(nenv)]

    @abstractmethod
    def run(self):
        raise NotImplementedError


text:
<?php

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

/**
 * Authorize.net CIM API Hosted Profile Page Request Class
 *
 * @since 2.0.0
 */
class WC_Authorize_Net_CIM_API_Hosted_Profile_Page_Request extends WC_Authorize_Net_CIM_API_Request {

	/**
	 * Creates XML for the hosted profile page request
	 *
	 * @since 2.0.0
	 * @param string $customer_id customer profile ID
	 */
	public function get_page_token( $customer_id ) {

		$this->request_type = 'getHostedProfilePageRequest';

		$this->request_data = array(
			'customerProfileId'     => $customer_id,
			'hostedProfileSettings' => array(
				'setting' => array(
					'settingName'  => 'hostedProfileReturnUrl',
					'settingValue' => get_permalink( wc_get_page_id( 'myaccount' ) ),
				),
			),
		);
	}

}


text:
package com.example.android.tv.recommendations.playback;

import android.content.ContentUris;
import android.content.Context;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.media.tv.TvContractCompat;
import android.support.media.tv.WatchNextProgram;
import android.util.Log;

import com.example.android.tv.recommendations.model.MockDatabase;
import com.example.android.tv.recommendations.model.Movie;
import com.example.android.tv.recommendations.util.AppLinkHelper;

/** Adds, updates, and removes the currently playing {@link Movie} from the "Watch Next" channel. */
public class WatchNextAdapter {

    private static final String TAG = "WatchNextAdapter";

    public void updateProgress(
            Context context, long channelId, Movie movie, long position, long duration) {
        Log.d(TAG, String.format("Updating the movie (%d) in watch next.", movie.getId()));

        Movie entity = MockDatabase.findMovieById(context, channelId, movie.getId());
        if (entity == null) {
            Log.e(
                    TAG,
                    String.format(
                            "Could not find movie in channel: channel id: %d, movie id: %d",
                            channelId, movie.getId()));
            return;
        }

        // TODO: step 12 add watch next program.
        WatchNextProgram program = createWatchNextProgram(channelId, entity, position, duration);
        if (entity.getWatchNextId() < 1L) {
            // Need to create program.
            Uri watchNextProgramUri =
                    context.getContentResolver()
                            .insert(
                                    TvContractCompat.WatchNextPrograms.CONTENT_URI,
                                    program.toContentValues());
            long watchNextId = ContentUris.parseId(watchNextProgramUri);
            entity.setWatchNextId(watchNextId);
            MockDatabase.saveMovie(context, channelId, entity);

            Log.d(TAG, "Watch Next program added: " + watchNextId);
        } else {
            // TODO: step 14 update program.
            // Update the progress and last engagement time of the program.
            context.getContentResolver()
                    .update(
                            TvContractCompat.buildWatchNextProgramUri(entity.getWatchNextId()),
                            program.toContentValues(),
                            null,
                            null);

            Log.d(TAG, "Watch Next program updated: " + entity.getWatchNextId());
        }
    }

    @NonNull
    private WatchNextProgram createWatchNextProgram(
            long channelId, Movie movie, long position, long duration) {
        // TODO: step 13 convert movie
        Uri posterArtUri = Uri.parse(movie.getCardImageUrl());
        Uri intentUri = AppLinkHelper.buildPlaybackUri(channelId, movie.getId(), position);

        WatchNextProgram.Builder builder = new WatchNextProgram.Builder();
        builder.setType(TvContractCompat.PreviewProgramColumns.TYPE_MOVIE)
                .setWatchNextType(TvContractCompat.WatchNextPrograms.WATCH_NEXT_TYPE_CONTINUE)
                .setLastEngagementTimeUtcMillis(System.currentTimeMillis())
                .setLastPlaybackPositionMillis((int) position)
                .setDurationMillis((int) duration)
                .setTitle(movie.getTitle())
                .setDescription(movie.getDescription())
                .setPosterArtUri(posterArtUri)
                .setIntentUri(intentUri);
        return builder.build();
    }

    public void removeFromWatchNext(Context context, long channelId, long movieId) {
        Movie movie = MockDatabase.findMovieById(context, channelId, movieId);
        if (movie == null || movie.getWatchNextId() < 1L) {
            Log.d(TAG, "No program to remove from watch next.");
            return;
        }

        // TODO: step 15 remove program
        int rows =
                context.getContentResolver()
                        .delete(
                                TvContractCompat.buildWatchNextProgramUri(movie.getWatchNextId()),
                                null,
                                null);
        Log.d(TAG, String.format("Deleted %d programs(s) from watch next", rows));

        // Sync our records with the system; remove reference to watch next program.
        movie.setWatchNextId(-1);
        MockDatabase.saveMovie(context, channelId, movie);
    }
}