text:
const gulp = require('gulp');
let config;
let parentDir;

module.exports = gulpConfig => {
  config = gulpConfig;
  parentDir = config.parentDir;

  return copy;
};

function copyFiles() {
  return gulp
    .src([
      `${parentDir}/build.js`,
      `${parentDir}/LICENSE`,
      `${parentDir}/package.json`,
      `${parentDir}/.npmignore`,
      `${parentDir}/README.md`,
      `${parentDir}/test.js`
    ])
    .pipe(gulp.dest(`${parentDir}/dist`));
}

function copyPolyfill() {
  return gulp
    .src([`${parentDir}/polyfill/*.js`])
    .pipe(gulp.dest(`${parentDir}/dist/polyfill`));
}

function copyTransform() {
  return gulp
    .src([`${parentDir}/utils/transform/*.js`])
    .pipe(gulp.dest(`${parentDir}/dist/transform`));
}

function copy(done) {
  return gulp.parallel(copyFiles, copyPolyfill, copyTransform)(done);
}


text:
package cgroup

import (
	"bufio"
	"os"
	"path/filepath"
	"strings"

	"github.com/lxc/lxd/lxd/db/cluster"
	"github.com/lxc/lxd/lxd/db/warningtype"
	"github.com/lxc/lxd/shared"
	"github.com/lxc/lxd/shared/logger"
)

var cgControllers = map[string]Backend{}
var cgNamespace bool

// Layout determines the cgroup layout on this system.
type Layout int

const (
	// CgroupsDisabled indicates that cgroups are not supported.
	CgroupsDisabled Layout = iota
	// CgroupsUnified indicates that this is a pure cgroup2 layout.
	CgroupsUnified
	// CgroupsHybrid indicates that this is a mixed cgroup1 and cgroup2 layout.
	CgroupsHybrid
	// CgroupsLegacy indicates that this is a pure cgroup1 layout.
	CgroupsLegacy
)

var cgLayout Layout

// Info contains system cgroup information.
type Info struct {
	// Layout is one of CgroupsDisabled, CgroupsUnified, CgroupsHybrid, CgroupsLegacy
	Layout Layout

	// Namespacing indicates support for the cgroup namespace
	Namespacing bool
}

// GetInfo returns basic system cgroup information.
func GetInfo() Info {
	info := Info{}
	info.Namespacing = cgNamespace
	info.Layout = cgLayout

	return info
}

// Mode returns the cgroup layout name.
func (info *Info) Mode() string {
	switch info.Layout {
	case CgroupsDisabled:
		return "disabled"
	case CgroupsUnified:
		return "cgroup2"
	case CgroupsHybrid:
		return "hybrid"
	case CgroupsLegacy:
		return "legacy"
	}

	return "unknown"
}

// Resource is a generic type used to abstract resource control features
// support for the legacy and unified hierarchy.
type Resource int

const (
	// Blkio resource control.
	Blkio Resource = iota

	// BlkioWeight resource control.
	BlkioWeight

	// CPU resource control.
	CPU

	// CPUAcct resource control.
	CPUAcct

	// CPUSet resource control.
	CPUSet

	// Devices resource control.
	Devices

	// Freezer resource control.
	Freezer

	// Hugetlb resource control.
	Hugetlb

	// Memory resource control.
	Memory

	// MemoryMaxUsage resource control.
	MemoryMaxUsage

	// MemorySwap resource control.
	MemorySwap

	// MemorySwapMaxUsage resource control.
	MemorySwapMaxUsage

	// MemorySwapUsage resource control.
	MemorySwapUsage

	// MemorySwappiness resource control.
	MemorySwappiness

	// NetPrio resource control.
	NetPrio

	// Pids resource control.
	Pids
)

// SupportsVersion indicates whether or not a given cgroup resource is
// controllable and in which type of cgroup filesystem.
func (info *Info) SupportsVersion(resource Resource) (Backend, bool) {
	switch resource {
	case Blkio:
		val, ok := cgControllers["blkio"]
		if ok {
			return val, ok
		}

		val, ok = cgControllers["io"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	case BlkioWeight:
		val, ok := cgControllers["blkio.weight"]
		if ok {
			return val, ok
		}

		val, ok = cgControllers["io"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	case CPU:
		val, ok := cgControllers["cpu"]
		return val, ok
	case CPUAcct:
		val, ok := cgControllers["cpuacct"]
		if ok {
			return val, ok
		}

		val, ok = cgControllers["cpu"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	case CPUSet:
		val, ok := cgControllers["cpuset"]
		return val, ok
	case Devices:
		val, ok := cgControllers["devices"]
		return val, ok
	case Freezer:
		val, ok := cgControllers["freezer"]
		return val, ok
	case Hugetlb:
		val, ok := cgControllers["hugetlb"]
		return val, ok
	case Memory:
		val, ok := cgControllers["memory"]
		return val, ok
	case MemoryMaxUsage:
		val, ok := cgControllers["memory.max_usage_in_bytes"]
		return val, ok
	case MemorySwap:
		val, ok := cgControllers["memory.memsw.limit_in_bytes"]
		if ok {
			return val, ok
		}

		val, ok = cgControllers["memory.swap.max"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	case MemorySwapMaxUsage:
		val, ok := cgControllers["memory.memsw.max_usage_in_bytes"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	case MemorySwapUsage:
		val, ok := cgControllers["memory.memsw.usage_in_bytes"]
		if ok {
			return val, ok
		}

		val, ok = cgControllers["memory.swap.current"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	case MemorySwappiness:
		val, ok := cgControllers["memory.swappiness"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	case NetPrio:
		val, ok := cgControllers["net_prio"]
		return val, ok
	case Pids:
		val, ok := cgControllers["pids"]
		if ok {
			return val, ok
		}

		return Unavailable, false
	}

	return Unavailable, false
}

// Supports indicates whether or not a given resource is controllable.
func (info *Info) Supports(resource Resource, cgroup *CGroup) bool {
	val, ok := info.SupportsVersion(resource)
	if val == V2 && cgroup != nil && !cgroup.UnifiedCapable {
		ok = false
	}

	return ok
}

// Warnings returns a list of CGroup warnings.
func (info *Info) Warnings() []cluster.Warning {
	warnings := []cluster.Warning{}

	if !info.Supports(Blkio, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupBlkio,
			LastMessage: "disk I/O limits will be ignored",
		})
	}

	if !info.Supports(BlkioWeight, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupBlkioWeight,
			LastMessage: "disk priority will be ignored",
		})
	}

	if !info.Supports(CPU, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupCPUController,
			LastMessage: "CPU time limits will be ignored",
		})
	}

	if !info.Supports(CPUAcct, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupCPUacctController,
			LastMessage: "CPU accounting will not be available",
		})
	}

	if !info.Supports(CPUSet, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupCPUController,
			LastMessage: "CPU pinning will be ignored",
		})
	}

	if !info.Supports(Devices, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupDevicesController,
			LastMessage: "device access control won't work",
		})
	}

	if !info.Supports(Freezer, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupFreezerController,
			LastMessage: "pausing/resuming containers won't work",
		})
	}

	if !info.Supports(Hugetlb, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupHugetlbController,
			LastMessage: "hugepage limits will be ignored",
		})
	}

	if !info.Supports(Memory, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupMemoryController,
			LastMessage: "memory limits will be ignored",
		})
	}

	if !info.Supports(NetPrio, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupNetworkPriorityController,
			LastMessage: "network priority will be ignored",
		})
	}

	if !info.Supports(Pids, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupPidsController,
			LastMessage: "process limits will be ignored",
		})
	}

	if !info.Supports(MemorySwap, nil) {
		warnings = append(warnings, cluster.Warning{
			TypeCode:    warningtype.MissingCGroupMemorySwapAccounting,
			LastMessage: "swap limits will be ignored",
		})
	}

	return warnings
}

// Init initializes cgroups.
func Init() {
	_, err := os.Stat("/proc/self/ns/cgroup")
	if err == nil {
		cgNamespace = true
	}

	// Go through the list of resource controllers for LXD.
	selfCg, err := os.Open("/proc/self/cgroup")
	if err != nil {
		if os.IsNotExist(err) {
			logger.Warnf("System doesn't appear to support CGroups")
		} else {
			logger.Errorf("Unable to load list of cgroups: %v", err)
		}

		cgLayout = CgroupsDisabled
		return
	}

	defer func() { _ = selfCg.Close() }()

	hasV1 := false
	hasV2 := false
	hasV2Root := false

	// Go through the file line by line.
	scanSelfCg := bufio.NewScanner(selfCg)
	for scanSelfCg.Scan() {
		line := strings.TrimSpace(scanSelfCg.Text())
		fields := strings.SplitN(line, ":", 3)

		// Deal with the V1 controllers.
		if fields[1] != "" {
			controllers := strings.Split(fields[1], ",")
			for _, controller := range controllers {
				cgControllers[controller] = V1
			}

			hasV1 = true
			continue
		}

		// Parse V2 controllers.
		path := fields[2]
		hybridPath := filepath.Join(cgPath, "unified", path, "cgroup.controllers")
		dedicatedPath := ""

		controllers, err := os.Open(hybridPath)
		if err != nil {
			if !os.IsNotExist(err) {
				logger.Errorf("Unable to load cgroup.controllers")
				return
			}

			dedicatedPath = filepath.Join(cgPath, path, "cgroup.controllers")
			controllers, err = os.Open(dedicatedPath)
			if err != nil && !os.IsNotExist(err) {
				logger.Errorf("Unable to load cgroup.controllers")
				return
			}
		}

		if err == nil {
			unifiedControllers := map[string]Backend{}

			// Record the fact that V2 is present at all.
			unifiedControllers["unified"] = V2

			scanControllers := bufio.NewScanner(controllers)
			for scanControllers.Scan() {
				line := strings.TrimSpace(scanControllers.Text())
				for _, entry := range strings.Split(line, " ") {
					unifiedControllers[entry] = V2
				}
			}
			hasV2 = true

			if dedicatedPath != "" {
				cgControllers = unifiedControllers
				hasV2Root = true
				break
			} else {
				for k, v := range unifiedControllers {
					cgControllers[k] = v
				}
			}
		}

		_ = controllers.Close()
	}

	// Discard weird setups that apply CGroupV1 trees on top of a CGroupV2 root.
	if hasV2Root && hasV1 {
		logger.Warn("Unsupported CGroup setup detected, V1 controllers on top of V2 root")
		hasV1 = false
	}

	// Check for additional legacy cgroup features
	val, ok := cgControllers["blkio"]
	if ok && val == V1 && shared.PathExists("/sys/fs/cgroup/blkio/blkio.weight") {
		cgControllers["blkio.weight"] = V1
	} else {
		val, ok := cgControllers["blkio"]
		if ok && val == V1 && shared.PathExists("/sys/fs/cgroup/blkio/blkio.bfq.weight") {
			cgControllers["blkio.weight"] = V1
		}
	}

	val, ok = cgControllers["memory"]
	if ok && val == V1 {
		if shared.PathExists("/sys/fs/cgroup/memory/memory.max_usage_in_bytes") {
			cgControllers["memory.max_usage_in_bytes"] = V1
		}

		if shared.PathExists("/sys/fs/cgroup/memory/memory.swappiness") {
			cgControllers["memory.swappiness"] = V1
		}

		if shared.PathExists("/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes") {
			cgControllers["memory.memsw.limit_in_bytes"] = V1
		}

		if shared.PathExists("/sys/fs/cgroup/memory/memory.memsw.usage_in_bytes") {
			cgControllers["memory.memsw.usage_in_bytes"] = V1
		}

		if shared.PathExists("/sys/fs/cgroup/memory/memory.memsw.max_usage_in_bytes") {
			cgControllers["memory.memsw.max_usage_in_bytes"] = V1
		}
	}

	val, ok = cgControllers["memory"]
	if ok && val == V2 {
		if shared.PathExists("/sys/fs/cgroup/init.scope/memory.swap.max") {
			cgControllers["memory.swap.max"] = V2
		}

		if shared.PathExists("/sys/fs/cgroup/init.scope/memory.swap.current") {
			cgControllers["memory.swap.current"] = V2
		}
	}

	if hasV1 && hasV2 {
		cgLayout = CgroupsHybrid
	} else if hasV1 {
		cgLayout = CgroupsLegacy
	} else if hasV2 {
		cgLayout = CgroupsUnified
	}

	// "io" and "blkio" controllers are the same thing.
	val, ok = cgControllers["io"]
	if ok {
		cgControllers["blkio"] = val
	}

	if cgLayout == CgroupsUnified {
		// With Cgroup2 devices is built-in (through eBPF).
		cgControllers["devices"] = V2

		// With Cgroup2 freezer is built-in.
		cgControllers["freezer"] = V2
	}
}

