text:
package rpc

import (
	"errors"
	"fmt"
	"strings"
	"testing"

	"v.io/v23/context"
	"v.io/v23/naming"
	"v.io/v23/vdl"
	"v.io/v23/verror"
)

// test tags.
var (
	tagAlpha   = vdl.StringValue(nil, "alpha")
	tagBeta    = vdl.StringValue(nil, "beta")
	tagGamma   = vdl.StringValue(nil, "gamma")
	tagDelta   = vdl.StringValue(nil, "delta")
	tagEpsilon = vdl.StringValue(nil, "epsilon")
)

var errApp = errors.New("app error")

type notags struct{}

func (o *notags) Method1(*context.T, ServerCall) error             { return nil }
func (o *notags) Method2(*context.T, ServerCall) (int, error)      { return 0, nil }
func (o *notags) Method3(*context.T, ServerCall, int) error        { return nil }
func (o *notags) Method4(*context.T, ServerCall, int) (int, error) { return 0, nil }
func (o *notags) Error(*context.T, ServerCall) error               { return errApp }

type tags struct{}

func (o *tags) Alpha(*context.T, ServerCall) error                               { return nil }
func (o *tags) Beta(*context.T, ServerCall) (int, error)                         { return 0, nil }
func (o *tags) Gamma(*context.T, ServerCall, int) error                          { return nil }
func (o *tags) Delta(*context.T, ServerCall, int) (int, error)                   { return 0, nil }
func (o *tags) Epsilon(*context.T, ServerCall, int, string) (int, string, error) { return 0, "", nil }
func (o *tags) Error(*context.T, ServerCall) error                               { return errApp }

//nolint:revive // API change required.
func (o *tags) Describe__() []InterfaceDesc {
	return []InterfaceDesc{{
		Methods: []MethodDesc{
			{Name: "Alpha", Tags: []*vdl.Value{tagAlpha}},
			{Name: "Beta", Tags: []*vdl.Value{tagBeta}},
			{Name: "Gamma", Tags: []*vdl.Value{tagGamma}},
			{Name: "Delta", Tags: []*vdl.Value{tagDelta}},
			{Name: "Epsilon", Tags: []*vdl.Value{tagEpsilon}},
		},
	}}
}

type (
	badcall        struct{}
	noInitCall     struct{ ServerCall }
	badInit1Call   struct{ ServerCall }
	badInit2Call   struct{ ServerCall }
	badInit3Call   struct{ ServerCall }
	noSendRecvCall struct{ ServerCall }
	badSend1Call   struct{ ServerCall }
	badSend2Call   struct{ ServerCall }
	badSend3Call   struct{ ServerCall }
	badRecv1Call   struct{ ServerCall }
	badRecv2Call   struct{ ServerCall }
	badRecv3Call   struct{ ServerCall }

	badoutargs struct{}

	badGlobber       struct{}
	badGlob1         struct{}
	badGlob2         struct{}
	badGlob3         struct{}
	badGlob4         struct{}
	badGlob5         struct{}
	badGlob6         struct{}
	badGlob7         struct{}
	badGlobChildren1 struct{}
	badGlobChildren2 struct{}
	badGlobChildren3 struct{}
	badGlobChildren4 struct{}
	badGlobChildren5 struct{}
	badGlobChildren6 struct{}
)

func (badcall) NonRPC1() error                               { return nil }
func (badcall) NonRPC2(int) error                            { return nil }
func (badcall) NonRPC3(int, string) error                    { return nil }
func (badcall) NonRPC4(*badcall) error                       { return nil }
func (badcall) NonRPC5(context.T, *badcall) error            { return nil }
func (badcall) NonRPC6(*context.T, *badcall) error           { return nil }
func (badcall) NoInit(*context.T, *noInitCall) error         { return nil }
func (badcall) BadInit1(*context.T, *badInit1Call) error     { return nil }
func (badcall) BadInit2(*context.T, *badInit2Call) error     { return nil }
func (badcall) BadInit3(*context.T, *badInit3Call) error     { return nil }
func (badcall) NoSendRecv(*context.T, *noSendRecvCall) error { return nil }
func (badcall) BadSend1(*context.T, *badSend1Call) error     { return nil }
func (badcall) BadSend2(*context.T, *badSend2Call) error     { return nil }
func (badcall) BadSend3(*context.T, *badSend3Call) error     { return nil }
func (badcall) BadRecv1(*context.T, *badRecv1Call) error     { return nil }
func (badcall) BadRecv2(*context.T, *badRecv2Call) error     { return nil }
func (badcall) BadRecv3(*context.T, *badRecv3Call) error     { return nil }

func (*badInit1Call) Init()                      {}
func (*badInit2Call) Init(int)                   {}
func (*badInit3Call) Init(StreamServerCall, int) {}
func (*noSendRecvCall) Init(StreamServerCall)    {}
func (*badSend1Call) Init(StreamServerCall)      {}
func (*badSend1Call) SendStream()                {}
func (*badSend2Call) Init(StreamServerCall)      {}
func (*badSend2Call) SendStream() interface {
	Send() error
} {
	return nil
}
func (*badSend3Call) Init(StreamServerCall) {}
func (*badSend3Call) SendStream() interface {
	Send(int)
} {
	return nil
}
func (*badRecv1Call) Init(StreamServerCall) {}
func (*badRecv1Call) RecvStream()           {}
func (*badRecv2Call) Init(StreamServerCall) {}
func (*badRecv2Call) RecvStream() interface {
	Advance() bool
	Value() int
} {
	return nil
}
func (*badRecv3Call) Init(StreamServerCall) {}
func (*badRecv3Call) RecvStream() interface {
	Advance()
	Value() int
	Error() error
} {
	return nil
}

func (badoutargs) NoFinalError1(*context.T, ServerCall)                {}
func (badoutargs) NoFinalError2(*context.T, ServerCall) string         { return "" }
func (badoutargs) NoFinalError3(*context.T, ServerCall) (bool, string) { return false, "" }

//nolint:revive // API change required.
func (badoutargs) NoFinalError4(*context.T, ServerCall) (error, string) { return nil, "" }

func (badGlobber) Globber() {}

//nolint:revive // API change required.
func (badGlob1) Glob__() {}

//nolint:revive // API change required.
func (badGlob2) Glob__(*context.T) {}

//nolint:revive // API change required.
func (badGlob3) Glob__(*context.T, ServerCall) {}

//nolint:revive // API change required.
func (badGlob4) Glob__(*context.T, ServerCall, string) {}

//nolint:revive // API change required.
func (badGlob5) Glob__(*context.T, ServerCall, string) <-chan naming.GlobReply { return nil }

//nolint:revive // API change required.
func (badGlob6) Glob__(*context.T, ServerCall, string) error { return nil }

//nolint:revive // API change required.
func (badGlob7) Glob__() (<-chan naming.GlobReply, error) { return nil, nil }

//nolint:revive // API change required.
func (badGlobChildren1) GlobChildren__() {}

//nolint:revive // API change required.
func (badGlobChildren2) GlobChildren__(*context.T) {}

//nolint:revive // API change required.
func (badGlobChildren3) GlobChildren__(*context.T, ServerCall) {}

//nolint:revive // API change required.
func (badGlobChildren4) GlobChildren__(*context.T, ServerCall) <-chan string { return nil }

//nolint:revive // API change required.
func (badGlobChildren5) GlobChildren__(*context.T, ServerCall) error { return nil }

//nolint:revive // API change required.
func (badGlobChildren6) GlobChildren__() (<-chan string, error) { return nil, nil }

const (
	badInit = `Init must have signature`
	badSend = `SendStream must have signature`
	badRecv = `RecvStream must have signature`
)