redpajama_set_name: RedPajamaGithub


text:
title: insall
date: 2018-09-28
---
# insall
    pip install --editable .
    -e, --editable <path/url>   Install a project in editable mode (i.e. setuptools "develop mode")
                              from a local project path or a VCS url.

# run
example: flaskr.py

    from flask import Flask
    app = Flask(__name__)

    @app.cli.command('ahui')
    def initdb_command():
        print('Initialized the database.')

    @app.route('/')
    def hello_world():
        return 'Hello, World!'

    if __name__ == '__main__':
        # 自带的线程太简陋了
        app.run(host='0.0.0.0',port=5000,debug=True, threaded = True)

run:

    $ FLASK_APP=flaskr flask ahui;  # ahui 是自定义的cli
    $ FLASK_APP=flaskr.py flask ahui;  # ahui 是自定义的cli
    $ FLASK_APP=hello python -m flask run; # run 是自带的cli
    $ FLASK_APP=flaskr flask initdb; # http server
    $ FLASK_APP=flaskr flask initdb --host='0.0.0.0' --port=8001; # exteExternally Visible Server
    $ FLASK_APP=flaskr flask initdb --host=0 --port=8001; # exteExternally Visible Server
    new file:   flaskr/flaskr.db

使用示例有几种方法:
1. FLASK_APP='flaskr'
    1. 先在当前目录下查找 import flaskr 包: \
    `app = flaskr.py/app`
    2. 如果没有找到就会找安装包\
    `python freeze|grep -i flaskr`
2. FLASK_APP='flaskr.factory:create_app()' 与第一种不同,获取到的:app变量是发生http请求时,才生成的\
    `app = __import__('flaskr.factory').create_app()`

## current app
 explicit way using the app_context() method: current_app 会根据ctx 变化而变化

    from flask import Flask, current_app

    app = Flask(__name__)
    with app.app_context():
        # within this block, current_app points to app.
        print current_app.name

## global

    from flask import g
    app = Flask(__name__)
    with app.app_context():
        g.a=1

## debug
其它常量:

    FLASK_DEBUG=1

    app.debug = True
    app.run()

    app.run(debug=True)

This does the following things:

    it activates the *automatic reloader*
    it activates the debugger
    it enables the debug mode on the Flask application.

更多的话,见实际的项目

### logger
with gunicorn

    # gunicorn_error_logger = logging.getLogger('gunicorn.error')
    # app.logger.handlers.extend(gunicorn_error_logger.handlers)
    app.logger.setLevel(logging.DEBUG)

    app.logger.debug('A value for debugging')
    app.logger.warning('A warning occurred (%d apples)', 42)
    app.logger.error('An error occurred')


text:
wcpan.telegram
==============

Telegram Bot API with Tornado.

Implemented Functions
---------------------

- Getting Updates
    - [x] Update
    - [x] getUpdates
    - [x] setWebhook
    - [x] deleteWebhook
    - [x] getWebhookInfo
    - [x] WebhookInfo
- Available Types
    - [x] User
    - [x] Chat
    - [x] Message
    - [x] MessageEntity
    - [x] PhotoSize
    - [x] Audio
    - [x] Document
    - [x] Video
    - [x] Voice
    - [x] VideoNote
    - [x] Contact
    - [x] Location
    - [x] Venue
    - [x] UserProfilePhotos
    - [x] ReplyKeyboardMarkup
    - [x] KeyboardButton
    - [x] ReplyKeyboardRemove
    - [x] InlineKeyboardMarkup
    - [x] InlineKeyboardButton
    - [x] CallbackQuery
    - [x] ForceReply
    - [ ] ChatPhoto
    - [x] ChatMember
    - [x] ResponseParameters
    - [x] InputFile
- Available Methods
    - [x] getMe
    - [x] sendMessage
    - [x] forwardMessage
    - [x] sendPhoto
    - [x] sendAudio
    - [x] sendDocument
    - [x] sendVideo
    - [x] sendVoice
    - [x] sendVoiceNote
    - [x] sendLocation
    - [x] sendVenue
    - [x] sendContact
    - [x] sendChatAction
    - [x] getUserProfilePhotos
    - [x] getFile
    - [x] kickChatMember
    - [x] unbanChatMember
    - [ ] restrictChatMember
    - [ ] promoteChatMember
    - [ ] exportChatInviteLink
    - [ ] setChatPhoto
    - [ ] deleteChatPhoto
    - [ ] setChatTitle
    - [ ] setChatDescription
    - [ ] pinChatMessage
    - [ ] unpinChatMessage
    - [x] leaveChat
    - [x] getChat
    - [x] getChatAdministrators
    - [x] getChatMembersCount
    - [x] getChatMember
    - [x] answerCallbackQuery
- Updating Messages
    - [x] editMessageText
    - [x] editMessageCaption
    - [x] editMessageReplyMarkup
    - [x] deleteMessage
- Stickers
    - [x] Sticker
    - [x] StickerSet
    - [x] MaskPosition
    - [x] sendSticker
    - [x] getStickerSet
    - [x] uploadStickerSet
    - [x] createNewStickerSet
    - [x] addStickerToSet
    - [x] setStickerPositionInSet
    - [x] deleteStickerFromSet
- Inline Mode
    - [x] InlineQuery
    - [x] answerInlineQuery
    - [x] InlineQueryResult
    - [x] InlineQueryResultArticle
    - [x] InlineQueryResultPhoto
    - [x] InlineQueryResultGif
    - [x] InlineQueryResultMpeg4Gif
    - [x] InlineQueryResultVideo
    - [x] InlineQueryResultAudio
    - [x] InlineQueryResultVoice
    - [x] InlineQueryResultDocument
    - [x] InlineQueryResultLocation
    - [x] InlineQueryResultVenue
    - [x] InlineQueryResultContact
    - [x] InlineQueryResultGame
    - [x] InlineQueryResultCachedPhoto
    - [x] InlineQueryResultCachedGif
    - [x] InlineQueryResultCachedMpeg4Gif
    - [x] InlineQueryResultCachedSticker
    - [x] InlineQueryResultCachedDocument
    - [x] InlineQueryResultCachedVideo
    - [x] InlineQueryResultCachedVoice
    - [x] InlineQueryResultCachedAudio
    - [x] InputMessageContent
    - [x] InputTextMessageContent
    - [x] InputLocationMessageContent
    - [x] InputVenueMessageContent
    - [x] InputContactMessageContent
    - [x] ChosenInlineResult
- Payments
    - [ ] sendInvoice
    - [ ] answerShippingQuery
    - [ ] answerPreCheckoutQuery
    - [ ] LabeledPrice
    - [ ] Invoice
    - [ ] ShippingAddress
    - [ ] OrderInfo
    - [ ] ShippingOption
    - [ ] SuccessfulPayment
    - [ ] ShippingQuery
    - [ ] PreCheckoutQuery
- Games
    - [x] sendGame
    - [x] Game
    - [x] Animation
    - [x] CallbackGame
    - [x] setGameScore
    - [x] getGameHighScores
    - [x] GameHighScore

High Level API Example
----------------------

``BotAgent`` is a high level undead, you can demand it to send requests:

.. code:: python

    from tornado import gen, ioloop
    from wcpan.telegram import api, types

    async def main():
        API_TOKEN = 'your_token'
        lich = api.BotAgent(API_TOKEN)
        talk_to = 42

        # getMe
        user = await lich.get_me()
        print(user)

        # getUpdates
        updates = await lich.get_updates()
        print(updates)

        # sendMessage
        message = await lich.send_message(talk_to, 'hello')
        print(message)

        # sendPhoto
        photo = types.InputFile('path_to_your_phoho.png')
        message = await lich.send_photo(talk_to, photo)
        print(message)

        # sendAudio
        audio = types.InputFile('path_to_your_audio.ogg')
        message = await lich.send_audio(talk_to, audio)
        print(message)

        # sendVideo
        video = types.InputFile('path_to_your_video.mp4')
        message = await lich.send_video(talk_to, video)
        print(message)

        # sendDocument
        document = types.InputFile('path_to_your_file.zip')
        message = await lich.send_document(talk_to, document)
        print(message)

    main_loop = ioloop.IOLoop.instance()
    main_loop.run_sync(main)

And let it handles updates:

.. code:: python

    from tornado import gen, ioloop
    from wcpan.telegram import api

    class KelThuzad(api.BotAgent):

        def __init__(self, api_token):
            super(KelThuzad, self).__init__(api_token)

        async def on_text(self, message):
            id_ = message.message_id
            chat = message.chat
            text = message.text
            # echo same text
            await self.send_message(chat.id_, text, reply_to_message_id=id_)

        async def on_video(self, message):
            chat = message.chat
            video = message.video
            # echo video without upload again
            await self.send_video(chat.id_, video.file_id, reply_to_message_id=id_)

    async def forever():
        API_TOKEN = 'your_token'
        lich = api.KelThuzad(API_TOKEN)
        await lich.poll()

    main_loop = ioloop.IOLoop.instance()
    main_loop.run_sync(forever)

Or handles updates by webhook:

.. code:: python

    from tornado import gen, ioloop, web
    from wcpan.telegram import api

    class HookHandler(api.BotHookHandler):

        async def on_text(self, message):
            lich = self.application.settings['lich']
            id_ = message.message_id
            chat = message.chat
            text = message.text
            # echo same text
            await lich.send_message(chat.id_, text, reply_to_message_id=id_)

    async def create_lich():
        API_TOKEN = 'your_token'
        lich = api.BotAgent(API_TOKEN)
        await lich.listen('https://your.host/hook')
        return lich

    main_loop = ioloop.IOLoop.instance()

    lich = main_loop.run_sync(create_lich)
    application = web.Application([
        (r"/hook", HookHandler),
    ], lich=lich)
    # please configure your own SSL proxy
    application.listen(8000)

    main_loop.start()

Low Level API Example
---------------------

``BotClient`` is also there, which provides simple and direct API mapping:

.. code:: python

    from tornado import gen, ioloop
    from wcpan.telegram import api, types

    async def main():
        API_TOKEN = 'your_token'
        ghoul = api.BotClient(API_TOKEN)
        talk_to = 42

        # getMe
        user = await ghoul.get_me()
        print(user)

        # getUpdates
        offset = 0
        updates = []
        while True:
            us = await ghoul.get_updates(offset)
            updates.extend(us)
            if not us:
                break
            offset = us[-1].update_id + 1
        print(updates)

        # sendMessage
        message = await ghoul.send_message(talk_to, 'hello')
        print(message)

        # sendDocument
        document = types.InputFile('path_to_your_file.zip')
        message = await lich.send_document(talk_to, document)
        print(message)

    main_loop = ioloop.IOLoop.instance()
    main_loop.run_sync(main)


text:
import { registerExamples } from '../register';
import { UISchemaElement } from '@jsonforms/core';

export const schema = {
  type: 'object',
  properties: {
    propText0: {type: 'string'},
    propText1: {type: 'string'},
    propText2: {type: 'string'},
    propText3: {type: 'string'},
    propText4: {type: 'string'},
    propText5: {type: 'string'},
    propText6: {type: 'string'},
    propText7: {type: 'string'},
    propText8: {type: 'string'},
    propText9: {type: 'string'},
    propNumber0: {type: 'number'},
    propNumber1: {type: 'number'},
    propNumber2: {type: 'number'},
    propNumber3: {type: 'number'},
    propNumber4: {type: 'number'},
    propNumber5: {type: 'number'},
    propNumber6: {type: 'number'},
    propNumber7: {type: 'number'},
    propNumber8: {type: 'number'},
    propNumber9: {type: 'number'},
  }
};

export const uischema: UISchemaElement = undefined;

export const data = {};

registerExamples([
  {
    name: '1645',
    label: 'Issue 1645',
    data,
    schema,
    uischema
  }
]);


text:
'use strict';

describe('Directive: rbSoundcloudPlaylist', function () {

  // load the directive's module
  beforeEach(module('robitApp'));

  var element,
    scope;

  beforeEach(inject(function ($rootScope) {
    scope = $rootScope.$new();
  }));

  it('should make hidden element visible', inject(function ($compile) {
    element = angular.element('<rb-soundcloud-playlist></rb-soundcloud-playlist>');
    element = $compile(element)(scope);
    expect(element.text()).toBe('this is the rbSoundcloudPlaylist directive');
  }));
});


text:
/*!
 * Copyright (c) 2015 by Contributors
 * \file cudnn_activation-inl.h
 * \brief
 * \author Bing Xu
*/

#ifndef MXNET_OPERATOR_NN_CUDNN_CUDNN_ACTIVATION_INL_H_
#define MXNET_OPERATOR_NN_CUDNN_CUDNN_ACTIVATION_INL_H_
#include <algorithm>
#include <vector>
#include "../activation-inl.h"
#include "../../../common/cuda/utils.h"

namespace mxnet {
namespace op {
template<typename DType>
class CuDNNActivationOp {
  STATIC_ASSERT_CUDNN_VERSION_GE(5000);

 public:
  CuDNNActivationOp() {
    dtype_ = mshadow::DataType<DType>::kCudnnFlag;
    nan_prop_ = CUDNN_NOT_PROPAGATE_NAN;
    CUDNN_CALL(cudnnCreateActivationDescriptor(&desc_));
    CUDNN_CALL(cudnnCreateTensorDescriptor(&shape_desc_));
  }

  void Init(const ActivationParam &param) {
    param_ = param;
    switch (param_.act_type) {
      case activation::kReLU:
        mode_ = CUDNN_ACTIVATION_RELU;
        break;
      case activation::kSigmoid:
        mode_ = CUDNN_ACTIVATION_SIGMOID;
        break;
      case activation::kTanh:
        mode_ = CUDNN_ACTIVATION_TANH;
        break;
      default:
        LOG(FATAL) << "Not implmented";
        break;
    }
    CUDNN_CALL(cudnnSetActivationDescriptor(desc_, mode_, nan_prop_, relu_ceil_));
  }

  ~CuDNNActivationOp() {
    CUDNN_CALL(cudnnDestroyTensorDescriptor(shape_desc_));
    CUDNN_CALL(cudnnDestroyActivationDescriptor(desc_));
  }

  void Forward(const OpContext &ctx, const TBlob &in_data,
      const OpReqType &req, const TBlob &out_data) {
    using namespace mshadow;
    using namespace mshadow::expr;
    Stream<gpu> *s = ctx.get_stream<gpu>();
    Tensor<gpu, 4, DType> data;
    Tensor<gpu, 4, DType> out;
    if (in_data.ndim() == 2) {
      Shape<4> dshape = Shape4(in_data.shape_[0],
                               in_data.shape_[1], 1, 1);
      data = in_data.get_with_shape<gpu, 4, DType>(dshape, s);
      out = out_data.get_with_shape<gpu, 4, DType>(dshape, s);
    } else {
      Shape<4> dshape;
      index_t size_left = in_data.Size();
      for (int i = 0; i < 3; ++i) {
        if (i < in_data.ndim()) {
          dshape[i] = in_data.shape_[i];
        } else {
          dshape[i] = 1;
        }
        size_left /= dshape[i];
      }
      dshape[3] = size_left;
      data = in_data.get_with_shape<gpu, 4, DType>(dshape, s);
      out = out_data.get_with_shape<gpu, 4, DType>(dshape, s);
    }
    typename DataType<DType>::ScaleType alpha = 1.0f;
    typename DataType<DType>::ScaleType beta = 0.0f;
    CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle);
    CUDNN_CALL(cudnnSetTensor4dDescriptor(shape_desc_,
                                          CUDNN_TENSOR_NCHW,
                                          dtype_,
                                          data.shape_[0],
                                          data.shape_[1],
                                          data.shape_[2],
                                          data.shape_[3]));
    CUDNN_CALL(cudnnActivationForward(s->dnn_handle_,
                                     desc_,
                                     &alpha,
                                     shape_desc_,
                                     data.dptr_,
                                     &beta,
                                     shape_desc_,
                                     out.dptr_));
  }

  // backward computation for cudnn activation operator. Note that for relu
  // it's okay to pass "out_data" as "in_data", since it doesn't make any
  // difference in terms of computing the gradient of relu.
  void Backward(const OpContext &ctx, const TBlob &out_grad,
      const TBlob &in_data, const TBlob &out_data,
      const OpReqType &req, const TBlob &in_grad) {
    using namespace mshadow;
    using namespace mshadow::expr;
    typename DataType<DType>::ScaleType alpha = 1.0f;
    typename DataType<DType>::ScaleType beta = 0.0f;
    Stream<gpu> *s = ctx.get_stream<gpu>();
    Tensor<gpu, 4, DType> grad;
    Tensor<gpu, 4, DType> data;
    Tensor<gpu, 4, DType> output_data;
    Tensor<gpu, 4, DType> input_grad;
    if (in_grad.ndim() == 2) {
      Shape<4> dshape = Shape4(in_grad.shape_[0],
                               in_grad.shape_[1], 1, 1);
      data = in_data.get_with_shape<gpu, 4, DType>(dshape, s);
      grad = out_grad.get_with_shape<gpu, 4, DType>(dshape, s);
      output_data = out_data.get_with_shape<gpu, 4, DType>(dshape, s);
      input_grad = in_grad.get_with_shape<gpu, 4, DType>(dshape, s);
    } else {
      Shape<4> dshape;
      index_t size_left = in_grad.Size();
      for (int i = 0; i < 3; ++i) {
        if (i < in_grad.ndim()) {
          dshape[i] = in_grad.shape_[i];
        } else {
          dshape[i] = 1;
        }
        size_left /= dshape[i];
      }
      dshape[3] = size_left;
      data = in_data.get_with_shape<gpu, 4, DType>(dshape, s);
      output_data = out_data.get_with_shape<gpu, 4, DType>(dshape, s);
      grad = out_grad.get_with_shape<gpu, 4, DType>(dshape, s);
      input_grad = in_grad.get_with_shape<gpu, 4, DType>(dshape, s);
    }
    CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle);
    CUDNN_CALL(cudnnSetTensor4dDescriptor(shape_desc_,
                                          CUDNN_TENSOR_NCHW,
                                          dtype_,
                                          data.shape_[0],
                                          data.shape_[1],
                                          data.shape_[2],
                                          data.shape_[3]));
    CUDNN_CALL(cudnnActivationBackward(s->dnn_handle_,
                                       desc_,
                                       &alpha,
                                       shape_desc_,
                                       output_data.dptr_,
                                       shape_desc_,
                                       grad.dptr_,
                                       shape_desc_,
                                       data.dptr_,
                                       &beta,
                                       shape_desc_,
                                       input_grad.dptr_));
  }