func TestTypeCheckMethods(t *testing.T) {
	type testcase struct {
		obj  interface{}
		want map[string]string
	}
	tests := []testcase{
		{struct{}{}, nil},
		{&notags{}, map[string]string{
			"Method1": "",
			"Method2": "",
			"Method3": "",
			"Method4": "",
			"Error":   "",
		}},
		{&tags{}, map[string]string{
			"Alpha":      "",
			"Beta":       "",
			"Gamma":      "",
			"Delta":      "",
			"Epsilon":    "",
			"Error":      "",
			"Describe__": verror.ErrInternal.Errorf(nil, "internal error: %v", errReservedMethod).Error(),
		}},

		{badcall{}, map[string]string{
			"NonRPC1":    errNonRPCMethod("NonRPC1").Error(),
			"NonRPC2":    errNonRPCMethod("NonRPC2").Error(),
			"NonRPC3":    errNonRPCMethod("NonRPC3").Error(),
			"NonRPC4":    errNonRPCMethod("NonRPC4").Error(),
			"NonRPC5":    errNonRPCMethod("NonRPC5").Error(),
			"NonRPC6":    errNonRPCMethod("NonRPC6").Error(),
			"NoInit":     "must have Init method",
			"BadInit1":   badInit,
			"BadInit2":   badInit,
			"BadInit3":   badInit,
			"NoSendRecv": "must have at least one of RecvStream or SendStream",
			"BadSend1":   badSend,
			"BadSend2":   badSend,
			"BadSend3":   badSend,
			"BadRecv1":   badRecv,
			"BadRecv2":   badRecv,
			"BadRecv3":   badRecv,
		}},
		{badoutargs{}, map[string]string{
			"NoFinalError1": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
			"NoFinalError2": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
			"NoFinalError3": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
			"NoFinalError4": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
		}},

		{badGlobber{}, map[string]string{
			"Globber": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobber).Error(),
		}},
		{badGlob1{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob2{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob3{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob4{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob5{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob6{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob7{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlobChildren1{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren2{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren3{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren4{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren5{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren6{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},

		// Test for backwards compatibility.
		{&tags{}, map[string]string{
			"Alpha":      "",
			"Beta":       "",
			"Gamma":      "",
			"Delta":      "",
			"Epsilon":    "",
			"Error":      "",
			"Describe__": verror.ErrInternal.Errorf(nil, "internal error: %v", errReservedMethod).Error(),
		}},
		{badoutargs{}, map[string]string{
			"NoFinalError1": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
			"NoFinalError2": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
			"NoFinalError3": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
			"NoFinalError4": verror.ErrAborted.Errorf(nil, "aborted: %v", errNoFinalErrorOutArg).Error(),
		}},
		{badGlobber{}, map[string]string{
			"Globber": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobber).Error(),
		}},
		{badGlob1{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob2{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob3{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob4{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob5{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob6{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlob7{}, map[string]string{
			"Glob__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlob).Error(),
		}},
		{badGlobChildren1{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren2{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren3{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren4{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren5{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
		{badGlobChildren6{}, map[string]string{
			"GlobChildren__": verror.ErrAborted.Errorf(nil, "aborted: %v", errBadGlobChildren).Error(),
		}},
	}

	for _, test := range tests {
		typecheck := TypeCheckMethods(test.obj)
		if got, want := typecheck, test.want; (got == nil) != (want == nil) {
			t.Errorf("TypeCheckMethods(%T) got %v, want %v", test.obj, got, want)
		}
		if got, want := len(typecheck), len(test.want); got != want {
			t.Errorf("TypeCheckMethods(%T) got len %d, want %d (got %q, want %q)", test.obj, got, want, typecheck, test.want)
		}
		for wantKey, wantVal := range test.want {
			gotVal, ok := typecheck[wantKey]
			if !ok {
				t.Errorf("TypeCheckMethods(%T) got %v, want key %q", test.obj, typecheck, wantKey)
			}
			if wantVal == "" && gotVal != nil {
				t.Errorf("TypeCheckMethods(%T) got method %q %q, want %q", test.obj, wantKey, gotVal, wantVal)
			}
			if got, want := strings.ToLower(fmt.Sprint(gotVal)), strings.ToLower(wantVal); !strings.Contains(got, want) {
				t.Errorf("TypeCheckMethods(%T) got method %q %q, want substr %q", test.obj, wantKey, got, want)
			}
		}
	}

}


text:
import {Component, OnInit} from 'angular2/core';

import {MdlService} from '../../blocks';
import {GameStateService} from '../gameState.service';
import {GameService} from '../game.service';
import {SessionService} from '../../session';

const styles = require('./presentGame.scss');
const template = require('./presentGame.html');

@Component({
    selector: 'present-game',
    styles: [styles],
    template: template
})
export class PresentGame implements OnInit {

    constructor(
        private gameService: GameService,
        private gameStateService: GameStateService,
        private _sessionService: SessionService
    ) { }

    ngOnInit() {
        MdlService.upgradeAllRegistered();
    }

    present(gameName: string) {
        this.gameStateService.registerGame(gameName);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System.Diagnostics;
using System.IO;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Logging;
using osu.Game.Models;
using osu.Game.Stores;

#nullable enable

namespace osu.Game.Tests.Database
{
    public class FileStoreTests : RealmTest
    {
        [Test]
        public void TestImportFile()
        {
            RunTestWithRealm((realmFactory, storage) =>
            {
                var realm = realmFactory.Context;
                var files = new RealmFileStore(realmFactory, storage);

                var testData = new MemoryStream(new byte[] { 0, 1, 2, 3 });

                realm.Write(() => files.Add(testData, realm));

                Assert.True(files.Storage.Exists("0/05/054edec1d0211f624fed0cbca9d4f9400b0e491c43742af2c5b0abebf0c990d8"));
                Assert.True(files.Storage.Exists(realm.All<RealmFile>().First().StoragePath));
            });
        }

        [Test]
        public void TestImportSameFileTwice()
        {
            RunTestWithRealm((realmFactory, storage) =>
            {
                var realm = realmFactory.Context;
                var files = new RealmFileStore(realmFactory, storage);

                var testData = new MemoryStream(new byte[] { 0, 1, 2, 3 });

                realm.Write(() => files.Add(testData, realm));
                realm.Write(() => files.Add(testData, realm));

                Assert.AreEqual(1, realm.All<RealmFile>().Count());
            });
        }

        [Test]
        public void TestDontPurgeReferenced()
        {
            RunTestWithRealm((realmFactory, storage) =>
            {
                var realm = realmFactory.Context;
                var files = new RealmFileStore(realmFactory, storage);

                var file = realm.Write(() => files.Add(new MemoryStream(new byte[] { 0, 1, 2, 3 }), realm));

                var timer = new Stopwatch();
                timer.Start();

                realm.Write(() =>
                {
                    // attach the file to an arbitrary beatmap
                    var beatmapSet = CreateBeatmapSet(CreateRuleset());

                    beatmapSet.Files.Add(new RealmNamedFileUsage(file, "arbitrary.resource"));

                    realm.Add(beatmapSet);
                });

                Logger.Log($"Import complete at {timer.ElapsedMilliseconds}");

                string path = file.StoragePath;

                Assert.True(realm.All<RealmFile>().Any());
                Assert.True(files.Storage.Exists(path));

                files.Cleanup();
                Logger.Log($"Cleanup complete at {timer.ElapsedMilliseconds}");

                Assert.True(realm.All<RealmFile>().Any());
                Assert.True(file.IsValid);
                Assert.True(files.Storage.Exists(path));
            });
        }

        [Test]
        public void TestPurgeUnreferenced()
        {
            RunTestWithRealm((realmFactory, storage) =>
            {
                var realm = realmFactory.Context;
                var files = new RealmFileStore(realmFactory, storage);

                var file = realm.Write(() => files.Add(new MemoryStream(new byte[] { 0, 1, 2, 3 }), realm));

                string path = file.StoragePath;

                Assert.True(realm.All<RealmFile>().Any());
                Assert.True(files.Storage.Exists(path));

                files.Cleanup();

                Assert.False(realm.All<RealmFile>().Any());
                Assert.False(file.IsValid);
                Assert.False(files.Storage.Exists(path));
            });
        }
    }
}


text:
package org.scalaide.util.internal.eclipse

import org.eclipse.jface.text.IRegion

object EmptyRegion extends IRegion {
  override def getOffset: Int = 0
  override def getLength: Int = 0
}


text:
/*
	VerbDestroyGadget.cpp
	(c)2000 Palestar Inc, Richard Lyle
*/

#include "Debug/Assert.h"
#include "VerbDestroyGadget.h"
#include "GameContext.h"

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

IMPLEMENT_FACTORY( VerbDestroyGadget, Verb );

BEGIN_PROPERTY_LIST( VerbDestroyGadget, Verb )
	ADD_TRANSMIT_PROPERTY( m_pFrom );
END_PROPERTY_LIST();

VerbDestroyGadget::VerbDestroyGadget()
{}

VerbDestroyGadget::VerbDestroyGadget( NounGadget * pGadget, Noun * pFrom ) : m_pFrom( pFrom )
{
	attachVerb( pGadget );
}

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

Verb::Priority VerbDestroyGadget::priority() const
{
	return CRITICAL;
}

Verb::Scope VerbDestroyGadget::scope() const
{
	return LOCAL;
}

bool VerbDestroyGadget::client() const
{
	return false;
}

bool VerbDestroyGadget::canAttach( Noun * pNoun )
{
	return WidgetCast<NounGadget>( pNoun ) != NULL;
}

void VerbDestroyGadget::onExecute()
{
	NounGadget * pGadget = WidgetCast<NounGadget>( target() );
	if ( validate( pGadget ) )
		pGadget->inflictDamage( tick(), m_pFrom, pGadget->maxDamage(), DAMAGE_EMP, Vector3( 0.0f ) );
}

//----------------------------------------------------------------------------
//EOF


text:
 - Fix console handler and how used levels

## 0.5.6 - 2014-02-03

 - Bug in rotating handler
 - Stable and define log remover

## 0.5.5 - 2014-01-30

 - Typo in file handler .reopen

## 0.5.4 - 2014-01-30

 - Make rotating handler work now both with size based and time based rotations.

## 0.5.3 - 2014-01-28

 - Some fixes for formats

## 0.5.2 - 2014-01-27

 - Time based log rotation

## 0.5.1 - 2014-01-25

- Fix last tests
- Small cleanup for file handler

## 0.5.0 - 2013-11-13

- General cleanup
- Remove timeout for handlers
- Improve perfomance
- Use util.format instead of own printf
- More accurate console replacement

## v0.3.0 - 2013-10-24

- added intel.handlers.Rotating
- added ignore options to intel.console()
- added chalk.enabled when colorize is used
- added padding and truncation to printf
- added Logger#handleExceptions to catch uncaught exceptions
- added stack traces when an exception is logged
- fork intel to support it myself
- changed Promises from Q to bluebird, significantly faster
- fixed Console handler from using accepting format options
- make format and dates compiled. Perfomance stability with any format

# inter Changelog

## v0.2.0 - 2013-10-04

- added Filters for Handlers and Loggers
- added Handler timeout option
- added pid to LogRecord
- added configuration using JSON
- changed Promises to LazyPromises
- changed printf to faster, smaller printf
- changed internal forEach to faster while loops
- removed node v0.6 support (it didn't work anyways)

## v0.1.0 - 2013-09-30

- Initial release.


text:
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
#         or more contributor license agreements.  See the NOTICE file
#         distributed with this work for additional information
#         regarding copyright ownership.  The ASF licenses this file
#         to you under the Apache License, Version 2.0 (the
#         "License"); you may not use this file except in compliance
#         with the License.  You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
#         Unless required by applicable law or agreed to in writing,
#         software distributed under the License is distributed on an
#         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#         KIND, either express or implied.  See the License for the
#         specific language governing permissions and limitations
#         under the License.
-->
# cordova-plugin-whitelist
這個外掛程式實現一個用於導航在科爾多瓦 4.0 應用程式 web 視圖的白名單策略
## 支援的科爾多瓦平臺
  * Android 4.0.0 或以上
  * iOS 4.0.0 或以上
## 導航白名單
控制 web 視圖本身可以導航到的 Url。適用于頂級導航只。
怪癖: 在 Android 上它也適用于 iframe 的非-結計畫。
預設情況下,只有到`file://` Url 導航允許。若要允許其他其他 Url,必須將`<allow-navigation>`標籤添加到您的`config.xml`:
    <!-- Allow links to example.com -->
    <allow-navigation href="http://example.com/*" />
    <!-- Wildcards are allowed for the protocol, as a prefix
         to the host, or as a suffix to the path -->
    <allow-navigation href="*://*.example.com/*" />
    <!-- A wildcard can be used to whitelist the entire network,
         over HTTP and HTTPS.
         *NOT RECOMMENDED* -->
    <allow-navigation href="*" />
    <!-- The above is equivalent to these three declarations -->
    <allow-navigation href="http://*/*" />
    <allow-navigation href="https://*/*" />
    <allow-navigation href="data:*" />
## 科爾多瓦-外掛程式-白名單
控制應用程式允許讓系統打開的 Url。 預設情況下,沒有外部 Url 允許。
在 android 系統,這相當於發送類型 BROWSEABLE 的意圖。
此白名單並不適用于只超連結和對`window.open ()`調用的外掛程式.
在`config.xml`中添加`<allow-intent>`標籤,像這樣:
    <!-- Allow links to web pages to open in a browser -->
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <!-- Allow links to example.com to open in a browser -->
    <allow-intent href="http://example.com/*" />
    <!-- Wildcards are allowed for the protocol, as a prefix
         to the host, or as a suffix to the path -->
    <allow-intent href="*://*.example.com/*" />
    <!-- Allow SMS links to open messaging app -->
    <allow-intent href="sms:*" />
    <!-- Allow tel: links to open the dialer -->
    <allow-intent href="tel:*" />
    <!-- Allow geo: links to open maps -->
    <allow-intent href="geo:*" />
    <!-- Allow all unrecognized URLs to open installed apps
         *NOT RECOMMENDED* -->
    <allow-intent href="*" />
## 網路請求白名單
網路請求的控制項 (圖像,XHRs 等) 允許 (通過科爾多瓦本機掛鉤)。
注意: 我們建議你使用內容的安全性原則 (見下文),這是更安全。 此白名單大多是為 webviews 不支援 CSP 的歷史。
在`config.xml`中添加`<access>`標記,像這樣:
    <!-- Allow images, xhrs, etc. to google.com -->
    <access origin="http://google.com" />
    <access origin="https://google.com" />
    <!-- Access to the subdomain maps.google.com -->
    <access origin="http://maps.google.com" />
    <!-- Access to all the subdomains on google.com -->
    <access origin="http://*.google.com" />
    <!-- Enable requests to content: URLs -->
    <access origin="content:///*" />
    <!-- Don't block any requests -->
    <access origin="*" />
沒有任何`<access>`標籤,只到`file://` Url 允許請求。 但是,預設的科爾多瓦應用程式包括`<access origin="*">` ,預設情況。
怪癖: Android 還允許對 HTTPs://ssl.gstatic.com/accessibility/javascript/android/ 請求預設情況下,因為這是對講正常所需。
### 內容安全政策
網路請求的控制項 (圖像,XHRs 等) 允許 (通過 web 視圖直接)。
對 Android 和 iOS,網路請求白名單 (見上文) 是不能夠過濾所有類型的請求 (例如`<video>` & Websocket 未被阻止)。 那麼,除了白名單中,你應使用[內容安全性原則](http://content-security-policy.com/) `< 元 >`標記您的所有頁面。
在 android 系統,對 CSP 系統 web 視圖的支援開始奇巧 (但是是上使用 web 視圖人行橫道上的所有版本可用)。
下面是一些示例 CSP 聲明為`.html`頁面:
    <!-- Good default declaration:
        * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
        * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
        * Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
            * Enable inline JS: add 'unsafe-inline' to default-src
            * Enable eval(): add 'unsafe-eval' to default-src
    -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *">
    <!-- Allow requests to foo.com -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' foo.com">
    <!-- Enable all requests, inline styles, and eval() -->
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
    <!-- Allow XHRs via https only -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' https:">
    <!-- Allow iframe to https://cordova.apache.org/ -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; frame-src 'self' https://cordova.apache.org">


text:
namespace Boo.Lang.Compiler.Ast
{
	using System.Collections;
	using System.Runtime.Serialization;

	[System.Serializable]
	public partial class RaiseStatement : Statement
	{
		protected Expression _exception;

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		new public RaiseStatement CloneNode()
		{
			return (RaiseStatement)Clone();
		}

		/// <summary>
		/// <see cref="Node.CleanClone"/>
		/// </summary>
		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		new public RaiseStatement CleanClone()
		{
			return (RaiseStatement)base.CleanClone();
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public NodeType NodeType
		{
			get { return NodeType.RaiseStatement; }
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public void Accept(IAstVisitor visitor)
		{
			visitor.OnRaiseStatement(this);
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public bool Matches(Node node)
		{
			if (node == null) return false;
			if (NodeType != node.NodeType) return false;
			var other = ( RaiseStatement)node;
			if (!Node.Matches(_modifier, other._modifier)) return NoMatch("RaiseStatement._modifier");
			if (!Node.Matches(_exception, other._exception)) return NoMatch("RaiseStatement._exception");
			return true;
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public bool Replace(Node existing, Node newNode)
		{
			if (base.Replace(existing, newNode))
			{
				return true;
			}
			if (_modifier == existing)
			{
				this.Modifier = (StatementModifier)newNode;
				return true;
			}
			if (_exception == existing)
			{
				this.Exception = (Expression)newNode;
				return true;
			}
			return false;
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override public object Clone()
		{
			RaiseStatement clone = (RaiseStatement)FormatterServices.GetUninitializedObject(typeof(RaiseStatement));
			clone._lexicalInfo = _lexicalInfo;
			clone._endSourceLocation = _endSourceLocation;
			clone._documentation = _documentation;
			clone._isSynthetic = _isSynthetic;
			clone._entity = _entity;
			if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();

			if (null != _modifier)
			{
				clone._modifier = _modifier.Clone() as StatementModifier;
				clone._modifier.InitializeParent(clone);
			}
			if (null != _exception)
			{
				clone._exception = _exception.Clone() as Expression;
				clone._exception.InitializeParent(clone);
			}
			return clone;
		}

		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		override internal void ClearTypeSystemBindings()
		{
			_annotations = null;
			_entity = null;
			if (null != _modifier)
			{
				_modifier.ClearTypeSystemBindings();
			}
			if (null != _exception)
			{
				_exception.ClearTypeSystemBindings();
			}

		}

		[System.Xml.Serialization.XmlElement]
		[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
		public Expression Exception
		{

			get { return _exception; }
			set
			{
				if (_exception != value)
				{
					_exception = value;
					if (null != _exception)
					{
						_exception.InitializeParent(this);
					}
				}
			}

		}

	}
}


text:
title: 命令拦截器--DeployCmd的执行过程总结
tags: [activiti]
---

DeploymentBuilderImpl类的deploy方法的执行最终会commandExecutor来执行

```
commandExecutor.execute(new DeployCmd<Deployment>(deploymentBuilder));
```

1)commandExecutor对象

RepositoryServiceImpl类成员,实际实现是ProcessEngineConfigurationImpl类的成员变量commandExecutorTxRequired(CommandExecutor类实例),是在初始化RepositoryService时注入的引用。而commandExecutorTxRequired的初始化是通过ProcessEngineConfigurationImpl类的commandInterceptorsTxRequired拦截器链的第一个拦截器(因为CommandInterceptor也实现了CommandExecutor接口)。

因此,实际的commandExecutor.execute方法应查看commandInterceptorsTxRequired拦截器链的执行。

2)拦截器链的执行

通过ProcessEngineConfigurationImpl类的源码可以查看到commandInterceptorsTxRequired拦截器链的初始化过程,包括自定义拦截器(customPreCommandInterceptorsTxRequired)默认命令拦截器(getDefaultCommandInterceptorsTxRequired),自定义后缀拦截器(customPostCommandInterceptorsTxRequired),以及最终的actualCommandExecutor命令执行拦截器,其中actualCommandExecutor也是实际的命令执行者。

```
protected void initCommandInterceptorsTxRequired() {
    if (commandInterceptorsTxRequired==null) {
      if (customPreCommandInterceptorsTxRequired!=null) {
        commandInterceptorsTxRequired = new ArrayList<CommandInterceptor>(customPreCommandInterceptorsTxRequired);
      } else {
        commandInterceptorsTxRequired = new ArrayList<CommandInterceptor>();
      }
      commandInterceptorsTxRequired.addAll(getDefaultCommandInterceptorsTxRequired());
      if (customPostCommandInterceptorsTxRequired!=null) {
        commandInterceptorsTxRequired.addAll(customPostCommandInterceptorsTxRequired);
      }
      commandInterceptorsTxRequired.add(actualCommandExecutor);
    }
}

protected void initActualCommandExecutor() {
    actualCommandExecutor = new CommandExecutorImpl();
}
```

注:拦截器前方的对象都会调用next.execute(command)将命令对象传递到拦截器链下的一个连接器进行执行,直到遍历完成整个拦截器。因此最终会教育actualCommandExecutor来结束拦截器链的执行。

可以看到命令拦截器增强了命令对象的执行,在命令执行过程中如记录日志(LogInterceptor)等信息。

3)actualCommandExecutor执行命令

```
public class CommandExecutorImpl extends CommandInterceptor {
  public <T> T execute(Command<T> command) {
    return command.execute(Context.getCommandContext());
  }
}
```

注:Context.getCommandContext()从线程堆栈中获取命令上下文环境对象。如果是部署命令,那么这里将调用DeployCmd类的execute方法。

4)DeployCmd的执行

```
public Deployment execute(CommandContext commandContext) {
    //加载部署的资源xml文件,并封装为DeploymentEntity对象
    DeploymentEntity deployment = deploymentBuilder.getDeployment();

    deployment.setDeploymentTime(ClockUtil.getCurrentTime());

    //判断是否过滤重复流程(流程没有任何变动是否仍然部署的问题)
    if ( deploymentBuilder.isDuplicateFilterEnabled() ) {
      //获取库中最新的部署对象
      DeploymentEntity existingDeployment = Context
        .getCommandContext()
        .getDeploymentManager()
        .findLatestDeploymentByName(deployment.getName());

      //在库中查询到,并且如果对象内容相同,则直接返回
      if ( (existingDeployment!=null)
           && !deploymentsDiffer(deployment, existingDeployment)) {
        return existingDeployment;
      }
    }

    //部署新流程
    deployment.setNew(true);

    //通过Context上下对象,获取操作数据库的Manager,
    //然后将部署信息保存到数据库中
    Context
      .getCommandContext()
      .getDeploymentManager()
      .insertDeployment(deployment);

    return deployment;
}
```


text:
package sql.fredy.share;

import java.text.DateFormat;
import javax.swing.table.DefaultTableCellRenderer;

public class JdbcTableTimeRenderer extends DefaultTableCellRenderer {
    DateFormat formatter;

    public JdbcTableTimeRenderer() {
        super();
    }

    public void setValue(Object value) {
        if ( formatter == null ) {
            formatter = DateFormat.getTimeInstance();
        }
        try {
        setText((value == null) ? "" : formatter.format(value));
        } catch (Exception e) {
            setText("");
        }
    }

}


text:
What Python subject do you want to learn next?

   {% include "choices/buttons/no-sql-datastore.html" %}

   {% include "choices/buttons/monitoring.html" %}

   {% include "choices/buttons/web-application-security.html" %}


text:
#ifndef TUDAT_COMPOSITE_FUNCTION_HODOGRAPHIC_SHAPING_H
#define TUDAT_COMPOSITE_FUNCTION_HODOGRAPHIC_SHAPING_H

#include "tudat/astro/low_thrust/shape_based/baseFunctionsHodographicShaping.h"
#include <cmath>
#include <vector>
#include <Eigen/Dense>

namespace tudat
{
namespace shape_based_methods
{

class CompositeFunctionHodographicShaping
{
public:

    //! Constructor.
    CompositeFunctionHodographicShaping(
            const std::vector< std::shared_ptr< BaseFunctionHodographicShaping > >& compositeFunctionComponents,
            const Eigen::VectorXd& compositeFunctionCoefficients ):
        compositeFunctionComponents_( compositeFunctionComponents ),
        compositeFunctionCoefficients_( compositeFunctionCoefficients ){ }

    //! Default destructor.
    /*!
     * Default destructor.
     */
    ~CompositeFunctionHodographicShaping( ) { }

    //! Return coefficients.
    /*!
     * Returns coefficients of composite function.
     */
    Eigen::VectorXd getCompositeFunctionCoefficients()
    {
        return compositeFunctionCoefficients_;
    }

    //! Reset coefficients.
    /*!
     * Resets the coefficients of the composite function.
     */
    void resetCompositeFunctionCoefficients( const Eigen::VectorXd& compositeFunctionCoefficients );

    //! Returns number of composite function components.
    /*!
     * Returns number of composite function components.
     */
    int getNumberOfCompositeFunctionComponents( )
    {
        return compositeFunctionComponents_.size( );
    }

    double evaluateCompositeFunctionCurrentTime( const double independentVariable );

    double evaluateCompositeFunctionDerivativeCurrentTime( const double independentVariable );

    double evaluateCompositeFunctionIntegralCurrentTime( const double independentVariable );

    double getComponentFunctionCurrentValue(
        const int componentIndex, const double currentTime );

    double getComponentFunctionDerivativeCurrentTime(
        const int componentIndex, const double currentTime );

    double getComponentFunctionIntegralCurrentTime(
        const int componentIndex, const double currentTime );

protected:

private:

    std::vector<  std::shared_ptr< BaseFunctionHodographicShaping > > compositeFunctionComponents_;

    //! Vector of coefficients.
    /*!
     * VectorXd containing coefficients corresponding to components of the composite function.
     */
    Eigen::VectorXd compositeFunctionCoefficients_;

};

} // namespace shape_based_methods
} // namespace tudat

#endif // TUDAT_COMPOSITE_FUNCTION_HODOGRAPHIC_SHAPING_H


text:
class LocalizationArraySerializer < BaseSerializer
  cached
  self.version = 9

  attributes :id, :lat, :long, :main

  def attributes
    data = super
    data['start_date'] = object.start_date.to_date.iso8601 if object.start_date.present?
    data['end_date']   = object.end_date.to_date.iso8601   if object.end_date.present?
    data
  end

  def cache_key
    self.class.cache_key << [object, object.updated_at]
  end
end


text:
/**
 * @file	src/core/Module.h
 * @date	dec. 2015
 * @author	PhRG - opticalp.fr
 */

/*
 Copyright (c) 2015 Ph. Renaud-Goud / Opticalp

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#ifndef SRC_MODULE_H_
#define SRC_MODULE_H_

#include "VerboseEntity.h"
#include "ParameterizedEntityWithWorkers.h"
#include "UniqueNameEntity.h"
#include "InPortUser.h"
#include "OutPortUser.h"
#include "ModuleTask.h"
#include "InitializedFlag.h"

#include "Poco/Thread.h"
#include "Poco/RunnableAdapter.h"
#include "Poco/ThreadLocal.h"
#include "Poco/RWLock.h"
#include "Poco/Mutex.h"

#include <map>
#include <set>
#include <list>

class ModuleFactory;

/**
 * Module
 *
 * Base class for any module.
 * A module is a single cell that processes data. It can be:
 *  - bound to a physical device: camera generating images,
 *  led controller, motion stage controller, ... i.e. either
 *  actuators or sensors
 *  - a computing cell: image processing, signal processing,
 *  ...
 *
 * The modules are closely bound to their ModuleTask s.
 * The module lists the tasks to be launched, and even can launch
 * the tasks when needed. The tasks are the only one to run the
 * modules (after having set runningTask).
 */
class Module: public VerboseEntity,
	public ParameterizedEntityWithWorkers,
	public UniqueNameEntity,
	public InPortUser, public OutPortUser
{
public:
	/**
	 * Constructor
	 *
	 * The implementation should at least do the following:
	 *  - explicitly call this constructor
	 *  - generate a name that will be returned by internalName()
	 *  - set the logger
	 *  - call @ref setCustomName after the internalName is set
	 *  - ParameterizedEntity::setParametersDefaultValue() should be called to set the parameters default values
	 *  - call @ref notifyCreation to let the module being registered
	 *  in the managers
	 *
	 * @param parent Parent module factory
	 * @param name Name to be used as task name. E.g. use the custom name
	 *
	 * @throw Poco::Exception forwarded from setCustomName or setInternalName
	 * if customName or internalName is already in use (or had a bad syntax).
	 */
	Module(ModuleFactory* parent, std::string name = ""):
	      mParent(parent),
		  ParameterizedEntityWithWorkers("module." + name),
		  reseting (false), resetDone(false),
		  lazyCancelling(false),
		  waitingCancelled(0),
		  immediateCancelling(false),
		  cancelRequested(false),
		  cancelDone(false),
		  cancelEffective(false),
		  cancellationListenerRunnable(*this, &Module::cancellationListen),
		  startingTask(NULL),
		  outputLocked(false)
	{
	}

	Module(ModuleFactory* parent, std::string name, bool applyParametersFromSettersWhenAllSet):
	      mParent(parent),
		  ParameterizedEntityWithWorkers("module." + name, applyParametersFromSettersWhenAllSet),
		  reseting (false), resetDone(false),
		  lazyCancelling(false),
          waitingCancelled(0),
          immediateCancelling(false),
          cancelRequested(false),
		  cancelDone(false),
		  cancelEffective(false),
		  cancellationListenerRunnable(*this, &Module::cancellationListen),
		  startingTask(NULL),
		  outputLocked(false)
	{
	}

	/**
	 * Destructor
	 *
	 * Notify any entity that could store a pointer on this.
	 *  - parent factory
	 *  - module manager
	 *  - dispatcher
	 *  - tasks
	 *
	 * The Module should not be deleted while running. E.g. CancelAll has
	 * to be called prior to any operation on the workflow, including Module
	 * deletion.
	 */
	virtual ~Module();

	/**
	 * Self-delete the module
	 *
	 * virtual in order to be implemented differently in EmptyModule
	 *
	 * @see Module::~Module()
	 */
	virtual void destroy() { delete this; }

	/**
	 * Custom name of the module
	 *
	 * @return Name defined by the user at creation time
	 * @see setCustomName()
	 */
	std::string name() { return UniqueNameEntity::name(); }

	/**
	 * Internal name of the module
	 *
	 * This name may include dynamic content (e.g. index number...)
	 * since no duplicates are allowed.
	 * @return Name computed by the module itself regarding internal
	 * considerations
	 * @see setInternalName()
	 */
	std::string internalName() { return mInternalName; }

	/**
	 * Description of the module
	 *
	 * This description does not include dynamic content bound to
	 * parameters (factory parameters or module parameters).
	 * It should be static in the derived classes,
	 * so it can be queried by the factory
	 * before module creation.
	 * @return full description of the module: functionalities, usage
	 */
	virtual std::string description() = 0;

	/**
	 * Get parent ModuleFactory
	 *
	 * e.g. to get factory parameters
	 */
	ModuleFactory* parent();

    /**
     * Launch a module task
     *
     * to be called by the UI or by any mean, but without new
     * input port data.
     *
	 * @param syncAllowed if true, try to sync start the module first.
     * @return The task created for the module to run. The
     * task can be used to check the state of the execution.
     */
	Poco::AutoPtr<ModuleTask> runModule(bool syncAllowed = false);

    /**
     * Enqueue a new task
     *
     * for this module. and pop it, if no task is running for this module.
     *
     * To be called
     *  - either by runModule if no trigging input port is involved.
     *  - or by a InPort::runTarget.
     *
	 * @param syncAllowed if true, try to sync start the module first.
	 *
     * @return true if the module is not running, and thus,
     * the new enqueued task should be started.
     *
     * @throw ExecutionAbortedException in case of cancellation.
     * The calling trigging port is not released.
     */
    void enqueueTask(ModuleTaskPtr& task, bool syncAllowed = false);

    /**
     * Try to unregister a task
     *
     * Async called by the thread manager when the task finishes,
	 * via a TaskUnregisterer, via the taskFinishedNotification
     */
	bool tryUnregisterTask(ModuleTask* pTask);

	/**
	 * Force the cancellation
	 *
	 *  - Cancel sources,
	 *  - cancel targets,
	 *  - purge the task queue,
	 *  - request the active tasks to stop
	 *  - call Module::cancel
	 *  - launch a listener to wait for the cancellation to be effective (on self)
	 *
	 * @return true if a cancellation is trigged.
	 * false if a cancellation process is already occuring.
	 */
	bool immediateCancel();

	/**
	 * Wait for the end of the current run to dispatch the cancellation.
	 *
	 * i.e. if running: let it run, let it send out the newly generated data, then,
	 * cancel... but avoid the launch of a new run.
	 *
	 * @warning Module::cancel is not called here
	 */
	void lazyCancel();

	/**
	 * Wait for the cancellation to be effective
	 */
	void waitCancelled();

	/**
	 * Reset the targets, then reset itself calling reset(),
	 * then reset sources.
	 *
	 * Check that cancelDoneEvent is set first.
	 */
	void moduleReset();

	/**
	 * Wait that all the threads are terminated for this module
	 *
	 * To be called asynchronously by immediateCancel or lazyCancel
	 *
	 * Call Module::cancelled when all the tasks have stopped
	 */
	void cancellationListen();

	/**
	 * Check if the module cancellation/reset is done.
	 */
	bool moduleReady();

protected:
	void addInPort(
			std::string name, std::string description,
	        int dataType,
	        size_t index )
	{ InPortUser::addInPort(this, name, description, dataType, index); }

	void addTrigPort(
            std::string name, std::string description,
            size_t index )
	{ InPortUser::addTrigPort(this, name, description, index); }

    void addOutPort(
            std::string name, std::string description,
            int dataType,
            size_t index )
	{ OutPortUser::addOutPort(this, name, description, dataType, index); }

	/**
	 * Set the running task thread local pointer.
	 *
	 * To be set to NULL in case of need to call the task forwarding functions.
	 *
	 * e.g. when calling reserveOutPorts() from setParameter
	 */
    void setRunningTask(ModuleTask* pTask) { *runningTask = pTask; }
    /**
     * Get the running task thread local pointer.
     */
    ModuleTask* getRunningTask() { return *runningTask; }

    /// @name forwarding methods to thread local: runningTask
    ///@{
    bool sleep(long milliseconds);
    bool yield();
	void setProgress(float progress);
    bool isCancelled();
    InPort* triggingPort();
    void setRunningState(ModuleTask::RunningStates state);
    ModuleTask::RunningStates getRunningState();
    ///}

    /**
	 * Canceling method to be called to force cancellation of the module
	 *
	 * Called by immediateCancel issuing either from:
	 *   * task cancel (direct call or cancelAll call)
	 *   * any outport sourceCancel
	 *
	 * immediateCancel verify first that the module is not already
	 * canceling.
	 *
	 * @warning The implementation should not throw exceptions
	 *
	 * @warning This method should not be called directly. Call immediateCancel instead.
	 */
	virtual void cancel() { }

	/**
	 * Reset the module to its initial state.
	 *
	 * Should achieve:
	 *  - reset running seqIndexes
	 *  - reset evtl flags, states,...
	 *
	 * Called by Module::resetWithTargets
	 *
	 * @warning The implementation should not throw exceptions
	 *
	 * @note Locks or mutexes should not be kept locked in case
	 * of exceptions, then no unlock should be necessary here
	 */
	virtual void reset() { }

	/**
	 * Method called by the task that identifies itself with pTask.
	 *
	 * Expire the output data, check the start condition,
	 * and call process().
	 *
	 * prepareTaskStart was previously called by MergeableTask::run
	 * to lock taskProcessingMutex and set Module::processing to true
	 *
	 * taskProcessingMutex is released in this function by a call to
	 * releaseProcessingMutex
	 *
	 * Manage ports release.
	 */
	void run(ModuleTask* pTask);

	/**
	 * Main logic called by run
	 *
	 * The caught input data should be locked before
	 * being used.
	 *
	 * Access to input ports data should be done via readInPort and
	 * readInPortDataAttribute. Call releaseAllInPorts when over.
	 *
	 * Access to output ports should be granted via reserveOutPorts
	 * and then data pointer should be accessed with getDataToWrite.
	 * Call notifyAllOutPortReady when over.
	 *
	 * In case of cancellation detected via Module::isCancelled or
	 * Module::yield or Module::sleep,
	 * a ExecutionAbortedException should be thrown
	 *
	 * @param startCond start condition as defined in virtual method
	 * startCondition. You should consider implementing your own
	 * startCondition method for non-standard cases.
	 *
	 * When the processing is done, processingTerminated should be
	 * called to allow the next tasks to be launched (taskProcessingMutex
	 * is released). It can gain some time if there is many output ports
	 * to reserve and if the result of the processing is buffered.
	 *
	 * @see startCondition
	 * @see setRunningState
	 */
	virtual void process(int startCond)
		{ poco_warning(logger(), name() + ": nothing to be done"); }

	/**
	 * Method to check if a sequence is running.
	 *
	 * It can be true even if the module has no task running.
	 *
	 * This method is used by ModuleTask::cancel to know if
	 * Module::cancel needs to be called if the task is not
	 * running.
	 */
	virtual bool seqRunning() { return false; }

    /**
     * Set the internal name of the module
     *
     * This method has to be called by the constructor
     * before setCustomName()
     * @throw Poco::ExistsException If internalName is already in use
     * @throw Poco::SyntaxException If internalName contains bad characters
     */
    void setInternalName(std::string internalName);

	/**
	 * Set the custom name of the module
	 *
	 * This method has to be called by the constructor.
	 * If customName is empty, use internalName().
     * @throw Poco::ExistsException If customName is already in use
     * @throw Poco::SyntaxException If customName contains bad characters
	 */
	void setCustomName(std::string customName);

	/**
	 * Notify the managers about the module creation
	 *
	 * Has to be called at the end of the constructors implementation
	 * in order to be registered in the ModuleManager and
	 * in the Dispatcher
	 */
	void notifyCreation();

	Poco::Logger& logger() { return VerboseEntity::logger(); }

	/**
	 * Look into the task queue, if a task was trigged by the given InPort.
	 *
	 * if true, merge the task.
	 */
	bool tryCatchInPortFromQueue(InPort* triggingPort);

	/**
	 * To be called by Module::process implementation
	 * when the processing is terminated
	 *
	 * to allow the next task to be ran.
	 *
	 * Shall be called only once in Module::process due
	 * to the outputMutex management
	 */
    void processingTerminated();

private:
	/**
	 * Parent module factory
	 *
	 * - to be notified when the module is deleted
	 * - to get the factory parameters (selectors, evtl parameters)
	 */
	ModuleFactory* mParent;

	std::string mInternalName; ///< internal name of the module

    /**
     * Launch the next task of the queue in the current thread
     *
     * and dequeue it.
     */
    void popTaskSync();

    /**
     * Launch the next task of the queue
     *
     * and dequeue it.
     *
     * Do nothing if the queue is empty.
     *
     * Require the taskStartingMutex to be available. Lock it.
     *
     * If the task start succeeded, taskStartingMutex is locked when the
     * function returns.
     */
    void popTask();

	bool reseting; ///< flag set when the reseting begins
	bool resetDone; ///< flag set when a reset just occurred

    /**
     * Check if a task is already starting
     * for this module
     *
     * or just running
     *
     * @param orRunning if true, check also if a task is running
     */
    bool taskIsStarting(bool orRunning = false);

	/**
	 * Check if a task is already running (or at least started)
	 * for this module
	 */
	bool taskIsRunning() { return taskIsStarting(true); }

    /**
     * Check if a task is already running or just pending
     * for this module.
     *
     * A task that is cancelling is considered as pending since
     * it is not really over yet.
     */
    bool taskIsPending();

    /**
     * Notify (self) that the cancellation is effective.
     */
    void cancelled();

    /**
     * Mutex used to lock immediateCancel, lazyCancel and cancelled
     *
     * to avoid async modification of immediateCancelling and cancelling.
     */
    Poco::Mutex cancelMutex;
	bool immediateCancelling; ///< flag set by immediateCancel and reset by cancelled
	bool lazyCancelling; ///< flag set by lazyCancel and reset by cancelled
	int waitingCancelled;
	bool cancelRequested; ///< flag set before calling Module::cancel, and reset on return
	bool cancelDone; ///< set when a cancellation just occurred via cancelled. Reset in moduleReset

	/**
	 * set if just cancelled and neighbours are cancelled to.
	 *
	 * Used by waitCancelled
	 * Reset by resetModule and runModule
	 */
	bool cancelEffective;

    /**
     * flag used to know if the thread is already waiting for the end
     * of the cancellation
     *
     * @see waitCancelled
     */
    Poco::ThreadLocal<InitializedFlag> waiting;

    Poco::RunnableAdapter<Module> cancellationListenerRunnable;
	Poco::Thread cancellationListenerThread;

	/**
	 * Wait for all the plugged mandatory parameters to be available.
	 *
	 * @throw ExecutionAbortedException on any cancellation (lazy cancel or immediate cancel)
	 */
	void waitParameters();

    Poco::ThreadLocal<ModuleTask*> runningTask; ///< task that executes this module
	/// Store the tasks assigned to this module. See registerTask(), unregisterTask()
	std::set<ModuleTaskPtr> allLaunchedTasks;
	std::list<ModuleTaskPtr> taskQueue; ///< enqueued tasks, waiting to be started. The order counts.
	ModuleTaskPtr startingTask; ///< task that is just started. no more in taskQueue, already in allLaunchedTasks.
	Poco::Mutex taskMngtMutex; ///< recursive mutex. lock the task management. Recursive because of its use in Module::enqueueTask

	/**
     * flag used to know if the module execution occured following
     * a sync start
     *
     * @see popTaskSync
     */
    Poco::ThreadLocal<InitializedFlag> startSyncPending;

	/**
	 * lock the launching of a new task as long as another task is already processing.
	 *
	 * This mutex is locked by popTask or popTaskSync
	 * and released by releaseProcessingMutex
	 *
	 * @see processing
	 */
	Poco::FastMutex taskProcessingMutex;
	void processingUnlock() { taskProcessingMutex.unlock(); }

	/**
     * Release Module::taskProcessingMutex via startingUnlock
     * if starting is set.
     */
    void releaseProcessingMutex(bool force = false);

	/**
	 * Lock the taskStartingMutex
	 *
	 * called by ModuleTask::prepareTask
	 *
	 * Release the taskMngtMutex in case of sync start
	 *
	 * @throw ExecutionAbortedException
	 * @throw TaskMergedException if the starting task is merged while trying to
	 * lock taskStartingMutex
	 */
	void prepareTaskStart(ModuleTask* pTask);

	Poco::FastMutex outputMutex; ///< used to keep the queue order to the access to the outputs
	bool outputLocked;
	void releaseOutputMutex();

    friend class ModuleTask; // access to setRunningTask, releaseAll
};

#endif /* SRC_MODULE_H_ */


text:
package com.siondream.core;

import java.util.Locale;

import ashley.core.Engine;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenManager;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Logger;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.siondream.core.assets.Assets;
import com.siondream.core.entity.components.TransformComponent;
import com.siondream.core.entity.factory.ComponentReaders.ColorComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.FontComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.MapComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.OverridePhysicsComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.ParticleComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.PhysicsComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.ShaderComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.SpineComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.SpriteComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.StateComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.TextureComponentReader;
import com.siondream.core.entity.factory.ComponentReaders.TransformComponentReader;
import com.siondream.core.entity.factory.EntityFactory;
import com.siondream.core.entity.systems.PhysicsSystem;
import com.siondream.core.physics.CategoryBitsManager;
import com.siondream.core.physics.CollisionHandler;
import com.siondream.core.tweeners.ActorTweener;
import com.siondream.core.tweeners.CameraTweener;
import com.siondream.core.tweeners.TransformTweener;

public class SionGame extends Game implements InputProcessor {

	private final String TAG = "SionGame";

	private Logger logger;
	private ObjectMap<Class<? extends SionScreen>, SionScreen> screens;
	private SionScreen nextScreen;
	private SionScreen currentScreen;
	private InputMultiplexer multiplexer;
	private ExtendViewport viewport;
	private OrthographicCamera camera;
	private ExtendViewport uiViewport;
	private OrthographicCamera uiCamera;

	private Assets assets;

	private Engine engine;
	private Stage stage;
	private TweenManager tweenManager;
	private LanguageManager languageManager;
	private World world;
	private double accumulator;
	private double currentTime;
	private ParticleEffectPools particlePools;
	private ShaderManager shaderManager;
	private EntityFactory entityFactory;
	private CategoryBitsManager categoryBitsManager;
	private CollisionHandler collisionHandler;

	@Override
	public void create() {
		Env.init(this);

		logger = new Logger(TAG, Env.debugLevel);

		logger.info("initialising");

		categoryBitsManager = new CategoryBitsManager();

		assets = new Assets("data/config/assets.json");
		assets.loadGroup("base");
		assets.finishLoading();

		screens = new ObjectMap<Class<? extends SionScreen>, SionScreen>();
		nextScreen = null;
		currentScreen = null;

		camera = new OrthographicCamera();
		viewport = new ExtendViewport(800 * Env.pixelsToMetres, 600 * Env.pixelsToMetres, 1280 * Env.pixelsToMetres, 720 * Env.pixelsToMetres, camera);

		uiCamera = new OrthographicCamera();
		uiViewport = new ExtendViewport(800, 600, 1280, 720, uiCamera);

		tweenManager = new TweenManager();
		Tween.registerAccessor(OrthographicCamera.class, new CameraTweener());
		Tween.registerAccessor(Actor.class, new ActorTweener());
		Tween.registerAccessor(TransformComponent.class, new TransformTweener());
		Tween.setCombinedAttributesLimit(4);

		world = new World(Env.gravity, Env.doSleep);
		collisionHandler = new CollisionHandler();
		world.setContactListener(collisionHandler);

		accumulator = 0.0;
		currentTime = TimeUtils.millis() / 1000.0;
		engine = new Engine();

		stage = new Stage();
		stage.setViewport(uiViewport);

		multiplexer = new InputMultiplexer();
		Gdx.input.setInputProcessor(multiplexer);
		Gdx.input.setCatchBackKey(Env.catchBack);
		Gdx.input.setCatchMenuKey(Env.catchMenu);
		multiplexer.addProcessor(this);

		languageManager = new LanguageManager("data/lang", Locale.getDefault().getLanguage());
		particlePools = new ParticleEffectPools();
		shaderManager = new ShaderManager();

		entityFactory = new EntityFactory();
		entityFactory.registerReader(new ColorComponentReader());
		entityFactory.registerReader(new FontComponentReader());
		entityFactory.registerReader(new MapComponentReader());
		entityFactory.registerReader(new OverridePhysicsComponentReader());
		entityFactory.registerReader(new ParticleComponentReader());
		entityFactory.registerReader(new PhysicsComponentReader());
		entityFactory.registerReader(new ShaderComponentReader());
		entityFactory.registerReader(new SpineComponentReader());
		entityFactory.registerReader(new SpriteComponentReader());
		entityFactory.registerReader(new StateComponentReader());
		entityFactory.registerReader(new TextureComponentReader());
		entityFactory.registerReader(new TransformComponentReader());
	}

	@Override
	public void dispose() {
		logger.info("shutting down");

		assets.dispose();
		world.dispose();
		stage.dispose();

		if (currentScreen != null) {
			currentScreen.dispose();
		}
	}

	@Override
	public void render() {

		double newTime = TimeUtils.millis() / 1000.0;
		double frameTime = Math.min(newTime - currentTime, 0.25);
		float deltaTime = (float)frameTime;

		currentTime = newTime;

		if (currentScreen != null) {
			currentScreen.render(deltaTime);
		}

		tweenManager.update(deltaTime);

		accumulator += frameTime;

		PhysicsSystem physics = engine.getSystem(PhysicsSystem.class);

		while (accumulator >= Env.physicsDeltaTime) {

			if (physics != null) {
				physics.update(Env.physicsDeltaTime);
			}

			world.step(Env.physicsDeltaTime, Env.velocityIterations, Env.positionIterations);
			accumulator -= Env.physicsDeltaTime;

			if (physics != null) {
				physics.interpolate(Env.physicsDeltaTime, (float)(accumulator / Env.physicsDeltaTime));
			}
		}

		engine.update(deltaTime);
		stage.act(deltaTime);

		performScreenChange();
	}

	@Override
	public void resize(int width, int height) {
		if (currentScreen != null) {
			currentScreen.resize(width, height);
		}
	}

	@Override
	public void pause() {
		if (currentScreen != null) {
			currentScreen.pause();
		}
	}

	@Override
	public void resume() {
		if (currentScreen != null) {
			currentScreen.resume();
		}
	}

	protected void addScreen(SionScreen screen) {
		screens.put(screen.getClass(), screen);
	}

	public <T extends SionScreen> T getScreen(Class<T> type) {
		return type.cast(screens.get(type));
	}

	@Override
	public void setScreen(Screen screen) {
		logger.error("method not supported");
	}

	public void setScreen(Class<? extends SionScreen> type) {
		SionScreen screen = screens.get(type);

		if (screen != null) {
			nextScreen = screen;
		}
		else {
			logger.error("invalid screen " + type.getName());
		}
	}

	public Assets getAssets() {
		return assets;
	}

	public OrthographicCamera getCamera() {
		return camera;
	}

	public Viewport getViewport() {
		return viewport;
	}

	public OrthographicCamera getUICamera() {
		return uiCamera;
	}

	public Viewport getUIViewport() {
		return uiViewport;
	}

	public World getWorld() {
		return world;
	}

	public Stage getStage() {
		return stage;
	}

	public TweenManager getTweenManager() {
		return tweenManager;
	}

	public Engine getEngine() {
		return engine;
	}

	public LanguageManager getLang() {
		return languageManager;
	}

	public InputMultiplexer getInputMultiplexer() {
		return multiplexer;
	}

	public ParticleEffectPools getParticlePools() {
		return particlePools;
	}

	public ShaderManager getShaderManager() {
		return shaderManager;
	}

	public EntityFactory getEntityFactory() {
		return entityFactory;
	}

	public CategoryBitsManager getCategoryBitsManager() {
		return categoryBitsManager;
	}

	public CollisionHandler getCollisionHandler() {
		return collisionHandler;
	}

	private void performScreenChange() {
		if (nextScreen != null) {
			logger.info("switching to screen " + screens.findKey(nextScreen, false));
			multiplexer.removeProcessor(currentScreen);
			setScreenInternal(nextScreen);
			multiplexer.addProcessor(currentScreen);
			nextScreen = null;
		}
	}

	private void setScreenInternal(SionScreen screen) {
		super.setScreen(screen);
		currentScreen = screen;
	}

	@Override
	public boolean keyDown(int keycode) {
		if (Env.debug) {
			if (keycode == Keys.F1) {
				Env.init(this);
			}
		}

		return stage.keyDown(keycode);
	}

	@Override
	public boolean keyUp(int keycode) {
		return stage.keyUp(keycode);
	}

	@Override
	public boolean keyTyped(char character) {
		return stage.keyTyped(character);
	}

	@Override
	public boolean touchDown(int screenX, int screenY, int pointer, int button) {
		return stage.touchDown(screenX, screenY, pointer, button);
	}

	@Override
	public boolean touchUp(int screenX, int screenY, int pointer, int button) {
		return stage.touchUp(screenX, screenY, pointer, button);
	}

	@Override
	public boolean touchDragged(int screenX, int screenY, int pointer) {
		return stage.touchDragged(screenX, screenY, pointer);
	}

	@Override
	public boolean mouseMoved(int screenX, int screenY) {
		return stage.mouseMoved(screenX, screenY);
	}

	@Override
	public boolean scrolled(int amount) {
		return stage.scrolled(amount);
	}
}


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

{% block title %}{{ pad.name }}{% endblock %}
{% block page_title %}{{ pad.name }}{% endblock %}

{% block content %}
  {% include "pads/form.html" %}
  Delete pad
{% endblock %}


text:
@implementation UIView (MasornyEqualSpace)

- (void) distributeSpacingHorizontallyWith:(NSArray*)views
{
    NSMutableArray *spaces = [NSMutableArray arrayWithCapacity:views.count+1];

    for ( int i = 0 ; i < views.count+1 ; ++i )
    {
        UIView *v = [UIView new];
        [spaces addObject:v];
        [self addSubview:v];

        [v mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(v.mas_height);
        }];
    }

    UIView *s0 = spaces[0];

    WEAKSELF

    [s0 mas_makeConstraints:^(MASConstraintMaker *make) {
        STRONGSELF
        make.left.equalTo(strongSelf.mas_left);
        make.centerY.equalTo(((UIView*)views[0]).mas_centerY);
    }];

    UIView *lastSpace = s0;
    for ( int i = 0 ; i < views.count; ++i )
    {
        UIView *obj = views[i];
        UIView *space = spaces[i+1];

        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(lastSpace.mas_right);
        }];

        [space mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(obj.mas_right);
            make.centerY.equalTo(obj.mas_centerY);
            make.width.equalTo(s0);
        }];

        lastSpace = space;
    }

    [lastSpace mas_makeConstraints:^(MASConstraintMaker *make) {
        STRONGSELF
        make.right.equalTo(strongSelf.mas_right);
    }];

}

- (void) distributeSpacingVerticallyWith:(NSArray*)views
{
    NSMutableArray *spaces = [NSMutableArray arrayWithCapacity:views.count+1];

    for ( int i = 0 ; i < views.count+1 ; ++i )
    {
        UIView *v = [UIView new];
        [spaces addObject:v];
        [self addSubview:v];

        [v mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(v.mas_height);
        }];
    }

    UIView *v0 = spaces[0];

    __weak __typeof(&*self)ws = self;

    [v0 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.mas_top);
        make.centerX.equalTo(((UIView*)views[0]).mas_centerX);
    }];

    UIView *lastSpace = v0;
    for ( int i = 0 ; i < views.count; ++i )
    {
        UIView *obj = views[i];
        UIView *space = spaces[i+1];

        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(lastSpace.mas_bottom);
        }];

        [space mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(obj.mas_bottom);
            make.centerX.equalTo(obj.mas_centerX);
            make.height.equalTo(v0);
        }];

        lastSpace = space;
    }

    [lastSpace mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(ws.mas_bottom);
    }];
}

@end


text:
package dms_enterprise

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// DatabaseInGetTableDBTopology is a nested struct in dms_enterprise response
type DatabaseInGetTableDBTopology struct {
	DbId      string  `json:"DbId" xml:"DbId"`
	DbName    string  `json:"DbName" xml:"DbName"`
	DbType    string  `json:"DbType" xml:"DbType"`
	EnvType   string  `json:"EnvType" xml:"EnvType"`
	TableList []Table `json:"TableList" xml:"TableList"`
}


text:
package com.iluwatar;

/**
 *
 * Party interface.
 *
 */
public interface Party {

	void addMember(PartyMember member);

	void act(PartyMember actor, Action action);

}


text:
from haversine import haversine, Unit
from math import pi
import pytest

from tests.geo_ressources import LYON, PARIS, NEW_YORK, LONDON, EXPECTED_LYON_PARIS

def haversine_test_factory(unit):
    def test():
        expected = EXPECTED_LYON_PARIS[unit]
        assert haversine(LYON, PARIS, unit=unit) == expected
        assert isinstance(unit.value, str)
        assert haversine(LYON, PARIS, unit=unit.value) == expected

    return test

test_kilometers = haversine_test_factory(Unit.KILOMETERS)
test_meters = haversine_test_factory(Unit.METERS)
test_miles = haversine_test_factory(Unit.MILES)
test_nautical_miles = haversine_test_factory(Unit.NAUTICAL_MILES)
test_feet = haversine_test_factory(Unit.FEET)
test_inches = haversine_test_factory(Unit.INCHES)
test_radians = haversine_test_factory(Unit.RADIANS)
test_degrees = haversine_test_factory(Unit.DEGREES)

def test_units_enum():
    from haversine.haversine import _CONVERSIONS
    assert all(unit in _CONVERSIONS for unit in Unit)

def test_haversine_deg_rad():
    """
    Test makes sure that one time around earth matches sphere circumference in degrees / radians.
    """
    p1, p2 = (45, 0), (-45, 180)
    assert haversine(p1, p2, unit=Unit.RADIANS) == pi
    assert round(haversine(p1, p2, unit=Unit.DEGREES), 13) == 180.0

@pytest.mark.parametrize(
    "oob_from,oob_to,proper_from,proper_to", [
        ((-90.0001, 0), (0, 0), (-89.9999, 180), (0, 0)),
        ((-90.0001, 30), (0, 0), (-89.9999, -150), (0, 0)),
        ((0, 0), (90.0001, 0), (0, 0), (89.9999, -180)),
        ((0, 0), (90.0001, 30), (0, 0), (89.9999, -150)),
        ((0, -180.0001), (0, 0), (0, 179.9999), (0, 0)),
        ((30, -180.0001), (0, 0), (30, 179.9999), (0, 0)),
        ((0, 0), (0, 180.0001), (0, 0), (0, -179.9999)),
        ((0, 0), (30, 180.0001), (0, 0), (30, -179.9999)),
    ]
)
def test_normalization(oob_from, oob_to, proper_from, proper_to):
    """
    Test makes sure that normalization works as expected by comparing distance of out of
    bounds points cases to equal cases where all points are within lat/lon ranges. The
    results are expected to be equal (within some tolerance to account for numerical
    issues).
    """
    normalized_during, normalized_already = (
        haversine(oob_from, oob_to, Unit.DEGREES, normalize=True),
        haversine(proper_from, proper_to, Unit.DEGREES, normalize=True),
    )
    assert normalized_during == pytest.approx(normalized_already, abs=1e-10)

@pytest.mark.parametrize(
    "oob_from,oob_to", [
        ((-90.0001, 0), (0, 0)),
        ((0, 0), (90.0001, 0)),
        ((0, -180.0001), (0, 0)),
        ((0, 0), (0, 180.0001)),
    ]
)
def test_out_of_bounds(oob_from, oob_to):
    """
    Test makes sure that a ValueError is raised when latitude or longitude values are out of bounds.
    """
    with pytest.raises(ValueError):
        haversine(oob_from, oob_to)
    with pytest.raises(ValueError):
        haversine(oob_from, oob_to, normalize=False)

@pytest.mark.parametrize(
    "in_bounds_from,in_bounds_to", [
        ((-90, 0), (0, 0)),
        ((0, 0), (90, 0)),
        ((0, -180), (0, 0)),
        ((0, 0), (0, 180)),
    ]
)
def test_in_bounds(in_bounds_from, in_bounds_to):
    """
    Test makes sure that a ValueError is NOT raised when latitude or longitude values are in bounds.
    """
    assert haversine(in_bounds_from, in_bounds_to) > 0

def test_haversine_deg_rad_great_circle_distance():
    """
    Test makes sure the haversine functions returns the great circle distance (https://en.wikipedia.org/wiki/Great-circle_distance) between two points on a sphere.
    See https://github.com/mapado/haversine/issues/45
    """
    p1, p2 = (0, -45), (0, 45)
    assert haversine(p1, p2, Unit.DEGREES) == 89.99999999999997


text:
`standings(season)`

Get division standings for a given season. Data exists from 1969 season to present, since this is when divisions were introduced.

## Arguments
`season:` Integer. Defaults to the current calendar year if no value is provided.

## Examples of valid queries

```python
from pybaseball import standings

# get the current season's up-to-date standings
data = standings()

# get the end-of-season division standings for the 1980 season
data = standings(1980)
```


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "omapincident_person".
 *
 * @property string $id
 * @property string $incident_id
 * @property string $person_first
 * @property string $person_last
 * @property string $person_email
 * @property string $person_phone
 * @property string $person_ip
 * @property string $person_date
 *
 * @property Incident $incident
 */
class Person extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'omapincident_person';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['incident_id'], 'integer'],
            [['person_date'], 'safe'],
            [['person_first', 'person_last'], 'string', 'max' => 200],
            [['person_email'], 'string', 'max' => 120],
            [['person_phone'], 'string', 'max' => 60],
            [['person_ip'], 'string', 'max' => 50],
            [['incident_id'], 'exist', 'skipOnError' => true, 'targetClass' => Incident::className(), 'targetAttribute' => ['incident_id' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'incident_id' => 'Incident ID',
            'person_first' => 'Person First',
            'person_last' => 'Person Last',
            'person_email' => 'Person Email',
            'person_phone' => 'Person Phone',
            'person_ip' => 'Person Ip',
            'person_date' => 'Person Date',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIncident()
    {
        return $this->hasOne(Incident::className(), ['id' => 'incident_id']);
    }
}


text:
// Original file: deps/envoy-api/envoy/type/metadata/v3/metadata.proto

/**
 * Represents metadata from :ref:`the upstream cluster<envoy_v3_api_field_config.cluster.v3.Cluster.metadata>`.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Cluster {
}

/**
 * Represents metadata from :ref:`the upstream cluster<envoy_v3_api_field_config.cluster.v3.Cluster.metadata>`.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Cluster__Output {
}

/**
 * Represents metadata from :ref:`the upstream
 * host<envoy_v3_api_field_config.endpoint.v3.LbEndpoint.metadata>`.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Host {
}

/**
 * Represents metadata from :ref:`the upstream
 * host<envoy_v3_api_field_config.endpoint.v3.LbEndpoint.metadata>`.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Host__Output {
}

/**
 * Represents dynamic metadata associated with the request.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Request {
}

/**
 * Represents dynamic metadata associated with the request.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Request__Output {
}

/**
 * Represents metadata from :ref:`the route<envoy_v3_api_field_config.route.v3.Route.metadata>`.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Route {
}

/**
 * Represents metadata from :ref:`the route<envoy_v3_api_field_config.route.v3.Route.metadata>`.
 */
export interface _envoy_type_metadata_v3_MetadataKind_Route__Output {
}

/**
 * Describes what kind of metadata.
 */
export interface MetadataKind {
  /**
   * Request kind of metadata.
   */
  'request'?: (_envoy_type_metadata_v3_MetadataKind_Request | null);
  /**
   * Route kind of metadata.
   */
  'route'?: (_envoy_type_metadata_v3_MetadataKind_Route | null);
  /**
   * Cluster kind of metadata.
   */
  'cluster'?: (_envoy_type_metadata_v3_MetadataKind_Cluster | null);
  /**
   * Host kind of metadata.
   */
  'host'?: (_envoy_type_metadata_v3_MetadataKind_Host | null);
  'kind'?: "request"|"route"|"cluster"|"host";
}

/**
 * Describes what kind of metadata.
 */
export interface MetadataKind__Output {
  /**
   * Request kind of metadata.
   */
  'request'?: (_envoy_type_metadata_v3_MetadataKind_Request__Output | null);
  /**
   * Route kind of metadata.
   */
  'route'?: (_envoy_type_metadata_v3_MetadataKind_Route__Output | null);
  /**
   * Cluster kind of metadata.
   */
  'cluster'?: (_envoy_type_metadata_v3_MetadataKind_Cluster__Output | null);
  /**
   * Host kind of metadata.
   */
  'host'?: (_envoy_type_metadata_v3_MetadataKind_Host__Output | null);
  'kind': "request"|"route"|"cluster"|"host";
}


text:
{% extends "base.html" %}
{% load i18n %}{% load socialaccount %}
{% block content %}

    Connect with Twitter

    {% if not connected_providers %}
        {% trans "Connect to one of the social networks above" %}
    {% elif not friends %}
        {% trans "No friends found" %}
    {% else %}

            {% for friend in friends %}

                {{ friend }}

            {% endfor %}

    {% endif %}

{% endblock %}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Kavaka 5: 94 (1978)

#### Original name
Dactylella megalospora Drechsler, 1954

### Remarks
null


text:
using System.Linq;

namespace ULocalizer.Classes.Configuration
{
    public class CConfigSection
    {
        public CObservableList<CConfigSectionItem> Items { get; private set; }

        public CConfigSection()
        {
            Items = new CObservableList<CConfigSectionItem>();
        }

        public void UpdateItem(string key,string value)
        {
            if (Items.FirstOrDefault(item => item.Key == key) != null)
            {
                Items.First(item => item.Key == key).Value = value;
            }
            else
            {
                Items.Add(new CConfigSectionItem {Key = key,Value = value});
            }
        }

        public void AddItem(string key, string value)
        {
            Items.Add(new CConfigSectionItem{Key = key,Value = value});
        }

    }
}


text:
namespace DotSpatial.Symbology
{
    /// <summary>
    /// Event args for events that need a feature layer selection.
    /// </summary>
    public class FeatureLayerSelectionEventArgs : FeatureLayerEventArgs
    {
        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="FeatureLayerSelectionEventArgs"/> class.
        /// </summary>
        /// <param name="fl">The feature layer.</param>
        /// <param name="selection">The selection.</param>
        public FeatureLayerSelectionEventArgs(IFeatureLayer fl, ISelection selection)
            : base(fl)
        {
            Selection = selection;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the list of changed features.
        /// </summary>
        public ISelection Selection { get; protected set; }

        #endregion
    }
}


text:
namespace arangodb {
namespace aql {

/// @brief Traversal condition finder
class TraversalConditionFinder : public WalkerWorker<ExecutionNode> {
 public:
  TraversalConditionFinder(ExecutionPlan* plan, bool* planAltered);

  ~TraversalConditionFinder() = default;

  bool before(ExecutionNode*) override final;

  bool enterSubquery(ExecutionNode*, ExecutionNode*) override final;

 private:
  bool isTrueOnNull(AstNode* condition, Variable const* pathVar) const;

 private:
  ExecutionPlan* _plan;
  std::unique_ptr<Condition> _condition;
  ::arangodb::containers::HashSet<VariableId> _filterVariables;
  bool* _planAltered;
};
}  // namespace aql
}  // namespace arangodb

#endif


text:
package org.dlw.ai.blackboard.dao.hibernate;

import java.util.List;

import org.dlw.ai.blackboard.dao.RuleSetDao;
import org.dlw.ai.blackboard.exception.RuleSetNameNotFoundException;
import org.dlw.ai.blackboard.rule.RuleSet;

/**
 * @author @author David L. Whitehurst
 * @version 1.0.0
 */
public class RuleSetDaoHibernate extends GenericDaoHibernate<RuleSet, Long> implements RuleSetDao {

    /**
     * Constructor, sets class object (dao subject) to RuleSet
     */
    public RuleSetDaoHibernate() {
        super(RuleSet.class);
    }

    /* (non-Javadoc)
     * @see org.dlw.ai.blackboard.dao.RuleSetDao#getRuleSets()
     */
    @SuppressWarnings("unchecked")
    public List<RuleSet> getRuleSets() {
        return getHibernateTemplate().find("from RuleSet r order by upper(r.name)");
    }

    /* (non-Javadoc)
     * @see org.dlw.ai.blackboard.dao.RuleSetDao#loadRuleSetByName(java.lang.String)
     */
    @SuppressWarnings("unchecked")
    public RuleSet getRuleSetByName(String name)
            throws RuleSetNameNotFoundException {
        List<RuleSet> ruleSet = getHibernateTemplate().find("from RuleSet where name=?", name);
        if (ruleSet == null || ruleSet.isEmpty()) {
            throw new RuleSetNameNotFoundException("name '" + name + "' not found...");
        } else {
            return (RuleSet) ruleSet.get(0);
        }
    }

    /* (non-Javadoc)
     * @see org.dlw.ai.blackboard.dao.RuleSetDao#saveRuleSet(org.dlw.ai.blackboard.rule.RuleSet)
     */
    public RuleSet saveRuleSet(RuleSet ruleSet) {
        getHibernateTemplate().saveOrUpdate(ruleSet);
        getHibernateTemplate().flush();
        return ruleSet;
    }

    /* (non-Javadoc)
     * @see org.dlw.ai.blackboard.dao.GenericDao#save(java.lang.Object)
     */
    public RuleSet save(RuleSet ruleSet) {
        return this.saveRuleSet(ruleSet);
    }

}


text:
<?php

namespace bone;

use \App as App;

class Variable{

    /**
     * a prefix for the table name incase you want to use the name variable for
     * something else.  Set this up in your definitions file like so:
     * Variable::$pre='my_prefix';     *
     * @var string
     * @disabled
     */
    private static $tpre = '';

    private static $sql = array(
        'get' => "SELECT * FROM `variable` WHERE `name` = :name;",
        'set' => "REPLACE INTO `variable` (`name`, `value`) VALUES (:name, :value);",
        'del' => "DELETE FROM `variable` WHERE `name` = :name;",
        'dump' => "SELECT * FROM `variable`;",
        'create' => "CREATE TABLE IF NOT EXISTS variable (
                        `name` varchar(128) NOT NULL DEFAULT ''
                        COMMENT 'The name of the variable.',
                        `value` longblob    NOT NULL
                        COMMENT 'The value of the variable.',
                    PRIMARY KEY (`name`));"
    );

    /**
     *  Gets the value of the variable named $name or returns the value of
     *  $default, which is NULL by default.
     * @param type $name
     * @param type $default
     * @example      *
     * $fella = Variable::get('app_dude', 'man');
     * Sets $fella to the stored value for 'app_dude', or 'man' if there's
     * no value there.
     */
    public static function get($name, $default = NULL){

        self::checkConnection();

        $prep = \bone\Settings::$db->prepare(self::$sql['get']);
        $prep->execute(array(':name' => $name));
        $rows = $prep->fetchAll();

        if($rows){
            return unserialize($rows[0]->value);
        }
         unset($prep);
        return $default;
    }

    private static function checkConnection(){
         if(is_null(\bone\Settings::$db)){
            throw new \Exception("Attempt to use \bone\Variable without database
            connection. Assign a connection at \bone\Settings::\$db");
            die;
        }
    }

    /**
     * Sets the value of a variable and pops it in to the database
     * @param type $name
     * @example path description
     * Variable::set('app_dude', 'man');      *
     * Sets the variable named 'app_dude' to t$value for 'app_dude', or 'man' if there's
     * no value there.
     */
    public static function set($name, $value){

        self::checkConnection();

       $prep = \bone\Settings::$db->prepare(self::$sql['set']);
       $svalue = serialize($value);
       $prep->execute(array(':name' => $name, ':value' => $svalue));
       unset($prep);
    }

    /**
     * Removes the variable from the system
     * @param type $name
     */
    public static function del($name){

        self::checkConnection();

        $prep = \bone\Settings::$db->prepare(self::$sql['del']);
        $prep->execute(array(':name' => $name));
        unset($prep);
    }

    /**
     * grabs an array of stored variables
     * @param array $exclude
     */
    public static function dump(array $exclude = array()){

        self::checkConnection();

         $rows = \bone\Settings::$db->query(self::$sql['dump']);
         $ret = array();

         foreach($rows as $row){
             if(!in_array($row->name, $exclude))
             $ret[$row->name] = unserialize($row->value);
         }

         return $ret;
    }

    /**
     * Installs the variable table to your database
     */
    public static function install(){
        self::checkConnection();
      \bone\Settings::$db->exec(self::$sql['create']);
    }

    /**
     * Add if statements to the SQL clause to be sure you're not over writting
     * and existing table.
     */
    public static function table(){

      self::checkConnection();

      $sql = "
        CREATE TABLE IF NOT EXISTS `variable` (
          `name` varchar(128) NOT NULL DEFAULT '' COMMENT 'The name of the variable.',
          `value` longblob NOT NULL COMMENT 'The value of the variable.',
          PRIMARY KEY (`name`)
        );";
      \bone\Settings::$db->query($sql);
    }

    /**
     * Adds all the variables requested to the data array if they are set and
     *
     */
    public static function addToData(&$data_array, $var_names = null){
        $ret = false;

        if(is_string($var_names)){
            $val = self::set($var_names, FALSE);
            if($val){
                $ret = TRUE;
                $other_array = array($var_names, $val);
            }
        }else{

            $all = self::dump();
            if(is_array($var_names)){
                foreach($var_names as $name => $value){
                    if(!in_array($name, $all)){
                        unset($all[$name]);
                    }
                }
            }else{
                $other_array = $all;
            }
        }

        array_merge($data_array, self::dump());
    }

}


text:
require 'ki_middleman'

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus

  # Run specs in random order to surface order dependencies. If you find an
  # order dependency and want to debug it, you can fix the order by providing
  # the seed, which is printed after each run.
  #     --seed 1234
  config.order = 'random'

  def capture_io
    require 'stringio'

    captured_stdout, captured_stderr = StringIO.new, StringIO.new

    orig_stdout, orig_stderr = $stdout, $stderr
    $stdout, $stderr         = captured_stdout, captured_stderr

    begin
      yield
    ensure
      $stdout = orig_stdout
      $stderr = orig_stderr
    end

    return captured_stdout.string, captured_stderr.string
  end
end

if ENV['COVERAGE']
  require 'simplecov'
  SimpleCov.start
end


text:
/**
 *  Class: Header
 *  Author: Niu Xiaoyu
 *  Date: 16/1/26
 *  Description:
 */
import React from 'react-native';
const {StyleSheet, Text, View, Component, TouchableOpacity, Image } = React;
const category = require('../../../assets/icons/category.png');
const myPortrait = require('../../../assets/portrait1.png')
var Actions = require('react-native-router-flux').Actions;
const styles = StyleSheet.create({
  page: {
    flex: 1
  },
  container: {
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center'
  },
  portrait: {
    margin: 5,
    height: 20,
    width: 20,
    borderRadius: 10,
  },
});

export default class Header extends Component {
  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    this.state = {};
  }

  render() {
    return (
      <View style={[this.props.style, styles.container]}>
        <View style={[styles.page, {paddingTop: 15}]} >
          <TouchableOpacity onPress={this.props.handleConfigMenu}>
            <Image style={styles.portrait} source={myPortrait} />
          </TouchableOpacity>
        </View>
        <View style={[styles.page, {paddingTop: 15, alignItems: 'center', justifyContent: 'center'}]}>
          <Text style={{fontSize: 25, color: '#000', fontWeight: 'bold'}}>乐趣</Text>
        </View>
        <View style={[styles.page, {paddingTop: 15, paddingRight: 10, alignItems: 'flex-end', justifyContent: 'flex-end'}]}>
          <TouchableOpacity onPress={Actions.category}>
            <Image source={category} />
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}


text:
package com.google.api.ads.dfp.jaxws.v201502;

import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for BillingBase.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *

 *

 * <simpleType name="BillingBase">
 *   <restriction base="{http://www.w3.org/2001/XMLSchema}string">
 *     <enumeration value="VOLUME"/>
 *     <enumeration value="REVENUE"/>
 *     <enumeration value="UNKNOWN"/>
 *   </restriction>
 * </simpleType>
 *

 *
 */
@XmlType(name = "BillingBase")
@XmlEnum
public enum BillingBase {

    /**
     *
     *                 Billing calculation (eg. proration) should be based on volume.
     *
     *
     */
    VOLUME,

    /**
     *
     *                 Billing calculation (eg. proration) should be based on revenue.
     *
     *
     */
    REVENUE,

    /**
     *
     *                 The value returned if the actual value is not exposed by the requested API version.
     *
     *
     */
    UNKNOWN;

    public String value() {
        return name();
    }

    public static BillingBase fromValue(String v) {
        return valueOf(v);
    }

}


text:
#import "S3TransferOperation.h"

@implementation S3TransferOperation

- (void)dealloc
{
    [_s3 release];
    [_putRequest release];
    [_getRequest release];
    [_requestMetadataFile release];
    [_error release];
    [_exception release];

    [super dealloc];
}

#pragma mark - Helper Methods

- (void)cleanup
{
    if(!_isPaused){
        [self removeRequestMetadataFile];
    }

}

- (void)pause
{
    self.isPaused = YES;
    if(!self.isCancelled){
        [self cancel];
    }
}

- (void)removeRequestMetadataFile
{
    if (self.requestMetadataFile == nil) {
        return;
    }
    NSError *error = nil;
    NSFileManager *fm = [NSFileManager defaultManager];

    if (![fm fileExistsAtPath:self.requestMetadataFile]) {
        AMZLogDebug(@"File %@ does not exist at path.", self.requestMetadataFile);
        return;
    }

    [fm removeItemAtPath:self.requestMetadataFile error:&error];
    if (error != nil) {
        AMZLogDebug(@"Error when removing file from S3TransferRequest: %@", error);
    }
}

@end


text:
import React from 'react'

import Content from './Content'
import ContentVariations from './ContentVariations'
import Types from './Types'
import Variations from './Variations'

const ListExamples = () => (
  <div>
    <Types />
    <Content />
    <Variations />
    <ContentVariations />
  </div>
)

export default ListExamples


text:
#ifndef STATEMENT_H
#define STATEMENT_H
#include "Node.h"
#include <string>

SWALLOW_NS_BEGIN

class SWALLOW_EXPORT Statement : public Node
{
public:
    Statement(NodeType nodeType);
private:
};
typedef std::shared_ptr<Statement> StatementPtr;

SWALLOW_NS_END

#endif//STATEMENT_H


text:
namespace SPControls.MarkdownTextView.Droid
{
    public static class MarkdownTextView
    {
        public static void Init() { }
    }
}