 private:
  cudnnDataType_t dtype_;
  cudnnActivationMode_t mode_;
  cudnnTensorDescriptor_t shape_desc_;
  ActivationParam param_;
  cudnnActivationDescriptor_t desc_;
  cudnnNanPropagation_t nan_prop_;
  double relu_ceil_;
};  // class CuDNNActivationOp
}  // namespace op
}  // namespace mxnet
#endif  // MXNET_OPERATOR_NN_CUDNN_CUDNN_ACTIVATION_INL_H_


text:
	#error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"		// main symbols

/////////////////////////////////////////////////////////////////////////////
// CAnyChatInputVideoApp:
// See AnyChatInputVideo.cpp for the implementation of this class
//

class CAnyChatInputVideoApp : public CWinApp
{
public:
	CAnyChatInputVideoApp();

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAnyChatInputVideoApp)
	public:
	virtual BOOL InitInstance();
	//}}AFX_VIRTUAL

// Implementation

	//{{AFX_MSG(CAnyChatInputVideoApp)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_ANYCHATINPUTVIDEO_H__1D2E8949_8456_4F49_9D6B_B94924D9DC74__INCLUDED_)


text:
<?php

namespace Octante\DockerComposeBundle\Model;

use Octante\DockerComposeBundle\Traits\DockerComposeList;

class DockerComposeSecurityOption
{
    use DockerComposeList;

    /**
     * @var array
     */
    private $securityOption;

    /**
     * @param $securityOption
     */
    public function addSecurityOption($securityOption)
    {
        $this->securityOption[$securityOption] = $securityOption;
    }

    /**
     * Remove security option from list.
     *
     * @param $securityOption
     */
    public function removeSecurityOption($securityOption)
    {
        unset($this->securityOption[$securityOption]);
    }

    /**
     * @return array
     */
    public function getSecurityOptions()
    {
        return $this->securityOption;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->getFormattedList(
            'security_opt',
            $this->securityOption
        );
    }
}


text:
package com.scwang.refreshlayout.activity.style;

import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;

import com.scwang.refreshlayout.R;
import com.scwang.refreshlayout.adapter.BaseRecyclerAdapter;
import com.scwang.refreshlayout.adapter.SmartViewHolder;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.Arrays;

import static android.R.layout.simple_list_item_2;
import static android.support.v7.widget.DividerItemDecoration.VERTICAL;

public class StoreHouseStyleActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private enum Item {
        橙色主题("更改为橙色主题颜色"),
        红色主题("更改为红色主题颜色"),
        绿色主题("更改为绿色主题颜色"),
        蓝色主题("更改为蓝色主题颜色"),
        ;
        public String name;
        Item(String name) {
            this.name = name;
        }
    }

    private Toolbar mToolbar;
    private RefreshLayout mRefreshLayout;
    private static boolean isFirstEnter = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_style_storehouse);

        mToolbar = (Toolbar)findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRefreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        if (isFirstEnter) {
            isFirstEnter = false;
            mRefreshLayout.autoRefresh();//第一次进入触发自动刷新,演示效果
        }

        View view = findViewById(R.id.recyclerView);
        if (view instanceof RecyclerView) {
            RecyclerView recyclerView = (RecyclerView) view;
            recyclerView.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.setAdapter(new BaseRecyclerAdapter<Item>(Arrays.asList(Item.values()), simple_list_item_2,this) {
                @Override
                protected void onBindViewHolder(SmartViewHolder holder, Item model, int position) {
                    holder.text(android.R.id.text1, model.name());
                    holder.text(android.R.id.text2, model.name);
                    holder.textColorId(android.R.id.text2, R.color.colorTextAssistant);
                }
            });
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (Item.values()[position]) {
            case 蓝色主题:
                setThemeColor(R.color.colorPrimary, R.color.colorPrimaryDark);
                break;
            case 绿色主题:
                setThemeColor(android.R.color.holo_green_light, android.R.color.holo_green_dark);
                break;
            case 红色主题:
                setThemeColor(android.R.color.holo_red_light, android.R.color.holo_red_dark);
                break;
            case 橙色主题:
                setThemeColor(android.R.color.holo_orange_light, android.R.color.holo_orange_dark);
                break;
        }
        mRefreshLayout.autoRefresh();
    }

    private void setThemeColor(int colorPrimary, int colorPrimaryDark) {
        mToolbar.setBackgroundResource(colorPrimary);
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.white);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, colorPrimaryDark));
        }
    }

}


text:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _

from password_policies.conf import settings
from password_policies.models import PasswordHistory
from password_policies.models import PasswordChangeRequired

def force_password_change(modeladmin, request, queryset):
    for user in queryset.all():
        PasswordChangeRequired.objects.create(user=user)
force_password_change.short_description = _('Force password change for selected'
                                            ' users')

class PasswordHistoryAdmin(admin.ModelAdmin):
    date_hierarchy = 'created'
    exclude = ('password',)
    list_display = ('id', 'user', 'created')
    list_display_links = ('id', 'user',)
    search_fields = settings.PASSWORD_HISTORY_ADMIN_SEARCH_FIELDS
    readonly_fields = ('user', 'created')

    def has_add_permission(self, request):
        return False

class PasswordChangeRequiredAdmin(admin.ModelAdmin):
    date_hierarchy = 'created'
    list_display = ('id', 'user', 'created')
    list_display_links = ('id', 'user',)
    search_fields = settings.PASSWORD_CHANGE_REQUIRED_ADMIN_SEARCH_FIELDS
    readonly_fields = ('user', 'created')

    def get_readonly_fields(self, request, obj=None):
        """
Sets the ``user`` and the ``created`` field to read only if an instance
already exists.
"""
        if obj:
            return ['user']
        else:
            return []

admin.site.register(PasswordHistory, PasswordHistoryAdmin)
admin.site.register(PasswordChangeRequired, PasswordChangeRequiredAdmin)


text:
UCLASS()
class ETHEREAL_API ACat : public AEtherealNPCMaster
{
	GENERATED_BODY()

public:

	// Sets default values for this actor's properties
	ACat(const FObjectInitializer& ObjectInitializer);

	// BeginPlay Override
	virtual void BeginPlay() override;

	// Called every frame
	virtual void Tick(float DeltaSeconds) override;

	// Targeting Reticle Mesh.
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Default)
	USkeletalMeshComponent* Mesh;
	USkeletalMesh* SM_Mesh;

	// Kick Audio
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Effects)
	UAudioComponent* CatAudio;
	USoundCue* S_CatAudio;

	// Interact with this NPC
	UFUNCTION(BlueprintCallable, Category = Default)
	void CustomInteract();

	// Blow up the chicken, cause you kicked it like an asshole!
	UFUNCTION(BlueprintCallable, Category = Default)
	void BlowUp();

	// Determines whether or not to drop an item
	UFUNCTION(BlueprintCallable, Category = Default)
	void DropItem();

	// Movement Speed
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Anim)
	float Speed;

	// Anim
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Anim)
	bool DoRoar;
};


text:
module Pnganim.Types (
	-- * Slice
	Slice(..),
	sliceWidth, sliceHeight, emptySlice, pixelSlice, sliceNull, slice, unionSlice
	) where

import Prelude.Unicode

import Data.Monoid

-- | Slice of image
data Slice = Slice {
	sliceLeft :: Int,
	sliceRight :: Int,
	sliceTop :: Int,
	sliceBottom :: Int }
		deriving (Eq, Ord, Read, Show)

-- | Width of slice
sliceWidth :: Slice → Int
sliceWidth s = sliceRight s - sliceLeft s

-- | Height of slice
sliceHeight :: Slice → Int
sliceHeight s = sliceBottom s - sliceTop s

-- | Empty slice
emptySlice :: Slice
emptySlice = Slice 0 0 0 0

-- | Slice of one pixel
pixelSlice :: Int → Int → Slice
pixelSlice x y = slice x (succ x) y (succ y)

-- | Is slice null
sliceNull :: Slice → Bool
sliceNull s = sliceWidth s ≡ 0 ∨ sliceHeight s ≡ 0

-- | Make slice
slice :: Int → Int → Int → Int → Slice
slice l r t b = if sliceNull s then emptySlice else s where
	s = Slice (min l r) (max l r) (min t b) (max t b)

-- | Union slices
unionSlice :: Slice → Slice → Slice
unionSlice l r = slice
	((min `both` sliceLeft) l r)
	((max `both` sliceRight) l r)
	((min `both` sliceTop) l r)
	((max `both` sliceBottom) l r)
	where
		both :: (b → b → b) → (a → b) → a → a → b
		both f g x y = f (g x) (g y)

instance Monoid Slice where
	mempty = emptySlice
	mappend = unionSlice


text:
namespace BeerApp.Web.Areas.Administration.ViewModels.Beer
{
    using System.ComponentModel.DataAnnotations;
    using Data.Models;
    using Infrastructure.Mapping;

    public class AdminBeerRequestViewModel : IMapTo<Beer>
    {
        [Required]
        [MaxLength(100)]
        public string Name { get; set; }

        [Required]
        [UIHint("BeerTypeIdEditor")]
        public int BeerTypeId { get; set; }

        [Required]
        [UIHint("CountryIdEditor")]
        public int CountryId { get; set; }

        [MaxLength(1000)]
        public string Description { get; set; }

        public int? ProducedSince { get; set; }

        [Required]
        public decimal AlcoholContaining { get; set; }

        public string PhotoUrl { get; set; }

    }
}


text:
title: "Inner-product space"
collection: notes
order_item: 130
permalink: /notes/inner-product_space
date: 2016-06-01
Tags:
  - Topology
  - Functional analysis
---

Inner product space is a *normed vector space* with an additional structure called an inner product. This additional structure associates each pair of vectors in the space with a scalar quantity known as the inner product of the vectors. Inner products allow the rigorous introduction of intuitive geometrical notions such as the length of a vector or the angle between two vectors. They also provide the means of defining orthogonality between vectors (zero inner product). Inner product spaces generalize Euclidean spaces (in which the inner product is the dot product, also known as the scalar product) to vector spaces of any (possibly infinite) dimension, and are studied in functional analysis.

An inner product naturally induces an associated norm, thus an inner product space is also a normed vector space. A complete space with an inner product is called a Hilbert space. An (incomplete) space with an inner product is called a pre-Hilbert space, since its completion with respect to the norm induced by the inner product is a Hilbert space. Inner product spaces over the field of complex numbers are sometimes referred to as unitary spaces.

Formally, an inner product space is a vector space V over the field F together with an inner product, i.e., with a map ${\displaystyle \langle \cdot ,\cdot \rangle :V\times V\to F}$.

that satisfies the following three axioms for all vectors ${\displaystyle x,y,z\in V}$ and all scalars ${\displaystyle a\in F}$:
* Conjugate symmetry: ${\displaystyle \langle x,y\rangle ={\overline {\langle y,x\rangle }}}$
* Linearity in the first argument: ${\displaystyle \langle ax,y\rangle =a\langle x,y\rangle }$ and ${\displaystyle \langle x+y,z\rangle =\langle x,z\rangle +\langle y,z\rangle }$.
* Positive-definiteness: ${\displaystyle \langle x,x\rangle \geq 0}$ and ${\displaystyle \langle x,x\rangle =0\Leftrightarrow x=\mathbf {0} }$.

#### See also
[Functional analysis](/notes/functional_analysis), [Normed space](/notes/normed_space), [Hilbert space](/notes/hilbert_space)


text:
#ifndef StorageQuotaClientImpl_h
#define StorageQuotaClientImpl_h

#include "modules/quota/StorageQuotaClient.h"
#include "wtf/Forward.h"

namespace blink {

class StorageQuotaClientImpl : public NoBaseWillBeGarbageCollectedFinalized<StorageQuotaClientImpl>, public StorageQuotaClient {
    WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(StorageQuotaClientImpl);
public:
    static PassOwnPtrWillBeRawPtr<StorageQuotaClientImpl> create()
    {
        return adoptPtrWillBeNoop(new StorageQuotaClientImpl());
    }

    ~StorageQuotaClientImpl() override;

    void requestQuota(ExecutionContext*, WebStorageQuotaType, unsigned long long newQuotaInBytes, StorageQuotaCallback*, StorageErrorCallback*) override;
    ScriptPromise requestPersistentQuota(ScriptState*, unsigned long long newQuotaInBytes) override;

    DEFINE_INLINE_VIRTUAL_TRACE() { StorageQuotaClient::trace(visitor); }

private:
    StorageQuotaClientImpl();
};

} // namespace blink

#endif // StorageQuotaClientImpl_h


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>invalid src: query-trailing-space</title>
<audio src="http://f:21/b?d #"></audio>


text:
/**
 * d3.ma.js - d3 magic for visualizing data based on object oriented principles
 * @version v0.3.0
 * @author Matt Ma <matt@mattmadesign.com>
 * @link https://github.com/mattma/d3.ma.js
 * @license MIT
 */
svg {
  font: 10px sans-serif;
}

.line {
  fill: none;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.area {
  fill: lightsteelblue;
}

.dot {
  fill: white;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.circles {
  stroke: steelblue;
}

/* ================ */
/* = Axis & Label Section = */
/* ================ */
.axis path, .axis line {
  fill: none;
  shape-rendering: crispEdges;
}

/* Axis Guides */
.axis .tick line {
  stroke: lightgrey;
  opacity: 0.8;
}

/* Axis itself on x and y */
.axis path {
  stroke: rgb(51, 51, 51);
  stroke-width: 1px;
}

/* When guides show, Y-Axis 0 position guide override X-Axis itself, so hide it */
.y.axis text+g line {
  stroke-width: 0;
}

.label {
  text-anchor: middle;
  font-size: 1.4em;
  fill: black;
  font-family: arial, helvetica, sans-serif;
  text-transform: capitalize;
}

/* ================ */
/* = Hover Intent = */
/* ================ */
.dotHover circle {
  fill-opacity: 0;
  stroke-opacity: 0;

  transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
  -moz-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;
  -webkit-transition: stroke-width 250ms linear, stroke-opacity 250ms linear;

  /* This need to be set by the color of the line or area, couid set color on the dot too for animation */
  /* Based on the parents, if parents has stroke color defined, it will use that color for circle */
  stroke: inherit;
  /* fill: purple; */
}

.dotHover circle.hover {
  stroke-width: 20px;
  fill-opacity: .5 !important;
  stroke-opacity: .5 !important;
}

/* ================= */
/* = Tooltip CSS = */
/* ================= */
 .d3maTooltip-pending-removal {
  position: absolute;
  pointer-events: none;
}

.d3maTooltip {
  position: absolute;
  background-color: rgba(255,255,255,0.75);
  padding: 3px 5px;
  text-align: center;
  border: 1px solid rgba(0,0,0,.2);
  z-index: 10000;

  font-family: Arial;
  font-size: 13px;
  -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
  box-shadow: 0 5px 10px rgba(0,0,0,.2);

  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;

  pointer-events: none;

  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* ================= */
/* = General Shape = */
/* ================= */
rect {
  -moz-transition: fill-opacity .5s linear;
  -webkit-transition: fill-opacity .5s linear;
  transition: fill-opacity .5s linear;
}

rect:hover {
  fill-opacity: 1;
}


text:
package org.datavaultplatform.broker.services;

import org.datavaultplatform.common.model.Vault;
import org.datavaultplatform.common.model.VaultReview;
import org.junit.Test;

import java.util.*;

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

public class VaultsReviewServiceTest {

    private VaultsReviewService vaultsReviewService = new VaultsReviewService();

    @Test
    public void testIsVaultForReview() {
        System.out.println("Test if vault due for review");

        // todo : needs expanded to be a comprehensive list of tests

        // Review date is today and Actioned date is 9 months ago
        assertTrue(isVaultForReview(0, -9));

        // Review date is 1 month in the past and Actioned date today
        assertFalse(isVaultForReview(-1, 0));

        // Review date is 1 month in the future and Actioned date is 9 months ago
        assertTrue(isVaultForReview(+1, -9));

        // Review date is 12 months in the future and Actioned date is 9 months ago
        assertFalse(isVaultForReview(+12, -9));
    }

    @Test
    public void testDueForReviewEmail() {
        System.out.println("Test if vault due for a review email");

        // todo : needs expanded to be a comprehensive list of tests

        // Review date is today and Actioned date is 9 months ago
        assertTrue(dueForReviewEmail(0, -9, true));

        // Review date is 1 month in the past and Actioned date today
        assertFalse(dueForReviewEmail(-1, 0, true));

        // Review date is 1 month in the past and Actioned date not set yet
        assertFalse(dueForReviewEmail(-1, 0, false));

        // Review date is 2 month in the past and Actioned date 1 month ago
        assertFalse(dueForReviewEmail(-2, -1, false));

        // Review date is 1 month in the future and Actioned date is 9 months ago
        assertTrue(dueForReviewEmail(+1, -9, true));

        // Review date is 12 months in the future and Actioned date is 9 months ago
        assertFalse(dueForReviewEmail(+12, -9, true));
    }

    private boolean isVaultForReview(int reviewDateOffset, int actionedDateOffset) {
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.MONTH, reviewDateOffset);
        Date reviewDate = c.getTime();

        c.setTime(new Date());
        c.add(Calendar.MONTH, actionedDateOffset);
        Date actionedDate = c.getTime();

        VaultReview vaultReview = new VaultReview();
        vaultReview.setActionedDate(actionedDate);
        List<VaultReview> vaultReviews = Collections.singletonList(vaultReview);

        Vault vault = new Vault();
        vault.setReviewDate(reviewDate);
        vault.setVaultReviews(vaultReviews);

        return vaultsReviewService.isVaultForReview(vault);
    }

    private boolean dueForReviewEmail(int reviewDateOffset, int actionedDateOffset, boolean actioned) {
        Calendar c = Calendar.getInstance();

        c.setTime(new Date());
        c.add(Calendar.MONTH, reviewDateOffset);
        Date reviewDate = c.getTime();

        c.setTime(new Date());
        c.add(Calendar.MONTH, actionedDateOffset);
        Date actionedDate = c.getTime();

        VaultReview vaultReview = new VaultReview();
        if (actioned) {
            vaultReview.setActionedDate(actionedDate);
        }
        List<VaultReview> vaultReviews = Collections.singletonList(vaultReview);

        Vault vault = new Vault();
        vault.setReviewDate(reviewDate);
        vault.setVaultReviews(vaultReviews);

        return vaultsReviewService.dueForReviewEmail(vault);
    }

}


text:
package org.multibit.viewsystem.swing.action;

import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.List;

import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;

import org.multibit.controller.bitcoin.BitcoinController;
import org.multibit.file.FileHandler;
import org.multibit.model.bitcoin.WalletData;
import org.multibit.viewsystem.swing.MultiBitFrame;
import org.multibit.viewsystem.swing.view.panels.HelpContentsPanel;

/**
 * This {@link Action} closes the active wallet.
 */
public class CloseWalletAction extends MultiBitSubmitAction {
    private static final long serialVersionUID = 1923933460523457765L;

    private MultiBitFrame mainFrame;

    /**
     * Creates a new {@link CloseWalletAction}.
     */
    public CloseWalletAction(BitcoinController bitcoinController, ImageIcon icon, MultiBitFrame mainFrame) {
        super(bitcoinController, "closeWalletAction.text", "closeWalletAction.tooltip", "closeWalletAction.mnemonicKey", icon);
        this.mainFrame = mainFrame;
        putValue(SHORT_DESCRIPTION, HelpContentsPanel.createTooltipTextForMenuItem(controller.getLocaliser().getString("closeWalletAction.tooltip")));
    }

    /**
     * Close the active wallet.
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (abort()) {
            return;
        }

        try {
            if (mainFrame != null) {
                if (EventQueue.isDispatchThread()) {
                    mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                } else {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                        }
                    });
                }
            }

            // Close the wallet.
            WalletData perWalletModelData = this.bitcoinController.getModel().getActivePerWalletModelData();

            // Unhook it from the PeerGroup.
            super.bitcoinController.getMultiBitService().getPeerGroup().removeWallet(perWalletModelData.getWallet());

            // Save it.
            FileHandler fileHandler = new FileHandler(super.bitcoinController);
            fileHandler.savePerWalletModelData(perWalletModelData, true);

            // Work out which wallet to select after the wallet is removed.
            String activeWalletFilename = perWalletModelData.getWalletFilename();

            List<WalletData> perWalletModelDataList = this.bitcoinController.getModel().getPerWalletModelDataList();
            int numberOfOpenWalletsBefore = perWalletModelDataList.size();
            int positionInList = -1;
            for (int i = 0; i < numberOfOpenWalletsBefore; i++) {
                if (activeWalletFilename.equals(perWalletModelDataList.get(i).getWalletFilename())) {
                    positionInList = i;
                    break;
                }
            }

            // By default select the first wallet.
            int newWalletToSelect = 0;

            if (numberOfOpenWalletsBefore > 1) {
                // If removing the last, then select the new last one.
                if (positionInList == numberOfOpenWalletsBefore - 1) {
                    newWalletToSelect = numberOfOpenWalletsBefore - 2;
                } else {
                    // Select the same position in the list
                    newWalletToSelect = positionInList;
                }
            } else {
                // One wallet open before. None after.
            }

            // Remove it from the model.
            this.bitcoinController.getModel().remove(perWalletModelData);

            // Set the new Wallet to be the active wallet.
            if (!this.bitcoinController.getModel().getPerWalletModelDataList().isEmpty()) {
                WalletData firstPerWalletModelData = this.bitcoinController.getModel().getPerWalletModelDataList().get(newWalletToSelect);
                this.bitcoinController.getModel().setActiveWalletByFilename(firstPerWalletModelData.getWalletFilename());
            } else {
                // No wallets are selected.
                // Clear all the views.
            }
        } finally {
            controller.fireRecreateAllViews(true);
            if (mainFrame != null) {
                if (EventQueue.isDispatchThread()) {
                    mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

                } else {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                        }
                    });
                }
            }
        }
    }
}


text:
import { escape } from 'lodash';
import emoji from 'actor-emoji';
import emojiDataCategories from 'actor-emoji/emoji_categories';
import { Path } from '../constants/ActorAppConstants';

emoji.include_title = true;
emoji.include_text = true;
emoji.use_sheet = true;
emoji.colons_mode = false;
emoji.img_set = 'apple';
emoji.img_sets = {
  'apple': {
    // 'path': Path.toEmoji + '/img-apple-64/',
    'sheet': Path.toEmoji + '/sheet_apple_64.png',
    'mask': 1
  },
  'google': {
    // 'path': Path.toEmoji + '/img-google-64/',
    'sheet': Path.toEmoji + '/sheet_google_64.png',
    'mask': 2
  },
  'twitter': {
    // 'path': Path.toEmoji + '/img-twitter-64/',
    'sheet': Path.toEmoji + '/sheet_twitter_64.png',
    'mask': 4
  },
  'emojione': {
    // 'path': Path.toEmoji + '/img-emojione-64/',
    'sheet': Path.toEmoji + '/sheet_emojione_64.png',
    'mask': 8
  }
};

export { emoji as emoji };

export const getEmojiCategories = () => {
  let emojiCategories = [];

  for (let category of emojiDataCategories.EmojiDataArray) {
    let title = category.CVDataTitle.replace(/^(.*)-/, '');
    let data = category.CVCategoryData.Data.split(',');
    let icon = '';

    switch (title) {
      case 'People':
        icon = ':grinning:';
        break;
      case 'Nature':
        icon = ':evergreen_tree:';
        break;
      case 'Foods':
        icon = ':hamburger:';
        break;
      case 'Celebration':
        icon = ':gift:';
        break;
      case 'Activity':
        icon = ':football:';
        break;
      case 'Places':
        icon = ':airplane:';
        break;
      case 'Objects':
        icon = ':bulb:';
        break;
      case 'Flags':
        icon = ':flag-ru:';
        break;
      case 'Symbols':
        icon = ':peace_symbol:';
        break;
      default:
    }

    emojiCategories.push({ title, icon, data });
  }

  return emojiCategories;
};

export const emojiRegexp = /([\uE000-\uF8FF]|\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDDFF])/g;

export const preloadEmojiSheet = () => (new Image()).src = emoji.img_sets[emoji.img_set].sheet;

export const escapeWithEmoji = (text) => {
  emoji.include_title = false;
  emoji.include_text = false;
  return emoji.replace_unified(escape(text));
};

export function processEmojiText(text) {
  emoji.include_title = true;
  emoji.include_text = true;
  emoji.change_replace_mode('css');

  let emojifiedText = text;
  emojifiedText = emoji.replace_colons(text);
  emojifiedText = emoji.replace_unified(emojifiedText);

  return emojifiedText;
}

export default {
  emoji,
  emojiRegexp,
  getEmojiCategories,
  preloadEmojiSheet,
  escapeWithEmoji
};


text:
result {
  root_default: initial;
  root_implicit: inner;
  root_explicit: inner;
  local_explicit: inner; }


text:
package org.karlsland.m3g.test;

/**
 * IndexBufferは単独では機能できないクラスであり、
 * TriangleStripArrayクラスを通して使用する。
 * 従ってここでのテストはない。
 */
public class TestIndexBuffer {

	// nothing to do.

}


text:
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Azure.Management.HDInsight.Job
{
    /// <summary>
    /// Operations for managing jobs against HDInsight clusters.
    /// </summary>
    public partial class JobOperationsExtensions
    {
        /// <summary>
        /// Gets the task log summary from execution of a jobDetails.
        /// </summary>
        /// <param name="jobId">
        /// Required. The id of the job.
        /// </param>
        /// <param name="targetDirectory">
        /// Required. The directory in which to download the logs to.
        /// </param>
        /// <param name="storageAccountName">
        /// The name of the storage account
        /// </param>
        /// <param name="storageAccountKey">
        ///
        /// </param>
        /// <param name="defaultContainer">
        ///
        /// </param>
        /// Cancellation token.
        /// </param>
        /// <returns>
        ///
        /// </returns>
        public static void DownloadJobTaskLogs(this IJobOperations operations, string jobId, string targetDirectory,
            string storageAccountName, string storageAccountKey, string defaultContainer)
        {
            Task.Factory.StartNew(
                (object s) =>
                    ((IJobOperations) s).DownloadJobTaskLogsAsync(jobId, targetDirectory, storageAccountName,
                        storageAccountKey, defaultContainer), operations, CancellationToken.None,
                TaskCreationOptions.None, TaskScheduler.Default)
                .Unwrap()
                .GetAwaiter()
                .GetResult();
        }

        /// <summary>
        /// Gets the task log summary from execution of a jobDetails.
        /// </summary>
        /// <param name="jobId">
        /// Required. The id of the job.
        /// </param>
        /// <param name="targetDirectory">
        /// Required. The directory in which to download the logs to.
        /// </param>
        /// <param name="storageAccountName">
        /// The name of the storage account.
        /// </param>
        /// <param name="storageAccountKey">
        /// The default storage account key.
        /// </param>
        /// <param name="defaultContainer">
        /// The default container.
        /// </param>
        /// Cancellation token.
        /// </param>
        /// <returns>
        ///
        /// </returns>
        public static Task DownloadJobTaskLogsAsync(this IJobOperations operations, string jobId, string targetDirectory,
            string storageAccountName, string storageAccountKey, string defaultContainer)
        {
            return operations.DownloadJobTaskLogsAsync(jobId, targetDirectory, storageAccountName, storageAccountKey,
                defaultContainer, CancellationToken.None);
        }

        /// <summary>
        /// Gets the output from the execution of an individual jobDetails.
        /// </summary>
        /// <param name="jobId">
        /// Required. The id of the job.
        /// </param>
        /// <param name="defaultContainer">
        /// Required. The default container.
        /// </param>
        /// <param name="storageAccountName">
        /// Required. The storage account the container lives on.
        /// </param>
        /// <returns>
        /// The output of an individual jobDetails by jobId.
        /// </returns>
        public static Stream GetJobOutput(this IJobOperations operations, string jobId, string storageAccountName,
            string storageAccountKey, string defaultContainer)
        {
            return Task.Factory.StartNew(
                (object s) =>
                    ((IJobOperations) s).GetJobOutputAsync(jobId, storageAccountName, storageAccountKey,
                        defaultContainer), operations,
                CancellationToken.None,
                TaskCreationOptions.None, TaskScheduler.Default)
                .Unwrap()
                .GetAwaiter()
                .GetResult();
        }

        /// <summary>
        /// Gets the output from the execution of an individual jobDetails.
        /// </summary>
        /// <param name="operations"></param>
        /// <param name="jobId">
        ///     Required. The id of the job.
        /// </param>
        /// <param name="storageAccountName">
        ///     Required. The storage account the container lives on.
        /// </param>
        /// <param name="storageAccountKey"></param>
        /// <param name="defaultContainer">
        ///     Required. The default container.
        /// </param>
        /// <returns>
        /// The output of an individual jobDetails by jobId.
        /// </returns>
        public static Task<Stream> GetJobOutputAsync(this IJobOperations operations, string jobId,
            string storageAccountName, string storageAccountKey, string defaultContainer)
        {
            return operations.GetJobOutputAsync(jobId, storageAccountName, storageAccountKey,
                        defaultContainer, CancellationToken.None);
        }

        /// <summary>
        /// Gets the error logs from the execution of an individual jobDetails.
        /// </summary>
        /// <param name="jobId">
        /// Required. The id of the job.
        /// </param>
        /// <param name="defaultContainer">
        /// Required. The default container.
        /// </param>
        /// <param name="storageAccountName">
        /// Required. The storage account the container lives on.
        /// </param>
        /// <returns>
        /// The error logs of an individual jobDetails by jobId.
        /// </returns>
        public static Stream GetJobErrorLogs(this IJobOperations operations, string jobId,
            string storageAccountName, string storageAccountKey, string defaultContainer)
        {
            return Task.Factory.StartNew(
                (object s) =>
                    ((IJobOperations)s).GetJobErrorLogsAsync(jobId, storageAccountName, storageAccountKey,
                        defaultContainer), operations,
                CancellationToken.None,
                TaskCreationOptions.None, TaskScheduler.Default)
                .Unwrap()
                .GetAwaiter()
                .GetResult();
        }

        /// <summary>
        /// Gets the error logs from the execution of an individual jobDetails.
        /// </summary>
        /// <param name="jobId">
        /// Required. The id of the job.
        /// </param>
        /// <param name="defaultContainer">
        /// Required. The default container.
        /// </param>
        /// <param name="storageAccountName">
        /// Required. The storage account the container lives on.
        /// </param>
        /// <returns>
        /// The error logs of an individual jobDetails by jobId.
        /// </returns>
        public static Task<Stream> GetJobErrorLogsAsync(this IJobOperations operations, string jobId,
            string storageAccountName, string storageAccountKey, string defaultContainer)
        {
            return operations.GetJobErrorLogsAsync(jobId, storageAccountName, storageAccountKey,
                        defaultContainer, CancellationToken.None);
        }

        /// <summary>
        /// Gets the task logs from the execution of an individual jobDetails.
        /// </summary>
        /// <param name="jobId">
        /// Required. The id of the job.
        /// </param>
        /// <param name="defaultContainer">
        /// Required. The default container.
        /// </param>
        /// <param name="storageAccountName">
        /// Required. The storage account the container lives on.
        /// </param>
        /// <returns>
        /// The task logs of an individual jobDetails by jobId.
        /// </returns>
        public static Stream GetJobTaskLogSummary(this IJobOperations operations, string jobId,
            string storageAccountName, string storageAccountKey, string defaultContainer)
        {
            return Task.Factory.StartNew(
                (object s) =>
                    ((IJobOperations)s).GetJobTaskLogSummaryAsync(jobId, storageAccountName, storageAccountKey,
                        defaultContainer), operations, CancellationToken.None,
                TaskCreationOptions.None, TaskScheduler.Default)
                .Unwrap()
                .GetAwaiter()
                .GetResult();
        }

        /// <summary>
        /// Gets the task logs from the execution of an individual jobDetails.
        /// </summary>
        /// <param name="jobId">
        /// Required. The id of the job.
        /// </param>
        /// <param name="defaultContainer">
        /// Required. The default container.
        /// </param>
        /// <param name="storageAccountName">
        /// Required. The storage account the container lives on.
        /// </param>
        /// <returns>
        /// The task logs of an individual jobDetails by jobId.
        /// </returns>
        public static Task<Stream> GetJobTaskLogSummaryAsync(this IJobOperations operations, string jobId,
            string storageAccountName, string storageAccountKey, string defaultContainer)
        {
            return operations.GetJobTaskLogSummaryAsync(jobId, storageAccountName, storageAccountKey,
                defaultContainer, CancellationToken.None);
        }

    }
}


text:
#import <SenTestingKit/SenTestingKit.h>

@interface UnirestTests : SenTestCase

@end


text:
.. _architecture:

============
Architecture
============

This page describes the architecture of MyTARDIS.

MyTARDIS is built on the Django web framework, which itself is
built on Python, thus MyTARDIS follows the architectural model
of Django.

Component Architecture
----------------------

The diagram below shows the major components of a typical
MyTARDIS installation.

.. image:: images/TardisComponentArchitecture.png
   :width: 800px

Web Server
  MyTARDIS is typically deployed with the standard `Apache Http <http://projects.apache.org/projects/http_server.html>`_ + `WSGI <http://code.google.com/p/modwsgi/>`_ + `Django <http://www.djangoproject.com/>`_ + `Python <http://docs.python.org/>`_ stack.
RDBMS
  Any of the Django supported databases may be used, typically Postgres.
Data Archive
  Normal file server, e.g. NFS, SAMBA.
Browser
  Typically Firefox
Ingestion
  Ingestion is normally site specific.

Functional Architecture
-----------------------

MyTARDIS follows the standard Django architecture, as shown below [JCDA]_:

.. image:: images/DjangoArchitecture-JeffCroft.png

The major functional modules in MyTARDIS are:

Auth
  Authentication and Authorisation.

Download
  Data download functionality.

Filters
  Processing of metadata as data is uploaded, e.g. extract EXIF metadata from JPEG files.

Management
  Additional commands for the Django CLI.  The backup utility is implemented as a Django command.

Migrations
  South database migration code.

Publish
  RIF-CS metadata publication.

Information on the individual modules is available from the :ref:`modindex`.

.. [JCDA] Thanks to `Jeff Croft <http://www.flickr.com/photos/jcroft/432038560/sizes/o/in/photostream/>`_ for the diagram.

Scalability Model
-----------------

At the component / module level, performance and Scalability within MyTARDIS is achieved by:

* Allowing long lived or compute intensive operations to be hosted on separate machines from the main web server.

  * E.g. by running multiple web servers and sending long lived operations, such as ingestion, to a server reserved for such operations.

* Performance and Scalability of the database is achieved by a combination of 1) optimising the SQL requests issued by MyTARDIS, and 2) database specific scalability, please refer to the appropriate database documentation.

* Performance and Scalability of the web server is provided through the normal mechanisms for apache / wsgi hosted python applications, e,g,:

  * Increasing individual Server capability

    * Individual Server performance / utilization may be managed by controlling the number of python (django) processes active at any one time.

  * Deploying multiple web servers

    * Multiple web servers may be deployed using standard mechanisms, e.g. hardware load balancers.  State (session) information is distributed using Django's standard session model.

* The Data Archive is a normal file system, e.g. NFS, SAMBA, etc., with performance and scalability dependent on the implementation and deployment.

* Extraction and formatting of metadata for ingestion is up to the client and may be distributed across any number of machines.

SQL Scalability Notes
^^^^^^^^^^^^^^^^^^^^^

The datafileparameter table is expected to be the single largest table by an order of magnitude, in the hundreds of millions of records (at the Australian Synchrotron).

For Postgres, this will probably be addressed by table partioning.  In this case using a date field to partition is often recommended.  Dates may be introduced as part of the support for anotations, raw data, versioned data and derived data.

Persistance and Data Architecture
---------------------------------

An introduction to how Tardis models Experiments, Datasets and Datafiles is provided in the :doc:`overview`.

Django provides an Object-Relational-Model that maps Django Models to the underlying relational database.  The models as defined in Django are:

.. image:: images/models-graphviz.png
   :width: 800px
   :target: _images/models-graphviz.png

An additional model diagram including the base Django models is also available: :doc:`ref/models-graphviz-all`.

The underlying SQL schema generated by Django is not normally referenced directly as it is managed through Django's ORM, however a version of the schema is available: :doc:`ref/sql-graphviz`.

Security Model
--------------

Authentication
^^^^^^^^^^^^^^

Access to data catalogued by MyTARDIS may be either public, i.e. anonymous access allowed, or private, requiring authentication.  The Authentication Framework is documented in :ref:`ref-authframework`.

Authorisation
^^^^^^^^^^^^^

MyTARDIS includes an extensible authorisation engine, documented in :ref:`ref-authframework`.

Web Server Security
^^^^^^^^^^^^^^^^^^^

The Django framework provides security against:

* `Cross Site Request Forgery protection <http://docs.djangoproject.com/en/1.2/ref/contrib/csrf/>`_
* `SQL Injection Attacks <http://docs.djangoproject.com/en/1.2/topics/db/sql/>`_

Class Diagram
-------------

Unless the application has a very rich business model (which MyTARDIS does not), a Class diagram doesn't convey much information in Django applications (it ends up being a flat list of classes).  To understand the context in which the MyTARDIS classes are created, please refer to the Django documentation, http://docs.djangoproject.com/ on the responsibilities of models, views, managers and templates.


text:
package org.jetbrains.yaml.structureView;

import com.intellij.ide.structureView.StructureViewTreeElement;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.yaml.YAMLBundle;
import org.jetbrains.yaml.psi.YAMLAlias;
import org.jetbrains.yaml.psi.YAMLScalar;
import org.jetbrains.yaml.psi.YAMLSequenceItem;
import org.jetbrains.yaml.psi.YAMLValue;

import javax.swing.*;
import java.util.Collection;

import static org.jetbrains.yaml.structureView.YAMLStructureViewFactory.ALIAS_ICON;

class YAMLStructureViewSequenceItem extends DuplicatedPsiTreeElementBase<YAMLSequenceItem> {
  YAMLStructureViewSequenceItem(@NotNull YAMLSequenceItem item, String path) {
    super(item, path + '-' + item.getItemIndex());
  }

  @NotNull
  @Override
  public Collection<StructureViewTreeElement> getChildrenBase() {
    return YAMLStructureViewFactory.createChildrenViewTreeElements(getItemValue(), getDetails());
  }

  @NotNull
  @Override
  public String getPresentableText() {
    if (getItemValue() instanceof YAMLScalar) {
      return ((YAMLScalar)getItemValue()).getTextValue();
    }
    else if (getItemValue() instanceof YAMLAlias) {
      return YAMLStructureViewFactory.getAliasPresentableText((YAMLAlias)getItemValue());
    }
    else {
      return YAMLBundle.message("YAMLStructureViewSequenceItem.element.name");
    }
  }

  @Nullable
  @Override
  public String getLocationString() {
    return null;
  }

  @NotNull
  @Override
  public Icon getIcon(boolean unused) {
    if (getItemValue() instanceof YAMLScalar) {
      return PlatformIcons.PROPERTY_ICON;
    }
    else if (getItemValue() instanceof YAMLAlias) {
      return ALIAS_ICON;
    }
    else {
      return PlatformIcons.XML_TAG_ICON;
    }
  }

  @Nullable
  private YAMLValue getItemValue() {
    return getElement().getValue();
  }
}


text:
This needs to be added to `.babelrc` before lingui commands can be run. Otherwise lingui doesn't get the right babel presets and `macros` plugin to extract strings.

```
	"presets": ["preact-cli/babel"],
	"plugins": ["macros"],
```

## Why not add it permanently?

Because then app breaks!


text:
package org.cru.godtools.s3;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3Client;

import javax.enterprise.inject.Default;
import javax.enterprise.inject.Produces;

/**
 * Created by ryancarlson on 7/11/15.
 */
public class AmazonS3ClientProducer
{

	@Produces
	@Default
	public AmazonS3Client amazonS3ClientProducer()
	{
		return new AmazonS3Client(new ProfileCredentialsProvider());
	}

}


text:
/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.displayvideo.v2;

/**
 * Available OAuth 2.0 scopes for use with the Display & Video 360 API.
 *
 * @since 1.4
 */
public class DisplayVideoScopes {

  /** Create, see, edit, and permanently delete your Display & Video 360 entities and reports. */
  public static final String DISPLAY_VIDEO = "https://www.googleapis.com/auth/display-video";

  /** Create, see, and edit Display & Video 360 Campaign entities and see billing invoices. */
  public static final String DISPLAY_VIDEO_MEDIAPLANNING = "https://www.googleapis.com/auth/display-video-mediaplanning";

  /** Private Service: https://www.googleapis.com/auth/display-video-user-management. */
  public static final String DISPLAY_VIDEO_USER_MANAGEMENT = "https://www.googleapis.com/auth/display-video-user-management";

  /** View and manage your reports in DoubleClick Bid Manager. */
  public static final String DOUBLECLICKBIDMANAGER = "https://www.googleapis.com/auth/doubleclickbidmanager";

  /**
   * Returns an unmodifiable set that contains all scopes declared by this class.
   *
   * @since 1.16
   */
  public static java.util.Set<String> all() {
    java.util.Set<String> set = new java.util.HashSet<String>();
    set.add(DISPLAY_VIDEO);
    set.add(DISPLAY_VIDEO_MEDIAPLANNING);
    set.add(DISPLAY_VIDEO_USER_MANAGEMENT);
    set.add(DOUBLECLICKBIDMANAGER);
    return java.util.Collections.unmodifiableSet(set);
  }

  private DisplayVideoScopes() {
  }
}


text:
import net.quasardb.qdb.exception.*;
import net.quasardb.qdb.*;
import org.junit.*;

public class QdbEntryNodeTest {
    @Test
    public void returnsAddressAndPort() {
        QdbBlob blob = Helpers.createEmptyBlob();

        QdbNode node = blob.node();
        Assert.assertEquals("127.0.0.1", node.hostName());
        Assert.assertEquals(Daemon.port(), node.port());
    }
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/language/v1/language_service.proto

namespace Google\Cloud\Language\V1;

if (false) {
    /**
     * This class is deprecated. Use Google\Cloud\Language\V1\ClassificationModelOptions\V2Model\ContentCategoriesVersion instead.
     * @deprecated
     */
    class ClassificationModelOptions_V2Model_ContentCategoriesVersion {}
}
class_exists(ClassificationModelOptions\V2Model\ContentCategoriesVersion::class);
@trigger_error('Google\Cloud\Language\V1\ClassificationModelOptions_V2Model_ContentCategoriesVersion is deprecated and will be removed in the next major release. Use Google\Cloud\Language\V1\ClassificationModelOptions\V2Model\ContentCategoriesVersion instead', E_USER_DEPRECATED);


text:
<?php
declare(strict_types = 1);

namespace MojoCode\SqlParser\Tests\Unit\DataTypes;

use MojoCode\SqlParser\AST\DataType\DoubleDataType;
use MojoCode\SqlParser\AST\DataType\FloatDataType;
use MojoCode\SqlParser\AST\DataType\RealDataType;
use MojoCode\SqlParser\Tests\Unit\AbstractDataTypeBaseTestCase;

/**
 * The FLOAT and DOUBLE types represent approximate numeric data values.
 */
class FloatingPointTypesTestAbstract extends AbstractDataTypeBaseTestCase
{
    /**
     * Data provider for canParseFloatingPointTypes()
     *
     * @return array
     */
    public function canParseFloatingPointTypesProvider(): array
    {
        return [
            'FLOAT without precision' => [
                'FLOAT',
                FloatDataType::class,
                null,
                null,
            ],
            'FLOAT with precision' => [
                'FLOAT(44)',
                FloatDataType::class,
                44,
                null,
            ],
            'FLOAT with precision and decimals' => [
                'FLOAT(44,5)',
                FloatDataType::class,
                44,
                5,
            ],
            'REAL without precision' => [
                'REAL',
                RealDataType::class,
                null,
                null,
            ],
            'REAL with precision' => [
                'REAL(44)',
                RealDataType::class,
                44,
                null,
            ],
            'REAL with precision and decimals' => [
                'REAL(44,5)',
                RealDataType::class,
                44,
                5,
            ],
            'DOUBLE without precision' => [
                'DOUBLE',
                DoubleDataType::class,
                null,
                null,
            ],
            'DOUBLE with precision' => [
                'DOUBLE(44)',
                DoubleDataType::class,
                44,
                null,
            ],
            'DOUBLE with precision and decimals' => [
                'DOUBLE(44,5)',
                DoubleDataType::class,
                44,
                5,
            ],
        ];
    }

    /**
     * @test
     * @dataProvider canParseFloatingPointTypesProvider
     * @param string $columnDefinition
     * @param string $className
     * @param int $precision
     * @param int $scale
     */
    public function canParseDataType(
        string $columnDefinition,
        string $className,
        int $precision = null,
        int $scale = null
    ) {
        $subject = $this->createSubject($columnDefinition);

        $this->assertInstanceOf($className, $subject->dataType);
        $this->assertSame($precision, $subject->dataType->precision);
        $this->assertSame($scale, $subject->dataType->scale);
    }
}


text:
package shiver.me.timbers.waiting;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static shiver.me.timbers.data.random.RandomStrings.someString;

@SuppressWarnings("unchecked")
public class WaiterAspectTest {

    private ServiceLoader<WaiterService, OptionsService> waiterLoader;
    private ServiceLoader<OptionsService, Wait> optionsLoader;
    private WaiterAspect aspect;

    @Before
    public void setUp() {
        waiterLoader = mock(ServiceLoader.class);
        optionsLoader = mock(ServiceLoader.class);
        aspect = new WaiterAspect(waiterLoader, optionsLoader);
    }

    @Test
    public void Can_create_a_waiter_aspect() {
        new WaiterAspect();
    }

    @Test
    public void Call_isMethod_for_100_percent_coverage()
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        final Method isMethod = WaiterAspect.class.getDeclaredMethod("isMethod");
        isMethod.setAccessible(true);
        isMethod.invoke(aspect);
    }

    @Test
    public void Can_wait_for_method_in_class() throws Throwable {

        final ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
        final Wait wait = mock(Wait.class);

        final WaiterService waiterService = mock(WaiterService.class);
        final OptionsService options = mock(OptionsService.class);

        final Signature signature = mock(Signature.class);
        final String[] toString = new String[1];
        final Object[] success = new Object[1];
        final Object expected = new Object();

        // Given
        given(joinPoint.getSignature()).willReturn(signature);
        given(signature.getDeclaringType()).willReturn(Object.class);
        given(signature.getName()).willReturn(someString());
        given(optionsLoader.load(wait)).willReturn(options);
        given(waiterLoader.load(options)).willReturn(waiterService);
        willAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                final Until until = (Until) invocation.getArguments()[0];
                toString[0] = until.toString();
                return success[0] = until.success();
            }
        }).given(waiterService).wait(any(Until.class));
        given(joinPoint.proceed()).willReturn(expected);

        // When
        final Object actual = aspect.waitOnClass(joinPoint, wait);

        // Then
        assertThat(actual, is(success[0]));
        assertThat(actual, is(expected));
        assertThat(joinPoint.toString(), is(toString[0]));
    }

    @Test
    public void Can_wait_for_method() throws Throwable {

        final ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
        final Wait wait = mock(Wait.class);

        final WaiterService waiterService = mock(WaiterService.class);
        final OptionsService options = mock(OptionsService.class);

        final String[] toString = new String[1];
        final Object[] success = new Object[1];
        final Object expected = new Object();

        // Given
        given(optionsLoader.load(wait)).willReturn(options);
        given(waiterLoader.load(options)).willReturn(waiterService);
        willAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                final Until until = (Until) invocation.getArguments()[0];
                toString[0] = until.toString();
                return success[0] = until.success();
            }
        }).given(waiterService).wait(any(Until.class));
        given(joinPoint.proceed()).willReturn(expected);

        // When
        final Object actual = aspect.waitOnMethod(joinPoint, wait);

        // Then
        assertThat(actual, is(success[0]));
        assertThat(actual, is(expected));
        assertThat(joinPoint.toString(), is(toString[0]));
    }

    @Test
    public void A_new_waiter_is_loaded_every_time() throws Throwable {

        final ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
        final Wait wait = mock(Wait.class);

        final Signature signature = mock(Signature.class);
        final WaiterService waiterService = mock(WaiterService.class);
        final OptionsService options = mock(OptionsService.class);

        // Given
        given(joinPoint.getSignature()).willReturn(signature);
        given(signature.getDeclaringType()).willReturn(Object.class);
        given(signature.getName()).willReturn(someString());
        given(optionsLoader.load(wait)).willReturn(options);
        given(waiterLoader.load(options)).willReturn(waiterService);

        // When
        aspect.waitOnClass(joinPoint, wait);
        aspect.waitOnMethod(joinPoint, wait);
        aspect.waitOnClass(joinPoint, wait);

        // Then
        verify(optionsLoader, times(3)).load(wait);
        verify(waiterLoader, times(3)).load(options);
        verify(waiterService, times(3)).wait(any(Until.class));
    }

    @Test
    public void Will_ignore_class_annotation_if_method_is_annotated() throws Throwable {

        final ProceedingJoinPoint joinPoint = mock(ProceedingJoinPoint.class);
        final Wait wait = mock(Wait.class);

        final Signature signature = mock(Signature.class);
        @Wait
        class WaitMethodOverride {
            @Wait
            private void overrideWaitMethod() {
            }
        }

        final Object expected = new Object();

        // Given
        given(joinPoint.getSignature()).willReturn(signature);
        given(signature.getDeclaringType()).willReturn(WaitMethodOverride.class);
        given(signature.getName()).willReturn("overrideWaitMethod");
        given(joinPoint.proceed()).willReturn(expected);

        // When
        final Object actual = aspect.waitOnClass(joinPoint, wait);

        // Then
        assertThat(actual, is(expected));
        verifyZeroInteractions(optionsLoader, waiterLoader);
    }
}


text:
(function(lytix) {

    'use strict';

    lytix.trackPage = function(path) {
        if (window.trak && trak.io) {
            trak.io.page_view(path);
        }
    };

    lytix.trackEvent = function(properties) {
        if (window.trak && trak.io && properties.action) {
            trak.io.track(properties.action, properties);
        }
    };

    lytix.init();

})(window.lytix);